All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.gluebooster.java.booster.basic.io.WriterDelegate Maven / Gradle / Ivy

package net.sf.gluebooster.java.booster.basic.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;

import net.sf.gluebooster.java.booster.essentials.logging.LogBooster;
import net.sf.gluebooster.java.booster.essentials.utils.TextBoostUtils;

/**
 * Delegate of a writer.
 * 
 * @author CBauer
 * 
 */
public class WriterDelegate extends Writer {

	/**
	 * The log of messages.
	 */
	private static LogBooster LOG = new LogBooster(WriterDelegate.class);

	/**
	 * Should the stack trace be logged additionally.
	 */
	private boolean logWritingStacktrace = false;

	/**
	 * Should a prefix be added to messages.
	 */
	private char[] prefix = null;

	/**
	 * The writer this delegate delegates to.
	 */
	private Writer writer;

	/**
	 * Should a flash be done as often as necessary. Default is true, because it
	 * is not ensured that there is a flush at the end of the program.
	 **/
	private boolean doAlwaysFlush = true;

	public WriterDelegate(Writer writer) {
		this.writer = writer;
	}

	@Override
	public void write(char[] cbuf, int off, int len) throws IOException {

		String textWithoutWhitespace = TextBoostUtils
				.removeWhitespace(new String(cbuf, off, len));
		// write the prefix before non empty characters
		if (prefix != null && !textWithoutWhitespace.isEmpty())
			writer.write(prefix);

		writer.write(cbuf, off, len);

		if (logWritingStacktrace && !textWithoutWhitespace.isEmpty()) {
			Throwable ex = new InterruptedException("stacktrace ");
			ex.fillInStackTrace();
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			String encoding = "utf-8";
			bytes.write("\n".charAt(0));
			PrintStream printer = new PrintStream(bytes, true, encoding);
			ex.printStackTrace(printer);
			writer.write(bytes.toString(encoding).toCharArray());
		}

		if (doAlwaysFlush)
			writer.flush();
	}

	@Override
	public void flush() throws IOException {
		writer.flush();

	}

	@Override
	public void close() throws IOException {
		writer.close();

	}

	public boolean isLogWritingStacktrace() {
		return logWritingStacktrace;
	}

	public void setLogWritingStacktrace(boolean logWritingStacktrace) {
		this.logWritingStacktrace = logWritingStacktrace;
	}

	public String getPrefix() {
		return new String(prefix);
	}

	public void setPrefix(String prefix) {
		if (prefix == null)
			this.prefix = null;
		else 
			this.prefix = prefix.toCharArray();
	}

	public Writer getWriter() {
		return writer;
	}

	public void setWriter(Writer writer) {
		this.writer = writer;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy