• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Guava Authors
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 package com.google.common.io;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 import static com.google.common.io.TestOption.CLOSE_THROWS;
21 import static com.google.common.io.TestOption.OPEN_THROWS;
22 import static com.google.common.io.TestOption.WRITE_THROWS;
23 
24 import com.google.common.collect.ImmutableSet;
25 
26 import java.io.FilterOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.util.Arrays;
30 
31 /**
32  * @author Colin Decker
33  */
34 public class TestOutputStream extends FilterOutputStream {
35 
36   private final ImmutableSet<TestOption> options;
37   private boolean closed;
38 
TestOutputStream(OutputStream out, TestOption... options)39   public TestOutputStream(OutputStream out, TestOption... options) throws IOException {
40     this(out, Arrays.asList(options));
41   }
42 
TestOutputStream(OutputStream out, Iterable<TestOption> options)43   public TestOutputStream(OutputStream out, Iterable<TestOption> options) throws IOException {
44     super(checkNotNull(out));
45     this.options = ImmutableSet.copyOf(options);
46     throwIf(OPEN_THROWS);
47   }
48 
closed()49   public boolean closed() {
50     return closed;
51   }
52 
53   @Override
write(byte[] b, int off, int len)54   public void write(byte[] b, int off, int len) throws IOException {
55     throwIf(closed);
56     throwIf(WRITE_THROWS);
57     super.write(b, off, len);
58   }
59 
60   @Override
write(int b)61   public void write(int b) throws IOException {
62     throwIf(closed);
63     throwIf(WRITE_THROWS);
64     super.write(b);
65   }
66 
67   @Override
close()68   public void close() throws IOException {
69     closed = true;
70     super.close();
71     throwIf(CLOSE_THROWS);
72   }
73 
throwIf(TestOption option)74   private void throwIf(TestOption option) throws IOException {
75     throwIf(options.contains(option));
76   }
77 
throwIf(boolean condition)78   private static void throwIf(boolean condition) throws IOException {
79     if (condition) {
80       throw new IOException();
81     }
82   }
83 }
84