/*
 *  Illustrates a real servlet counter
 *  Upon startup, the servlet loads the current count
 *  from the counter.txt file.
 *  Upon shutdown, the servlet saves the current count
 *  back to the counter.txt file
 */

package pjberkel;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * CounterPerist Servlet
 * Adapted from Jason Hunter, "Java Servlet Programming"
 * Sebastopol, CA:  O'Reilly, 1999
 * See Example 3-4:  A fully persisent counter (p. 59)
 */

public class CounterPersist extends HttpServlet {
	String fileName = "counter.txt";
	int count;

	//  At Start-up, load the counter from file
	//  In the event of any exception, initialize
	//  count to 0.
	public void init () {
		try {
			FileReader fileReader = new FileReader (fileName);
			BufferedReader bufferedReader = new BufferedReader (fileReader);
			String initial = bufferedReader.readLine();
			count = Integer.parseInt (initial);
		} catch (FileNotFoundException e) {
			count = 0;
		} catch (IOException e) {
			count = 0;
		} catch (NumberFormatException e) {
			count = 0;
		}
	}

	//  Handle an HTTP GET Request
	public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException  {
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		count++;
		out.println ("Since first loading, this servlet has "
			+"been accessed "+ count + " times.");
		out.close();
    }

    //  At Shutdown, store counter back to file
    public void destroy() {
		try {
			FileWriter fileWriter = new FileWriter (fileName);
			String countStr = Integer.toString (count);
			fileWriter.write (countStr);
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}




