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