1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * 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
30 extends InputStream
31 {
32 private InheritableThreadLocal m_streams = new InheritableThreadLocal();
33
34 /**
35 * Bind the specified stream to the current thread.
36 *
37 * @param input the stream to bind
38 * @return the InputStream that was previously active
39 */
40 public InputStream bindStream( InputStream input )
41 {
42 InputStream oldValue = getStream();
43 m_streams.set( input );
44 return oldValue;
45 }
46
47 /**
48 * Closes stream associated with current thread.
49 *
50 * @throws IOException if an error occurs
51 */
52 public void close()
53 throws IOException
54 {
55 InputStream input = getStream();
56 if( null != input )
57 {
58 input.close();
59 }
60 }
61
62 /**
63 * Read byte from stream associated with current thread.
64 *
65 * @return the byte read from stream
66 * @throws IOException if an error occurs
67 */
68 public int read()
69 throws IOException
70 {
71 InputStream input = getStream();
72 if( null != input )
73 {
74 return input.read();
75 }
76 else
77 {
78 return -1;
79 }
80 }
81
82 /**
83 * Utility method to retrieve stream bound to current thread (if any).
84 *
85 * @return the input stream
86 */
87 private InputStream getStream()
88 {
89 return (InputStream)m_streams.get();
90 }
91 }