1 57 58 package org.apache.soap.util.mime; 59 60 import java.io.*; 61 import org.apache.soap.Constants; 62 import javax.activation.*; 63 64 73 74 public class ByteArrayDataSource implements DataSource { 75 private byte[] data; private String type; 78 85 public ByteArrayDataSource(File f, String type) throws IOException { 86 this(new FileInputStream(f), type); 87 if (this.type == null) 88 this.type = FileTypeMap.getDefaultFileTypeMap().getContentType(f); 89 } 90 91 97 public ByteArrayDataSource(InputStream is, String type) 98 throws IOException { 99 this.type = type; 100 101 ByteArrayOutputStream os = new ByteArrayOutputStream(); 102 103 byte buf[] = new byte[4096]; 104 int len; 105 while (true){ 106 len = is.read(buf); 107 if (len < 0) 108 break; 109 os.write(buf, 0, len); 110 } 111 data = os.toByteArray(); 112 } 113 114 120 public ByteArrayDataSource(byte[] data, String type) 121 { 122 this.type = type; 123 this.data = data; 124 } 125 126 134 public ByteArrayDataSource(String data, String type) 135 { 136 this.type = type; 137 try { 138 this.data = data.getBytes(MimeUtils.getEncoding(type, 139 Constants.HEADERVAL_DEFAULT_CHARSET)); 140 } catch (UnsupportedEncodingException uex) { 141 } 142 } 143 144 149 public InputStream getInputStream() throws IOException { 150 if (data == null) 151 throw new IOException("No data."); 152 return new ByteArrayInputStream(data); 153 } 154 155 159 public OutputStream getOutputStream() throws IOException { 160 throw new IOException("getOutputStream() not supported."); 161 } 162 163 168 public String getContentType() { 169 return type; 170 } 171 172 177 public void setContentType(String type) { 178 this.type = type; 179 } 180 181 184 public String getName() { 185 return ""; 186 } 187 188 193 public void writeTo(OutputStream os) throws IOException { 194 os.write(data); 195 } 196 197 202 public byte[] toByteArray() { 203 return data; 204 } 205 206 211 public int getSize() { 212 if (data == null) 213 return -1; 214 else 215 return data.length; 216 } 217 218 225 public String getText() { 226 try { 227 return new String (data, MimeUtils.getEncoding(type, 228 Constants.HEADERVAL_DEFAULT_CHARSET)); 229 } catch (UnsupportedEncodingException uex) { 230 try { 231 return new String (data, Constants.HEADERVAL_DEFAULT_CHARSET); 232 } catch (UnsupportedEncodingException uex1) { 233 return null; 234 } 235 } 236 } 237 } 238 | Popular Tags |