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 */
029public class DemuxInputStream extends InputStream {
030
031    private final InheritableThreadLocal<InputStream> inputStreamLocal = new InheritableThreadLocal<>();
032
033    /**
034     * Construct a new instance.
035     */
036    public DemuxInputStream() {
037        // empty
038    }
039
040    /**
041     * Binds the specified stream to the current thread.
042     *
043     * @param input the stream to bind
044     * @return the InputStream that was previously active
045     */
046    public InputStream bindStream(final InputStream input) {
047        final InputStream oldValue = inputStreamLocal.get();
048        inputStreamLocal.set(input);
049        return oldValue;
050    }
051
052    /**
053     * Closes stream associated with current thread.
054     *
055     * @throws IOException if an error occurs
056     */
057    @SuppressWarnings("resource") // we actually close the stream here
058    @Override
059    public void close() throws IOException {
060        IOUtils.close(inputStreamLocal.get());
061    }
062
063    /**
064     * Reads 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() throws IOException {
071        final InputStream inputStream = inputStreamLocal.get();
072        if (null != inputStream) {
073            return inputStream.read();
074        }
075        return EOF;
076    }
077}