1 21 22 package org.apache.derby.iapi.services.io; 23 24 import java.io.InputStream ; 25 import java.io.FilterInputStream ; 26 import java.io.IOException ; 27 28 32 public class LimitInputStream extends FilterInputStream implements Limit { 33 34 protected int remainingBytes; 35 protected boolean limitInPlace; 36 37 40 public LimitInputStream(InputStream in) { 41 super(in); 42 clearLimit(); 43 } 44 45 public int read() throws IOException { 46 47 if (!limitInPlace) 48 return super.read(); 49 50 if (remainingBytes == 0) 51 return -1; 53 54 int value = super.read(); 55 if (value >= 0) 56 remainingBytes--; 57 return value; 58 59 } 60 61 public int read(byte b[], int off, int len) throws IOException { 62 63 if (!limitInPlace) 64 return super.read(b, off, len); 65 66 67 if (remainingBytes == 0) 68 return -1; 69 70 if (remainingBytes < len) { 71 len = remainingBytes; } 73 74 len = super.read(b, off, len); 75 if (len > 0) 76 remainingBytes -= len; 77 78 return len; 79 } 80 81 public long skip(long count) throws IOException { 82 if (!limitInPlace) 83 return super.skip(count); 84 85 if (remainingBytes == 0) 86 return 0; 88 if (remainingBytes < count) 89 count = remainingBytes; 90 91 count = super.skip(count); 92 remainingBytes -= count; 93 return count; 94 } 95 96 public int available() throws IOException { 97 98 if (!limitInPlace) 99 return super.available(); 100 101 if (remainingBytes == 0) 102 return 0; 104 int actualLeft = super.available(); 105 106 if (remainingBytes < actualLeft) 107 return remainingBytes; 108 109 110 return actualLeft; 111 } 112 113 114 124 public void setLimit(int length) { 125 remainingBytes = length; 126 limitInPlace = true; 127 return; 128 } 129 130 137 public int clearLimit() { 138 int leftOver = remainingBytes; 139 limitInPlace = false; 140 remainingBytes = -1; 141 return leftOver; 142 } 143 144 public void setInput(InputStream in) { 145 this.in = in; 146 } 147 } 148 | Popular Tags |