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 */
017package org.apache.commons.io.input;
018
019import static org.apache.commons.io.IOUtils.EOF;
020
021import java.io.IOException;
022import java.io.InputStream;
023
024/**
025 * Data written to this stream is forwarded to a stream that has been associated
026 * with this thread.
027 *
028 * @version $Id: DemuxInputStream.java 1586350 2014-04-10 15:57:20Z ggregory $
029 */
030public class DemuxInputStream
031    extends InputStream
032{
033    private final InheritableThreadLocal<InputStream> m_streams = new InheritableThreadLocal<InputStream>();
034
035    /**
036     * Bind the specified stream to the current thread.
037     *
038     * @param input the stream to bind
039     * @return the InputStream that was previously active
040     */
041    public InputStream bindStream( final InputStream input )
042    {
043        final InputStream oldValue = m_streams.get();
044        m_streams.set( input );
045        return oldValue;
046    }
047
048    /**
049     * Closes stream associated with current thread.
050     *
051     * @throws IOException if an error occurs
052     */
053    @Override
054    public void close()
055        throws IOException
056    {
057        final InputStream input = m_streams.get();
058        if( null != input )
059        {
060            input.close();
061        }
062    }
063
064    /**
065     * Read byte from stream associated with current thread.
066     *
067     * @return the byte read from stream
068     * @throws IOException if an error occurs
069     */
070    @Override
071    public int read()
072        throws IOException
073    {
074        final InputStream input = m_streams.get();
075        if( null != input )
076        {
077            return input.read();
078        }
079        else
080        {
081            return EOF;
082        }
083    }
084}