| 1 | /* |
| 2 | * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | * contributor license agreements. See the NOTICE file distributed with |
| 4 | * this work for additional information regarding copyright ownership. |
| 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | * (the "License"); you may not use this file except in compliance with |
| 7 | * the License. You may obtain a copy of the License at |
| 8 | * |
| 9 | * https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | package org.apache.commons.io.input; |
| 18 | |
| 19 | import static org.apache.commons.io.IOUtils.EOF; |
| 20 | |
| 21 | import java.io.IOException; |
| 22 | import java.io.InputStream; |
| 23 | |
| 24 | import org.apache.commons.io.IOUtils; |
| 25 | |
| 26 | /** |
| 27 | * Data written to this stream is forwarded to a stream that has been associated with this thread. |
| 28 | */ |
| 29 | public class DemuxInputStream extends InputStream { |
| 30 | |
| 31 | private final InheritableThreadLocal<InputStream> inputStreamLocal = new InheritableThreadLocal<>(); |
| 32 | |
| 33 | /** |
| 34 | * Construct a new instance. |
| 35 | */ |
| 36 | public DemuxInputStream() { |
| 37 | // empty |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Binds the specified stream to the current thread. |
| 42 | * |
| 43 | * @param input the stream to bind |
| 44 | * @return the InputStream that was previously active |
| 45 | */ |
| 46 | public InputStream bindStream(final InputStream input) { |
| 47 | final InputStream oldValue = inputStreamLocal.get(); |
| 48 | inputStreamLocal.set(input); |
| 49 | return oldValue; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Closes stream associated with current thread. |
| 54 | * |
| 55 | * @throws IOException if an error occurs |
| 56 | */ |
| 57 | @SuppressWarnings("resource") // we actually close the stream here |
| 58 | @Override |
| 59 | public void close() throws IOException { |
| 60 | IOUtils.close(inputStreamLocal.get()); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Reads byte from stream associated with current thread. |
| 65 | * |
| 66 | * @return the byte read from stream |
| 67 | * @throws IOException if an error occurs |
| 68 | */ |
| 69 | @Override |
| 70 | public int read() throws IOException { |
| 71 | final InputStream inputStream = inputStreamLocal.get(); |
| 72 | if (null != inputStream) { |
| 73 | return inputStream.read(); |
| 74 | } |
| 75 | return EOF; |
| 76 | } |
| 77 | } |