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     * Binds 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 = inputStreamLocal.get();
041        inputStreamLocal.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    @SuppressWarnings("resource") // we actually close the stream here
051    @Override
052    public void close() throws IOException {
053        IOUtils.close(inputStreamLocal.get());
054    }
055
056    /**
057     * Reads byte from stream associated with current thread.
058     *
059     * @return the byte read from stream
060     * @throws IOException if an error occurs
061     */
062    @Override
063    public int read() throws IOException {
064        final InputStream inputStream = inputStreamLocal.get();
065        if (null != inputStream) {
066            return inputStream.read();
067        }
068        return EOF;
069    }
070}