1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.commons.csv;
21
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.stream.Stream;
30
31 import org.apache.commons.io.function.IOConsumer;
32 import org.apache.commons.io.function.IOStream;
33 import org.apache.commons.lang3.ArrayUtils;
34 import org.junit.jupiter.api.Test;
35
36
37
38
39
40
41 class JiraCsv318Test {
42
43 private void checkOutput(final ByteArrayOutputStream baos) {
44 checkOutput(baos.toString());
45 }
46
47 private void checkOutput(final String string) {
48 assertEquals("col a,col b,col c", string.trim());
49 }
50
51 private Stream<String> newParallelStream() {
52
53 return newStream().parallel();
54 }
55
56 private CSVPrinter newPrinter(final ByteArrayOutputStream baos) throws IOException {
57 return new CSVPrinter(new PrintWriter(baos), CSVFormat.DEFAULT);
58 }
59
60 private Stream<String> newSequentialStream() {
61
62 return newStream().sequential();
63 }
64
65 private Stream<String> newStream() {
66 return Stream.of("col a", "col b", "col c");
67 }
68
69 @Test
70 void testDefaultStream() throws IOException {
71 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
72 try (CSVPrinter printer = newPrinter(baos)) {
73 printer.printRecord(newStream());
74 }
75 checkOutput(baos);
76 }
77
78 @SuppressWarnings("resource")
79 @Test
80 void testParallelIOStream() throws IOException {
81 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
82 try (CSVPrinter printer = newPrinter(baos)) {
83 IOStream.adapt(newParallelStream()).forEachOrdered(printer::print);
84 }
85
86 checkOutput(baos);
87 }
88
89 @SuppressWarnings("resource")
90 @Test
91 void testParallelIOStreamSynchronizedPrinterNotUsed() throws IOException {
92 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
93 try (CSVPrinter printer = newPrinter(baos)) {
94 synchronized (printer) {
95 IOStream.adapt(newParallelStream()).forEachOrdered(IOConsumer.noop());
96 }
97 }
98 final List<String> list = new ArrayList<>();
99 try (CSVPrinter printer = newPrinter(baos)) {
100 synchronized (printer) {
101 IOStream.adapt(newParallelStream()).forEachOrdered(list::add);
102 }
103 }
104
105 checkOutput(String.join(",", list.toArray(ArrayUtils.EMPTY_STRING_ARRAY)));
106 }
107
108 @Test
109 void testParallelStream() throws IOException {
110 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
111 try (CSVPrinter printer = newPrinter(baos)) {
112 printer.printRecord(newParallelStream());
113 }
114 checkOutput(baos);
115 }
116
117 @Test
118 void testSequentialStream() throws IOException {
119 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
120 try (CSVPrinter printer = newPrinter(baos)) {
121 printer.printRecord(newSequentialStream());
122 }
123 checkOutput(baos);
124 }
125 }