    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    private final InheritableThreadLocal<InputStream> inputStream = new InheritableThreadLocal<>();
    031
    032    /**
    033     * Binds the specified stream to the current thread.
    034     *
    035     * @param input the stream to bind
    036     * @return the InputStream that was previously active
    037     */
    038    public InputStream bindStream(final InputStream input) {
    039        final InputStream oldValue = inputStream.get();
    040        inputStream.set(input);
    041        return oldValue;
    042    }
    043
    044    /**
    045     * Closes stream associated with current thread.
    046     *
    047     * @throws IOException if an error occurs
    048     */
    049    @Override
    050    public void close() throws IOException {
    051        IOUtils.close(inputStream.get());
    052    }
    053
    054    /**
    055     * Reads byte from stream associated with current thread.
    056     *
    057     * @return the byte read from stream
    058     * @throws IOException if an error occurs
    059     */
    060    @Override
    061    public int read() throws IOException {
    062        final InputStream input = inputStream.get();
    063        if (null != input) {
    064            return input.read();
    065        }
    066        return EOF;
    067    }
    068}