OutputHandler.java

00001 /* 
00002 ** Author(s): Miguel Calejo
00003 ** Contact:   interprolog@declarativa.com, http://www.declarativa.com
00004 ** Copyright (C) Declarativa, Portugal, 2000-2002
00005 ** Use and distribution, without any warranties, under the terms of the 
00006 ** GNU Library General Public License, readable in http://www.fsf.org/copyleft/lgpl.html
00007 */
00008 package com.declarativa.interprolog.util;
00009 import java.io.*;
00010 import java.util.*;
00011 import com.declarativa.interprolog.*;
00012 
00015 public class OutputHandler extends Thread {
00016         InputStream sourceStream;
00017         Vector listeners;
00018         private boolean ignoreStreamEnd;
00019         
00020         public OutputHandler(InputStream s){
00021                 if (s instanceof BufferedInputStream) sourceStream = s;
00022                 else sourceStream = new BufferedInputStream(s);
00023                 listeners = new Vector();
00024                 ignoreStreamEnd=false;
00025         }
00026         
00027         public synchronized void addOutputListener(OutputListener ol){
00028                 listeners.addElement(ol);
00029         }
00030         public synchronized void removeOutputListener(OutputListener ol){
00031                 listeners.removeElement(ol);
00032         }
00033         
00034         public boolean hasListener(OutputListener ol){
00035                 return listeners.contains(ol);
00036         }
00037         
00038         public void run(){
00039                 byte[] buffer = new byte[1024]; 
00040                 while(true) {
00041                         try{
00042                                 int nchars = sourceStream.read(buffer,0,buffer.length);
00043                                 if (nchars==-1){
00044                                         fireStreamEnded();
00045                                         break;
00046                                 } else fireABs(buffer,nchars);
00047                         } catch (IOException ex){ throw new IPException("Problem fetching output:"+ex);}
00048                 }
00049         }
00050         synchronized void fireStreamEnded(){
00051                 if (ignoreStreamEnd) return;
00052                 for (int L=0; L<listeners.size(); L++)
00053                         ((OutputListener)(listeners.elementAt(L))).streamEnded();
00054         }
00055         synchronized void fireABs(byte[] buffer,int nbytes){
00056                 for (int L=0; L<listeners.size(); L++)
00057                         ((OutputListener)(listeners.elementAt(L))).analyseBytes(buffer,nbytes);
00058         }
00059         
00060         public void setIgnoreStreamEnd(boolean ignore){
00061                 ignoreStreamEnd=ignore;
00062         }
00063 }
00064 

Generated on Wed Jul 26 13:30:44 2006 for XSB by  doxygen 1.4.5