Search in sources :

Example 21 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project undertow by undertow-io.

the class BinaryEndpointServlet method init.

@Override
public void init(ServletConfig c) throws ServletException {
    String websocketPath = "/partial";
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(BinaryPartialEndpoint.class, websocketPath).build();
    ServerContainer serverContainer = (ServerContainer) c.getServletContext().getAttribute("javax.websocket.server.ServerContainer");
    try {
        serverContainer.addEndpoint(config);
    } catch (DeploymentException ex) {
        throw new ServletException("Error deploying websocket endpoint:", ex);
    }
}
Also used : ServletException(javax.servlet.ServletException) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DeploymentException(javax.websocket.DeploymentException) ServerContainer(javax.websocket.server.ServerContainer)

Example 22 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project undertow by undertow-io.

the class Bootstrap method handleDeployment.

@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
    WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
    if (info == null) {
        return;
    }
    Supplier<XnioWorker> worker = info.getWorker();
    ByteBufferPool buffers = info.getBuffers();
    if (buffers == null) {
        ServerWebSocketContainer defaultContainer = UndertowContainerProvider.getDefaultContainer();
        if (defaultContainer == null) {
            throw JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNullAndNoDefault();
        }
        JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNull();
        buffers = defaultContainer.getBufferPool();
    }
    final List<ThreadSetupHandler> setup = new ArrayList<>();
    setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
    setup.addAll(deploymentInfo.getThreadSetupActions());
    InetSocketAddress bind = null;
    if (info.getClientBindAddress() != null) {
        bind = new InetSocketAddress(info.getClientBindAddress(), 0);
    }
    List<Extension> extensions = new ArrayList<>();
    for (ExtensionHandshake e : info.getExtensions()) {
        extensions.add(new ExtensionImpl(e.getName(), Collections.emptyList()));
    }
    ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), servletContext.getClassLoader(), worker, buffers, setup, info.isDispatchToWorkerThread(), bind, info.getReconnectHandler(), extensions);
    try {
        for (Class<?> annotation : info.getAnnotatedEndpoints()) {
            container.addEndpoint(annotation);
        }
        for (ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
            container.addEndpoint(programatic);
        }
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
    servletContext.setAttribute(ServerContainer.class.getName(), container);
    info.containerReady(container);
    SecurityActions.addContainer(deploymentInfo.getClassLoader(), container);
    deploymentInfo.addListener(Servlets.listener(WebSocketListener.class));
    deploymentInfo.addDeploymentCompleteListener(new ServletContextListener() {

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            container.validateDeployment();
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
}
Also used : ByteBufferPool(io.undertow.connector.ByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServletContextListener(javax.servlet.ServletContextListener) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ServletExtension(io.undertow.servlet.ServletExtension) Extension(javax.websocket.Extension) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) ContextClassLoaderSetupAction(io.undertow.servlet.core.ContextClassLoaderSetupAction) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) DeploymentException(javax.websocket.DeploymentException) ServletContextEvent(javax.servlet.ServletContextEvent) ServerContainer(javax.websocket.server.ServerContainer)

Example 23 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project quickstart by wildfly.

the class Frontend method init.

public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext servletContext) {
    if (servletContext == null) {
        log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "ServletContext not available"));
        return;
    }
    ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute("javax.websocket.server.ServerContainer");
    if (serverContainer == null) {
        log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "javax.websocket.server.ServerContainer ServerContainer not available"));
        return;
    }
    // WebSocket does not honor CDI contexts in the default configuration; by default a new object is created for each new
    // websocket.
    // We can work around this by supplying a custom ServerEndpointConfig.Configurator that returns the same instance of the
    // endpoint for each new websocket. Unfortunately this precludes us from using annotations, and forces us to extend the
    // abstract class Endpoint, and forces us to add the server endpoint programmatically upon startup of the servlet
    // context.
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(Frontend.class, WEBSOCKET_PATH).configurator(new ServerEndpointConfig.Configurator() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException {
            if (endpointClass.isAssignableFrom(Frontend.class)) {
                return (T) Frontend.this;
            }
            return super.getEndpointInstance(endpointClass);
        }
    }).build();
    try {
        serverContainer.addEndpoint(config);
    } catch (DeploymentException e) {
        log.log(Level.SEVERE, format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, e.getMessage()), e);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DeploymentException(javax.websocket.DeploymentException) ServerContainer(javax.websocket.server.ServerContainer)

Example 24 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project openremote by openremote.

the class DefaultWebsocketComponent method deploy.

@Override
protected void deploy() throws Exception {
    WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
    getConsumers().forEach((key, value) -> {
        String endpointPath = WEBSOCKET_PATH + "/" + key;
        LOG.info("Deploying websocket endpoint: " + endpointPath);
        webSocketDeploymentInfo.addEndpoint(ServerEndpointConfig.Builder.create(WebsocketAdapter.class, endpointPath).configurator(new DefaultContainerConfigurator() {

            @SuppressWarnings("unchecked")
            @Override
            public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                return (T) new WebsocketAdapter(value);
            }

            @Override
            public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
                String realm = Optional.ofNullable(request.getHeaders().get(Constants.REALM_PARAM_NAME)).map(realms -> realms.isEmpty() ? null : realms.get(0)).orElse(null);
                Principal principal = request.getUserPrincipal();
                AuthContext authContext = null;
                if (principal instanceof KeycloakPrincipal) {
                    KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) principal;
                    authContext = new AccessTokenAuthContext(keycloakPrincipal.getKeycloakSecurityContext().getRealm(), keycloakPrincipal.getKeycloakSecurityContext().getToken());
                } else if (principal instanceof BasicAuthContext) {
                    authContext = (BasicAuthContext) principal;
                } else if (principal != null) {
                    LOG.info("Unsupported user principal type: " + principal);
                }
                config.getUserProperties().put(ConnectionConstants.HANDSHAKE_AUTH, authContext);
                config.getUserProperties().put(ConnectionConstants.HANDSHAKE_REALM, realm);
                super.modifyHandshake(config, request, response);
            }
        }).build());
    });
    // We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
    // an internal asynchronous message queue for processing, so we don't need a separate worker thread
    // pool for websocket frame processing
    webSocketDeploymentInfo.setDispatchToWorkerThread(false);
    // Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
    // when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
    webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(OptionMap.builder().set(Options.WORKER_TASK_MAX_THREADS, 1).set(Options.WORKER_NAME, "WebsocketInternalClient").set(Options.THREAD_DAEMON, true).getMap()));
    boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
    webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
    String deploymentName = "WebSocket Deployment";
    deploymentInfo = new DeploymentInfo().setDeploymentName(deploymentName).setContextPath(WEBSOCKET_PATH).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo).setClassLoader(WebsocketComponent.class.getClassLoader());
    // Require authentication, but authorize specific roles later in Camel
    WebResourceCollection resourceCollection = new WebResourceCollection();
    resourceCollection.addUrlPattern("/*");
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
    constraint.addWebResourceCollection(resourceCollection);
    deploymentInfo.addSecurityConstraints(constraint);
    HttpHandler handler = WebService.addServletDeployment(container, deploymentInfo, true);
    websocketHttpHandler = pathStartsWithHandler(deploymentName, WEBSOCKET_PATH, handler);
    // Give web socket handler higher priority than any other handlers already added
    webService.getRequestHandlers().add(0, websocketHttpHandler);
}
Also used : HttpHandler(io.undertow.server.HttpHandler) WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) AuthContext(org.openremote.container.security.AuthContext) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) HandshakeResponse(javax.websocket.HandshakeResponse) WebsocketAdapter(org.openremote.container.web.socket.WebsocketAdapter) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) DefaultContainerConfigurator(io.undertow.websockets.jsr.DefaultContainerConfigurator) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) Principal(java.security.Principal) HandshakeRequest(javax.websocket.server.HandshakeRequest) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 25 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat by apache.

the class TestWsServerContainer method testDuplicatePaths_04.

@Test
public void testDuplicatePaths_04() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());
    ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(Object.class, "/a/{var1}/{var2}").build();
    ServerEndpointConfig configB = ServerEndpointConfig.Builder.create(Object.class, "/a/b/{var2}").build();
    sc.addEndpoint(configA);
    sc.addEndpoint(configB);
    Assert.assertEquals(configA, sc.findMapping("/a/x/y").getConfig());
    Assert.assertEquals(configB, sc.findMapping("/a/b/y").getConfig());
}
Also used : TesterServletContext(org.apache.tomcat.unittest.TesterServletContext) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) Test(org.junit.Test) WebSocketBaseTest(org.apache.tomcat.websocket.WebSocketBaseTest)

Aggregations

ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)49 DeploymentException (javax.websocket.DeploymentException)17 ServerEndpoint (javax.websocket.server.ServerEndpoint)14 Test (org.junit.Test)13 ServletException (javax.servlet.ServletException)10 TesterServletContext (org.apache.tomcat.unittest.TesterServletContext)10 WebSocketBaseTest (org.apache.tomcat.websocket.WebSocketBaseTest)10 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)7 Endpoint (javax.websocket.Endpoint)6 ServerContainer (javax.websocket.server.ServerContainer)6 Server (org.eclipse.jetty.server.Server)6 ServerConnector (org.eclipse.jetty.server.ServerConnector)6 IOException (java.io.IOException)5 EndpointInstance (org.eclipse.jetty.websocket.jsr356.endpoints.EndpointInstance)5 Before (org.junit.Before)5 HandshakeResponse (javax.websocket.HandshakeResponse)4 HandshakeRequest (javax.websocket.server.HandshakeRequest)4 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3