1 19 package org.netbeans.modules.xml.tools.lib; 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 import org.netbeans.tax.io.*; 36 37 43 public final class Convertors { 44 45 46 49 public static String documentToString(final Document doc) { 50 51 final String [] str = new String [1]; 52 53 Runnable run = new Runnable () { 55 public void run () { 56 try { 57 str[0] = doc.getText(0, doc.getLength()); 58 } catch (javax.swing.text.BadLocationException e) { 59 e.printStackTrace(); 61 } 62 } 63 }; 64 65 doc.render(run); 66 return str[0]; 67 68 } 69 70 73 public static InputSource documentToInputSource(Document doc) { 74 String text = documentToString(doc); 75 Reader reader = new StringReader (text); 76 InputSource in = new InputSource ("StringReader"); in.setCharacterStream(reader); 78 return in; 79 } 80 81 82 86 public static String readerToString(Reader reader) throws IOException { 87 88 BufferedReader fastReader = new BufferedReader (reader); 89 StringBuffer buf = new StringBuffer (1024); 90 try { 91 for (int i = fastReader.read(); i >= 0; i = fastReader.read()) { 92 buf.append((char)i); 93 } 94 } catch (EOFException eof) { 95 } 97 98 return buf.toString(); 99 } 100 101 104 public static String treeToString(TreeDocumentRoot doc) throws IOException { 105 106 StringWriter out = new StringWriter (); 107 TreeStreamResult result = new TreeStreamResult(out); 108 TreeWriter writer = result.getWriter(doc); 109 110 try { 111 writer.writeDocument(); 112 return out.toString(); 113 } catch (TreeException ex) { 114 throw new IOException ("Cannot read tree " + ex.getMessage()); 116 } finally { 117 try { 118 out.close(); 119 } catch (IOException ioex) { 120 } 122 } 123 124 } 125 126 public static byte[] treeToByteArray(TreeDocumentRoot doc) throws IOException { 127 128 ByteArrayOutputStream out = new ByteArrayOutputStream (1024 * 8); 129 TreeStreamResult result = new TreeStreamResult(out); 130 TreeWriter writer = result.getWriter(doc); 131 132 try { 133 writer.writeDocument(); 134 byte[] array = out.toByteArray(); 135 return array; 136 } catch (TreeException ex) { 137 throw new IOException ("Cannot read tree " + ex.getMessage()); 139 } finally { 140 try { 141 out.close(); 142 } catch (IOException ioex) { 143 } 145 } 146 } 147 } 148 | Popular Tags |