Search in sources :

Example 11 with Endpoint

use of jakarta.websocket.Endpoint in project spring-framework by spring-projects.

the class TomcatRequestUpgradeStrategy method upgrade.

// for old doUpgrade variant in Tomcat 9.0.55
@SuppressWarnings("deprecation")
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    HttpServletRequest servletRequest = ServerHttpRequestDecorator.getNativeRequest(request);
    HttpServletResponse servletResponse = ServerHttpResponseDecorator.getNativeResponse(response);
    HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
    DataBufferFactory bufferFactory = response.bufferFactory();
    // Trigger WebFlux preCommit actions and upgrade
    return exchange.getResponse().setComplete().then(Mono.deferContextual(contextView -> {
        Endpoint endpoint = new StandardWebSocketHandlerAdapter(ContextWebSocketHandler.decorate(handler, contextView), session -> new TomcatWebSocketSession(session, handshakeInfo, bufferFactory));
        String requestURI = servletRequest.getRequestURI();
        DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint);
        config.setSubprotocols(subProtocol != null ? Collections.singletonList(subProtocol) : Collections.emptyList());
        WsServerContainer container = getContainer(servletRequest);
        try {
            container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap());
        } catch (Exception ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    }));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) RequestUpgradeStrategy(org.springframework.web.reactive.socket.server.RequestUpgradeStrategy) Mono(reactor.core.publisher.Mono) ServerContainer(jakarta.websocket.server.ServerContainer) Supplier(java.util.function.Supplier) TomcatWebSocketSession(org.springframework.web.reactive.socket.adapter.TomcatWebSocketSession) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Endpoint(jakarta.websocket.Endpoint) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) WsServerContainer(org.apache.tomcat.websocket.server.WsServerContainer) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator) ServerHttpResponseDecorator(org.springframework.http.server.reactive.ServerHttpResponseDecorator) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) ContextWebSocketHandler(org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) StandardWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Assert(org.springframework.util.Assert) WsServerContainer(org.apache.tomcat.websocket.server.WsServerContainer) StandardWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TomcatWebSocketSession(org.springframework.web.reactive.socket.adapter.TomcatWebSocketSession) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Endpoint(jakarta.websocket.Endpoint) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 12 with Endpoint

use of jakarta.websocket.Endpoint in project spring-framework by spring-projects.

the class EndpointConnectionManager method openConnection.

@Override
protected void openConnection() {
    this.taskExecutor.execute(() -> {
        try {
            if (logger.isInfoEnabled()) {
                logger.info("Connecting to WebSocket at " + getUri());
            }
            Endpoint endpointToUse = this.endpoint;
            if (endpointToUse == null) {
                Assert.state(this.endpointProvider != null, "No endpoint set");
                endpointToUse = this.endpointProvider.getHandler();
            }
            ClientEndpointConfig endpointConfig = this.configBuilder.build();
            this.session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri());
            logger.info("Successfully connected to WebSocket");
        } catch (Throwable ex) {
            logger.error("Failed to connect to WebSocket", ex);
        }
    });
}
Also used : Endpoint(jakarta.websocket.Endpoint) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig)

Example 13 with Endpoint

use of jakarta.websocket.Endpoint in project spring-framework by spring-projects.

the class StandardWebSocketClient method doHandshakeInternal.

@Override
protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, HttpHeaders headers, final URI uri, List<String> protocols, List<WebSocketExtension> extensions, Map<String, Object> attributes) {
    int port = getPort(uri);
    InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port);
    InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port);
    final StandardWebSocketSession session = new StandardWebSocketSession(headers, attributes, localAddress, remoteAddress);
    final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create().configurator(new StandardWebSocketClientConfigurator(headers)).preferredSubprotocols(protocols).extensions(adaptExtensions(extensions)).build();
    endpointConfig.getUserProperties().putAll(getUserProperties());
    final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session);
    Callable<WebSocketSession> connectTask = () -> {
        this.webSocketContainer.connectToServer(endpoint, endpointConfig, uri);
        return session;
    };
    if (this.taskExecutor != null) {
        return this.taskExecutor.submitListenable(connectTask);
    } else {
        ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask);
        task.run();
        return task;
    }
}
Also used : StandardWebSocketHandlerAdapter(org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter) Endpoint(jakarta.websocket.Endpoint) ListenableFutureTask(org.springframework.util.concurrent.ListenableFutureTask) StandardWebSocketSession(org.springframework.web.socket.adapter.standard.StandardWebSocketSession) InetSocketAddress(java.net.InetSocketAddress) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) Endpoint(jakarta.websocket.Endpoint) WebSocketSession(org.springframework.web.socket.WebSocketSession) StandardWebSocketSession(org.springframework.web.socket.adapter.standard.StandardWebSocketSession)

Example 14 with Endpoint

use of jakarta.websocket.Endpoint in project tomcat by apache.

the class WsSci method onStartup.

@Override
public void onStartup(Set<Class<?>> clazzes, ServletContext ctx) throws ServletException {
    WsServerContainer sc = init(ctx, true);
    if (clazzes == null || clazzes.size() == 0) {
        return;
    }
    // Group the discovered classes by type
    Set<ServerApplicationConfig> serverApplicationConfigs = new HashSet<>();
    Set<Class<? extends Endpoint>> scannedEndpointClazzes = new HashSet<>();
    Set<Class<?>> scannedPojoEndpoints = new HashSet<>();
    try {
        // wsPackage is "jakarta.websocket."
        String wsPackage = ContainerProvider.class.getName();
        wsPackage = wsPackage.substring(0, wsPackage.lastIndexOf('.') + 1);
        for (Class<?> clazz : clazzes) {
            int modifiers = clazz.getModifiers();
            if (!Modifier.isPublic(modifiers) || Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers) || !isExported(clazz)) {
                // package - skip it.
                continue;
            }
            // Protect against scanning the WebSocket API JARs
            if (clazz.getName().startsWith(wsPackage)) {
                continue;
            }
            if (ServerApplicationConfig.class.isAssignableFrom(clazz)) {
                serverApplicationConfigs.add((ServerApplicationConfig) clazz.getConstructor().newInstance());
            }
            if (Endpoint.class.isAssignableFrom(clazz)) {
                @SuppressWarnings("unchecked") Class<? extends Endpoint> endpoint = (Class<? extends Endpoint>) clazz;
                scannedEndpointClazzes.add(endpoint);
            }
            if (clazz.isAnnotationPresent(ServerEndpoint.class)) {
                scannedPojoEndpoints.add(clazz);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new ServletException(e);
    }
    // Filter the results
    Set<ServerEndpointConfig> filteredEndpointConfigs = new HashSet<>();
    Set<Class<?>> filteredPojoEndpoints = new HashSet<>();
    if (serverApplicationConfigs.isEmpty()) {
        filteredPojoEndpoints.addAll(scannedPojoEndpoints);
    } else {
        for (ServerApplicationConfig config : serverApplicationConfigs) {
            Set<ServerEndpointConfig> configFilteredEndpoints = config.getEndpointConfigs(scannedEndpointClazzes);
            if (configFilteredEndpoints != null) {
                filteredEndpointConfigs.addAll(configFilteredEndpoints);
            }
            Set<Class<?>> configFilteredPojos = config.getAnnotatedEndpointClasses(scannedPojoEndpoints);
            if (configFilteredPojos != null) {
                filteredPojoEndpoints.addAll(configFilteredPojos);
            }
        }
    }
    try {
        // Deploy endpoints
        for (ServerEndpointConfig config : filteredEndpointConfigs) {
            sc.addEndpoint(config);
        }
        // Deploy POJOs
        for (Class<?> clazz : filteredPojoEndpoints) {
            sc.addEndpoint(clazz, true);
        }
    } catch (DeploymentException e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) ServerApplicationConfig(jakarta.websocket.server.ServerApplicationConfig) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) ServletException(jakarta.servlet.ServletException) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) DeploymentException(jakarta.websocket.DeploymentException) HashSet(java.util.HashSet)

Example 15 with Endpoint

use of jakarta.websocket.Endpoint in project tomcat by apache.

the class TestWsWebSocketContainer method doBufferTest.

private void doBufferTest(boolean isTextBuffer, boolean isServerBuffer, boolean isTextMessage, boolean pass) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    if (isServerBuffer) {
        if (isTextBuffer) {
            ctx.addParameter(org.apache.tomcat.websocket.server.Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024");
        } else {
            ctx.addParameter(org.apache.tomcat.websocket.server.Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024");
        }
    } else {
        if (isTextBuffer) {
            wsContainer.setDefaultMaxTextMessageBufferSize(1024);
        } else {
            wsContainer.setDefaultMaxBinaryMessageBufferSize(1024);
        }
    }
    tomcat.start();
    Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_BASIC));
    BasicHandler<?> handler;
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    if (isTextMessage) {
        handler = new BasicText(latch);
    } else {
        handler = new BasicBinary(latch);
    }
    wsSession.addMessageHandler(handler);
    try {
        if (isTextMessage) {
            wsSession.getBasicRemote().sendText(MESSAGE_TEXT_4K);
        } else {
            wsSession.getBasicRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
        }
    } catch (IOException ioe) {
    // Some messages sends are expected to fail. Assertions further on
    // in this method will check for the correct behaviour so ignore any
    // exception here.
    }
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Queue<?> messages = handler.getMessages();
    if (pass) {
        Assert.assertEquals(1, messages.size());
        if (isTextMessage) {
            Assert.assertEquals(MESSAGE_TEXT_4K, messages.peek());
        } else {
            Assert.assertEquals(ByteBuffer.wrap(MESSAGE_BINARY_4K), messages.peek());
        }
    } else {
        // give the session a chance to complete the close process.
        for (int i = 0; i < 500; i++) {
            if (!wsSession.isOpen()) {
                break;
            }
            Thread.sleep(10);
        }
        Assert.assertFalse(wsSession.isOpen());
    }
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(jakarta.websocket.WebSocketContainer) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) BasicBinary(org.apache.tomcat.websocket.TesterMessageCountClient.BasicBinary) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) BasicText(org.apache.tomcat.websocket.TesterMessageCountClient.BasicText) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Session(jakarta.websocket.Session)

Aggregations

Endpoint (jakarta.websocket.Endpoint)21 ServerEndpoint (jakarta.websocket.server.ServerEndpoint)15 Test (org.junit.Test)12 ClientEndpointConfig (jakarta.websocket.ClientEndpointConfig)5 Session (jakarta.websocket.Session)4 WebSocketContainer (jakarta.websocket.WebSocketContainer)4 URI (java.net.URI)4 Context (org.apache.catalina.Context)4 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)4 Tomcat (org.apache.catalina.startup.Tomcat)4 ArrayList (java.util.ArrayList)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 TesterEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint)3 TesterProgrammaticEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint)3 EndpointConfig (jakarta.websocket.EndpointConfig)2 ServerEndpointConfig (jakarta.websocket.server.ServerEndpointConfig)2 List (java.util.List)2 AsyncText (org.apache.tomcat.websocket.TesterMessageCountClient.AsyncText)2 TesterAnnotatedEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint)2 ServletException (jakarta.servlet.ServletException)1