Search in sources :

Example 1 with Filter

use of javax.servlet.Filter in project jetty.project by eclipse.

the class WebFilterAnnotation method apply.

/**
     * @see DiscoveredAnnotation#apply()
     */
public void apply() {
    // TODO verify against rules for annotation v descriptor
    Class clazz = getTargetClass();
    if (clazz == null) {
        LOG.warn(_className + " cannot be loaded");
        return;
    }
    //Servlet Spec 8.1.2
    if (!Filter.class.isAssignableFrom(clazz)) {
        LOG.warn(clazz.getName() + " is not assignable from javax.servlet.Filter");
        return;
    }
    MetaData metaData = _context.getMetaData();
    WebFilter filterAnnotation = (WebFilter) clazz.getAnnotation(WebFilter.class);
    if (filterAnnotation.value().length > 0 && filterAnnotation.urlPatterns().length > 0) {
        LOG.warn(clazz.getName() + " defines both @WebFilter.value and @WebFilter.urlPatterns");
        return;
    }
    String name = (filterAnnotation.filterName().equals("") ? clazz.getName() : filterAnnotation.filterName());
    String[] urlPatterns = filterAnnotation.value();
    if (urlPatterns.length == 0)
        urlPatterns = filterAnnotation.urlPatterns();
    FilterHolder holder = _context.getServletHandler().getFilter(name);
    if (holder == null) {
        //Filter with this name does not already exist, so add it
        holder = _context.getServletHandler().newFilterHolder(new Source(Source.Origin.ANNOTATION, clazz.getName()));
        holder.setName(name);
        holder.setHeldClass(clazz);
        metaData.setOrigin(name + ".filter.filter-class", filterAnnotation, clazz);
        holder.setDisplayName(filterAnnotation.displayName());
        metaData.setOrigin(name + ".filter.display-name", filterAnnotation, clazz);
        for (WebInitParam ip : filterAnnotation.initParams()) {
            holder.setInitParameter(ip.name(), ip.value());
            metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz);
        }
        FilterMapping mapping = new FilterMapping();
        mapping.setFilterName(holder.getName());
        if (urlPatterns.length > 0) {
            ArrayList<String> paths = new ArrayList<String>();
            for (String s : urlPatterns) {
                paths.add(ServletPathSpec.normalize(s));
            }
            mapping.setPathSpecs(paths.toArray(new String[paths.size()]));
        }
        if (filterAnnotation.servletNames().length > 0) {
            ArrayList<String> names = new ArrayList<String>();
            for (String s : filterAnnotation.servletNames()) {
                names.add(s);
            }
            mapping.setServletNames(names.toArray(new String[names.size()]));
        }
        EnumSet<DispatcherType> dispatcherSet = EnumSet.noneOf(DispatcherType.class);
        for (DispatcherType d : filterAnnotation.dispatcherTypes()) {
            dispatcherSet.add(d);
        }
        mapping.setDispatcherTypes(dispatcherSet);
        metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz);
        holder.setAsyncSupported(filterAnnotation.asyncSupported());
        metaData.setOrigin(name + ".filter.async-supported", filterAnnotation, clazz);
        _context.getServletHandler().addFilter(holder);
        _context.getServletHandler().addFilterMapping(mapping);
    } else {
        //init-params of the same name.
        for (WebInitParam ip : filterAnnotation.initParams()) {
            //if (holder.getInitParameter(ip.name()) == null)
            if (metaData.getOrigin(name + ".filter.init-param." + ip.name()) == Origin.NotSet) {
                holder.setInitParameter(ip.name(), ip.value());
                metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz);
            }
        }
        FilterMapping[] mappings = _context.getServletHandler().getFilterMappings();
        boolean mappingExists = false;
        if (mappings != null) {
            for (FilterMapping m : mappings) {
                if (m.getFilterName().equals(name)) {
                    mappingExists = true;
                    break;
                }
            }
        }
        //from the annotation
        if (!mappingExists) {
            FilterMapping mapping = new FilterMapping();
            mapping.setFilterName(holder.getName());
            if (urlPatterns.length > 0) {
                ArrayList<String> paths = new ArrayList<String>();
                for (String s : urlPatterns) {
                    paths.add(ServletPathSpec.normalize(s));
                }
                mapping.setPathSpecs(paths.toArray(new String[paths.size()]));
            }
            if (filterAnnotation.servletNames().length > 0) {
                ArrayList<String> names = new ArrayList<String>();
                for (String s : filterAnnotation.servletNames()) {
                    names.add(s);
                }
                mapping.setServletNames(names.toArray(new String[names.size()]));
            }
            EnumSet<DispatcherType> dispatcherSet = EnumSet.noneOf(DispatcherType.class);
            for (DispatcherType d : filterAnnotation.dispatcherTypes()) {
                dispatcherSet.add(d);
            }
            mapping.setDispatcherTypes(dispatcherSet);
            _context.getServletHandler().addFilterMapping(mapping);
            metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz);
        }
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) WebFilter(javax.servlet.annotation.WebFilter) ArrayList(java.util.ArrayList) FilterMapping(org.eclipse.jetty.servlet.FilterMapping) Source(org.eclipse.jetty.servlet.Source) WebFilter(javax.servlet.annotation.WebFilter) Filter(javax.servlet.Filter) MetaData(org.eclipse.jetty.webapp.MetaData) WebInitParam(javax.servlet.annotation.WebInitParam) DispatcherType(javax.servlet.DispatcherType)

Example 2 with Filter

use of javax.servlet.Filter in project jetty.project by eclipse.

the class ProxyServletTest method testResponseHeadersAreNotRemoved.

@Test
public void testResponseHeadersAreNotRemoved() throws Exception {
    startServer(new EmptyHttpServlet());
    startProxy();
    proxyContext.stop();
    final String headerName = "X-Test";
    final String headerValue = "test-value";
    proxyContext.addFilter(new FilterHolder(new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            ((HttpServletResponse) response).addHeader(headerName, headerValue);
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }
    }), "/*", EnumSet.of(DispatcherType.REQUEST));
    proxyContext.start();
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(headerValue, response.getHeaders().get(headerName));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Filter(javax.servlet.Filter) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) FilterConfig(javax.servlet.FilterConfig) Test(org.junit.Test)

Example 3 with Filter

use of javax.servlet.Filter in project druid by druid-io.

the class JettyTest method setupInjector.

@Override
protected Injector setupInjector() {
    return Initialization.makeInjectorWithModules(GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of(new Module() {

        @Override
        public void configure(Binder binder) {
            JsonConfigProvider.bindInstance(binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", null));
            binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class);
            Multibinder<ServletFilterHolder> multibinder = Multibinder.newSetBinder(binder, ServletFilterHolder.class);
            multibinder.addBinding().toInstance(new ServletFilterHolder() {

                @Override
                public String getPath() {
                    return "/*";
                }

                @Override
                public Map<String, String> getInitParameters() {
                    return null;
                }

                @Override
                public Class<? extends Filter> getFilterClass() {
                    return DummyAuthFilter.class;
                }

                @Override
                public Filter getFilter() {
                    return null;
                }

                @Override
                public EnumSet<DispatcherType> getDispatcherType() {
                    return null;
                }
            });
            Jerseys.addResource(binder, SlowResource.class);
            Jerseys.addResource(binder, ExceptionResource.class);
            Jerseys.addResource(binder, DefaultResource.class);
            LifecycleModule.register(binder, Server.class);
        }
    }));
}
Also used : EnumSet(java.util.EnumSet) Self(io.druid.guice.annotations.Self) ServletFilterHolder(io.druid.server.initialization.jetty.ServletFilterHolder) Binder(com.google.inject.Binder) Filter(javax.servlet.Filter) DruidNode(io.druid.server.DruidNode) Module(com.google.inject.Module) LifecycleModule(io.druid.guice.LifecycleModule) Map(java.util.Map)

Example 4 with Filter

use of javax.servlet.Filter in project hadoop by apache.

the class TestCheckUploadContentTypeFilter method test.

private void test(String method, String operation, String contentType, boolean upload, boolean error) throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.reset(request);
    Mockito.when(request.getMethod()).thenReturn(method);
    Mockito.when(request.getParameter(HttpFSFileSystem.OP_PARAM)).thenReturn(operation);
    Mockito.when(request.getParameter(HttpFSParametersProvider.DataParam.NAME)).thenReturn(Boolean.toString(upload));
    Mockito.when(request.getContentType()).thenReturn(contentType);
    FilterChain chain = Mockito.mock(FilterChain.class);
    Filter filter = new CheckUploadContentTypeFilter();
    filter.doFilter(request, response, chain);
    if (error) {
        Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_BAD_REQUEST), Mockito.contains("Data upload"));
    } else {
        Mockito.verify(chain).doFilter(request, response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Filter(javax.servlet.Filter) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 5 with Filter

use of javax.servlet.Filter in project atmosphere by Atmosphere.

the class ReflectorServletProcessor method loadFilterClasses.

private void loadFilterClasses(ServletConfig sc, URLClassLoader urlC) throws Exception {
    for (Map.Entry<String, String> fClassAndName : filtersClassAndNames.entrySet()) {
        String fClass = fClassAndName.getKey();
        String filterName = fClassAndName.getValue();
        Filter f = loadFilter(urlC, fClass);
        if (filterName == null) {
            if (sc.getInitParameter(APPLICATION_NAME) != null) {
                filterName = sc.getInitParameter(APPLICATION_NAME);
            } else {
                filterName = f.getClass().getSimpleName();
            }
        }
        FilterConfigImpl fc = new FilterConfigImpl(sc);
        fc.setFilter(f);
        fc.setFilterName(filterName);
        filterChain.addFilter(fc);
        logger.info("Installing Filter {}", filterName);
    }
}
Also used : FilterConfigImpl(org.atmosphere.util.FilterConfigImpl) Filter(javax.servlet.Filter) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Filter (javax.servlet.Filter)189 FilterChain (javax.servlet.FilterChain)69 Test (org.junit.Test)57 HttpServletRequest (javax.servlet.http.HttpServletRequest)55 HttpServletResponse (javax.servlet.http.HttpServletResponse)46 ServletRequest (javax.servlet.ServletRequest)44 ServletResponse (javax.servlet.ServletResponse)44 ServletException (javax.servlet.ServletException)30 FilterConfig (javax.servlet.FilterConfig)26 IOException (java.io.IOException)25 ServletContext (javax.servlet.ServletContext)20 Injector (com.google.inject.Injector)18 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)17 OncePerRequestFilter (org.springframework.web.filter.OncePerRequestFilter)14 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12 Map (java.util.Map)10 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)10 ArrayList (java.util.ArrayList)8 Hashtable (java.util.Hashtable)8 DispatcherType (javax.servlet.DispatcherType)8