File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\util\HeadBufferingStream.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.util;
25
26 import org.apache.commons.io.output.ByteArrayOutputStream;
27
28 import java.io.FilterInputStream;
29 import java.io.InputStream;
30 import java.io.IOException;
31
32 /**
33 * {@link FilterInputStream} that buffers the first N bytes to a byte array on the side.
34 * This byte array can be then accessed later.
35 *
36 * <p>
37 * Useful for sniffing the content of the stream after the error is discovered.
38 *
39 * @author Kohsuke Kawaguchi
40 */
41 public class HeadBufferingStream extends FilterInputStream {
42 private final ByteArrayOutputStream side;
43 private final int sideBufferSize;
44
45 public HeadBufferingStream(InputStream in, int sideBufferSize) {
46 super(in);
47 this.sideBufferSize = sideBufferSize;
48 this.side = new ByteArrayOutputStream(sideBufferSize);
49 }
50
51 @Override
52 public int read() throws IOException {
53 int i = in.read();
54 if(i>=0 && space()>0)
55 side.write(i);
56 return i;
57 }
58
59 @Override
60 public int read(byte b[], int off, int len) throws IOException {
61 int r = in.read(b, off, len);
62 if(r>0) {
63 int sp = space();
64 if(sp>0)
65 side.write(b,off,Math.min(r, sp));
66 }
67 return r;
68 }
69
70 /**
71 * Available space in the {@link #side} buffer.
72 */
73 private int space() {
74 return sideBufferSize-side.size();
75 }
76
77 /**
78 * Read until we fill up the side buffer.
79 */
80 public void fillSide() throws IOException {
81 byte[] buf = new byte[space()];
82 while(space()>0) {
83 if(read(buf)<0)
84 return;
85 }
86 }
87
88 /**
89 * Gets the side buffer content.
90 */
91 public byte[] getSideBuffer() {
92 return side.toByteArray();
93 }
94 }
95