// Assignment 4 - Pipe-and-Filter KWIC Indexing.
// Concurrent Programming, CS 498-598
// Summer 2002
//
// This code is unmaintained and may be obsolete (as well as being incorrect).
// See the answer to assignment 4 for possible updates.

abstract class 
FilterRunnableTemplate
implements Runnable {

  abstract protected void process_input(Object o);
  abstract protected void misbehave();
  abstract protected boolean isValidObject(Object o);
  abstract protected boolean isMisbehavingObject(Object o);

  protected buffer inb, outb;
  protected String filterName;


  protected void
  end_loop() {

    // Convention dictates filter termination on a null object, which
    // is passed downstream.

    try { outb.put(null); }
    catch (InterruptedException ie) { }
    }


  FilterRunnableTemplate(String fn, buffer ib, buffer ob) {
    filterName = fn;
    inb = ib;
    outb = ob;
    }


  protected Object
  input_object() {

    // Default input behavior: get the next object from the input buffer.

    try { return inb.get(); }
    catch (InterruptedException ie) { 
      throw new Error();
      }
    }


  protected void
  output_object(Object o) {

    // Default output behavior: put the object to the output buffer.

    try { outb.put(o); }
    catch (InterruptedException ie) { 
      throw new Error();
      }
    }


  public void
  run() {

    // The generic algorithm for filter processing.

    while (true) {
      Object o = input_object();
      if (o == null)
	break;

      if (!isValidObject(o)) {
	System.err.println(filterName + " received an object from " +
			   o.getClass() + ".");
	throw new Error();
	}

      if (isMisbehavingObject(o))
	misbehave();
      else
	process_input(o);
      }

    end_loop();
    }
  }


syntax highlighted by Code2HTML, v. 0.9