1 /*
2 * Copyright 2007, 2008 Ange Optimization ApS
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 /**
17 * @author Kim Hansen
18 */
19 package eu.simuline.octave.util;
20
21 import java.io.IOException;
22 import java.io.Writer;
23
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.commons.logging.Log;
26
27 /**
28 * Executes the actions on a single writer to multiple writers.
29 *
30 * If the list of writers in the constructor is empty
31 * everything that is written will be discarted.
32 *
33 * If there is thrown one or more exception all writers will still be accessed,
34 * the exceptions will be logged and the last exception thrown
35 * will be passed on outside.
36 */
37 public final class TeeWriter extends Writer {
38
39 private static final Log LOG = LogFactory.getLog(TeeWriter.class);
40
41 private final Writer[] writers;
42
43 /**
44 * Create a writer that doesn't do anything.
45 */
46 public TeeWriter() {
47 // this.writers = new Writer[0];
48 this(new Writer[0]);
49 }
50
51 /**
52 * Create a single writer that writes to multiple writers.
53 *
54 * @param writers
55 * the list of writers that should be written to.
56 */
57 public TeeWriter(final Writer... writers) {
58 this.writers = writers;
59 }
60
61 @Override
62 public void write(final char[] cbuf, final int off, final int len)
63 throws IOException {
64
65 IOException ioe = null;
66 for (final Writer writer : writers) {
67 try {
68 writer.write(cbuf, off, len);
69 } catch (final IOException e) {
70 LOG.debug("Exception during write()", e);
71 ioe = e;
72 }
73 }
74 if (ioe != null) {
75 throw ioe;
76 }
77 }
78
79 @Override
80 public void flush() throws IOException {
81 IOException ioe = null;
82 for (final Writer writer : writers) {
83 try {
84 writer.flush();
85 } catch (final IOException e) {
86 LOG.debug("Exception during flush()", e);
87 ioe = e;
88 }
89 }
90 if (ioe != null) {
91 throw ioe;
92 }
93 }
94
95 @Override
96 public void close() throws IOException {
97 IOException ioe = null;
98 for (final Writer writer : writers) {
99 try {
100 writer.close();
101 } catch (final IOException e) {
102 LOG.debug("Exception during close()", e);
103 ioe = e;
104 }
105 }
106 if (ioe != null) {
107 throw ioe;
108 }
109 }
110
111 }