001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.io.input; 018 019 import java.io.IOException; 020 import java.io.InputStream; 021 022 /** 023 * Data written to this stream is forwarded to a stream that has been associated 024 * with this thread. 025 * 026 * @author <a href="mailto:peter@apache.org">Peter Donald</a> 027 * @version $Revision: 736890 $ $Date: 2009-01-22 21:02:22 -0500 (Thu, 22 Jan 2009) $ 028 */ 029 public class DemuxInputStream 030 extends InputStream 031 { 032 private final InheritableThreadLocal<InputStream> m_streams = new InheritableThreadLocal<InputStream>(); 033 034 /** 035 * Bind the specified stream to the current thread. 036 * 037 * @param input the stream to bind 038 * @return the InputStream that was previously active 039 */ 040 public InputStream bindStream( InputStream input ) 041 { 042 InputStream oldValue = m_streams.get(); 043 m_streams.set( input ); 044 return oldValue; 045 } 046 047 /** 048 * Closes stream associated with current thread. 049 * 050 * @throws IOException if an error occurs 051 */ 052 @Override 053 public void close() 054 throws IOException 055 { 056 InputStream input = m_streams.get(); 057 if( null != input ) 058 { 059 input.close(); 060 } 061 } 062 063 /** 064 * Read byte from stream associated with current thread. 065 * 066 * @return the byte read from stream 067 * @throws IOException if an error occurs 068 */ 069 @Override 070 public int read() 071 throws IOException 072 { 073 InputStream input = m_streams.get(); 074 if( null != input ) 075 { 076 return input.read(); 077 } 078 else 079 { 080 return -1; 081 } 082 } 083 }