Usage monitor - decorator


import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;

/* This decorator monitors the number of times a file is opened by the client
   to give an indication of the frequency of use of the file.
*/
public class UsageMonitor extends Component{

  private Component c;              //server contained in decorator
                                    //may be another decorator
  private Hashtable usage = new Hashtable();//used to hold usage stats
  
  private UsageWindow w;

  public UsageMonitor(Component server) {    
    c = server;      
    w = new UsageWindow();               //store ref to contained component
  } // end UsageMonitor()

  public boolean open(String filename) {
    int count;
    if (usage.containsKey(filename)){
      count = ((Integer)usage.get(filename)).intValue() + 1;
      usage.put(filename,new Integer(count));
      w.update(filename,count);
    }
    else {
      usage.put(filename,new Integer(1));
      w.add(filename);
    }    
    return c.open(filename);  //pass on request to server
  } //end open()

  public String read(String filename) {
    return c.read(filename);            //pass on request to server
  } //end read()

  public boolean endOfFile(String filename) {
    return c.endOfFile(filename);      //pass on request to server
  } //end endOfFile()  

  public void close(String filename) {
    c.close(filename);                 //pass on request to server
  } //end close()

} //end class Logger


class UsageWindow extends Frame {      //window displays the usage information
                                       //and is continuously updated
  private List files = new List(10);
  private List counts = new List(10);

  public UsageWindow() {
    super("Usage statistics");
    enableEvents(WindowEvent.WINDOW_CLOSING);
    setSize(200,100);
    setLayout(new GridLayout(1,2));
    add(files);
    add(counts);
    setBackground(Color.pink);
    setVisible(true);
  } //end UsageWindow

  public void processWindowEvent(WindowEvent we){
    if (we.getID() == WindowEvent.WINDOW_CLOSING){
      dispose();
      System.exit(0);
    } //end if
    super.processWindowEvent(we);
  } //end processWindowEvent()

  public void add(String filename) {
    files.add(filename);
    counts.add((new Integer(1)).toString());
  } //end add()
  
  public void update(String filename,int count) {
    for (int i = 0; i < files.getItemCount(); i++)
      if (filename.equals(files.getItem(i))){
        counts.replaceItem((new Integer(count)).toString(),i);
	break;
      } //end if	
  } //end update()

} //end class UsageWindow