Search in sources :

Example 26 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project jetty.project by eclipse.

the class CrossOriginFilterTest method testSimpleRequestWithWildcardOrigin.

@Test
public void testSimpleRequestWithWildcardOrigin() throws Exception {
    FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
    tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    CountDownLatch latch = new CountDownLatch(1);
    tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
    String origin = "http://foo.example.com";
    String request = "" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "Origin: " + origin + "\r\n" + "\r\n";
    String response = tester.getResponses(request);
    Assert.assertTrue(response.contains("HTTP/1.1 200"));
    Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
    Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
    Assert.assertTrue(!response.contains("Vary"));
    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 27 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project jetty.project by eclipse.

the class MultipartFilterTest method testBodyAlreadyConsumed.

@Test
public void testBodyAlreadyConsumed() throws Exception {
    tester.addServlet(NullServlet.class, "/null");
    FilterHolder holder = new FilterHolder();
    holder.setName("reader");
    holder.setFilter(new ReadAllFilter());
    tester.getContext().getServletHandler().addFilter(holder);
    FilterMapping mapping = new FilterMapping();
    mapping.setFilterName("reader");
    mapping.setPathSpec("/*");
    tester.getContext().getServletHandler().prependFilterMapping(mapping);
    String boundary = "XyXyXy";
    // generated and parsed test
    HttpTester.Request request = HttpTester.newRequest();
    HttpTester.Response response;
    request.setMethod("POST");
    request.setVersion("HTTP/1.0");
    request.setHeader("Host", "tester");
    request.setURI("/context/null");
    request.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    request.setContent("How now brown cow");
    try (StacklessLogging stackless = new StacklessLogging(ServletHandler.class)) {
        response = HttpTester.parseResponse(tester.getResponses(request.generate()));
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) FilterMapping(org.eclipse.jetty.servlet.FilterMapping) Matchers.containsString(org.hamcrest.Matchers.containsString) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) HttpTester(org.eclipse.jetty.http.HttpTester) Test(org.junit.Test)

Example 28 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project jetty.project by eclipse.

the class AltFilterTest method testEcho.

@Test
public void testEcho() throws Exception {
    WSServer wsb = new WSServer(testdir, "app");
    wsb.copyWebInf("alt-filter-web.xml");
    // the endpoint (extends javax.websocket.Endpoint)
    wsb.copyClass(BasicEchoSocket.class);
    try {
        wsb.start();
        URI uri = wsb.getServerBaseURI();
        WebAppContext webapp = wsb.createWebAppContext();
        wsb.deployWebapp(webapp);
        FilterHolder filterWebXml = webapp.getServletHandler().getFilter("wsuf-test");
        assertThat("Filter[wsuf-test]", filterWebXml, notNullValue());
        FilterHolder filterSCI = webapp.getServletHandler().getFilter("Jetty_WebSocketUpgradeFilter");
        assertThat("Filter[Jetty_WebSocketUpgradeFilter]", filterSCI, nullValue());
        WebSocketClient client = new WebSocketClient(bufferPool);
        try {
            client.start();
            JettyEchoSocket clientEcho = new JettyEchoSocket();
            Future<Session> future = client.connect(clientEcho, uri.resolve("echo"));
            // wait for connect
            future.get(1, TimeUnit.SECONDS);
            clientEcho.sendMessage("Hello Echo");
            Queue<String> msgs = clientEcho.awaitMessages(1);
            Assert.assertEquals("Expected message", "Hello Echo", msgs.poll());
        } finally {
            client.stop();
        }
    } finally {
        wsb.stop();
    }
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) URI(java.net.URI) Session(org.eclipse.jetty.websocket.api.Session) Test(org.junit.Test)

Example 29 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project jetty.project by eclipse.

the class WebSocketUpgradeFilterTest method data.

@Parameterized.Parameters(name = "{0}")
public static List<Object[]> data() {
    final WebSocketCreator infoCreator = (req, resp) -> new InfoSocket();
    List<Object[]> cases = new ArrayList<>();
    // Embedded WSUF.configureContext(), directly app-ws configuration
    cases.add(new Object[] { "wsuf.configureContext/Direct configure", (ServerProvider) () -> {
        Server server1 = new Server();
        ServerConnector connector = new ServerConnector(server1);
        connector.setPort(0);
        server1.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server1.setHandler(context);
        WebSocketUpgradeFilter wsuf = WebSocketUpgradeFilter.configureContext(context);
        wsuf.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        wsuf.addMapping("/info/*", infoCreator);
        server1.start();
        return server1;
    } });
    // Embedded WSUF.configureContext(), apply app-ws configuration via attribute
    cases.add(new Object[] { "wsuf.configureContext/Attribute based configure", (ServerProvider) () -> {
        Server server12 = new Server();
        ServerConnector connector = new ServerConnector(server12);
        connector.setPort(0);
        server12.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server12.setHandler(context);
        WebSocketUpgradeFilter.configureContext(context);
        NativeWebSocketConfiguration configuration = (NativeWebSocketConfiguration) context.getServletContext().getAttribute(NativeWebSocketConfiguration.class.getName());
        assertThat("NativeWebSocketConfiguration", configuration, notNullValue());
        configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        configuration.addMapping("/info/*", infoCreator);
        server12.start();
        return server12;
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via attribute
    cases.add(new Object[] { "wsuf/addFilter/Attribute based configure", (ServerProvider) () -> {
        Server server13 = new Server();
        ServerConnector connector = new ServerConnector(server13);
        connector.setPort(0);
        server13.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server13.setHandler(context);
        context.addFilter(WebSocketUpgradeFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        NativeWebSocketConfiguration configuration = new NativeWebSocketConfiguration(context.getServletContext());
        configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        configuration.addMapping("/info/*", infoCreator);
        context.setAttribute(NativeWebSocketConfiguration.class.getName(), configuration);
        server13.start();
        return server13;
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via wsuf constructor
    cases.add(new Object[] { "wsuf/addFilter/WSUF Constructor configure", new ServerProvider() {

        @Override
        public Server newServer() throws Exception {
            Server server = new Server();
            ServerConnector connector = new ServerConnector(server);
            connector.setPort(0);
            server.addConnector(connector);
            ServletContextHandler context = new ServletContextHandler();
            context.setContextPath("/");
            server.setHandler(context);
            NativeWebSocketConfiguration configuration = new NativeWebSocketConfiguration(context.getServletContext());
            configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
            configuration.addMapping("/info/*", infoCreator);
            context.addBean(configuration, true);
            FilterHolder wsufHolder = new FilterHolder(new WebSocketUpgradeFilter(configuration));
            context.addFilter(wsufHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
            server.start();
            return server;
        }
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via ServletContextListener
    cases.add(new Object[] { "wsuf.configureContext/ServletContextListener configure", (ServerProvider) () -> {
        Server server14 = new Server();
        ServerConnector connector = new ServerConnector(server14);
        connector.setPort(0);
        server14.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server14.setHandler(context);
        context.addFilter(WebSocketUpgradeFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        context.addEventListener(new InfoContextListener());
        server14.start();
        return server14;
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via ServletContextListener
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server15 = new WSServer(testDir, "/");
        server15.copyWebInf("wsuf-config-via-listener.xml");
        server15.copyClass(InfoSocket.class);
        server15.copyClass(InfoContextAttributeListener.class);
        server15.start();
        WebAppContext webapp = server15.createWebAppContext();
        server15.deployWebapp(webapp);
        return server15.getServer();
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via ServletContextListener with WEB-INF/lib/jetty-http.jar
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener/jetty-http.jar", new ServerProvider() {

        @Override
        public Server newServer() throws Exception {
            File testDir = getNewTestDir();
            WSServer server = new WSServer(testDir, "/");
            server.copyWebInf("wsuf-config-via-listener.xml");
            server.copyClass(InfoSocket.class);
            server.copyClass(InfoContextAttributeListener.class);
            // Add a jetty-http.jar to ensure that the classloader constraints
            // and the WebAppClassloader setup is sane and correct
            // The odd version string is present to capture bad regex behavior in Jetty
            server.copyLib(org.eclipse.jetty.http.pathmap.PathSpec.class, "jetty-http-9.99.999.jar");
            server.start();
            WebAppContext webapp = server.createWebAppContext();
            server.deployWebapp(webapp);
            return server.getServer();
        }
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via Servlet.init
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/Servlet.init", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server16 = new WSServer(testDir, "/");
        server16.copyWebInf("wsuf-config-via-servlet-init.xml");
        server16.copyClass(InfoSocket.class);
        server16.copyClass(InfoServlet.class);
        server16.start();
        WebAppContext webapp = server16.createWebAppContext();
        server16.deployWebapp(webapp);
        return server16.getServer();
    } });
    // xml based, wsuf, on alternate url-pattern and config attribute location
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener/alt-config", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server17 = new WSServer(testDir, "/");
        server17.copyWebInf("wsuf-alt-config-via-listener.xml");
        server17.copyClass(InfoSocket.class);
        server17.copyClass(InfoContextAltAttributeListener.class);
        server17.start();
        WebAppContext webapp = server17.createWebAppContext();
        server17.deployWebapp(webapp);
        return server17.getServer();
    } });
    return cases;
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) MavenTestingUtils(org.eclipse.jetty.toolchain.test.MavenTestingUtils) RunWith(org.junit.runner.RunWith) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) WebSocketFrame(org.eclipse.jetty.websocket.common.WebSocketFrame) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) TextFrame(org.eclipse.jetty.websocket.common.frames.TextFrame) URI(java.net.URI) Server(org.eclipse.jetty.server.Server) EnumSet(java.util.EnumSet) Parameterized(org.junit.runners.Parameterized) EventQueue(org.eclipse.jetty.toolchain.test.EventQueue) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ServerConnector(org.eclipse.jetty.server.ServerConnector) DispatcherType(javax.servlet.DispatcherType) BlockheadClient(org.eclipse.jetty.websocket.common.test.BlockheadClient) Matchers.containsString(org.hamcrest.Matchers.containsString) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) ArrayList(java.util.ArrayList) ServerConnector(org.eclipse.jetty.server.ServerConnector) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File)

Example 30 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder 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)

Aggregations

FilterHolder (org.eclipse.jetty.servlet.FilterHolder)84 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)44 Test (org.junit.Test)35 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)32 Server (org.eclipse.jetty.server.Server)21 CountDownLatch (java.util.concurrent.CountDownLatch)18 Filter (javax.servlet.Filter)11 IOException (java.io.IOException)10 URL (java.net.URL)10 DispatcherType (javax.servlet.DispatcherType)9 ServletException (javax.servlet.ServletException)8 AuthenticationToken (org.apache.hadoop.security.authentication.server.AuthenticationToken)8 ServerConnector (org.eclipse.jetty.server.ServerConnector)8 File (java.io.File)7 HttpURLConnection (java.net.HttpURLConnection)7 PrivilegedActionException (java.security.PrivilegedActionException)7 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)7 FilterMapping (org.eclipse.jetty.servlet.FilterMapping)7 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)7 List (java.util.List)6