1 |
package dk.thoerup.traininfoservice; |
2 |
|
3 |
import java.util.Timer; |
4 |
import java.util.TimerTask; |
5 |
import java.util.logging.Logger; |
6 |
|
7 |
import javax.servlet.ServletContext; |
8 |
import javax.servlet.ServletContextEvent; |
9 |
import javax.servlet.ServletContextListener; |
10 |
import javax.servlet.annotation.WebListener; |
11 |
|
12 |
@WebListener |
13 |
public class StatisticsListener implements ServletContextListener { |
14 |
|
15 |
Logger log = Logger.getLogger(StatisticsListener.class.getName()); |
16 |
|
17 |
Timer timer = null; |
18 |
int update_interval; |
19 |
|
20 |
public void contextInitialized(ServletContextEvent sce) { |
21 |
|
22 |
update_interval = getUpdateInterval( sce.getServletContext() ); |
23 |
|
24 |
|
25 |
|
26 |
if (! sce.getServletContext().getRealPath("/").startsWith("/home/app/") ) { |
27 |
//if path not starts with /home/app then it is not running on a production server and we only collects stats on prod servers |
28 |
log.info("This is not a prod. server, dont start Statistics saver"); |
29 |
return; |
30 |
} |
31 |
|
32 |
|
33 |
|
34 |
if ( update_interval > 0 ) { |
35 |
log.info("Statistics saver started with update_interval=" + update_interval); |
36 |
timer = new Timer(); |
37 |
|
38 |
TimerTask statsUpdate = new TimerTask() { |
39 |
@Override |
40 |
public void run() { |
41 |
Statistics.getInstance().saveStats(); |
42 |
} |
43 |
}; |
44 |
|
45 |
timer.schedule(statsUpdate, 0, update_interval); |
46 |
} else { |
47 |
log.info("Statistics saver disabled (update_interval == 0) "); |
48 |
} |
49 |
} |
50 |
|
51 |
|
52 |
public void contextDestroyed(ServletContextEvent sce) { |
53 |
log.info("StatisticsListener::contextDestroyed"); |
54 |
if ( update_interval > 0 ) { |
55 |
timer.cancel(); |
56 |
Statistics.getInstance().saveStats(); |
57 |
} |
58 |
} |
59 |
|
60 |
private int getUpdateInterval(ServletContext cntx) { |
61 |
int interval = 0; |
62 |
try { |
63 |
String intervalStr = cntx.getInitParameter("stats_interval"); |
64 |
interval = Integer.parseInt(intervalStr); |
65 |
} catch (Exception e) {} |
66 |
|
67 |
return interval; |
68 |
} |
69 |
} |