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