1package tests.support; 2 3import java.io.IOException; 4import java.io.Writer; 5 6/** 7 * An implementation of {@code OutputStream} that should serve as the 8 * underlying stream for classes to be tested. 9 * In particular this implementation allows to have IOExecptions thrown on demand. 10 * For simplicity of use and understanding all fields are public. 11 */ 12public class Support_ASimpleWriter extends Writer { 13 14 public static final int DEFAULT_BUFFER_SIZE = 32; 15 16 public char[] buf; 17 18 public int pos; 19 20 public int size; 21 22 // Set to true when exception is wanted: 23 public boolean throwExceptionOnNextUse = false; 24 25 public Support_ASimpleWriter() { 26 this(DEFAULT_BUFFER_SIZE); 27 } 28 29 public Support_ASimpleWriter(boolean throwException) { 30 this(DEFAULT_BUFFER_SIZE); 31 throwExceptionOnNextUse = throwException; 32 } 33 34 public Support_ASimpleWriter(int bufferSize) { 35 buf = new char[bufferSize]; 36 pos = 0; 37 size = bufferSize; 38 } 39 40 @Override 41 public void close() throws IOException { 42 if (throwExceptionOnNextUse) { 43 throw new IOException("Exception thrown for testing purpose."); 44 } 45 } 46 47 @Override 48 public void flush() throws IOException { 49 if (throwExceptionOnNextUse) { 50 throw new IOException("Exception thrown for testing purpose."); 51 } 52 } 53 54 @Override 55 public void write(char[] src, int offset, int count) throws IOException { 56 if (throwExceptionOnNextUse) { 57 throw new IOException("Exception thrown for testing purpose."); 58 } 59 if (offset < 0 || count < 0 || (offset + count) > buf.length) { 60 throw new IndexOutOfBoundsException(); 61 } 62 try { 63 System.arraycopy(src, offset, buf, pos, count); 64 pos += count; 65 } catch (IndexOutOfBoundsException e) { 66 pos = size; 67 throw new IOException("Internal Buffer Overflow"); 68 } 69 } 70 71 public byte[] toByteArray() { 72 byte[] toReturn = new byte[pos]; 73 System.arraycopy(buf, 0, toReturn, 0, pos); 74 return toReturn; 75 } 76 77 public String toString() { 78 return new String(buf, 0, pos); 79 } 80} 81