1 package org.columba.core.io; 17 18 import java.io.ByteArrayInputStream ; 19 import java.io.ByteArrayOutputStream ; 20 import java.io.File ; 21 import java.io.FileInputStream ; 22 import java.io.FileNotFoundException ; 23 import java.io.FileOutputStream ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.util.ArrayList ; 27 import java.util.List ; 28 29 35 public class CloneStreamMaster { 36 private static int uid = 0; 37 38 private InputStream master; 39 40 private int nextId; 41 42 private List <InputStream > streamList; 43 44 private File tempFile; 45 46 private byte[] buffer; 47 48 private int openClones; 49 50 private boolean usesFile; 51 52 private int size; 53 54 60 public CloneStreamMaster(InputStream master) throws IOException { 61 super(); 62 this.master = master; 63 64 streamList = new ArrayList <InputStream >(2); 65 66 if (this.master.available() > 51200) { 67 tempFile = File.createTempFile("columba-stream-clone" + (uid++), 68 ".tmp"); 69 70 tempFile.deleteOnExit(); 72 73 FileOutputStream tempOut = new FileOutputStream (tempFile); 74 75 size = (int) StreamUtils.streamCopy(master, tempOut); 76 77 tempOut.close(); 78 79 usesFile = true; 80 } else { 81 ByteArrayOutputStream tempOut = new ByteArrayOutputStream (); 82 83 size = (int) StreamUtils.streamCopy(master, tempOut); 84 tempOut.close(); 85 86 buffer = tempOut.toByteArray(); 87 usesFile = false; 88 } 89 90 this.master.close(); 91 } 92 93 98 public CloneInputStream getClone() { 99 if (usesFile) { 100 try { 101 streamList.add(new FileInputStream (tempFile)); 103 } catch (FileNotFoundException e) { 104 e.printStackTrace(); 105 106 } 108 } else { 109 streamList.add(new ByteArrayInputStream (buffer)); 110 } 111 112 openClones++; 113 114 return new CloneInputStream(this, nextId++); 115 } 116 117 public int read(int id) throws IOException { 118 return streamList.get(id).read(); 119 } 120 121 public int read(int id, byte[] out, int offset, int length) 122 throws IOException { 123 return streamList.get(id).read(out, offset, length); 124 } 125 126 129 public int available() throws IOException { 130 return size; 131 } 132 133 136 @Override 137 protected void finalize() throws Throwable { 138 super.finalize(); 139 140 if (usesFile) { 141 tempFile.delete(); 143 } 144 } 145 146 149 public void close(int id) throws IOException { 150 streamList.get(id).close(); 151 } 152 } 153 | Popular Tags |