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.Charsets.UTF_8; 20 21import java.io.FilterWriter; 22import java.io.IOException; 23import java.io.OutputStreamWriter; 24import java.io.UnsupportedEncodingException; 25import java.io.Writer; 26 27/** 28 * A char sink for testing that has configurable behavior. 29 * 30 * @author Colin Decker 31 */ 32public class TestCharSink extends CharSink implements TestStreamSupplier { 33 34 private final TestByteSink byteSink; 35 36 public TestCharSink(TestOption... options) { 37 this.byteSink = new TestByteSink(options); 38 } 39 40 public String getString() { 41 try { 42 return new String(byteSink.getBytes(), UTF_8.name()); 43 } catch (UnsupportedEncodingException e) { 44 throw new AssertionError(); 45 } 46 } 47 48 @Override 49 public boolean wasStreamOpened() { 50 return byteSink.wasStreamOpened(); 51 } 52 53 @Override 54 public boolean wasStreamClosed() { 55 return byteSink.wasStreamClosed(); 56 } 57 58 @Override 59 public Writer openStream() throws IOException { 60 // using TestByteSink's output stream to get option behavior, so flush to it on every write 61 return new FilterWriter(new OutputStreamWriter(byteSink.openStream(), UTF_8)) { 62 @Override 63 public void write(int c) throws IOException { 64 super.write(c); 65 flush(); 66 } 67 68 @Override 69 public void write(char[] cbuf, int off, int len) throws IOException { 70 super.write(cbuf, off, len); 71 flush(); 72 } 73 74 @Override 75 public void write(String str, int off, int len) throws IOException { 76 super.write(str, off, len); 77 flush(); 78 } 79 }; 80 } 81} 82