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