StreamPumper.java 1.98 KB
Newer Older
Kim Gyeongeun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
package jp.agentec.sinaburocast.common.proc;

import java.io.BufferedReader;
import java.io.IOException;

import jp.agentec.sinaburocast.common.SinaburoConstant.Formats;

import org.apache.commons.logging.Log;

/**
 * 標準出力、標準出力読み出し専用スレッド・クラス
 * 
 * @author tsukada
 *
 */
public class StreamPumper extends Thread {
	private String type;
	private BufferedReader br;
	private StringBuffer sb;
	private Log logger;
	private String logLevel;
	private boolean endOfStream = false;
	private boolean finish = false;
	private static final int SLEEP_TIME = 5;

	public StreamPumper(String type, BufferedReader br, StringBuffer sb, Log logger, String logLevel) {
		this.br = br;
		this.type = type;
		this.sb = sb;
		this.logger = logger;
		this.logLevel = logLevel;
	}

	/**
	 * ストリーム出力をログ出力する
	 * @throws IOException
	 */
	public void pumpStream() throws IOException {
		if (!endOfStream) {
			String line = br.readLine();

			if (line == null) {
				endOfStream = true;
			} else {
				if (logLevel == null) {
				}
				else if (logLevel.equals("debug")) {
					if (logger.isDebugEnabled()){
						logger.debug(type + ": " + line);
					}
				}
				else if (logLevel.equals("info")) {
					if (logger.isInfoEnabled()){
						logger.info(type + ": " + line);
					}
				}
				else if (logLevel.equals("warn")) {
					logger.warn(type + ": " + line);
				}
				else if (logLevel.equals("error")) {
					logger.error(type + ": " + line);
				}

				if (sb != null) {
					sb.append(line+ Formats.RETURN);
				}
			}
		}
	}

	/**
	 * 終了フラグを立てる
	 */
	public void finish() {
		finish = true;
	}

	public void run() {
		try {
			try {
				while (!endOfStream && !finish) {
					pumpStream();
					sleep(SLEEP_TIME);
				}
			} catch (InterruptedException e) {
				if (logger != null) {
					logger.warn(e.getMessage());
				}
			}
			br.close();
		} catch (IOException e) {
			if (logger != null) {
				logger.warn(e.getMessage());
			}
		}
	}
}