package com.cadrlife.devsearch.agent.service;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Writer;
public class LoggingWriter extends Writer {
private static final String NEWLINE = System.getProperty("line.separator");
private final StringBuilder builder = new StringBuilder();
private final LogHook logHook;
public static interface LogHook {
void log(String msg);
}
public LoggingWriter(LogHook logHook) {
Preconditions.checkNotNull(logHook);
this.logHook = logHook;
}
private void logIfNeeded() {
while (builder.length() > 0) {
synchronized (builder) {
final int newlineIndex = builder.indexOf(NEWLINE);
if (newlineIndex < 0) {
return;
}
if (newlineIndex == 0) {
builder.delete(0, NEWLINE.length());
// Maybe don't need to do blank lines
logHook.log("");
}
final String msg = builder.substring(0, newlineIndex);
builder.delete(0, newlineIndex + NEWLINE.length());
logHook.log(msg);
}
}
}
@Override
public void write(int c) throws IOException {
synchronized (builder) {
builder.append((char) c);
}
logIfNeeded();
}
@Override
public void write(char[] cbuf) throws IOException {
synchronized (builder) {
builder.append(cbuf);
}
logIfNeeded();
}
@Override
public void write(String str) throws IOException {
synchronized (builder) {
builder.append(str);
}
logIfNeeded();
}
@Override
public void write(String str, int off, int len) throws IOException {
synchronized (builder) {
builder.append(str);
}
logIfNeeded();
}
@Override
public Writer append(CharSequence csq) throws IOException {
synchronized (builder) {
builder.append(csq);
}
logIfNeeded();
return this;
}
@Override
public Writer append(CharSequence csq, int start, int end) throws IOException {
synchronized (builder) {
builder.append(csq, start, end);
}
logIfNeeded();
return this;
}
@Override
public Writer append(char c) throws IOException {
synchronized (builder) {
builder.append(c);
}
logIfNeeded();
return this;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (builder) {
builder.append(cbuf, off, len);
}
logIfNeeded();
}
@Override
public void flush() throws IOException {
logIfNeeded();
}
@Override
public void close() throws IOException {
synchronized (builder) {
if (builder.length() > 0 && builder.lastIndexOf(NEWLINE) < builder.length() - NEWLINE.length()) {
builder.append(NEWLINE);
}
logIfNeeded();
}
}
}