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.io.IOException;
25 import java.util.Collections;
26
27 import javax.servlet.Filter;
28 import javax.servlet.FilterChain;
29 import javax.servlet.FilterConfig;
30 import javax.servlet.ServletContext;
31 import javax.servlet.ServletException;
32 import javax.servlet.ServletRequest;
33 import javax.servlet.ServletResponse;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpSession;
36
37 import org.codehaus.plexus.PlexusContainer;
38
39 import com.opensymphony.xwork2.util.logging.Logger;
40 import com.opensymphony.xwork2.util.logging.LoggerFactory;
41
42 /***
43 * Creates a plexus container for the application, session, and request
44 */
45 public class PlexusFilter implements Filter {
46 private static final Logger LOG = LoggerFactory.getLogger(PlexusObjectFactory.class);
47 private static final String CHILD_CONTAINER_NAME = "request";
48
49 private static boolean loaded = false;
50
51 private ServletContext ctx;
52
53 /***
54 * @return Returns if the container is loaded.
55 */
56 public static boolean isLoaded() {
57 return loaded;
58 }
59
60
61
62
63 public void init(FilterConfig filterConfig) throws ServletException {
64 ctx = filterConfig.getServletContext();
65 loaded = true;
66 }
67
68
69
70
71 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
72 PlexusContainer child = null;
73 try {
74 try {
75 HttpServletRequest request = (HttpServletRequest) req;
76 HttpSession session = request.getSession(false);
77 PlexusContainer parent;
78 if (session != null) {
79 parent = (PlexusContainer) session.getAttribute(PlexusLifecycleListener.KEY);
80 } else {
81 parent = (PlexusContainer) ctx.getAttribute(PlexusLifecycleListener.KEY);
82 }
83
84 if (parent.hasChildContainer(CHILD_CONTAINER_NAME)) {
85 LOG.warn("Plexus container (scope: request) alredy exist.");
86 child = parent.getChildContainer(CHILD_CONTAINER_NAME);
87 } else {
88 child = parent.createChildContainer(CHILD_CONTAINER_NAME, Collections.EMPTY_LIST, Collections.EMPTY_MAP);
89 PlexusUtils.configure(child, "plexus-request.xml");
90 child.initialize();
91 child.start();
92 }
93 PlexusThreadLocal.setPlexusContainer(child);
94 } catch (Exception e) {
95 LOG.error("Error initializing plexus container (scope: request)", e);
96 }
97
98 chain.doFilter(req, res);
99 }
100 finally {
101 try {
102 if (child != null) {
103 child.dispose();
104 }
105 PlexusThreadLocal.setPlexusContainer(null);
106 } catch (Exception e) {
107 LOG.error("Error disposing plexus container (scope: request)", e);
108 }
109 }
110 }
111
112
113
114
115 public void destroy() {
116 }
117 }