Initial import
[jpf-core.git] / src / main / gov / nasa / jpf / util / SplitOutputStream.java
1 /*
2  * Copyright (C) 2014, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The Java Pathfinder core (jpf-core) platform is licensed under the
7  * Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  * 
10  *        http://www.apache.org/licenses/LICENSE-2.0. 
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and 
16  * limitations under the License.
17  */
18 package gov.nasa.jpf.util;
19
20 import java.io.IOException;
21 import java.io.OutputStream;
22 import java.util.Arrays;
23
24 public class SplitOutputStream extends OutputStream {
25
26   private final OutputStream m_sinks[];
27
28   public SplitOutputStream(OutputStream... sinks) {
29     int i;
30
31     if (sinks.length <= 0) {
32       throw new IllegalArgumentException("sinks.length <= 0 : " + sinks.length);
33     }
34
35     for (i = sinks.length; --i >= 0;) {
36       if (sinks[i] == null) {
37         throw new NullPointerException("sinks[i] == null : " + i);
38       }
39     }
40
41     m_sinks = Arrays.copyOf(sinks, sinks.length);
42   }
43
44   @Override
45   public void write(int data) throws IOException {
46     int i;
47
48     for (i = m_sinks.length; --i >= 0;) {
49       m_sinks[i].write(data);
50     }
51   }
52
53   @Override
54   public void write(byte buffer[], int offset, int length) throws IOException {
55     int i;
56
57     if (buffer == null) {
58       throw new NullPointerException("buffer == null");
59     }
60
61     if (offset < 0) {
62       throw new IndexOutOfBoundsException("offset < 0 : " + offset);
63     }
64
65     if (length < 0) {
66       throw new IndexOutOfBoundsException("length < 0 : " + length);
67     }
68
69     if (offset + length > buffer.length) {
70       throw new IndexOutOfBoundsException("offset + length > buffer.length : " + offset + " + " + length + " > " + buffer.length);
71     }
72
73     if (length == 0) {
74       return;
75     }
76
77     for (i = m_sinks.length; --i >= 0;) {
78       m_sinks[i].write(buffer, offset, length);
79     }
80   }
81
82   @Override
83   public void flush() throws IOException {
84     int i;
85
86     for (i = m_sinks.length; --i >= 0;) {
87       m_sinks[i].flush();
88     }
89   }
90
91   @Override
92   public void close() throws IOException {
93     int i;
94
95     for (i = m_sinks.length; --i >= 0;) {
96       m_sinks[i].close();
97     }
98   }
99 }