1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.logging;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.FilterOutputStream;
23 import java.io.IOException;
24 import java.io.PrintStream;
25 import java.util.function.Consumer;
26
27 public class LoggingOutputStream extends FilterOutputStream {
28
29 static final byte[] LINE_SEP = System.lineSeparator().getBytes();
30
31 final EolBaos buf;
32 final Consumer<String> consumer;
33
34 public LoggingOutputStream(Consumer<String> consumer) {
35 this(new EolBaos(), consumer);
36 }
37
38 LoggingOutputStream(EolBaos out, Consumer<String> consumer) {
39 super(out);
40 this.buf = out;
41 this.consumer = consumer;
42 }
43
44 public PrintStream printStream() {
45 return new LoggingPrintStream(this);
46 }
47
48 @Override
49 public void write(int b) throws IOException {
50 super.write(b);
51 if (buf.isEol()) {
52 String line = new String(buf.toByteArray(), 0, buf.size() - LINE_SEP.length);
53 ProjectBuildLogAppender.updateMdc();
54 consumer.accept(line);
55 buf.reset();
56 }
57 }
58
59 public void forceFlush() {
60 if (buf.size() > 0) {
61 String line = new String(buf.toByteArray(), 0, buf.size());
62 ProjectBuildLogAppender.updateMdc();
63 consumer.accept(line);
64 buf.reset();
65 }
66 }
67
68 static class EolBaos extends ByteArrayOutputStream {
69 boolean isEol() {
70 if (count >= LINE_SEP.length) {
71 for (int i = 0; i < LINE_SEP.length; i++) {
72 if (buf[count - LINE_SEP.length + i] != LINE_SEP[i]) {
73 return false;
74 }
75 }
76 return true;
77 }
78 return false;
79 }
80 }
81
82 public static class LoggingPrintStream extends PrintStream {
83 public LoggingPrintStream(LoggingOutputStream out) {
84 super(out, true);
85 }
86
87 public void forceFlush() {
88 ((LoggingOutputStream) out).forceFlush();
89 }
90 }
91
92 public static void forceFlush(PrintStream ps) {
93 if (ps instanceof LoggingPrintStream) {
94 ((LoggingPrintStream) ps).forceFlush();
95 }
96 }
97 }