1 8 package org.jboss.axis.attachments; 9 10 import org.jboss.logging.Logger; 11 12 import javax.activation.DataSource ; 13 import java.io.ByteArrayInputStream ; 14 import java.io.ByteArrayOutputStream ; 15 import java.io.File ; 16 import java.io.FileInputStream ; 17 import java.io.FileOutputStream ; 18 import java.io.IOException ; 19 import java.io.InputStream ; 20 import java.io.OutputStream ; 21 22 27 public class ManagedMemoryDataSource implements DataSource 28 { 29 private static Logger log = Logger.getLogger(ManagedMemoryDataSource.class); 30 31 32 protected String contentType = "application/octet-stream"; 34 private byte[] contentData; 36 37 private File cacheFile; 39 40 42 43 public static final int READ_CHUNK_SZ = 32 * 1024; 44 45 46 public static final int MAX_MEMORY_SZ = 64 * 1024; 47 48 53 public ManagedMemoryDataSource(InputStream inputStream, String contentType) throws IOException 54 { 55 if (contentType != null) 56 this.contentType = contentType; 57 58 ByteArrayOutputStream baos = new ByteArrayOutputStream (READ_CHUNK_SZ); 59 OutputStream os = baos; 60 61 byte[] bytes = new byte[READ_CHUNK_SZ]; 62 int read = inputStream.read(bytes); 63 while (read > 0) 64 { 65 os.write(bytes, 0, read); 66 67 if (baos != null && baos.size() > MAX_MEMORY_SZ) 68 { 69 cacheFile = File.createTempFile("attachment", ".dat"); 71 cacheFile.deleteOnExit(); 72 73 log.debug("Created cache file: " + cacheFile.toURL()); 74 os = new FileOutputStream (cacheFile); 75 os.write(baos.toByteArray()); 76 baos = null; 77 } 78 79 read = inputStream.read(bytes); 80 } 81 os.flush(); 82 os.close(); 83 84 if (baos != null) 85 { 86 log.debug("Using in memory cache: " + baos.size()); 87 this.contentData = baos.toByteArray(); 88 } 89 } 90 91 public String getContentType() 92 { 93 return contentType; 94 } 95 96 public InputStream getInputStream() throws IOException 97 { 98 if (contentData != null) 99 return new ByteArrayInputStream (contentData); 100 else if (cacheFile != null) 101 return new FileInputStream (cacheFile); 102 else 103 throw new IllegalStateException ("No cache available"); 104 } 105 106 public String getName() 107 { 108 return null; 109 } 110 111 public OutputStream getOutputStream() throws IOException 112 { 113 return null; 114 } 115 116 117 protected void finalize() throws Throwable 118 { 119 super.finalize(); 120 121 if (cacheFile != null) 122 cacheFile.delete(); 123 } 124 } 125 | Popular Tags |