1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package net.sourceforge.servletspy.config;
23
24 import java.io.InputStream;
25 import java.net.URL;
26
27 import javax.servlet.ServletContextEvent;
28 import javax.servlet.ServletContextListener;
29
30 /***
31 * @author arno schumacher
32 */
33 public final class Loader implements ServletContextListener {
34 private static final String CONFIG_RESOURCE = "servlet-spy.xml";
35
36 private static class Problem extends RuntimeException {
37 private static final long serialVersionUID = 3046326989811674823L;
38
39 private Problem(final Throwable t) {
40 super(t);
41 }
42
43 public Problem(final String string) {
44 super(string);
45 }
46 }
47
48 private ContextHandlerFactory contextHandlerFactory = null;
49
50 public synchronized void contextInitialized(final ServletContextEvent arg0) {
51 if (contextHandlerFactory != null) {
52 contextHandlerFactory.destroy();
53 contextHandlerFactory = null;
54 }
55
56 URL url = Thread.currentThread().getContextClassLoader().getResource(
57 CONFIG_RESOURCE);
58 if (url == null) {
59 throw new Problem("Could not find configuration resource '"
60 + CONFIG_RESOURCE + "'");
61 }
62
63 try {
64 InputStream is = url.openStream();
65 ServletSpy servletSpy = ServletSpy.fromXML(is, "UTF-8");
66 contextHandlerFactory = new ContextHandlerFactory(servletSpy);
67 is.close();
68 arg0.getServletContext().setAttribute("SpyConfiguration",
69 servletSpy);
70 } catch (Exception e) {
71 throw new Problem(e);
72 }
73 }
74
75 public synchronized void contextDestroyed(final ServletContextEvent arg0) {
76 if (contextHandlerFactory == null) {
77 return;
78 }
79 contextHandlerFactory.destroy();
80 contextHandlerFactory = null;
81 }
82 }