01: /*
02: * Copyright 2007 Tim Peierls
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
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: * Utilities for making Injector and ServletContext instances available.
30: * @author Tim Peierls [tim at peierls dot net]
31: */
32: class DwrGuiceUtil {
33: /**
34: * Returns the Injector instance published in the current servlet context.
35: */
36: static Injector getInjector() {
37: return getPublishedInjector(getServletContext());
38: }
39:
40: /**
41: * Gets the servlet context from the current web context, if one exists,
42: * otherwise gets it from the thread-local stash.
43: */
44: static ServletContext getServletContext() {
45: WebContext webcx = WebContextFactory.get();
46: if (webcx != null) {
47: return webcx.getServletContext();
48: } else {
49: return servletContexts.get().getFirst();
50: }
51: }
52:
53: /**
54: * Thread-locally pushes a servlet context. Call {@link #popServletContext}
55: * in a finally block when calling this method.
56: */
57: static void pushServletContext(ServletContext context) {
58: servletContexts.get().addFirst(context);
59: }
60:
61: /**
62: * Pops a thread-locally stashed servlet context. Call this in
63: * a finally block when {@link #pushServletContext} is called.
64: */
65: static void popServletContext() {
66: servletContexts.get().removeFirst();
67: }
68:
69: private static final ThreadLocal<LinkedList<ServletContext>> servletContexts = new ThreadLocal<LinkedList<ServletContext>>() {
70: @Override
71: protected LinkedList<ServletContext> initialValue() {
72: return new LinkedList<ServletContext>();
73: }
74: };
75: }
|