FileDocCategorySizeDatePackage
GenericCounter.javaAPI DocExample2543Tue Feb 08 11:30:34 GMT 2000None

GenericCounter

public class GenericCounter extends HttpServlet

Fields Summary
private Hashtable
counts
Constructors Summary
Methods Summary
public voiddestroy()

    // Try to save the accumulated count
    try {
      FileWriter fileWriter = new FileWriter(getClass().getName() + ".counts");
      BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
      Enumeration keys = counts.keys();
      Enumeration elements = counts.elements();
      String output = null;
      while (keys.hasMoreElements() && elements.hasMoreElements()) {
        String name = (String) keys.nextElement();
        int[] val = (int[]) elements.nextElement();
        bufferedWriter.write(name + " " + val[0] + "\n");
      }
      bufferedWriter.close();
      fileWriter.close();
      return;
    }
    catch (IOException e) { }  // problem during write
  
public intincrementAndGetCount(java.lang.String uri)

    int[] holder = (int[])counts.get(uri);
    if (holder == null) {
      // Initialize the count to 0
      holder = new int[1];
      holder[0] = 0;
      counts.put(uri, holder);  // save the holder
    }
    holder[0]++;                // increment
    return holder[0];
  
public voidinit(javax.servlet.ServletConfig config)


        
    // Always call super.init(config) first
    super.init(config);

    // Try to load the initial page counts from the saved persistent state
    try {
      FileReader fileReader = new FileReader(getClass().getName() + ".counts");
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      String line = null;
      String uri = null;
      String count = null;
      int[] holder = null;  // holder for the count, to make it an object
      while ((line = bufferedReader.readLine()) != null) {
        StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.countTokens() < 2) continue;  // bogus line
        uri = tokenizer.nextToken();
        count = tokenizer.nextToken();
        // Store the uri/count pair in the counts hashtable
        // The count is saved as an int[1] to make it an "object"
        try {
          holder = new int[1];
          holder[0] = Integer.parseInt(count);
          counts.put(uri, holder);
        }
        catch (NumberFormatException e) { }  // bogus line
      }
    }
    catch (FileNotFoundException e) { }  // no saved state
    catch (IOException e) { }            // problem during read