FileDocCategorySizeDatePackage
CounterBean.javaAPI DocExample2584Thu Jun 28 16:14:16 BST 2001com.ora.jsp.beans.counter

CounterBean.java

package com.ora.jsp.beans.counter;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

/**
 * This class maintains page counters.
 *
 * Note that this class is intended to be used in session and application
 * scope so regular setter and getter methods for pageContext can not be 
 * used; all info needed to get and increment the counter value must be 
 * provided as parameters to the corresponding
 * method to avoid multi-threading issues.
 *
 * @author Hans Bergsten, Gefion software <hans@gefionsoftware.com>
 * @version 1.0.1
 */
public class CounterBean implements Serializable {
    /* 
     * Hashtable with a URI as key and an int[] as value.
     * An int[] of size 1 is used to hold the counter value
     * instead of an Integer to avoid the cost of instantiation
     * when incrementing
     */
    private Hashtable counters = new Hashtable();

    /**
     * Returns the current value of the counter for this page.
     *
     * @param uri the URI for the page, as provided by 
     *            HttpServletRequest.getRequestURI()
     * @return the current counter value, or -1 if it's not found
     */
    public int getCurrentValue(String uri) {
        int value = -1;
        int[] counter = (int[]) counters.get(uri);
        if (counter != null) {
            value = counter[0];
        }
        return value; 
    }
    
    /**
     * Increments the counter for this page and returns the new value.
     *
     * @param uri the URI for the page, as provided by 
     *            HttpServletRequest.getRequestURI()
     * @return the current counter value incremented by one
     */
    public int getNextValue(String uri) {
        incrementValue(uri);
        return getCurrentValue(uri);
    }
    
    /**
     * Increments the counter for this page. If the permanent is true,
     * the new value is also saved in a file.
     *
     * @param uri the URI for the page, as provided by 
     *            HttpServletRequest.getRequestURI()
     */
    public void incrementValue(String uri) {
        /*
         * Synchronized block for incrementing the counter to handle
         * concurrent calls from multiple threads
         */
        synchronized (counters) {
            int[] counter = (int[]) counters.get(uri);
            if (counter == null) {
                counter = new int[1];
                counter[0] = 0;
            }
            counter[0]++;
            counters.put(uri, counter);
        }
    }
}