1 package net.trajano.twiff.internal.listener;
2
3 import static net.trajano.twiff.internal.TwiffInternal.APP_CONTAINER_KEY;
4 import static net.trajano.twiff.internal.TwiffInternal.HTTP_SESSION_CONTAINER_KEY;
5 import javax.servlet.ServletContext;
6 import javax.servlet.http.HttpSession;
7 import javax.servlet.http.HttpSessionEvent;
8 import javax.servlet.http.HttpSessionListener;
9 import net.trajano.twiff.container.ContainerBuilder;
10 import net.trajano.twiff.internal.ServletContextAdapterImpl;
11 import org.picocontainer.MutablePicoContainer;
12 import org.picocontainer.PicoContainer;
13 import org.picocontainer.defaults.DefaultPicoContainer;
14
15 /***
16 * This populates the container within the
17 * {@link javax.servlet.http.HttpSession}. This should not be registered in the
18 * <i>web.xml</i> file directly, instead register the
19 * {@link net.trajano.twiff.web.TwiffListener} listener.
20 *
21 * @author Archimedes Trajano
22 */
23 public class PicoHttpSessionListener implements HttpSessionListener {
24 /***
25 * Calls the container builder to add session level objects. *
26 *
27 * @param event
28 * session event.
29 * @param container
30 * the container to populate
31 */
32 protected void buildContainer(final HttpSessionEvent event, final MutablePicoContainer container) {
33 HttpSession session = event.getSession();
34 ServletContextAdapterImpl servletContextAdapter = new ServletContextAdapterImpl(session.getServletContext());
35 ContainerBuilder builder = servletContextAdapter.getContainerBuilder();
36 builder.buildSessionLevelContainer(container);
37 }
38
39 /***
40 * @see HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
41 */
42 public final void sessionCreated(final HttpSessionEvent event) {
43 HttpSession session = event.getSession();
44 ServletContext context = event.getSession().getServletContext();
45 PicoContainer parentContainer = (PicoContainer) context.getAttribute(APP_CONTAINER_KEY);
46 assert parentContainer != null;
47 MutablePicoContainer container = new DefaultPicoContainer(parentContainer);
48 buildContainer(event, container);
49 session.setAttribute(HTTP_SESSION_CONTAINER_KEY, container);
50 }
51
52 /***
53 * This will dispose the container inside an attribute of the HTTP session
54 * and remove the container attribute as well.
55 *
56 * @see HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
57 */
58 public final void sessionDestroyed(final HttpSessionEvent event) {
59 HttpSession session = event.getSession();
60 MutablePicoContainer container = (MutablePicoContainer) session.getAttribute(HTTP_SESSION_CONTAINER_KEY);
61 assert container != null;
62 container.dispose();
63 session.removeAttribute(HTTP_SESSION_CONTAINER_KEY);
64 }
65 }