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