1 package org.apache.maven.surefire.report;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.io.PrintStream;
25
26 import static java.lang.System.setErr;
27 import static java.lang.System.setOut;
28 import static org.apache.maven.surefire.util.internal.StringUtils.NL;
29
30
31
32
33
34 public final class ConsoleOutputCapture
35 {
36 public static void startCapture( ConsoleOutputReceiver target )
37 {
38 setOut( new ForwardingPrintStream( true, target ) );
39 setErr( new ForwardingPrintStream( false, target ) );
40 }
41
42 private static final class ForwardingPrintStream
43 extends PrintStream
44 {
45 private final boolean isStdout;
46 private final ConsoleOutputReceiver target;
47
48 ForwardingPrintStream( boolean stdout, ConsoleOutputReceiver target )
49 {
50 super( new NullOutputStream() );
51 isStdout = stdout;
52 this.target = target;
53 }
54
55 @Override
56 public void write( byte[] buf, int off, int len )
57 {
58
59
60 target.writeTestOutput( buf, off, len, isStdout );
61 }
62
63 @Override
64 public void write( byte[] b )
65 throws IOException
66 {
67 target.writeTestOutput( b, 0, b.length, isStdout );
68 }
69
70 @Override
71 public void write( int b )
72 {
73 try
74 {
75 write( new byte[] { (byte) b } );
76 }
77 catch ( IOException e )
78 {
79 setError();
80 }
81 }
82
83 @Override
84 public void println( String s )
85 {
86 if ( s == null )
87 {
88 s = "null";
89 }
90 final byte[] bytes = ( s + NL ).getBytes();
91 target.writeTestOutput( bytes, 0, bytes.length, isStdout );
92 }
93
94 @Override
95 public void close()
96 {
97 }
98
99 @Override
100 public void flush()
101 {
102 }
103 }
104
105 private static final class NullOutputStream
106 extends OutputStream
107 {
108 @Override
109 public void write( int b ) throws IOException
110 {
111
112 }
113 }
114 }