| 1 |
/* |
| 2 |
* Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 |
* contributor license agreements. See the NOTICE file distributed with |
| 4 |
* this work for additional information regarding copyright ownership. |
| 5 |
* The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 |
* (the "License"); you may not use this file except in compliance with |
| 7 |
* the License. You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
*/ |
| 17 |
package org.apache.lucene.gradle; |
| 18 |
|
| 19 |
import java.io.IOException; |
| 20 |
import java.io.Writer; |
| 21 |
|
| 22 |
/** |
| 23 |
* Prefixes every new line with a given string, synchronizing multiple streams to emit consistent lines. |
| 24 |
*/ |
| 25 |
public class PrefixedWriter extends Writer { |
| 26 |
Writer sink; |
| 27 |
|
| 28 |
private final static char LF = '\n'; |
| 29 |
private final String prefix; |
| 30 |
private final StringBuilder lineBuffer = new StringBuilder(); |
| 31 |
private final int maxLineLength; |
| 32 |
|
| 33 |
public PrefixedWriter(String prefix, Writer sink, int maxLineLength) { |
| 34 |
super(sink); |
| 35 |
this.sink = sink; |
| 36 |
this.prefix = prefix; |
| 37 |
this.maxLineLength = maxLineLength; |
| 38 |
} |
| 39 |
|
| 40 |
@Override |
| 41 |
public void write(int c) throws IOException { |
| 42 |
if (lineBuffer.length() == maxLineLength || c == LF) { |
| 43 |
sink.write(prefix); |
| 44 |
sink.write(lineBuffer.toString()); |
| 45 |
sink.write(LF); |
| 46 |
|
| 47 |
lineBuffer.setLength(0); |
| 48 |
if (c != LF) { |
| 49 |
lineBuffer.append((char) c); |
| 50 |
} |
| 51 |
} else { |
| 52 |
lineBuffer.append((char) c); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
@Override |
| 57 |
public void write(char[] cbuf, int off, int len) throws IOException { |
| 58 |
for (int i = off; i < off + len; i++) { |
| 59 |
write(cbuf[i]); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
@Override |
| 64 |
public void flush() throws IOException { |
| 65 |
// don't pass flushes. |
| 66 |
} |
| 67 |
|
| 68 |
@Override |
| 69 |
public void close() throws IOException { |
| 70 |
throw new UnsupportedOperationException(); |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Complete the current line (emit LF if not at the start of the line already). |
| 75 |
*/ |
| 76 |
public void completeLine() throws IOException { |
| 77 |
if (lineBuffer.length() > 0) { |
| 78 |
write(LF); |
| 79 |
} |
| 80 |
} |
| 81 |
} |