1 16 package org.apache.axis.attachments; 17 18 import javax.activation.DataSource ; 19 import javax.xml.transform.stream.StreamSource ; 20 import java.io.ByteArrayInputStream ; 21 import java.io.ByteArrayOutputStream ; 22 import java.io.IOException ; 23 import java.io.InputStream ; 24 import java.io.OutputStream ; 25 import java.io.Reader ; 26 import java.io.BufferedReader ; 27 import java.io.BufferedInputStream ; 28 import java.net.URL ; 29 30 public class SourceDataSource implements DataSource { 31 public static final String CONTENT_TYPE = "text/xml"; 32 33 private final String name; 34 private final String contentType; 35 private byte[] data; 36 private ByteArrayOutputStream os; 37 38 public SourceDataSource(String name, StreamSource data) { 39 this(name, CONTENT_TYPE, data); 40 } 42 public SourceDataSource(String name, String contentType, StreamSource data) { 43 this.name = name; 44 this.contentType = contentType == null ? CONTENT_TYPE : contentType; 45 os = new ByteArrayOutputStream (); 46 try { 47 if (data != null) { 48 Reader reader = data.getReader(); 50 if (reader != null) { 51 reader = new BufferedReader (reader); 52 int ch; 53 while ((ch = reader.read())!=-1) { 54 os.write(ch); 55 } 56 } else { 57 InputStream is = data.getInputStream(); 59 if (is == null) { 60 String id = data.getSystemId(); 62 if (id != null) { 63 URL url = new URL (id); 64 is = url.openStream(); 65 } 66 } 67 if (is != null) { 68 is = new BufferedInputStream (is); 69 byte[] bytes = null; 71 int avail; 72 while ((avail = is.available()) > 0) { 73 if (bytes == null || avail > bytes.length) 74 bytes = new byte[avail]; 75 is.read(bytes, 0, avail); 76 os.write(bytes, 0, avail); 77 } 78 } 79 } 80 } 81 } catch (Exception e) { 82 } 84 } 86 public String getName() { 87 return name; 88 } 90 public String getContentType() { 91 return contentType; 92 } 94 public InputStream getInputStream() throws IOException { 95 if (os.size() != 0) { 96 data = os.toByteArray(); 97 os.reset(); 98 } 99 return new ByteArrayInputStream (data == null ? new byte[0] : data); 100 } 102 public OutputStream getOutputStream() throws IOException { 103 if (os.size() != 0) { 104 data = os.toByteArray(); 105 os.reset(); 106 } 107 return os; 108 } } | Popular Tags |