001package com.identityworksllc.iiq.common;
002
003import org.apache.commons.logging.Log;
004
005import java.io.OutputStream;
006
007/**
008 * Implements an OutputStream that will write to the given logger whenever any
009 * newline is encountered. The output is buffered until a newline.
010 */
011public class CommonsLoggingOutputStream extends OutputStream {
012    private final Level level;
013
014    /**
015     * A representation of the log level
016     */
017    public enum Level {
018        Fatal,
019        Error,
020        Warn,
021        Info,
022        Debug,
023        Trace
024    }
025
026    /**
027     * The buffer holding the string we've collected so far
028     */
029    private String buffer;
030
031    /**
032     * The logger
033     */
034    private final Log logger;
035
036    /**
037     * Constructs a new OutputStream that will write to the given logger at the
038     * given level whenever a newline is encountered in the byte stream.
039     *
040     * @param level The log level
041     * @param logger The logger to write to
042     */
043    public CommonsLoggingOutputStream(Level level, Log logger) {
044        this.logger = logger;
045        this.level = level;
046        this.buffer = "";
047    }
048
049    /**
050     * Writes a byte to the output stream. This method flushes automatically at the end of a line.
051     *
052     * @see OutputStream#write(int)
053     */
054    public void write (int b) {
055        byte[] bytes = new byte[1];
056        bytes[0] = (byte) (b & 0xff);
057        buffer += new String(bytes);
058
059        if (buffer.endsWith("\n")) {
060            buffer = buffer.substring(0, buffer.length () - 1);
061            flush();
062        }
063    }
064
065    /**
066     * Flushes the output stream.
067     *
068     * @see OutputStream#flush()
069     */
070    public void flush () {
071        switch(level) {
072            case Trace:
073                if (logger.isTraceEnabled()) {
074                    logger.trace(buffer);
075                }
076                break;
077            case Debug:
078                if (logger.isDebugEnabled()) {
079                    logger.debug(buffer);
080                }
081                break;
082            case Info:
083                if (logger.isInfoEnabled()) {
084                    logger.info(buffer);
085                }
086                break;
087            case Warn:
088                if (logger.isWarnEnabled()) {
089                    logger.warn(buffer);
090                }
091                break;
092            case Error:
093                if (logger.isErrorEnabled()) {
094                    logger.error(buffer);
095                }
096                break;
097            case Fatal:
098                if (logger.isFatalEnabled()) {
099                    logger.fatal(buffer);
100                }
101                break;
102        }
103        buffer = "";
104    }
105}