package weblogic.taglib.counter;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
 * This class synchronizes access to the count hits file.
 */

public class Count {
  
  synchronized static public int getCount(File filestore) {
    if (!filestore.exists()) {
      return 0;
    }
    ObjectInputStream os = null; 
    try { 
      os = new ObjectInputStream(new FileInputStream(filestore));
      int count =  os.readInt();
      return count;
    } catch(IOException e) {
      System.out.println("Unable to read from counter file: "+filestore);
      return 0;
    } finally {
      try {
        os.close();
      } catch(Exception e) {
        System.out.println("Unable to close counter file: "+filestore);
        e.printStackTrace();
      }
    }
  }
  
  synchronized static public void incCount(File filestore) {
    int count = 0;
    // Attempt to read the current count from the filestore
    if (filestore.exists()) { 
      // try to read the current count
      ObjectInputStream is = null; 
      try {
        is = new ObjectInputStream(new FileInputStream(filestore));
        count = is.readInt();
      } catch(Exception e) {
        System.out.println("Unable to read from counter file: "+filestore);
        e.printStackTrace();
      } finally {
        try {
          is.close();
        } catch(Exception e) {
          System.out.println("Unable to close counter file: "+filestore);
          e.printStackTrace();
        }
      }
    }
    
    
    // Increament the obtained count
    count++;
    // Now write out the incremented count
    ObjectOutputStream os = null;
    try {
      os = new ObjectOutputStream(new FileOutputStream(filestore));
      os.writeInt(count);
    }catch(Exception e) {
      System.out.println("Unable to write to counter file: "+filestore);
      e.printStackTrace();
    } finally {
      try {
        os.close();
      } catch(Exception e) {
        System.out.println("Unable to close output stream to counter file: "+filestore);
        e.printStackTrace();
      }
    }
  }
}
  

