1 36 package org.columba.ristretto.io; 37 38 import java.io.ByteArrayOutputStream ; 39 import java.io.File ; 40 import java.io.FileOutputStream ; 41 import java.io.IOException ; 42 import java.io.InputStream ; 43 import java.io.OutputStream ; 44 45 53 public class TempSourceFactory { 54 55 58 public static int MAX_IN_RAM_SIZE = 51200; protected static String TEMP_PREFIX = "ristretto_"; 60 protected static String TEMP_POSTFIX = "tmp"; 61 protected static int BUFFER_SIZE = 51200; 62 63 private static int counter = 0; 64 65 73 public static Source createTempSource( 74 InputStream in, 75 int size) 76 throws IOException { 77 78 if(size != -1 && (size < MAX_IN_RAM_SIZE 79 || in.available() < MAX_IN_RAM_SIZE) ) { 80 81 ByteArrayOutputStream out = new ByteArrayOutputStream (); 83 84 copyStream(in, out, size); 85 86 out.close(); 87 88 return new ByteBufferSource(out.toByteArray()); 89 } else { 90 File tempFile = createTempFile(); 91 92 OutputStream out = new FileOutputStream (tempFile); 93 94 copyStream(in, out, size); 95 96 out.close(); 97 98 return new FileSource(tempFile); 100 } 101 102 } 103 104 111 public static Source createTempSource( 112 InputStream in) 113 throws IOException { 114 return TempSourceFactory.createTempSource(in, -1); 115 } 116 117 118 124 public static boolean useMemoryTemp(int size) { 125 return size < MAX_IN_RAM_SIZE; 126 } 127 128 135 public static File createTempFile() throws IOException { 136 File tempFile = 138 File.createTempFile(TEMP_PREFIX + nextID(), TEMP_POSTFIX); 139 tempFile.deleteOnExit(); 140 return tempFile; 141 } 142 143 private static synchronized int nextID() { 144 return counter++; 145 } 146 147 private static int copyStream( 148 InputStream in, 149 OutputStream out, 150 int size) 151 throws IOException { 152 byte[] buffer = new byte[BUFFER_SIZE]; 153 154 int copied = 0; 155 int actSize; 156 157 if (size != -1) { 158 159 while (size - copied > 0) { 160 actSize = 161 in.read( 162 buffer, 163 0, 164 size - copied >= BUFFER_SIZE 165 ? BUFFER_SIZE 166 : size - copied); 167 if (actSize == -1) 168 break; 169 out.write(buffer, 0, actSize); 170 copied += actSize; 171 } 172 } else { 173 while (true) { 174 actSize = 175 in.read(buffer); 176 if (actSize == -1) 177 break; 178 out.write(buffer, 0, actSize); 179 copied += actSize; 180 } 181 } 182 183 return copied; 184 } 185 186 } 187 | Popular Tags |