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 07:39:07 +0100 (Mon, 28 Aug 2006) $ 28 */ 29 public class DemuxInputStream 30 extends InputStream 31 { 32 private InheritableThreadLocal<InputStream> m_streams = new InheritableThreadLocal<InputStream>(); 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 */ bindStream( InputStream input )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 @Override close()53 public void close() 54 throws IOException 55 { 56 InputStream input = getStream(); 57 if( null != input ) 58 { 59 input.close(); 60 } 61 } 62 63 /** 64 * Read byte from stream associated with current thread. 65 * 66 * @return the byte read from stream 67 * @throws IOException if an error occurs 68 */ 69 @Override read()70 public int read() 71 throws IOException 72 { 73 InputStream input = getStream(); 74 if( null != input ) 75 { 76 return input.read(); 77 } 78 else 79 { 80 return -1; 81 } 82 } 83 84 /** 85 * Utility method to retrieve stream bound to current thread (if any). 86 * 87 * @return the input stream 88 */ getStream()89 private InputStream getStream() 90 { 91 return m_streams.get(); 92 } 93 } 94