01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.commons.io.input;
18:
19: import java.io.IOException;
20: import java.io.InputStream;
21:
22: /**
23: * Data written to this stream is forwarded to a stream that has been associated
24: * with this thread.
25: *
26: * @author <a href="mailto:peter@apache.org">Peter Donald</a>
27: * @version $Revision: 437567 $ $Date: 2006-08-28 08:39:07 +0200 (Mo, 28 Aug 2006) $
28: */
29: public class DemuxInputStream extends InputStream {
30: private InheritableThreadLocal m_streams = new InheritableThreadLocal();
31:
32: /**
33: * Bind the specified stream to the current thread.
34: *
35: * @param input the stream to bind
36: * @return the InputStream that was previously active
37: */
38: public InputStream bindStream(InputStream input) {
39: InputStream oldValue = getStream();
40: m_streams.set(input);
41: return oldValue;
42: }
43:
44: /**
45: * Closes stream associated with current thread.
46: *
47: * @throws IOException if an error occurs
48: */
49: public void close() throws IOException {
50: InputStream input = getStream();
51: if (null != input) {
52: input.close();
53: }
54: }
55:
56: /**
57: * Read byte from stream associated with current thread.
58: *
59: * @return the byte read from stream
60: * @throws IOException if an error occurs
61: */
62: public int read() throws IOException {
63: InputStream input = getStream();
64: if (null != input) {
65: return input.read();
66: } else {
67: return -1;
68: }
69: }
70:
71: /**
72: * Utility method to retrieve stream bound to current thread (if any).
73: *
74: * @return the input stream
75: */
76: private InputStream getStream() {
77: return (InputStream) m_streams.get();
78: }
79: }
|