01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.admin.common;
05:
06: import org.apache.commons.io.IOUtils;
07: import org.apache.commons.lang.StringUtils;
08:
09: import java.io.BufferedReader;
10: import java.io.IOException;
11: import java.io.InputStream;
12: import java.io.InputStreamReader;
13:
14: import javax.swing.SwingUtilities;
15:
16: public class StreamReader extends Thread {
17: TextPaneUpdater m_updater;
18: InputStream m_stream;
19: InputStreamReader m_streamReader;
20: BufferedReader m_bufferedReader;
21: boolean m_stop;
22: OutputStreamListener m_listener;
23: String m_trigger;
24:
25: public StreamReader(InputStream stream,
26: OutputStreamListener listener, String trigger) {
27: this (stream, null, listener, trigger);
28: }
29:
30: public StreamReader(InputStream stream, TextPaneUpdater updater,
31: OutputStreamListener listener, String trigger) {
32: m_updater = updater;
33: m_stream = stream;
34: m_streamReader = new InputStreamReader(stream);
35: m_bufferedReader = new BufferedReader(m_streamReader);
36: m_stop = false;
37: m_listener = listener;
38: m_trigger = trigger;
39: }
40:
41: public void setTriggerListener(OutputStreamListener listener) {
42: m_listener = listener;
43: }
44:
45: public void setTrigger(String trigger) {
46: m_trigger = trigger;
47: }
48:
49: public void run() {
50: String line;
51:
52: while (!m_stop) {
53: try {
54: if ((line = m_bufferedReader.readLine()) == null) {
55: IOUtils.closeQuietly(m_bufferedReader);
56: return;
57: } else {
58: if (m_updater != null) {
59: update(line);
60: }
61: if (m_listener != null && m_trigger != null
62: && StringUtils.contains(line, m_trigger)) {
63: SwingUtilities.invokeLater(new Runnable() {
64: public void run() {
65: m_listener.triggerEncountered();
66: }
67: });
68: }
69: continue;
70: }
71: } catch (IOException ioe) {
72: IOUtils.closeQuietly(m_bufferedReader);
73: return;
74: }
75: }
76:
77: IOUtils.closeQuietly(m_bufferedReader);
78: }
79:
80: private void update(String line) {
81: try {
82: m_updater.setLine(line);
83: SwingUtilities.invokeAndWait(m_updater);
84: } catch (Exception e) {/**/
85: }
86: }
87:
88: public synchronized void finish() {
89: m_stop = true;
90: IOUtils.closeQuietly(m_bufferedReader);
91: }
92: }
|