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 com.declarativa.interprolog.util.*; 00010 import java.util.*; 00011 00013 public class Recognizer implements OutputListener{ 00014 Vector listeners; 00015 int nextInPattern; // next byte to recognize 00016 byte[] bytePattern; 00017 boolean collectRestOfBuffer; 00018 00019 public Recognizer(){ 00020 this(null); 00021 } 00022 public Recognizer(String pattern){ 00023 this(pattern,false); 00024 } 00025 public Recognizer(String pattern,boolean collectRestOfBuffer){ 00026 listeners = new Vector(); 00027 if (pattern==null) bytePattern=new byte[0]; 00028 else bytePattern = pattern.getBytes(); 00029 nextInPattern=0; 00030 this.collectRestOfBuffer=collectRestOfBuffer; 00031 } 00032 00033 public int numberListeners(){ return listeners.size(); } 00034 00035 // OutputListener methods: 00036 public void analyseBytes(byte[] buffer,int nbytes){ 00037 if (bytePattern.length==0) 00038 fireRecognized(new String(buffer,0,nbytes)); 00039 else for(int b=0;b<nbytes;b++) { 00040 if(buffer[b]==bytePattern[nextInPattern]){ 00041 nextInPattern++; 00042 if (nextInPattern>=bytePattern.length) { 00043 nextInPattern = 0; 00044 if (collectRestOfBuffer && b+1<nbytes) { 00045 fireRecognized(new String(buffer,b+1,nbytes-(b+1))); 00046 break; 00047 } 00048 else fireRecognized(""); 00049 } 00050 } 00051 else nextInPattern = 0; 00052 } 00053 } 00054 public void streamEnded(){ 00055 throw new IPException("Unexpected end of stream, Prolog may have died abruptly"); 00056 } 00057 00058 public synchronized void addRecognizerListener(RecognizerListener l){ 00059 listeners.addElement(l); 00060 } 00061 public synchronized void removeRecognizerListener(RecognizerListener l){ 00062 listeners.removeElement(l); 00063 } 00064 void fireRecognized(String extra){ 00065 for (int l=0; l<listeners.size(); l++) 00066 ((RecognizerListener)(listeners.elementAt(l))).recognized(this,extra); 00067 } 00068 } 00069