// GcStatFrame.java
// $Id: GcStatFrame.java,v 1.2 1998/03/18 10:05:28 bmahe Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package org.w3c.jigsaw.status ;

import org.w3c.www.http.*;
import org.w3c.tools.resources.* ;
import org.w3c.jigsaw.http.* ;
import org.w3c.jigsaw.frames.*;
import org.w3c.jigsaw.html.HtmlGenerator ;

/**
 * This class implements a GC counter.
 * It counts the number of GC that has occured since the system was brought up.
 */

class GcCounter {
    private static int count= 0 ;

    private static synchronized void incrCounter() {
	count++ ;
    }

    private static synchronized int getCount() {
	return count ;
    }

    public static int getGcCount() {
	System.runFinalization() ;
	return getCount() ;
    }

    public void finalize() {
	incrCounter() ;
	new GcCounter() ;
    }

    static {
	new GcCounter() ;
    }
}

/**
 * Each time you get this resource, it fill run the GC.
 */

public class GcStatFrame extends HTTPFrame {
  protected Runtime runtime = null ;

  public void registerResource(FramedResource resource) {
    super.registerOtherResource(resource);
  }

  /**
   * Dump the current memory status.
   * @param request The request we are to reply to.
   */

  protected Reply dumpMemoryStatus (Request request) {
    HtmlGenerator g = new HtmlGenerator ("Memory Status") ;
    g.meta("Refresh", "5") ;
    addStyleSheet(g);
    g.append("<h1>Memory status</h1>") ;
    g.append("<p>Free memory : "+runtime.freeMemory()) ;
    g.append("<p>Total memory: "+runtime.totalMemory()) ;
    g.append("<p>GC count: "+GcCounter.getGcCount()) ;
    g.append("<hr>") ;
    // Reply back:
    Reply  reply = request.makeReply(HTTP.OK) ;
    reply.setStream (g) ;
    return reply ;
  }

  /**
   * Perform a GC and display memory status.
   * @param request The request to handle.
   */
     
  public Reply get (Request request) {
    return dumpMemoryStatus(request) ;
  }

  /**
   * Initialize the thread lister.
   * Just get a pointer to our runtime object.
   * @param values The default attribute values.
   */

  public void initialize(Object values[]) {
    super.initialize(values) ;
    runtime = Runtime.getRuntime() ;
  }
    
}
