    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> inputStreamLocal = 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 = inputStreamLocal.get();
    040        inputStreamLocal.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    @SuppressWarnings("resource") // we actually close the stream here
    050    @Override
    051    public void close() throws IOException {
    052        IOUtils.close(inputStreamLocal.get());
    053    }
    054
    055    /**
    056     * Reads byte from stream associated with current thread.
    057     *
    058     * @return the byte read from stream
    059     * @throws IOException if an error occurs
    060     */
    061    @SuppressWarnings("resource")
    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}