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 21 import com.google.common.collect.ImmutableSet; 22 import java.io.ByteArrayInputStream; 23 import java.io.IOException; 24 import java.io.InputStream; 25 import java.util.Random; 26 27 /** 28 * A byte source for testing that has configurable behavior. 29 * 30 * @author Colin Decker 31 */ 32 public final class TestByteSource extends ByteSource implements TestStreamSupplier { 33 34 private final byte[] bytes; 35 private final ImmutableSet<TestOption> options; 36 37 private boolean inputStreamOpened; 38 private boolean inputStreamClosed; 39 TestByteSource(byte[] bytes, TestOption... options)40 TestByteSource(byte[] bytes, TestOption... options) { 41 this.bytes = checkNotNull(bytes); 42 this.options = ImmutableSet.copyOf(options); 43 } 44 45 @Override wasStreamOpened()46 public boolean wasStreamOpened() { 47 return inputStreamOpened; 48 } 49 50 @Override wasStreamClosed()51 public boolean wasStreamClosed() { 52 return inputStreamClosed; 53 } 54 55 @Override openStream()56 public InputStream openStream() throws IOException { 57 inputStreamOpened = true; 58 return new RandomAmountInputStream(new In(), new Random()); 59 } 60 61 private final class In extends TestInputStream { 62 In()63 public In() throws IOException { 64 super(new ByteArrayInputStream(bytes), options); 65 } 66 67 @Override close()68 public void close() throws IOException { 69 inputStreamClosed = true; 70 super.close(); 71 } 72 } 73 } 74