API Overview API Index Package Overview Direct link to this page
JavaOnTracks 0.1.2
  net.jot.web. JOTRequestCounter View Javadoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

/*
------------------------------------
JavaOnTracks          Thibaut Colar
tcolar-jot AT colar DOT net
Artistic Licence 2.0
http://www.javaontracks.net
------------------------------------
 */
package net.jot.web;

import java.util.Date;
import java.util.Hashtable;
import javax.servlet.http.HttpServletRequest;

/**
 *Use to "throttle" requests
 * You create a counter with a  unique name and how many minutes it stores data for (in memory)
 * then call addRequest() to count how many request for this IP, in the time span.
 * @author tcolar
 */
public class JOTRequestCounter {
    int minutes=60;
    long tableDate=new Date().getTime();
    Hashtable table=new Hashtable();
    
    public JOTRequestCounter(int minutes)
    {
        this.minutes=minutes;
    }

    /**
     * Count a request and returns how many from this IP in the timespan(including this one)
     * @param request
     * @return
     */
    public int countRequest(HttpServletRequest request)
    {
        Date now=new Date();
        if(now.getTime()>tableDate+minutes*60000)
        {
            table.clear();
            tableDate=now.getTime();
        }
        
        String ip=request.getRemoteAddr();
        int value=1;
        Object o=table.get(ip);
        if(o!=null)
        {
            value=((Integer)o).intValue()+1;;
        }
            
        table.put(ip, new Integer(value));
        return value;
    }
}

Generated By: JavaOnTracks Doclet 0.1.5     ©Thibaut Colar