1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package com.aragost.javahg.internals;
27
28 import java.io.IOException;
29 import java.io.InputStream;
30
31 import com.aragost.javahg.log.Logger;
32 import com.aragost.javahg.log.LoggerFactory;
33
34
35
36
37 public class BlockInputStream extends InputStream {
38
39 private static final Logger LOG = LoggerFactory.getLogger(BlockInputStream.class);
40
41 public static final BlockInputStream EMPTY = new BlockInputStream();
42
43 private final InputStream stream;
44
45
46
47
48 private final char channel;
49
50
51
52
53 private final int length;
54
55
56
57
58 private int countDown;
59
60 private BlockInputStream() {
61 this.stream = null;
62 this.channel = 'o';
63 this.countDown = this.length = 0;
64 }
65
66
67
68
69
70
71
72
73
74
75 BlockInputStream(InputStream stream) throws IOException {
76 this.stream = stream;
77 this.channel = (char) stream.read();
78 this.length = this.countDown = readInt();
79 if (this.countDown == -1) {
80 throw new InvalidStreamException();
81 }
82 if (Character.isUpperCase(this.channel)) {
83
84
85 this.countDown = 0;
86 }
87 }
88
89 @Override
90 public int read() throws IOException {
91 if (countDown == 0) {
92 return -1;
93 } else {
94 this.countDown--;
95 int read = this.stream.read();
96 LOG.debug("stdout char: {}", (char) read);
97 return read;
98 }
99 }
100
101 @Override
102 public int read(byte[] b, int off, int len) throws IOException {
103 if (this.countDown == 0) {
104 return -1;
105 }
106 if (len > this.countDown) {
107 len = this.countDown;
108 }
109 int result = stream.read(b, off, len);
110 if (result == -1) {
111
112
113
114
115
116 throw new IOException("Unexpected EOF");
117 }
118 this.countDown -= result;
119 if (LOG.isDebugEnabled()) {
120 LOG.debug("read {}: '{}'", "" + this.channel + result, new String(b, off, result));
121 }
122 return result;
123 }
124
125 @Override
126 public int available() throws IOException {
127 if (this.countDown == 0) {
128 return 0;
129 }
130 int underlyingAvailable = this.stream.available();
131 return underlyingAvailable > this.countDown ? this.countDown : underlyingAvailable;
132 }
133
134
135
136
137
138
139 int readInt() throws IOException {
140 return Utils.readBigEndian(this.stream);
141 }
142
143 char getChannel() {
144 return this.channel;
145 }
146
147 int getLength() {
148 return length;
149 }
150
151 int getBytesLeft() {
152 return this.countDown;
153 }
154
155
156
157
158
159 public static class InvalidStreamException extends RuntimeException {
160
161 private static final long serialVersionUID = 1L;
162
163 }
164
165 }