1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.directwebremoting.guice;
17
18 import com.google.inject.Injector;
19
20 import java.util.LinkedList;
21
22 import javax.servlet.ServletContext;
23
24 import org.directwebremoting.WebContext;
25 import org.directwebremoting.WebContextFactory;
26 import static org.directwebremoting.guice.DwrGuiceServletContextListener.getPublishedInjector;
27
28
29 /**
30 * Utilities for making Injector and ServletContext instances available.
31 * @author Tim Peierls [tim at peierls dot net]
32 */
33 class DwrGuiceUtil
34 {
35 /**
36 * Returns the Injector instance published in the current servlet context.
37 */
38 static Injector getInjector()
39 {
40 return getPublishedInjector(getServletContext());
41 }
42
43 /**
44 * Gets the servlet context from the current web context, if one exists,
45 * otherwise gets it from the thread-local stash.
46 */
47 static ServletContext getServletContext()
48 {
49 WebContext webcx = WebContextFactory.get();
50 if (webcx != null)
51 {
52 return webcx.getServletContext();
53 }
54 else
55 {
56 return servletContexts.get().getFirst();
57 }
58 }
59
60 /**
61 * Thread-locally pushes a servlet context. Call {@link #popServletContext}
62 * in a finally block when calling this method.
63 */
64 static void pushServletContext(ServletContext context)
65 {
66 servletContexts.get().addFirst(context);
67 }
68
69 /**
70 * Pops a thread-locally stashed servlet context. Call this in
71 * a finally block when {@link #pushServletContext} is called.
72 */
73 static void popServletContext()
74 {
75 servletContexts.get().removeFirst();
76 }
77
78 private static final ThreadLocal<LinkedList<ServletContext>> servletContexts =
79 new ThreadLocal<LinkedList<ServletContext>>()
80 {
81 protected LinkedList<ServletContext> initialValue()
82 {
83 return new LinkedList<ServletContext>();
84 }
85 };
86 }