1 25 26 package org.objectweb.petals.util; 27 28 import java.io.BufferedInputStream ; 29 import java.io.ByteArrayInputStream ; 30 import java.io.StringWriter ; 31 import java.io.UnsupportedEncodingException ; 32 import java.util.Properties ; 33 34 import javax.xml.transform.OutputKeys ; 35 import javax.xml.transform.Result ; 36 import javax.xml.transform.Source ; 37 import javax.xml.transform.Transformer ; 38 import javax.xml.transform.TransformerConfigurationException ; 39 import javax.xml.transform.TransformerFactory ; 40 import javax.xml.transform.TransformerFactoryConfigurationError ; 41 import javax.xml.transform.stream.StreamResult ; 42 import javax.xml.transform.stream.StreamSource ; 43 44 52 public final class SourceHelper { 53 54 private static Transformer transformer; 55 56 private SourceHelper() { 57 } 59 60 66 public static Source createSource(String msg) { 67 StreamSource source = new StreamSource (); 68 try { 69 byte[] msgByte= msg.getBytes("UTF-8"); 70 ByteArrayInputStream in = new ByteArrayInputStream (msgByte); 71 source.setInputStream(in); 72 } catch (UnsupportedEncodingException e) { 73 } 75 return source; 76 } 77 78 public static String createString(Source s) throws Exception { 79 80 String result = null; 81 82 if (s != null) { 83 84 if (s instanceof StreamSource ) { 85 StreamSource ss = (StreamSource ) s; 86 if (ss.getInputStream() != null) { 87 if (ss.getInputStream().markSupported()) { 88 ss.getInputStream().reset(); 89 } 90 byte[] buf = new byte[ss.getInputStream().available()]; 91 BufferedInputStream bis = new BufferedInputStream (ss 92 .getInputStream()); 93 bis.read(buf); 94 result = new String (buf); 95 } 96 else if (ss.getReader() != null) { 97 StringBuffer stringBuffer = new StringBuffer (); 98 int readThisTime = 0; 99 char[] cbuf = new char[4096]; 100 while (readThisTime != -1) { 101 readThisTime = ss.getReader().read(cbuf, 0, 4096); 102 if (readThisTime!= -1) { 103 stringBuffer.append(cbuf, 0, readThisTime); 104 } 105 } 106 result = stringBuffer.toString(); 107 } 108 109 } else { 110 111 StringWriter buffer = new StringWriter (); 112 Result sresult = new StreamResult (buffer); 113 Transformer transform = getTransformer(); 114 transform.transform(s, sresult); 115 result = buffer.toString(); 116 } 117 } 118 119 return result; 120 } 121 public static Transformer getTransformer() 122 throws TransformerConfigurationException , 123 TransformerFactoryConfigurationError { 124 if (transformer == null) { 125 transformer = TransformerFactory.newInstance().newTransformer(); 126 Properties props = new Properties (); 127 props.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); 128 transformer.setOutputProperties(props); 129 } 130 return transformer; 131 } 132 133 } 134 | Popular Tags |