| @@ -0,0 +1,94 @@ | |||
| package altk.common.engine.util; | |||
| import java.io.IOException; | |||
| import java.io.InputStream; | |||
| import java.io.InputStreamReader; | |||
| import java.nio.CharBuffer; | |||
| import java.nio.charset.CharsetDecoder; | |||
| import org.apache.log4j.Logger; | |||
| /** | |||
| * Wrapper of InputStreamReader to add logging capability. | |||
| * @author Yuk-Ming | |||
| * | |||
| */ | |||
| public class LoggingInputStreamReader extends InputStreamReader | |||
| { | |||
| private static final int CharBuffer_SIZE = 200; | |||
| private CharBuffer buf = CharBuffer.allocate(CharBuffer_SIZE); | |||
| private static Logger myLogger = Logger.getLogger(LoggingInputStreamReader.class); | |||
| private Logger isLogger; | |||
| public LoggingInputStreamReader(InputStream in, CharsetDecoder decoder, Logger isLogger) | |||
| { | |||
| super(in, decoder); | |||
| this.isLogger = isLogger; | |||
| } | |||
| @Override | |||
| public int read() throws IOException | |||
| { | |||
| int c = super.read(); | |||
| if (c != -1) | |||
| { | |||
| append((char)c); | |||
| } | |||
| return c; | |||
| } | |||
| @Override | |||
| public int read(char[] cbuf, int offset, int length) throws IOException | |||
| { | |||
| int n = super.read(cbuf, offset, length); | |||
| for (int i = offset; i < offset + n; i++) | |||
| { | |||
| append(cbuf[i]); | |||
| } | |||
| return n; | |||
| } | |||
| private void append(char c) | |||
| { | |||
| if ((char)c == '\n') | |||
| { | |||
| logPartial(); | |||
| } | |||
| else | |||
| { | |||
| buf.put((char)c); | |||
| if (!buf.hasRemaining()) logPartial(); | |||
| } | |||
| } | |||
| private void logPartial() | |||
| { | |||
| if (buf.position() == 0) return; | |||
| String logContent = new String(buf.array(), 0, buf.position()); | |||
| isLogger.info(logContent); | |||
| buf.clear(); | |||
| } | |||
| @Override | |||
| public void close() | |||
| { | |||
| // Read any remaining characters for logging purpose. | |||
| try | |||
| { | |||
| while (read() != -1); | |||
| super.close(); | |||
| logPartial(); | |||
| } | |||
| catch (IOException e) | |||
| { | |||
| logPartial(); | |||
| myLogger.warn("Caught exception while reaading unwanted trailing chars in stream"); | |||
| } | |||
| } | |||
| } | |||