1 25 package org.archive.io; 26 27 import java.io.File ; 28 import java.io.IOException ; 29 import java.io.OutputStream ; 30 31 32 40 public class ReplayInputStream extends SeekInputStream 41 { 42 private BufferedSeekInputStream diskStream; 43 private byte[] buffer; 44 private long position; 45 46 51 private long size = -1; 52 53 56 protected long responseBodyStart = -1; 57 58 59 72 public ReplayInputStream(byte[] buffer, long size, long responseBodyStart, 73 String backingFilename) 74 throws IOException 75 { 76 this(buffer, size, backingFilename); 77 this.responseBodyStart = responseBodyStart; 78 } 79 80 91 public ReplayInputStream(byte[] buffer, long size, String backingFilename) 92 throws IOException 93 { 94 this.buffer = buffer; 95 this.size = size; 96 if (size > buffer.length) { 97 RandomAccessInputStream rais = new RandomAccessInputStream( 98 new File (backingFilename)); 99 diskStream = new BufferedSeekInputStream(rais, 4096); 100 } 101 } 102 103 public long setToResponseBodyStart() throws IOException { 104 position(responseBodyStart); 105 return this.position; 106 } 107 108 109 112 public int read() throws IOException { 113 if (position == size) { 114 return -1; } 116 if (position < buffer.length) { 117 int c = buffer[(int) position] & 0xFF; 119 position++; 120 return c; 121 } 122 int c = diskStream.read(); 123 if (c >= 0) { 124 position++; 125 } 126 return c; 127 } 128 129 134 public int read(byte[] b, int off, int len) throws IOException { 135 if (position == size) { 136 return -1; } 138 if (position < buffer.length) { 139 int toCopy = (int)Math.min(size - position, 140 Math.min(len, buffer.length - position)); 141 System.arraycopy(buffer, (int)position, b, off, toCopy); 142 if (toCopy > 0) { 143 position += toCopy; 144 } 145 return toCopy; 146 } 147 int read = diskStream.read(b,off,len); 149 if(read>0) { 150 position += read; 151 } 152 return read; 153 } 154 155 public void readFullyTo(OutputStream os) throws IOException { 156 byte[] buf = new byte[4096]; 157 int c = read(buf); 158 while (c != -1) { 159 os.write(buf,0,c); 160 c = read(buf); 161 } 162 } 163 164 167 public void close() throws IOException { 168 super.close(); 169 if(diskStream != null) { 170 diskStream.close(); 171 } 172 } 173 174 178 public long getSize() 179 { 180 return size; 181 } 182 183 187 public long remaining() { 188 return size - position; 189 } 190 191 192 198 public void position(long p) throws IOException { 199 if (p < 0) { 200 throw new IOException ("Negative seek offset."); 201 } 202 if (p >= size) { 203 throw new IOException ("Desired position exceeds size."); 204 } 205 if (p < buffer.length) { 206 if (position > buffer.length) { 208 diskStream.position(0); 209 } 210 } else { 211 diskStream.position(p - buffer.length); 212 } 213 this.position = p; 214 } 215 216 217 public long position() throws IOException { 218 return position; 219 } 220 } 221 | Popular Tags |