1 package ca.uhn.hl7v2.hoh.util;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.SocketTimeoutException;
6
7 public class SplitInputStream extends InputStream {
8
9 private int myBytesUntilSplit;
10 private InputStream myWrap;
11
12 public SplitInputStream(InputStream theWrap, int theSplitPoint) {
13 myBytesUntilSplit = theSplitPoint;
14 myWrap = theWrap;
15 }
16
17
18
19
20
21
22 @Override
23 public int read(byte[] theB) throws IOException {
24 throw new UnsupportedOperationException();
25 }
26
27
28
29
30
31
32 @Override
33 public int read(byte[] theB, int theOff, int theLen) throws IOException {
34 if (myBytesUntilSplit < 0) {
35
36 } else if (myBytesUntilSplit > 0 && theLen > myBytesUntilSplit) {
37 theLen = myBytesUntilSplit;
38 } else {
39 myBytesUntilSplit = -1;
40 theLen = 0;
41 throw new SocketTimeoutException();
42 }
43 int retVal = myWrap.read(theB, theOff, theLen);
44 myBytesUntilSplit -= retVal;
45 return retVal;
46 }
47
48
49
50
51
52
53 @Override
54 public long skip(long theN) throws IOException {
55 myBytesUntilSplit -= theN;
56 return myWrap.skip(theN);
57 }
58
59
60
61
62
63
64 @Override
65 public int available() throws IOException {
66 return myBytesUntilSplit >= 0 ? Math.min(myBytesUntilSplit, myWrap.available()) : myWrap.available();
67 }
68
69
70
71
72
73
74 @Override
75 public void close() throws IOException {
76 myWrap.close();
77 }
78
79
80
81
82
83
84 @Override
85 public synchronized void mark(int theReadlimit) {
86 throw new UnsupportedOperationException();
87 }
88
89
90
91
92
93
94 @Override
95 public synchronized void reset() throws IOException {
96 throw new UnsupportedOperationException();
97 }
98
99
100
101
102
103
104 @Override
105 public boolean markSupported() {
106 throw new UnsupportedOperationException();
107 }
108
109 @Override
110 public int read() throws IOException {
111 if (myBytesUntilSplit == 0) {
112 myBytesUntilSplit--;
113 throw new SocketTimeoutException();
114 }
115 int retVal = myWrap.read();
116 if (retVal != -1) {
117 myBytesUntilSplit--;
118 }
119 return retVal;
120 }
121
122 }