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
024import org.apache.commons.io.IOUtils;
025
026/**
027 * Data written to this stream is forwarded to a stream that has been associated with this thread.
028 *
029 */
030public class DemuxInputStream extends InputStream {
031    private final InheritableThreadLocal<InputStream> inputStream = new InheritableThreadLocal<>();
032
033    /**
034     * Bind the specified stream to the current thread.
035     *
036     * @param input the stream to bind
037     * @return the InputStream that was previously active
038     */
039    public InputStream bindStream(final InputStream input) {
040        final InputStream oldValue = inputStream.get();
041        inputStream.set(input);
042        return oldValue;
043    }
044
045    /**
046     * Closes stream associated with current thread.
047     *
048     * @throws IOException if an error occurs
049     */
050    @Override
051    public void close() throws IOException {
052        IOUtils.close(inputStream.get());
053    }
054
055    /**
056     * Read byte from stream associated with current thread.
057     *
058     * @return the byte read from stream
059     * @throws IOException if an error occurs
060     */
061    @Override
062    public int read() throws IOException {
063        final InputStream input = inputStream.get();
064        if (null != input) {
065            return input.read();
066        }
067        return EOF;
068    }
069}