Search in sources :

Example 1 with WebSocketCreator

use of org.eclipse.jetty.websocket.servlet.WebSocketCreator 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 2 with WebSocketCreator

use of org.eclipse.jetty.websocket.servlet.WebSocketCreator in project jetty.project by eclipse.

the class NativeWebSocketConfiguration method addMapping.

/**
     * Manually add a WebSocket mapping.
     * <p>
     *     If mapping is added before this configuration is started, then it is persisted through
     *     stop/start of this configuration's lifecycle.  Otherwise it will be removed when
     *     this configuration is stopped.
     * </p>
     *
     * @param pathSpec the pathspec to respond on
     * @param creator the websocket creator to activate on the provided mapping.
     */
public void addMapping(PathSpec pathSpec, WebSocketCreator creator) {
    WebSocketCreator wsCreator = creator;
    if (!isRunning()) {
        wsCreator = new PersistedWebSocketCreator(creator);
    }
    mappings.put(pathSpec, wsCreator);
}
Also used : WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator)

Example 3 with WebSocketCreator

use of org.eclipse.jetty.websocket.servlet.WebSocketCreator in project jetty.project by eclipse.

the class WebSocketUpgradeFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (configuration == null) {
        // no configuration, cannot operate
        LOG.debug("WebSocketUpgradeFilter is not operational - missing " + NativeWebSocketConfiguration.class.getName());
        chain.doFilter(request, response);
        return;
    }
    WebSocketServletFactory factory = configuration.getFactory();
    if (factory == null) {
        // no factory, cannot operate
        LOG.debug("WebSocketUpgradeFilter is not operational - no WebSocketServletFactory configured");
        chain.doFilter(request, response);
        return;
    }
    try {
        HttpServletRequest httpreq = (HttpServletRequest) request;
        HttpServletResponse httpresp = (HttpServletResponse) response;
        if (!factory.isUpgradeRequest(httpreq, httpresp)) {
            // Not an upgrade request, skip it
            chain.doFilter(request, response);
            return;
        }
        // Since this is a filter, we need to be smart about determining the target path
        String contextPath = httpreq.getContextPath();
        String target = httpreq.getRequestURI();
        if (target.startsWith(contextPath)) {
            target = target.substring(contextPath.length());
        }
        MappedResource<WebSocketCreator> resource = configuration.getMatch(target);
        if (resource == null) {
            // no match.
            chain.doFilter(request, response);
            return;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("WebSocket Upgrade detected on {} for endpoint {}", target, resource);
        }
        WebSocketCreator creator = resource.getResource();
        // Store PathSpec resource mapping as request attribute
        httpreq.setAttribute(PathSpec.class.getName(), resource.getPathSpec());
        // We have an upgrade request
        if (factory.acceptWebSocket(creator, httpreq, httpresp)) {
            // We have a socket instance created
            return;
        }
        // due to incoming request constraints (controlled by WebSocketCreator)
        if (response.isCommitted()) {
            // not much we can do at this point.
            return;
        }
    } catch (ClassCastException e) {
        // We are in some kind of funky non-http environment.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Not a HttpServletRequest, skipping WebSocketUpgradeFilter");
        }
    }
    // not an Upgrade request
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) PathSpec(org.eclipse.jetty.http.pathmap.PathSpec)

Example 4 with WebSocketCreator

use of org.eclipse.jetty.websocket.servlet.WebSocketCreator in project spark by perwendel.

the class WebSocketCreatorFactoryTest method testCreateWebSocketHandler.

@Test
public void testCreateWebSocketHandler() {
    WebSocketCreator annotated = WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(AnnotatedHandler.class));
    assertTrue(annotated instanceof SparkWebSocketCreator);
    assertTrue(SparkWebSocketCreator.class.cast(annotated).getHandler() instanceof AnnotatedHandler);
    WebSocketCreator listener = WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(ListenerHandler.class));
    assertTrue(listener instanceof SparkWebSocketCreator);
    assertTrue(SparkWebSocketCreator.class.cast(listener).getHandler() instanceof ListenerHandler);
}
Also used : SparkWebSocketCreator(spark.embeddedserver.jetty.websocket.WebSocketCreatorFactory.SparkWebSocketCreator) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) SparkWebSocketCreator(spark.embeddedserver.jetty.websocket.WebSocketCreatorFactory.SparkWebSocketCreator) Test(org.junit.Test)

Example 5 with WebSocketCreator

use of org.eclipse.jetty.websocket.servlet.WebSocketCreator in project traccar by tananaev.

the class AsyncSocketServlet method configure.

@Override
public void configure(WebSocketServletFactory factory) {
    factory.getPolicy().setIdleTimeout(Context.getConfig().getLong("web.timeout", ASYNC_TIMEOUT));
    factory.setCreator(new WebSocketCreator() {

        @Override
        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
            if (req.getSession() != null) {
                long userId = (Long) req.getSession().getAttribute(SessionResource.USER_ID_KEY);
                return new AsyncSocket(userId);
            } else {
                return null;
            }
        }
    });
}
Also used : WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) ServletUpgradeRequest(org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest) ServletUpgradeResponse(org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse)

Aggregations

WebSocketCreator (org.eclipse.jetty.websocket.servlet.WebSocketCreator)16 ServletUpgradeRequest (org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest)6 ServletUpgradeResponse (org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse)6 PathSpec (org.eclipse.jetty.http.pathmap.PathSpec)5 WebSocketServletFactory (org.eclipse.jetty.websocket.servlet.WebSocketServletFactory)5 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)4 Test (org.junit.Test)4 HashMap (java.util.HashMap)3 Server (org.eclipse.jetty.server.Server)3 NativeWebSocketConfiguration (org.eclipse.jetty.websocket.server.NativeWebSocketConfiguration)3 WebSocketUpgradeFilter (org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter)3 IOException (java.io.IOException)2 ServletContext (javax.servlet.ServletContext)2 ServletPathSpec (org.eclipse.jetty.http.pathmap.ServletPathSpec)2 ServerConnector (org.eclipse.jetty.server.ServerConnector)2 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)2 WebSocketServerFactory (org.eclipse.jetty.websocket.server.WebSocketServerFactory)2 WebSocketServlet (org.eclipse.jetty.websocket.servlet.WebSocketServlet)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 InstrumentedQueuedThreadPool (com.codahale.metrics.jetty9.InstrumentedQueuedThreadPool)1