Switch from javax.mail to net.jaekl.qd.SendMail.
[cfb.git] / test / net / jaekl / qd / util / InputStreamMock.java
1 package net.jaekl.qd.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.nio.charset.Charset;
7 import java.util.ArrayList;
8
9 public class InputStreamMock extends InputStream {
10         private ByteArrayInputStream m_bais;
11         
12         public InputStreamMock() { 
13                 m_bais = new ByteArrayInputStream(new byte[0]);
14         }
15         
16         @Override
17         public int read() throws IOException {
18                 return m_bais.read();
19         }
20
21         public void mock_append(byte[] addition) {
22                 byte[] old = readAll();
23                 byte[] combined = new byte[old.length + addition.length];
24                 for (int idx = 0; idx < old.length; ++idx) {
25                         combined[idx] = old[idx];
26                 }
27                 for (int idx = 0; idx < addition.length; ++idx) {
28                         combined[old.length + idx] = addition[idx];
29                 }
30                 
31                 mock_reset(combined);
32         }
33         
34         public void mock_append(String addition, Charset charset) 
35         {
36                 mock_append(addition.getBytes(charset));
37         }
38         
39         public void mock_reset(byte[] newData) {
40                 m_bais = new ByteArrayInputStream(newData);
41         }
42         
43         // Read all remaining bytes in the inputstream
44         private byte[] readAll() {
45                 // This is horribly inefficient; don't use in production code
46                 ArrayList<Byte> data = new ArrayList<Byte>();
47                 int b = m_bais.read();
48                 while ((-1) != b) {
49                         data.add(Byte.valueOf((byte)b));
50                 }
51                 byte[] result = new byte[data.size()];
52                 for (int idx = 0; idx < result.length; ++idx) {
53                         result[idx] = data.get(idx).byteValue();
54                 }
55                 
56                 return result;
57         }
58 }