1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.plexus;
22
23 import java.util.Collections;
24
25 import javax.servlet.ServletContext;
26 import javax.servlet.ServletContextEvent;
27 import javax.servlet.ServletContextListener;
28 import javax.servlet.http.HttpSession;
29 import javax.servlet.http.HttpSessionEvent;
30 import javax.servlet.http.HttpSessionListener;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.codehaus.plexus.DefaultPlexusContainer;
35 import org.codehaus.plexus.PlexusContainer;
36
37 /***
38 * Manages the Plexus lifecycle for the servlet and session contexts
39 */
40 public class PlexusLifecycleListener implements ServletContextListener, HttpSessionListener {
41 private static final Log log = LogFactory.getLog(PlexusObjectFactory.class);
42
43 private static boolean loaded = false;
44 public static final String KEY = "struts.plexus.container";
45
46 /***
47 * @return Returns if the container is loaded.
48 */
49 public static boolean isLoaded() {
50 return loaded;
51 }
52
53
54
55
56 public void contextInitialized(ServletContextEvent servletContextEvent) {
57 loaded = true;
58
59 try {
60 PlexusContainer pc = new DefaultPlexusContainer();
61 PlexusUtils.configure(pc, "plexus-application.xml");
62 ServletContext ctx = servletContextEvent.getServletContext();
63 ctx.setAttribute(KEY, pc);
64
65 pc.initialize();
66 pc.start();
67 } catch (Exception e) {
68 log.error("Error initializing plexus container (scope: application)", e);
69 }
70 }
71
72
73
74
75 public void contextDestroyed(ServletContextEvent servletContextEvent) {
76 try {
77 ServletContext ctx = servletContextEvent.getServletContext();
78 PlexusContainer pc = (PlexusContainer) ctx.getAttribute(KEY);
79 pc.dispose();
80 } catch (Exception e) {
81 log.error("Error disposing plexus container (scope: application)", e);
82 }
83 }
84
85
86
87
88 public void sessionCreated(HttpSessionEvent httpSessionEvent) {
89 try {
90 HttpSession session = httpSessionEvent.getSession();
91 ServletContext ctx = session.getServletContext();
92 PlexusContainer parent = (PlexusContainer) ctx.getAttribute(KEY);
93 PlexusContainer child = parent.createChildContainer("session", Collections.EMPTY_LIST, Collections.EMPTY_MAP);
94 session.setAttribute(KEY, child);
95 PlexusUtils.configure(child, "plexus-session.xml");
96 child.initialize();
97 child.start();
98 } catch (Exception e) {
99 log.error("Error initializing plexus container (scope: session)", e);
100 }
101 }
102
103
104
105
106 public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
107 try {
108 HttpSession session = httpSessionEvent.getSession();
109 PlexusContainer child = (PlexusContainer) session.getAttribute(KEY);
110 child.dispose();
111 } catch (Exception e) {
112 log.error("Error initializing plexus container (scope: session)", e);
113 }
114 }
115 }