November 2, 2015

Extending OutputStream

It was very helpful when using: ((ChannelExec) channel).setErrStream(new Log4JOutputStream());

Review JSch - Examples - Exec.java

Example 1

package sawalha.poc.sch;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4JOutputStream extends OutputStream {

    static Logger log = LogManager.getLogger(ExecCli.class.getName());
    StringBuffer str = new StringBuffer();

    @Override
    public void write(int b) throws IOException {
        char current = (char) b;
        if (current == '\n') {
            log.error(str.toString());
            // Reset it
            str.setLength(0);
        } else {
            str.append(current);
        }
    }
}

Example 2

package sawalha.poc.sch;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4JOutputStream extends OutputStream {

    static Logger log = LogManager.getLogger(ExecCli.class.getName());
    StringBuffer str = new StringBuffer();

    @Override
    public void close() throws IOException {
        super.close();
        log.error(str.toString());
    }

    @Override
    public void write(int b) throws IOException {
        int[] bytes = { b };
        write(bytes, 0, bytes.length);
    }

    public void write(int[] bytes, int offset, int length) {
        String s = new String(bytes, offset, length);
        str.append(s);
    }

}

No comments: