001: /*
002: * ReaderThread.java
003: *
004: * Copyright (C) 2000-2004 Peter Graves
005: *
006: * This program is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU General Public License
008: * as published by the Free Software Foundation; either version 2
009: * of the License, or (at your option) any later version.
010: *
011: * This program is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014: * GNU General Public License for more details.
015: *
016: * You should have received a copy of the GNU General Public License
017: * along with this program; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
019: */
020:
021: package org.armedbear.j;
022:
023: import java.io.BufferedReader;
024: import java.io.IOException;
025: import java.io.InputStream;
026: import java.io.InputStreamReader;
027: import java.io.UnsupportedEncodingException;
028:
029: public class ReaderThread extends Thread {
030: private char[] buf = new char[4096];
031: private InputStream inputStream;
032: private BufferedReader reader;
033: private boolean done = false;
034: private int timeOut = 10; // Milliseconds.
035:
036: public ReaderThread(InputStream inputStream) {
037: super ("reader thread");
038: this .inputStream = inputStream;
039: String encoding = Editor.preferences().getStringProperty(
040: Property.DEFAULT_ENCODING);
041: try {
042: reader = new BufferedReader(new InputStreamReader(
043: inputStream, encoding));
044: } catch (UnsupportedEncodingException e) {
045: Log.debug(e);
046: reader = new BufferedReader(new InputStreamReader(
047: inputStream));
048: }
049: }
050:
051: public void setTimeOut(int n) {
052: timeOut = n;
053: }
054:
055: public void run() {
056: while (!done) {
057: String s = read();
058: if (s == null)
059: return;
060: update(filter(s));
061: }
062: }
063:
064: public void cancel() {
065: interrupt();
066: if (inputStream != null) {
067: try {
068: inputStream.close();
069: } catch (IOException e) {
070: Log.error(e);
071: }
072: inputStream = null;
073: }
074: }
075:
076: private String read() {
077: StringBuffer sb = new StringBuffer();
078: try {
079: do {
080: int numChars = reader.read(buf, 0, buf.length); // Blocks.
081: if (numChars < 0) {
082: done = true;
083: break;
084: }
085: if (numChars > 0)
086: sb.append(buf, 0, numChars);
087: Thread.sleep(timeOut);
088: } while (reader.ready());
089: } catch (IOException e) {
090: return null;
091: } catch (InterruptedException e) {
092: return null;
093: } catch (Throwable t) {
094: return null;
095: }
096: return sb.toString();
097: }
098:
099: public String filter(String s) {
100: return s;
101: }
102:
103: public void update(String s) {
104: }
105: }
|