/*
* Copyright (c) 2010-2015 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.cli.ninja.util;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
/**
* @author Viliam Repan (lazyman)
*/
public class LogWriter extends Writer implements Serializable {
private StringBuilder builder = new StringBuilder();
private Logger target;
public LogWriter(Logger target) {
this.target = target;
}
@Override
public void close() throws IOException {
log();
}
@Override
public void flush() throws IOException {
log();
}
/**
* Append a single character to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(char value) {
builder.append(value);
return this;
}
/**
* Append a character sequence to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(CharSequence value) {
builder.append(value);
return this;
}
/**
* Append a portion of a character sequence to the {@link StringBuilder}.
*
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(CharSequence value, int start, int end) {
builder.append(value, start, end);
return this;
}
/**
* Write a String to the {@link StringBuilder}.
*
* @param value The value to write
*/
@Override
public void write(String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Write a portion of a character array to the {@link StringBuilder}.
*
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(char[] value, int offset, int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
private void log() {
if (builder.length() == 0) {
return;
}
target.info(builder.toString());
builder = new StringBuilder();
}
}