01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://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.output;
18:
19: import java.io.IOException;
20: import java.io.OutputStream;
21:
22: /**
23: * Data written to this stream is forwarded to a stream that has been associated
24: * with this thread.
25: *
26: * @author <a href="mailto:peter@apache.org">Peter Donald</a>
27: * @version $Revision: 437567 $ $Date: 2006-08-28 08:39:07 +0200 (Mo, 28 Aug 2006) $
28: */
29: public class DemuxOutputStream extends OutputStream {
30: private InheritableThreadLocal m_streams = new InheritableThreadLocal();
31:
32: /**
33: * Bind the specified stream to the current thread.
34: *
35: * @param output the stream to bind
36: * @return the OutputStream that was previously active
37: */
38: public OutputStream bindStream(OutputStream output) {
39: OutputStream stream = getStream();
40: m_streams.set(output);
41: return stream;
42: }
43:
44: /**
45: * Closes stream associated with current thread.
46: *
47: * @throws IOException if an error occurs
48: */
49: public void close() throws IOException {
50: OutputStream output = getStream();
51: if (null != output) {
52: output.close();
53: }
54: }
55:
56: /**
57: * Flushes stream associated with current thread.
58: *
59: * @throws IOException if an error occurs
60: */
61: public void flush() throws IOException {
62: OutputStream output = getStream();
63: if (null != output) {
64: output.flush();
65: }
66: }
67:
68: /**
69: * Writes byte to stream associated with current thread.
70: *
71: * @param ch the byte to write to stream
72: * @throws IOException if an error occurs
73: */
74: public void write(int ch) throws IOException {
75: OutputStream output = getStream();
76: if (null != output) {
77: output.write(ch);
78: }
79: }
80:
81: /**
82: * Utility method to retrieve stream bound to current thread (if any).
83: *
84: * @return the output stream
85: */
86: private OutputStream getStream() {
87: return (OutputStream) m_streams.get();
88: }
89: }
|