01: package pygmy.handlers;
02:
03: import pygmy.core.*;
04:
05: import java.io.*;
06: import java.util.HashMap;
07: import java.util.Collections;
08: import java.util.Map;
09: import java.util.Iterator;
10:
11: public class StatsHandler extends AbstractHandler {
12:
13: public static final ConfigOption FILE_OPTION = new ConfigOption(
14: "file", "stats.log", "File name for the stats.");
15:
16: private String filename;
17: private Map statsMap = Collections.synchronizedMap(new HashMap());
18:
19: public boolean initialize(String handlerName, Server server) {
20: super .initialize(handlerName, server);
21: filename = FILE_OPTION.getProperty(server, getName());
22: return true;
23: }
24:
25: protected boolean handleBody(HttpRequest request,
26: HttpResponse response) throws IOException {
27: UrlStatistics stats = (UrlStatistics) statsMap.get(request
28: .getUrl());
29: if (stats == null) {
30: stats = new UrlStatistics(System.currentTimeMillis());
31: statsMap.put(request.getUrl(), stats);
32: } else {
33: stats.lastTime = System.currentTimeMillis();
34: }
35: stats.increment();
36: saveStatistics();
37: return false;
38: }
39:
40: private void saveStatistics() throws IOException {
41: Writer file = new BufferedWriter(new FileWriter(filename));
42: try {
43: for (Iterator i = statsMap.keySet().iterator(); i.hasNext();) {
44: String url = (String) i.next();
45: UrlStatistics stats = (UrlStatistics) statsMap.get(url);
46: synchronized (stats) {
47: file.write(url + " " + stats.count() + " "
48: + stats.getFirstTime() + " "
49: + stats.getLastTime() + "\n");
50: }
51: }
52: } finally {
53: file.close();
54: }
55: }
56:
57: public static class UrlStatistics {
58: private long lastTime;
59: private int count;
60: private long firstTime;
61:
62: public UrlStatistics(long currentTime) {
63: this .firstTime = currentTime;
64: this .lastTime = currentTime;
65: }
66:
67: public synchronized void lastTime(long currentTime) {
68: lastTime = currentTime;
69: }
70:
71: public synchronized void increment() {
72: count++;
73: }
74:
75: public synchronized long getFirstTime() {
76: return firstTime;
77: }
78:
79: public synchronized long getLastTime() {
80: return lastTime;
81: }
82:
83: public synchronized int count() {
84: return count;
85: }
86: }
87: }
|