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