001 package org.apache.commons.ssl.asn1; 002 003 import java.io.EOFException; 004 import java.io.IOException; 005 import java.io.InputStream; 006 007 class DefiniteLengthInputStream 008 extends LimitedInputStream { 009 private int _length; 010 011 DefiniteLengthInputStream( 012 InputStream in, 013 int length) { 014 super(in); 015 016 if (length < 0) { 017 throw new IllegalArgumentException("negative lengths not allowed"); 018 } 019 020 this._length = length; 021 } 022 023 public int read() 024 throws IOException { 025 if (_length > 0) { 026 int b = _in.read(); 027 028 if (b < 0) { 029 throw new EOFException(); 030 } 031 032 --_length; 033 return b; 034 } 035 036 setParentEofDetect(true); 037 038 return -1; 039 } 040 041 public int read(byte[] buf, int off, int len) 042 throws IOException { 043 if (_length > 0) { 044 int toRead = Math.min(len, _length); 045 int numRead = _in.read(buf, off, toRead); 046 047 if (numRead < 0) 048 throw new EOFException(); 049 050 _length -= numRead; 051 return numRead; 052 } 053 054 setParentEofDetect(true); 055 056 return -1; 057 } 058 059 byte[] toByteArray() 060 throws IOException { 061 byte[] bytes = new byte[_length]; 062 063 if (_length > 0) { 064 int pos = 0; 065 do { 066 int read = _in.read(bytes, pos, _length - pos); 067 068 if (read < 0) { 069 throw new EOFException(); 070 } 071 072 pos += read; 073 } 074 while (pos < _length); 075 076 _length = 0; 077 } 078 079 setParentEofDetect(true); 080 081 return bytes; 082 } 083 }