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