1 11 package org.eclipse.team.internal.core.streams; 12 13 import java.io.FilterInputStream ; 14 import java.io.IOException ; 15 import java.io.InputStream ; 16 import java.io.InterruptedIOException ; 17 18 import org.eclipse.core.runtime.OperationCanceledException; 19 20 30 public class SizeConstrainedInputStream extends FilterInputStream { 31 private boolean discardOnClose; 32 private long bytesRemaining; 33 34 41 public SizeConstrainedInputStream(InputStream in, long size, boolean discardOnClose) { 42 super(in); 43 this.bytesRemaining = size; 44 this.discardOnClose = discardOnClose; 45 } 46 47 52 public void close() throws IOException { 53 try { 54 if (discardOnClose) { 55 while (bytesRemaining != 0 && skip(bytesRemaining) != 0); 56 } 57 } catch (OperationCanceledException e) { 58 } finally { 62 bytesRemaining = 0; 63 } 64 } 65 66 71 public int available() throws IOException { 72 int amount = in.available(); 73 if (amount > bytesRemaining) amount = (int) bytesRemaining; 74 return amount; 75 } 76 77 84 public int read() throws IOException { 85 if (bytesRemaining == 0) return -1; 86 int b = in.read(); 87 if (b != -1) bytesRemaining -= 1; 88 return b; 89 } 90 91 98 public int read(byte[] buffer, int offset, int length) throws IOException { 99 if (length > bytesRemaining) { 100 if (bytesRemaining == 0) return -1; 101 length = (int) bytesRemaining; 102 } 103 try { 104 int count = in.read(buffer, offset, length); 105 if (count != -1) bytesRemaining -= count; 106 return count; 107 } catch (InterruptedIOException e) { 108 bytesRemaining -= e.bytesTransferred; 109 throw e; 110 } 111 } 112 113 120 public long skip(long amount) throws IOException { 121 if (amount > bytesRemaining) amount = bytesRemaining; 122 try { 123 long count = in.skip(amount); 124 bytesRemaining -= count; 125 return count; 126 } catch (InterruptedIOException e) { 127 bytesRemaining -= e.bytesTransferred; 128 throw e; 129 } 130 } 131 132 135 public boolean markSupported() { 136 return false; 137 } 138 } 139 | Popular Tags |