forked from utPLSQL/utPLSQL-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystemCapturer.java
More file actions
105 lines (80 loc) · 2.54 KB
/
SystemCapturer.java
File metadata and controls
105 lines (80 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package org.utplsql.cli.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
/** All credit to Manasjyoti Sharma: https://stackoverflow.com/a/30665299
*/
public abstract class SystemCapturer {
private ByteArrayOutputStream baos;
private PrintStream previous;
private boolean capturing;
protected abstract PrintStream getOriginalStream();
protected abstract void setSystemStream( PrintStream stream );
public void start() {
if (capturing) {
return;
}
capturing = true;
previous = getOriginalStream();
baos = new ByteArrayOutputStream();
OutputStream outputStreamCombiner =
new OutputStreamCombiner(Arrays.asList(previous, baos));
PrintStream custom = new PrintStream(outputStreamCombiner);
setSystemStream(custom);
}
public String stop() {
if (!capturing) {
return "";
}
setSystemStream(previous);
String capturedValue = baos.toString();
baos = null;
previous = null;
capturing = false;
return capturedValue;
}
private static class OutputStreamCombiner extends OutputStream {
private List<OutputStream> outputStreams;
public OutputStreamCombiner(List<OutputStream> outputStreams) {
this.outputStreams = outputStreams;
}
public void write(int b) throws IOException {
for (OutputStream os : outputStreams) {
os.write(b);
}
}
public void flush() throws IOException {
for (OutputStream os : outputStreams) {
os.flush();
}
}
public void close() throws IOException {
for (OutputStream os : outputStreams) {
os.close();
}
}
}
public static class SystemOutCapturer extends SystemCapturer {
@Override
protected PrintStream getOriginalStream() {
return System.out;
}
@Override
protected void setSystemStream(PrintStream stream) {
System.setOut(stream);
}
}
public static class SystemErrCapturer extends SystemCapturer {
@Override
protected PrintStream getOriginalStream() {
return System.err;
}
@Override
protected void setSystemStream(PrintStream stream) {
System.setErr(stream);
}
}
}