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