1 19 package org.netbeans.tax.io; 20 21 import java.io.Reader ; 22 import java.io.StringReader ; 23 import java.io.StringWriter ; 24 import java.io.BufferedReader ; 25 import java.io.IOException ; 26 import java.io.EOFException ; 27 import java.io.ByteArrayOutputStream ; 28 29 import javax.swing.text.Document ; 30 31 import org.xml.sax.InputSource ; 32 33 import org.netbeans.tax.TreeException; 34 import org.netbeans.tax.TreeDocumentRoot; 35 36 42 public final class Convertors { 43 44 45 48 public static String documentToString (final Document doc) { 49 50 final String [] str = new String [1]; 51 52 Runnable run = new Runnable () { 54 public void run () { 55 try { 56 str[0] = doc.getText (0, doc.getLength ()); 57 } catch (javax.swing.text.BadLocationException e) { 58 e.printStackTrace (); 60 } 61 } 62 }; 63 64 doc.render (run); 65 return str[0]; 66 67 } 68 69 72 public static InputSource documentToInputSource (Document doc) { 73 String text = documentToString (doc); 74 Reader reader = new StringReader (text); 75 InputSource in = new InputSource ("StringReader"); in.setCharacterStream (reader); 77 return in; 78 } 79 80 81 85 public static String readerToString (Reader reader) throws IOException { 86 87 BufferedReader fastReader = new BufferedReader (reader); 88 StringBuffer buf = new StringBuffer (1024); 89 try { 90 for (int i = fastReader.read (); i >= 0; i = fastReader.read ()) { 91 buf.append ((char)i); 92 } 93 } catch (EOFException eof) { 94 } 96 97 return buf.toString (); 98 } 99 100 103 public static String treeToString (TreeDocumentRoot doc) throws IOException { 104 105 StringWriter out = new StringWriter (); 106 TreeStreamResult result = new TreeStreamResult (out); 107 TreeWriter writer = result.getWriter (doc); 108 109 try { 110 writer.writeDocument (); 111 return out.toString (); 112 } catch (TreeException ex) { 113 throw new IOException ("Cannot read tree " + ex.getMessage ()); 115 } finally { 116 try { 117 out.close (); 118 } catch (IOException ioex) { 119 } 121 } 122 123 } 124 125 public static byte[] treeToByteArray (TreeDocumentRoot doc) throws IOException { 126 127 ByteArrayOutputStream out = new ByteArrayOutputStream (1024 * 8); 128 TreeStreamResult result = new TreeStreamResult (out); 129 TreeWriter writer = result.getWriter (doc); 130 131 try { 132 writer.writeDocument (); 133 byte[] array = out.toByteArray (); 134 return array; 135 } catch (TreeException ex) { 136 throw new IOException ("Cannot read tree " + ex.getMessage ()); 138 } finally { 139 try { 140 out.close (); 141 } catch (IOException ioex) { 142 } 144 } 145 } 146 } 147 | Popular Tags |