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 import java.io.FilterOutputStream; 26 import java.io.IOException; 27 import java.io.OutputStream; 28 import java.util.Arrays; 29 30 /** @author Colin Decker */ 31 public class TestOutputStream extends FilterOutputStream { 32 33 private final ImmutableSet<TestOption> options; 34 private boolean closed; 35 TestOutputStream(OutputStream out, TestOption... options)36 public TestOutputStream(OutputStream out, TestOption... options) throws IOException { 37 this(out, Arrays.asList(options)); 38 } 39 TestOutputStream(OutputStream out, Iterable<TestOption> options)40 public TestOutputStream(OutputStream out, Iterable<TestOption> options) throws IOException { 41 super(checkNotNull(out)); 42 this.options = ImmutableSet.copyOf(options); 43 throwIf(OPEN_THROWS); 44 } 45 closed()46 public boolean closed() { 47 return closed; 48 } 49 50 @Override write(byte[] b, int off, int len)51 public void write(byte[] b, int off, int len) throws IOException { 52 throwIf(closed); 53 throwIf(WRITE_THROWS); 54 super.write(b, off, len); 55 } 56 57 @Override write(int b)58 public void write(int b) throws IOException { 59 throwIf(closed); 60 throwIf(WRITE_THROWS); 61 super.write(b); 62 } 63 64 @Override close()65 public void close() throws IOException { 66 closed = true; 67 super.close(); 68 throwIf(CLOSE_THROWS); 69 } 70 throwIf(TestOption option)71 private void throwIf(TestOption option) throws IOException { 72 throwIf(options.contains(option)); 73 } 74 throwIf(boolean condition)75 private static void throwIf(boolean condition) throws IOException { 76 if (condition) { 77 throw new IOException(); 78 } 79 } 80 } 81