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