Search in sources :

Example 71 with Filter

use of javax.servlet.Filter in project guice by google.

the class ServletTest method testRequestAndResponseBindings_matchesPassedParameters.

public void testRequestAndResponseBindings_matchesPassedParameters() throws Exception {
    final int[] filterInvoked = new int[1];
    final boolean[] servletInvoked = new boolean[1];
    createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {
            final HttpServletRequest[] previousReq = new HttpServletRequest[1];
            final HttpServletResponse[] previousResp = new HttpServletResponse[1];
            final Provider<ServletRequest> servletReqProvider = getProvider(ServletRequest.class);
            final Provider<HttpServletRequest> reqProvider = getProvider(HttpServletRequest.class);
            final Provider<ServletResponse> servletRespProvider = getProvider(ServletResponse.class);
            final Provider<HttpServletResponse> respProvider = getProvider(HttpServletResponse.class);
            Filter filter = new Filter() {

                @Override
                public void init(FilterConfig filterConfig) {
                }

                @Override
                public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
                    filterInvoked[0]++;
                    assertSame(req, servletReqProvider.get());
                    assertSame(req, reqProvider.get());
                    if (previousReq[0] != null) {
                        assertEquals(req, previousReq[0]);
                    }
                    assertSame(resp, servletRespProvider.get());
                    assertSame(resp, respProvider.get());
                    if (previousResp[0] != null) {
                        assertEquals(resp, previousResp[0]);
                    }
                    chain.doFilter(previousReq[0] = new HttpServletRequestWrapper((HttpServletRequest) req), previousResp[0] = new HttpServletResponseWrapper((HttpServletResponse) resp));
                    assertSame(req, reqProvider.get());
                    assertSame(resp, respProvider.get());
                }

                @Override
                public void destroy() {
                }
            };
            filter("/*").through(filter);
            // filter twice to test wrapping in filters
            filter("/*").through(filter);
            serve("/*").with(new HttpServlet() {

                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
                    servletInvoked[0] = true;
                    assertSame(req, servletReqProvider.get());
                    assertSame(req, reqProvider.get());
                    assertSame(resp, servletRespProvider.get());
                    assertSame(resp, respProvider.get());
                }
            });
        }
    });
    GuiceFilter filter = new GuiceFilter();
    filter.doFilter(newFakeHttpServletRequest(), newFakeHttpServletResponse(), new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
            throw new IllegalStateException("Shouldn't get here");
        }
    });
    assertEquals(2, filterInvoked[0]);
    assertTrue(servletInvoked[0]);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletTestUtils.newFakeHttpServletRequest(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest) ServletTestUtils.newFakeHttpServletResponse(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServlet(javax.servlet.http.HttpServlet) FilterChain(javax.servlet.FilterChain) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) ServletTestUtils.newFakeHttpServletResponse(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Provider(com.google.inject.Provider) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletTestUtils.newFakeHttpServletRequest(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest) ServletException(javax.servlet.ServletException) Filter(javax.servlet.Filter) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) FilterConfig(javax.servlet.FilterConfig)

Example 72 with Filter

use of javax.servlet.Filter in project guice by google.

the class ServletTest method testRequestAndResponseBindings_wrappingFilter.

public void testRequestAndResponseBindings_wrappingFilter() throws Exception {
    final HttpServletRequest request = newFakeHttpServletRequest();
    final ImmutableMap<String, String[]> wrappedParamMap = ImmutableMap.of("wrap", new String[] { "a", "b" });
    final HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {

        @Override
        public Map<String, String[]> getParameterMap() {
            return wrappedParamMap;
        }

        @Override
        public Object getAttribute(String attr) {
            // Ensure that attributes are stored on the original request object.
            throw new UnsupportedOperationException();
        }
    };
    final HttpServletResponse response = newFakeHttpServletResponse();
    final HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
    final boolean[] filterInvoked = new boolean[1];
    final Injector injector = createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {
            filter("/*").through(new Filter() {

                @Inject
                Provider<ServletRequest> servletReqProvider;

                @Inject
                Provider<HttpServletRequest> reqProvider;

                @Inject
                Provider<ServletResponse> servletRespProvider;

                @Inject
                Provider<HttpServletResponse> respProvider;

                @Override
                public void init(FilterConfig filterConfig) {
                }

                @Override
                public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
                    filterInvoked[0] = true;
                    assertSame(req, servletReqProvider.get());
                    assertSame(req, reqProvider.get());
                    assertSame(resp, servletRespProvider.get());
                    assertSame(resp, respProvider.get());
                    chain.doFilter(requestWrapper, responseWrapper);
                    assertSame(req, reqProvider.get());
                    assertSame(resp, respProvider.get());
                }

                @Override
                public void destroy() {
                }
            });
        }
    });
    GuiceFilter filter = new GuiceFilter();
    final boolean[] chainInvoked = new boolean[1];
    FilterChain filterChain = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
            chainInvoked[0] = true;
            assertSame(requestWrapper, servletRequest);
            assertSame(requestWrapper, injector.getInstance(ServletRequest.class));
            assertSame(requestWrapper, injector.getInstance(HTTP_REQ_KEY));
            assertSame(responseWrapper, servletResponse);
            assertSame(responseWrapper, injector.getInstance(ServletResponse.class));
            assertSame(responseWrapper, injector.getInstance(HTTP_RESP_KEY));
            assertSame(servletRequest.getParameterMap(), injector.getInstance(REQ_PARAMS_KEY));
            InRequest inRequest = injector.getInstance(InRequest.class);
            assertSame(inRequest, injector.getInstance(InRequest.class));
        }
    };
    filter.doFilter(request, response, filterChain);
    assertTrue(chainInvoked[0]);
    assertTrue(filterInvoked[0]);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletTestUtils.newFakeHttpServletRequest(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest) ServletTestUtils.newFakeHttpServletResponse(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) FilterChain(javax.servlet.FilterChain) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) ServletTestUtils.newFakeHttpServletResponse(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Provider(com.google.inject.Provider) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletTestUtils.newFakeHttpServletRequest(com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) Filter(javax.servlet.Filter) Injector(com.google.inject.Injector) FilterConfig(javax.servlet.FilterConfig)

Example 73 with Filter

use of javax.servlet.Filter in project guice by google.

the class FilterDefinitionTest method testFilterInitAndConfig.

public final void testFilterInitAndConfig() throws ServletException {
    Injector injector = createMock(Injector.class);
    Binding<Filter> binding = createMock(Binding.class);
    final MockFilter mockFilter = new MockFilter();
    expect(binding.acceptScopingVisitor((BindingScopingVisitor<Boolean>) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(Filter.class))).andReturn(binding);
    expect(injector.getInstance(Key.get(Filter.class))).andReturn(mockFilter).anyTimes();
    replay(binding, injector);
    // some init params
    // noinspection SSBasedInspection
    final Map<String, String> initParams = new ImmutableMap.Builder<String, String>().put("ahsd", "asdas24dok").put("ahssd", "asdasd124ok").buildOrThrow();
    ServletContext servletContext = createMock(ServletContext.class);
    final String contextName = "thing__!@@44";
    expect(servletContext.getServletContextName()).andReturn(contextName);
    replay(servletContext);
    String pattern = "/*";
    final FilterDefinition filterDef = new FilterDefinition(Key.get(Filter.class), UriPatternType.get(UriPatternType.SERVLET, pattern), initParams, null);
    filterDef.init(servletContext, injector, Sets.<Filter>newIdentityHashSet());
    assertTrue(filterDef.getFilter() instanceof MockFilter);
    final FilterConfig filterConfig = mockFilter.getConfig();
    assertTrue(null != filterConfig);
    assertEquals(contextName, filterConfig.getServletContext().getServletContextName());
    assertEquals(filterConfig.getFilterName(), Key.get(Filter.class).toString());
    final Enumeration<String> names = filterConfig.getInitParameterNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        assertTrue(initParams.containsKey(name));
        assertEquals(filterConfig.getInitParameter(name), initParams.get(name));
    }
    verify(binding, injector, servletContext);
}
Also used : ImmutableMap(com.google.common.collect.ImmutableMap) Filter(javax.servlet.Filter) Injector(com.google.inject.Injector) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig)

Example 74 with Filter

use of javax.servlet.Filter in project guice by google.

the class FilterDefinitionTest method testGetFilterIfMatchingNotMatching.

public void testGetFilterIfMatchingNotMatching() throws ServletException {
    String pattern = "/*";
    final FilterDefinition filterDef = new FilterDefinition(Key.get(Filter.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    HttpServletRequest servletRequest = createMock(HttpServletRequest.class);
    ServletContext servletContext = createMock(ServletContext.class);
    Injector injector = createMock(Injector.class);
    // Safe because mock will only ever return Filter
    @SuppressWarnings("unchecked") Binding<Filter> binding = createMock(Binding.class);
    final MockFilter mockFilter = new MockFilter() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        // suppress rest of chain...
        }
    };
    expect(injector.getBinding(Key.get(Filter.class))).andReturn(binding);
    expect(binding.acceptScopingVisitor((BindingScopingVisitor<Boolean>) anyObject())).andReturn(true);
    expect(injector.getInstance(Key.get(Filter.class))).andReturn(mockFilter).anyTimes();
    expect(servletRequest.getContextPath()).andReturn("/a_context_path");
    expect(servletRequest.getRequestURI()).andReturn("/test.html");
    replay(servletRequest, binding, injector);
    filterDef.init(servletContext, injector, Sets.<Filter>newIdentityHashSet());
    Filter filter = filterDef.getFilterIfMatching(servletRequest);
    assertNull(filter);
    verify(servletRequest, binding, injector);
}
Also used : ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) FilterChain(javax.servlet.FilterChain) HttpServletRequest(javax.servlet.http.HttpServletRequest) Filter(javax.servlet.Filter) Injector(com.google.inject.Injector) ServletContext(javax.servlet.ServletContext)

Example 75 with Filter

use of javax.servlet.Filter in project guice by google.

the class FilterDefinition method init.

public void init(final ServletContext servletContext, Injector injector, Set<Filter> initializedSoFar) throws ServletException {
    // This absolutely must be a singleton, and so is only initialized once.
    if (!Scopes.isSingleton(injector.getBinding(filterKey))) {
        throw new ServletException("Filters must be bound as singletons. " + filterKey + " was not bound in singleton scope.");
    }
    Filter filter = injector.getInstance(filterKey);
    this.filter.set(filter);
    // in the filter chain.
    if (initializedSoFar.contains(filter)) {
        return;
    }
    // initialize our filter with the configured context params and servlet context
    filter.init(new FilterConfig() {

        @Override
        public String getFilterName() {
            return filterKey.toString();
        }

        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public String getInitParameter(String s) {
            return initParams.get(s);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return Iterators.asEnumeration(initParams.keySet().iterator());
        }
    });
    initializedSoFar.add(filter);
}
Also used : ServletException(javax.servlet.ServletException) Enumeration(java.util.Enumeration) Filter(javax.servlet.Filter) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig)

Aggregations

Filter (javax.servlet.Filter)185 FilterChain (javax.servlet.FilterChain)67 Test (org.junit.Test)57 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 ServletRequest (javax.servlet.ServletRequest)43 ServletResponse (javax.servlet.ServletResponse)43 ServletException (javax.servlet.ServletException)28 FilterConfig (javax.servlet.FilterConfig)25 IOException (java.io.IOException)23 ServletContext (javax.servlet.ServletContext)20 Injector (com.google.inject.Injector)17 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)16 OncePerRequestFilter (org.springframework.web.filter.OncePerRequestFilter)13 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12 Map (java.util.Map)9 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)9 ArrayList (java.util.ArrayList)8 Hashtable (java.util.Hashtable)8 DispatcherType (javax.servlet.DispatcherType)8