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.READ_THROWS; 23 import static com.google.common.io.TestOption.SKIP_THROWS; 24 25 import com.google.common.collect.ImmutableSet; 26 27 import java.io.FilterInputStream; 28 import java.io.IOException; 29 import java.io.InputStream; 30 import java.util.Arrays; 31 32 /** 33 * @author Colin Decker 34 */ 35 public class TestInputStream extends FilterInputStream { 36 37 private final ImmutableSet<TestOption> options; 38 private boolean closed; 39 TestInputStream(InputStream in, TestOption... options)40 public TestInputStream(InputStream in, TestOption... options) throws IOException { 41 this(in, Arrays.asList(options)); 42 } 43 TestInputStream(InputStream in, Iterable<TestOption> options)44 public TestInputStream(InputStream in, Iterable<TestOption> options) throws IOException { 45 super(checkNotNull(in)); 46 this.options = ImmutableSet.copyOf(options); 47 throwIf(OPEN_THROWS); 48 } 49 closed()50 public boolean closed() { 51 return closed; 52 } 53 54 @Override read()55 public int read() throws IOException { 56 throwIf(closed); 57 throwIf(READ_THROWS); 58 return in.read(); 59 } 60 61 @Override read(byte[] b, int off, int len)62 public int read(byte[] b, int off, int len) throws IOException { 63 throwIf(closed); 64 throwIf(READ_THROWS); 65 return in.read(b, off, len); 66 } 67 68 @Override skip(long n)69 public long skip(long n) throws IOException { 70 throwIf(closed); 71 throwIf(SKIP_THROWS); 72 return in.skip(n); 73 } 74 75 @Override available()76 public int available() throws IOException { 77 throwIf(closed); 78 return options.contains(TestOption.AVAILABLE_ALWAYS_ZERO) ? 0 : in.available(); 79 } 80 81 @Override close()82 public void close() throws IOException { 83 closed = true; 84 throwIf(CLOSE_THROWS); 85 in.close(); 86 } 87 throwIf(TestOption option)88 private void throwIf(TestOption option) throws IOException { 89 throwIf(options.contains(option)); 90 } 91 throwIf(boolean condition)92 private static void throwIf(boolean condition) throws IOException { 93 if (condition) { 94 throw new IOException(); 95 } 96 } 97 } 98