Search in sources :

Example 1 with WebSocketServletFactory

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

use of org.eclipse.jetty.websocket.servlet.WebSocketServletFactory in project camel by apache.

the class WebsocketEndpointConfigurationTest method testSetServletThreadPool.

@Test
public void testSetServletThreadPool() throws Exception {
    port = AvailablePortFinder.getNextAvailable(16332);
    String uri = "websocket://localhost:" + port + "/bar?bufferSize=25000&maxIdleTime=3000";
    WebsocketEndpoint websocketEndpoint = (WebsocketEndpoint) context.getEndpoint(uri);
    WebsocketComponent component = websocketEndpoint.getComponent();
    QueuedThreadPool qtp = new QueuedThreadPool(20, 1);
    component.setThreadPool(qtp);
    Consumer consumer = websocketEndpoint.createConsumer(processor);
    component.connect((WebsocketProducerConsumer) consumer);
    assertNotNull(consumer);
    assertEquals(WebsocketConsumer.class, consumer.getClass());
    // just check the servlet initial parameters
    ConnectorRef conector = WebsocketComponent.getConnectors().values().iterator().next();
    ServletContextHandler context = (ServletContextHandler) conector.server.getHandler();
    String buffersize = context.getInitParameter("bufferSize");
    assertEquals("Got a wrong buffersize", "25000", buffersize);
    String maxIdleTime = context.getInitParameter("maxIdleTime");
    assertEquals("Got a wrong maxIdleTime", "3000", maxIdleTime);
    WebSocketServletFactory factory = (WebSocketServletFactory) context.getServletContext().getAttribute(WebSocketServletFactory.class.getName());
    int factoryBufferSize = factory.getPolicy().getInputBufferSize();
    assertEquals("Got a wrong buffersize", 25000, factoryBufferSize);
    long factoryMaxIdleTime = factory.getPolicy().getIdleTimeout();
    assertEquals("Got a wrong maxIdleTime", 3000, factoryMaxIdleTime);
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Consumer(org.apache.camel.Consumer) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ConnectorRef(org.apache.camel.component.websocket.WebsocketComponent.ConnectorRef) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 3 with WebSocketServletFactory

use of org.eclipse.jetty.websocket.servlet.WebSocketServletFactory in project camel by apache.

the class WebsocketEndpointConfigurationTest method testSetServletInitalparameters.

@Test
public void testSetServletInitalparameters() throws Exception {
    port = AvailablePortFinder.getNextAvailable(16330);
    String uri = "websocket://localhost:" + port + "/bar?bufferSize=25000&maxIdleTime=3000&maxTextMessageSize=500&maxBinaryMessageSize=550";
    WebsocketEndpoint websocketEndpoint = (WebsocketEndpoint) context.getEndpoint(uri);
    WebsocketComponent component = websocketEndpoint.getComponent();
    component.setMinThreads(1);
    component.setMaxThreads(20);
    Consumer consumer = websocketEndpoint.createConsumer(processor);
    component.connect((WebsocketProducerConsumer) consumer);
    assertNotNull(consumer);
    assertEquals(WebsocketConsumer.class, consumer.getClass());
    // just check the servlet initial parameters
    ConnectorRef conector = WebsocketComponent.getConnectors().values().iterator().next();
    ServletContextHandler context = (ServletContextHandler) conector.server.getHandler();
    String buffersize = context.getInitParameter("bufferSize");
    assertEquals("Got a wrong buffersize", "25000", buffersize);
    String maxIdleTime = context.getInitParameter("maxIdleTime");
    assertEquals("Got a wrong maxIdleTime", "3000", maxIdleTime);
    String maxTextMessageSize = context.getInitParameter("maxTextMessageSize");
    assertEquals("Got a wrong maxTextMessageSize", "500", maxTextMessageSize);
    String maxBinaryMessageSize = context.getInitParameter("maxBinaryMessageSize");
    assertEquals("Got a wrong maxBinaryMessageSize", "550", maxBinaryMessageSize);
    WebSocketServletFactory factory = (WebSocketServletFactory) context.getServletContext().getAttribute(WebSocketServletFactory.class.getName());
    int factoryBufferSize = factory.getPolicy().getInputBufferSize();
    assertEquals("Got a wrong buffersize", 25000, factoryBufferSize);
    long factoryMaxIdleTime = factory.getPolicy().getIdleTimeout();
    assertEquals("Got a wrong maxIdleTime", 3000, factoryMaxIdleTime);
    int factoryMaxTextMessageSize = factory.getPolicy().getMaxTextMessageSize();
    assertEquals("Got a wrong maxTextMessageSize", 500, factoryMaxTextMessageSize);
    int factoryMaxBinaryMessageSize = factory.getPolicy().getMaxBinaryMessageSize();
    assertEquals("Got a wrong maxBinaryMessageSize", 550, factoryMaxBinaryMessageSize);
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Consumer(org.apache.camel.Consumer) ConnectorRef(org.apache.camel.component.websocket.WebsocketComponent.ConnectorRef) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 4 with WebSocketServletFactory

use of org.eclipse.jetty.websocket.servlet.WebSocketServletFactory in project jphp by jphp-compiler.

the class PHttpServer method addWebSocket.

@Signature
public void addWebSocket(Environment env, String path, ArrayMemory _handlers) {
    WebSocketParam param = _handlers.toBean(env, WebSocketParam.class);
    ContextHandler contextHandler = new ContextHandler(path);
    contextHandler.setHandler(new WebSocketHandler() {

        @Override
        public void configure(WebSocketServletFactory factory) {
            factory.setCreator(new WebSocketCreator() {

                @Override
                public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
                    return new WebSocket(env, param);
                }
            });
        }
    });
    handlers.addHandler(contextHandler);
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) WebSocketHandler(org.eclipse.jetty.websocket.server.WebSocketHandler) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) ServletUpgradeRequest(org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest) ServletUpgradeResponse(org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse) Signature(php.runtime.annotation.Reflection.Signature)

Example 5 with WebSocketServletFactory

use of org.eclipse.jetty.websocket.servlet.WebSocketServletFactory in project main by JohnPeng739.

the class WebsocketServerFactory method afterPropertiesSet.

/**
 * {@inheritDoc}
 *
 * @see InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() throws Exception {
    boolean enabled = env.getProperty("websocket.enabled", Boolean.class, true);
    if (!enabled) {
        // 显式配置enable为false,表示不进行初始化。
        return;
    }
    final int port = env.getProperty("websocket.port", Integer.class, 9997);
    String websocketClassesStr = "websocket.service.classes";
    String websocketServiceClassesDef = this.env.getProperty(websocketClassesStr);
    if (StringUtils.isBlank(websocketServiceClassesDef)) {
        if (logger.isWarnEnabled()) {
            logger.warn(String.format("You not define [%s], will not ", websocketClassesStr));
        }
    } else {
        String[] classesDefs = websocketServiceClassesDef.split(",");
        for (String classesDef : classesDefs) {
            if (!StringUtils.isBlank(classesDef)) {
                List<Class<?>> websocketClasses = (List) this.context.getBean(classesDef, List.class);
                if (websocketClasses != null && !websocketClasses.isEmpty()) {
                    websocketClasses.forEach((clazz) -> {
                        WsSessionListener listener = (WsSessionListener) context.getBean(clazz);
                        socketBeans.put(listener.getPath(), new SimpleWsObject(listener));
                    });
                }
            }
        }
        Server server = new Server(port);
        server.setHandler(new WebSocketHandler() {

            @Override
            public void configure(WebSocketServletFactory factory) {
                factory.setCreator(new MyWebsocketCreator());
            }
        });
        server.setStopAtShutdown(true);
        server.setStopTimeout(10);
        super.setServer(server);
        server.start();
        if (logger.isInfoEnabled()) {
            logger.info(String.format("Start Websocket server success, listen port: %d.", port));
        }
    }
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Server(org.eclipse.jetty.server.Server) SimpleWsObject(org.mx.service.server.websocket.SimpleWsObject) WebSocketHandler(org.eclipse.jetty.websocket.server.WebSocketHandler) List(java.util.List) WsSessionListener(org.mx.service.server.websocket.WsSessionListener)

Aggregations

WebSocketServletFactory (org.eclipse.jetty.websocket.servlet.WebSocketServletFactory)16 Server (org.eclipse.jetty.server.Server)7 WebSocketHandler (org.eclipse.jetty.websocket.server.WebSocketHandler)6 WebSocketCreator (org.eclipse.jetty.websocket.servlet.WebSocketCreator)6 ServerConnector (org.eclipse.jetty.server.ServerConnector)5 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)5 ServletUpgradeRequest (org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest)5 IOException (java.io.IOException)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 Consumer (org.apache.camel.Consumer)3 ConnectorRef (org.apache.camel.component.websocket.WebsocketComponent.ConnectorRef)3 WebSocketServlet (org.eclipse.jetty.websocket.servlet.WebSocketServlet)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Request (org.eclipse.jetty.server.Request)2 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)2 ServletUpgradeResponse (org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse)2 Test (org.junit.Test)2 InstrumentedQueuedThreadPool (com.codahale.metrics.jetty9.InstrumentedQueuedThreadPool)1 BuckEventExternalInterface (com.facebook.buck.event.external.events.BuckEventExternalInterface)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1