PageRenderTime 102ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 1ms

/extensions/servlet/test/com/google/inject/servlet/ServletTest.java

https://gitlab.com/metamorphiccode/guice
Java | 471 lines | 375 code | 76 blank | 20 comment | 4 complexity | 804e289d866a508e6e8ebb98827b7358 MD5 | raw file
  1. /**
  2. * Copyright (C) 2006 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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 com.google.inject.servlet;
  17. import static com.google.inject.Asserts.assertContains;
  18. import static com.google.inject.Asserts.reserialize;
  19. import static com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest;
  20. import static com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse;
  21. import static java.lang.annotation.ElementType.FIELD;
  22. import static java.lang.annotation.ElementType.METHOD;
  23. import static java.lang.annotation.ElementType.PARAMETER;
  24. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  25. import com.google.common.collect.ImmutableMap;
  26. import com.google.common.collect.Lists;
  27. import com.google.inject.AbstractModule;
  28. import com.google.inject.BindingAnnotation;
  29. import com.google.inject.CreationException;
  30. import com.google.inject.Guice;
  31. import com.google.inject.Inject;
  32. import com.google.inject.Injector;
  33. import com.google.inject.Key;
  34. import com.google.inject.Module;
  35. import com.google.inject.Provider;
  36. import com.google.inject.Provides;
  37. import com.google.inject.ProvisionException;
  38. import com.google.inject.internal.Errors;
  39. import com.google.inject.name.Named;
  40. import com.google.inject.name.Names;
  41. import com.google.inject.servlet.ServletScopes.NullObject;
  42. import com.google.inject.util.Providers;
  43. import junit.framework.TestCase;
  44. import java.io.IOException;
  45. import java.io.Serializable;
  46. import java.lang.annotation.Retention;
  47. import java.lang.annotation.Target;
  48. import java.util.Map;
  49. import javax.servlet.Filter;
  50. import javax.servlet.FilterChain;
  51. import javax.servlet.FilterConfig;
  52. import javax.servlet.ServletException;
  53. import javax.servlet.ServletRequest;
  54. import javax.servlet.ServletResponse;
  55. import javax.servlet.http.HttpServlet;
  56. import javax.servlet.http.HttpServletRequest;
  57. import javax.servlet.http.HttpServletRequestWrapper;
  58. import javax.servlet.http.HttpServletResponse;
  59. import javax.servlet.http.HttpServletResponseWrapper;
  60. import javax.servlet.http.HttpSession;
  61. /**
  62. * @author crazybob@google.com (Bob Lee)
  63. */
  64. public class ServletTest extends TestCase {
  65. private static final Key<HttpServletRequest> HTTP_REQ_KEY = Key.get(HttpServletRequest.class);
  66. private static final Key<HttpServletResponse> HTTP_RESP_KEY = Key.get(HttpServletResponse.class);
  67. private static final Key<Map<String, String[]>> REQ_PARAMS_KEY
  68. = new Key<Map<String, String[]>>(RequestParameters.class) {};
  69. private static final Key<InRequest> IN_REQUEST_NULL_KEY = Key.get(InRequest.class, Null.class);
  70. private static final Key<InSession> IN_SESSION_KEY = Key.get(InSession.class);
  71. private static final Key<InSession> IN_SESSION_NULL_KEY = Key.get(InSession.class, Null.class);
  72. @Override
  73. public void setUp() {
  74. //we need to clear the reference to the pipeline every test =(
  75. GuiceFilter.reset();
  76. }
  77. public void testScopeExceptions() throws Exception {
  78. Injector injector = Guice.createInjector(new AbstractModule() {
  79. @Override protected void configure() {
  80. install(new ServletModule());
  81. }
  82. @Provides @RequestScoped String provideString() { return "foo"; }
  83. @Provides @SessionScoped Integer provideInteger() { return 1; }
  84. @Provides @RequestScoped @Named("foo") String provideNamedString() { return "foo"; }
  85. });
  86. try {
  87. injector.getInstance(String.class);
  88. fail();
  89. } catch(ProvisionException oose) {
  90. assertContains(oose.getMessage(), "Cannot access scoped [java.lang.String].");
  91. }
  92. try {
  93. injector.getInstance(Integer.class);
  94. fail();
  95. } catch(ProvisionException oose) {
  96. assertContains(oose.getMessage(), "Cannot access scoped [java.lang.Integer].");
  97. }
  98. Key<?> key = Key.get(String.class, Names.named("foo"));
  99. try {
  100. injector.getInstance(key);
  101. fail();
  102. } catch(ProvisionException oose) {
  103. assertContains(oose.getMessage(), "Cannot access scoped [" + Errors.convert(key) + "]");
  104. }
  105. }
  106. public void testRequestAndResponseBindings() throws Exception {
  107. final Injector injector = createInjector();
  108. final HttpServletRequest request = newFakeHttpServletRequest();
  109. final HttpServletResponse response = newFakeHttpServletResponse();
  110. final boolean[] invoked = new boolean[1];
  111. GuiceFilter filter = new GuiceFilter();
  112. FilterChain filterChain = new FilterChain() {
  113. public void doFilter(ServletRequest servletRequest,
  114. ServletResponse servletResponse) {
  115. invoked[0] = true;
  116. assertSame(request, servletRequest);
  117. assertSame(request, injector.getInstance(ServletRequest.class));
  118. assertSame(request, injector.getInstance(HTTP_REQ_KEY));
  119. assertSame(response, servletResponse);
  120. assertSame(response, injector.getInstance(ServletResponse.class));
  121. assertSame(response, injector.getInstance(HTTP_RESP_KEY));
  122. assertSame(servletRequest.getParameterMap(), injector.getInstance(REQ_PARAMS_KEY));
  123. }
  124. };
  125. filter.doFilter(request, response, filterChain);
  126. assertTrue(invoked[0]);
  127. }
  128. public void testRequestAndResponseBindings_wrappingFilter() throws Exception {
  129. final HttpServletRequest request = newFakeHttpServletRequest();
  130. final ImmutableMap<String, String[]> wrappedParamMap
  131. = ImmutableMap.of("wrap", new String[]{"a", "b"});
  132. final HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {
  133. @Override public Map getParameterMap() {
  134. return wrappedParamMap;
  135. }
  136. @Override public Object getAttribute(String attr) {
  137. // Ensure that attributes are stored on the original request object.
  138. throw new UnsupportedOperationException();
  139. }
  140. };
  141. final HttpServletResponse response = newFakeHttpServletResponse();
  142. final HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
  143. final boolean[] filterInvoked = new boolean[1];
  144. final Injector injector = createInjector(new ServletModule() {
  145. @Override protected void configureServlets() {
  146. filter("/*").through(new Filter() {
  147. @Inject Provider<ServletRequest> servletReqProvider;
  148. @Inject Provider<HttpServletRequest> reqProvider;
  149. @Inject Provider<ServletResponse> servletRespProvider;
  150. @Inject Provider<HttpServletResponse> respProvider;
  151. public void init(FilterConfig filterConfig) {}
  152. public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
  153. throws IOException, ServletException {
  154. filterInvoked[0] = true;
  155. assertSame(req, servletReqProvider.get());
  156. assertSame(req, reqProvider.get());
  157. assertSame(resp, servletRespProvider.get());
  158. assertSame(resp, respProvider.get());
  159. chain.doFilter(requestWrapper, responseWrapper);
  160. assertSame(req, reqProvider.get());
  161. assertSame(resp, respProvider.get());
  162. }
  163. public void destroy() {}
  164. });
  165. }
  166. });
  167. GuiceFilter filter = new GuiceFilter();
  168. final boolean[] chainInvoked = new boolean[1];
  169. FilterChain filterChain = new FilterChain() {
  170. public void doFilter(ServletRequest servletRequest,
  171. ServletResponse servletResponse) {
  172. chainInvoked[0] = true;
  173. assertSame(requestWrapper, servletRequest);
  174. assertSame(requestWrapper, injector.getInstance(ServletRequest.class));
  175. assertSame(requestWrapper, injector.getInstance(HTTP_REQ_KEY));
  176. assertSame(responseWrapper, servletResponse);
  177. assertSame(responseWrapper, injector.getInstance(ServletResponse.class));
  178. assertSame(responseWrapper, injector.getInstance(HTTP_RESP_KEY));
  179. assertSame(servletRequest.getParameterMap(), injector.getInstance(REQ_PARAMS_KEY));
  180. InRequest inRequest = injector.getInstance(InRequest.class);
  181. assertSame(inRequest, injector.getInstance(InRequest.class));
  182. }
  183. };
  184. filter.doFilter(request, response, filterChain);
  185. assertTrue(chainInvoked[0]);
  186. assertTrue(filterInvoked[0]);
  187. }
  188. public void testRequestAndResponseBindings_matchesPassedParameters() throws Exception {
  189. final int[] filterInvoked = new int[1];
  190. final boolean[] servletInvoked = new boolean[1];
  191. createInjector(new ServletModule() {
  192. @Override protected void configureServlets() {
  193. final HttpServletRequest[] previousReq = new HttpServletRequest[1];
  194. final HttpServletResponse[] previousResp = new HttpServletResponse[1];
  195. final Provider<ServletRequest> servletReqProvider = getProvider(ServletRequest.class);
  196. final Provider<HttpServletRequest> reqProvider = getProvider(HttpServletRequest.class);
  197. final Provider<ServletResponse> servletRespProvider = getProvider(ServletResponse.class);
  198. final Provider<HttpServletResponse> respProvider = getProvider(HttpServletResponse.class);
  199. Filter filter = new Filter() {
  200. public void init(FilterConfig filterConfig) {}
  201. public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
  202. throws IOException, ServletException {
  203. filterInvoked[0]++;
  204. assertSame(req, servletReqProvider.get());
  205. assertSame(req, reqProvider.get());
  206. if (previousReq[0] != null) {
  207. assertEquals(req, previousReq[0]);
  208. }
  209. assertSame(resp, servletRespProvider.get());
  210. assertSame(resp, respProvider.get());
  211. if (previousResp[0] != null) {
  212. assertEquals(resp, previousResp[0]);
  213. }
  214. chain.doFilter(
  215. previousReq[0] = new HttpServletRequestWrapper((HttpServletRequest) req),
  216. previousResp[0] = new HttpServletResponseWrapper((HttpServletResponse) resp));
  217. assertSame(req, reqProvider.get());
  218. assertSame(resp, respProvider.get());
  219. }
  220. public void destroy() {}
  221. };
  222. filter("/*").through(filter);
  223. filter("/*").through(filter); // filter twice to test wrapping in filters
  224. serve("/*").with(new HttpServlet() {
  225. @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
  226. servletInvoked[0] = true;
  227. assertSame(req, servletReqProvider.get());
  228. assertSame(req, reqProvider.get());
  229. assertSame(resp, servletRespProvider.get());
  230. assertSame(resp, respProvider.get());
  231. }
  232. });
  233. }
  234. });
  235. GuiceFilter filter = new GuiceFilter();
  236. filter.doFilter(newFakeHttpServletRequest(), newFakeHttpServletResponse(), new FilterChain() {
  237. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
  238. throw new IllegalStateException("Shouldn't get here");
  239. }
  240. });
  241. assertEquals(2, filterInvoked[0]);
  242. assertTrue(servletInvoked[0]);
  243. }
  244. public void testNewRequestObject()
  245. throws CreationException, IOException, ServletException {
  246. final Injector injector = createInjector();
  247. final HttpServletRequest request = newFakeHttpServletRequest();
  248. GuiceFilter filter = new GuiceFilter();
  249. final boolean[] invoked = new boolean[1];
  250. FilterChain filterChain = new FilterChain() {
  251. public void doFilter(ServletRequest servletRequest,
  252. ServletResponse servletResponse) {
  253. invoked[0] = true;
  254. assertNotNull(injector.getInstance(InRequest.class));
  255. assertNull(injector.getInstance(IN_REQUEST_NULL_KEY));
  256. }
  257. };
  258. filter.doFilter(request, null, filterChain);
  259. assertTrue(invoked[0]);
  260. }
  261. public void testExistingRequestObject()
  262. throws CreationException, IOException, ServletException {
  263. final Injector injector = createInjector();
  264. final HttpServletRequest request = newFakeHttpServletRequest();
  265. GuiceFilter filter = new GuiceFilter();
  266. final boolean[] invoked = new boolean[1];
  267. FilterChain filterChain = new FilterChain() {
  268. public void doFilter(ServletRequest servletRequest,
  269. ServletResponse servletResponse) {
  270. invoked[0] = true;
  271. InRequest inRequest = injector.getInstance(InRequest.class);
  272. assertSame(inRequest, injector.getInstance(InRequest.class));
  273. assertNull(injector.getInstance(IN_REQUEST_NULL_KEY));
  274. assertNull(injector.getInstance(IN_REQUEST_NULL_KEY));
  275. }
  276. };
  277. filter.doFilter(request, null, filterChain);
  278. assertTrue(invoked[0]);
  279. }
  280. public void testNewSessionObject()
  281. throws CreationException, IOException, ServletException {
  282. final Injector injector = createInjector();
  283. final HttpServletRequest request = newFakeHttpServletRequest();
  284. GuiceFilter filter = new GuiceFilter();
  285. final boolean[] invoked = new boolean[1];
  286. FilterChain filterChain = new FilterChain() {
  287. public void doFilter(ServletRequest servletRequest,
  288. ServletResponse servletResponse) {
  289. invoked[0] = true;
  290. assertNotNull(injector.getInstance(InSession.class));
  291. assertNull(injector.getInstance(IN_SESSION_NULL_KEY));
  292. }
  293. };
  294. filter.doFilter(request, null, filterChain);
  295. assertTrue(invoked[0]);
  296. }
  297. public void testExistingSessionObject()
  298. throws CreationException, IOException, ServletException {
  299. final Injector injector = createInjector();
  300. final HttpServletRequest request = newFakeHttpServletRequest();
  301. GuiceFilter filter = new GuiceFilter();
  302. final boolean[] invoked = new boolean[1];
  303. FilterChain filterChain = new FilterChain() {
  304. public void doFilter(ServletRequest servletRequest,
  305. ServletResponse servletResponse) {
  306. invoked[0] = true;
  307. InSession inSession = injector.getInstance(InSession.class);
  308. assertSame(inSession, injector.getInstance(InSession.class));
  309. assertNull(injector.getInstance(IN_SESSION_NULL_KEY));
  310. assertNull(injector.getInstance(IN_SESSION_NULL_KEY));
  311. }
  312. };
  313. filter.doFilter(request, null, filterChain);
  314. assertTrue(invoked[0]);
  315. }
  316. public void testHttpSessionIsSerializable() throws Exception {
  317. final Injector injector = createInjector();
  318. final HttpServletRequest request = newFakeHttpServletRequest();
  319. final HttpSession session = request.getSession();
  320. GuiceFilter filter = new GuiceFilter();
  321. final boolean[] invoked = new boolean[1];
  322. FilterChain filterChain = new FilterChain() {
  323. public void doFilter(ServletRequest servletRequest,
  324. ServletResponse servletResponse) {
  325. invoked[0] = true;
  326. assertNotNull(injector.getInstance(InSession.class));
  327. assertNull(injector.getInstance(IN_SESSION_NULL_KEY));
  328. }
  329. };
  330. filter.doFilter(request, null, filterChain);
  331. assertTrue(invoked[0]);
  332. HttpSession deserializedSession = reserialize(session);
  333. String inSessionKey = IN_SESSION_KEY.toString();
  334. String inSessionNullKey = IN_SESSION_NULL_KEY.toString();
  335. assertTrue(deserializedSession.getAttribute(inSessionKey) instanceof InSession);
  336. assertEquals(NullObject.INSTANCE, deserializedSession.getAttribute(inSessionNullKey));
  337. }
  338. public void testGuiceFilterConstructors() throws Exception {
  339. final RuntimeException servletException = new RuntimeException();
  340. final RuntimeException chainException = new RuntimeException();
  341. final Injector injector = createInjector(new ServletModule() {
  342. @Override protected void configureServlets() {
  343. serve("/*").with(new HttpServlet() {
  344. @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
  345. throw servletException;
  346. }
  347. });
  348. }
  349. });
  350. final HttpServletRequest request = newFakeHttpServletRequest();
  351. FilterChain filterChain = new FilterChain() {
  352. public void doFilter(ServletRequest servletRequest,
  353. ServletResponse servletResponse) {
  354. throw chainException;
  355. }
  356. };
  357. try {
  358. new GuiceFilter().doFilter(request, null, filterChain);
  359. fail();
  360. } catch (RuntimeException e) {
  361. assertSame(servletException, e);
  362. }
  363. try {
  364. injector.getInstance(GuiceFilter.class).doFilter(request, null, filterChain);
  365. fail();
  366. } catch (RuntimeException e) {
  367. assertSame(servletException, e);
  368. }
  369. try {
  370. injector.getInstance(Key.get(GuiceFilter.class, ScopingOnly.class))
  371. .doFilter(request, null, filterChain);
  372. fail();
  373. } catch (RuntimeException e) {
  374. assertSame(chainException, e);
  375. }
  376. }
  377. private Injector createInjector(Module... modules) throws CreationException {
  378. return Guice.createInjector(Lists.<Module>asList(new AbstractModule() {
  379. @Override
  380. protected void configure() {
  381. install(new ServletModule());
  382. bind(InSession.class);
  383. bind(IN_SESSION_NULL_KEY).toProvider(Providers.<InSession>of(null)).in(SessionScoped.class);
  384. bind(InRequest.class);
  385. bind(IN_REQUEST_NULL_KEY).toProvider(Providers.<InRequest>of(null)).in(RequestScoped.class);
  386. }
  387. }, modules));
  388. }
  389. @SessionScoped
  390. static class InSession implements Serializable {}
  391. @RequestScoped
  392. static class InRequest {}
  393. @BindingAnnotation @Retention(RUNTIME) @Target({PARAMETER, METHOD, FIELD})
  394. @interface Null {}
  395. }