View Javadoc
1   /*
2    * Copyright (C) 2010, 2013 Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util.io;
12  
13  import java.io.IOException;
14  import java.io.InputStream;
15  import java.io.OutputStream;
16  
17  /**
18   * Input stream that copies data read to another output stream.
19   *
20   * This stream is primarily useful with a
21   * {@link org.eclipse.jgit.util.TemporaryBuffer}, where any data read or skipped
22   * by the caller is also duplicated into the temporary buffer. Later the
23   * temporary buffer can then be used instead of the original source stream.
24   *
25   * During close this stream copies any remaining data from the source stream
26   * into the destination stream.
27   */
28  public class TeeInputStream extends InputStream {
29  	private byte[] skipBuffer;
30  
31  	private InputStream src;
32  
33  	private OutputStream dst;
34  
35  	/**
36  	 * Initialize a tee input stream.
37  	 *
38  	 * @param src
39  	 *            source stream to consume.
40  	 * @param dst
41  	 *            destination to copy the source to as it is consumed. Typically
42  	 *            this is a {@link org.eclipse.jgit.util.TemporaryBuffer}.
43  	 */
44  	public TeeInputStream(InputStream src, OutputStream dst) {
45  		this.src = src;
46  		this.dst = dst;
47  	}
48  
49  	/** {@inheritDoc} */
50  	@Override
51  	public int read() throws IOException {
52  		byte[] b = skipBuffer();
53  		int n = read(b, 0, 1);
54  		return n == 1 ? b[0] & 0xff : -1;
55  	}
56  
57  	/** {@inheritDoc} */
58  	@Override
59  	public long skip(long count) throws IOException {
60  		long skipped = 0;
61  		long cnt = count;
62  		final byte[] b = skipBuffer();
63  		while (0 < cnt) {
64  			final int n = src.read(b, 0, (int) Math.min(b.length, cnt));
65  			if (n <= 0)
66  				break;
67  			dst.write(b, 0, n);
68  			skipped += n;
69  			cnt -= n;
70  		}
71  		return skipped;
72  	}
73  
74  	/** {@inheritDoc} */
75  	@Override
76  	public int read(byte[] b, int off, int len) throws IOException {
77  		if (len == 0)
78  			return 0;
79  
80  		int n = src.read(b, off, len);
81  		if (0 < n)
82  			dst.write(b, off, n);
83  		return n;
84  	}
85  
86  	/** {@inheritDoc} */
87  	@Override
88  	public void close() throws IOException {
89  		byte[] b = skipBuffer();
90  		for (;;) {
91  			int n = src.read(b);
92  			if (n <= 0)
93  				break;
94  			dst.write(b, 0, n);
95  		}
96  		dst.close();
97  		src.close();
98  	}
99  
100 	private byte[] skipBuffer() {
101 		if (skipBuffer == null)
102 			skipBuffer = new byte[2048];
103 		return skipBuffer;
104 	}
105 }