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 final 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 }
55 else
56 {
57 capture = new CapturingPrintStream( quiet );
58 System.setOut( capture );
59 MavenSlf4jSimpleFriend.init();
60 }
61 }
62
63 public static CapturingPrintStream get()
64 {
65 if ( System.out instanceof CapturingPrintStream )
66 {
67 return (CapturingPrintStream) System.out;
68 }
69 return null;
70 }
71
72 public static String getOutput()
73 {
74 CapturingPrintStream stream = get();
75 if ( stream != null )
76 {
77 stream.flush();
78 return stream.buffer.toString();
79 }
80 return "";
81 }
82 }