1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.net.io;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24
25 import org.junit.Assert;
26 import org.junit.Test;
27
28 public class ToNetASCIIInputStreamTest {
29
30 private static final String ASCII =
31
32 @Test
33 public void testToNetASCIIInputStream1() throws Exception
34 {
35 byteTest(false, "", "");
36 byteTest(false, "\r", "\r");
37 byteTest(false, "a", "a");
38 byteTest(false, "a\nb", "a\r\nb");
39 byteTest(false, "a\r\nb", "a\r\nb");
40 byteTest(false, "\n", "\r\n");
41 byteTest(false, "Hello\nWorld\n", "Hello\r\nWorld\r\n");
42 byteTest(false, "Hello\nWorld\r\n", "Hello\r\nWorld\r\n");
43 byteTest(false, "Hello\nWorld\n\r", "Hello\r\nWorld\r\n\r");
44 }
45
46 @Test
47 public void testToNetASCIIInputStream_single_bytes() throws Exception
48 {
49 byteTest(true, "", "");
50 byteTest(true, "\r", "\r");
51 byteTest(true, "\n", "\r\n");
52 byteTest(true, "a", "a");
53 byteTest(true, "a\nb", "a\r\nb");
54 byteTest(true, "a\r\nb", "a\r\nb");
55 byteTest(true, "Hello\nWorld\n", "Hello\r\nWorld\r\n");
56 byteTest(true, "Hello\nWorld\r\n", "Hello\r\nWorld\r\n");
57 byteTest(true, "Hello\nWorld\n\r", "Hello\r\nWorld\r\n\r");
58 }
59
60 private void byteTest(boolean byByte, String input, String expect) throws IOException {
61 byte[] data = input.getBytes(ASCII);
62 byte[] expected = expect.getBytes(ASCII);
63 InputStream source = new ByteArrayInputStream(data);
64 ToNetASCIIInputStream toNetASCII = new ToNetASCIIInputStream(source);
65 byte[] output = new byte[data.length*2];
66
67 int length = byByte ?
68 getSingleBytes(toNetASCII, output) :
69 getBuffer(toNetASCII, output);
70
71 byte[] result = new byte[length];
72 System.arraycopy(output, 0, result, 0, length);
73 Assert.assertArrayEquals("Failed converting "+input,expected, result);
74 toNetASCII.close();
75 }
76
77 private int getSingleBytes(ToNetASCIIInputStream toNetASCII, byte[] output)
78 throws IOException {
79 int b;
80 int length=0;
81 while((b=toNetASCII.read()) != -1) {
82 output[length++]=(byte)b;
83 }
84 return length;
85 }
86
87 private int getBuffer(ToNetASCIIInputStream toNetASCII, byte[] output)
88 throws IOException {
89 int length=0;
90 int remain=output.length;
91 int chunk;
92 int offset=0;
93 while(remain > 0 && (chunk=toNetASCII.read(output,offset,remain)) != -1){
94 length+=chunk;
95 offset+=chunk;
96 remain-=chunk;
97 }
98 return length;
99 }
100
101 }