1 package org.apache.maven.plugins.pmd;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.io.PrintStream;
23
24 import org.slf4j.impl.MavenSlf4jSimpleFriend;
25
26 /**
27 * Captures log output from simple slf4j for asserting in unit tests.
28 */
29 class CapturingPrintStream extends PrintStream {
30 private boolean quiet;
31 private StringBuilder buffer = new StringBuilder();
32
33 private CapturingPrintStream( boolean quiet ) {
34 super( System.out, true );
35 this.quiet = quiet;
36 }
37
38 @Override
39 public void println( String x )
40 {
41 if ( !quiet )
42 {
43 super.println( x );
44 }
45 buffer.append( x ).append( System.lineSeparator() );
46 }
47
48 public static void init( boolean quiet )
49 {
50 CapturingPrintStream capture = get();
51 if ( capture != null )
52 {
53 capture.buffer.setLength( 0 );
54 capture.quiet = quiet;
55 }
56 else
57 {
58 capture = new CapturingPrintStream( quiet );
59 System.setOut( capture );
60 MavenSlf4jSimpleFriend.init();
61 }
62 }
63
64 public static CapturingPrintStream get()
65 {
66 if ( System.out instanceof CapturingPrintStream )
67 {
68 return (CapturingPrintStream) System.out;
69 }
70 return null;
71 }
72
73 public static String getOutput()
74 {
75 CapturingPrintStream stream = get();
76 if ( stream != null )
77 {
78 stream.flush();
79 return stream.buffer.toString();
80 }
81 return "";
82 }
83 }