Search in sources :

Example 6 with WebSocketHttpHeaders

use of org.springframework.web.socket.WebSocketHttpHeaders in project spring-integration by spring-projects.

the class WebSocketParserTests method testCustomInboundChannelAdapterAndClientContainer.

@Test
public void testCustomInboundChannelAdapterAndClientContainer() throws URISyntaxException {
    assertSame(this.clientInboundChannel, TestUtils.getPropertyValue(this.customInboundAdapter, "outputChannel"));
    assertSame(this.errorChannel, TestUtils.getPropertyValue(this.customInboundAdapter, "errorChannel"));
    assertSame(this.clientWebSocketContainer, TestUtils.getPropertyValue(this.customInboundAdapter, "webSocketContainer"));
    assertEquals(2000L, TestUtils.getPropertyValue(this.customInboundAdapter, "messagingTemplate.sendTimeout"));
    assertEquals(200, TestUtils.getPropertyValue(this.customInboundAdapter, "phase"));
    assertFalse(TestUtils.getPropertyValue(this.customInboundAdapter, "autoStartup", Boolean.class));
    assertEquals(Integer.class, TestUtils.getPropertyValue(this.customInboundAdapter, "payloadType", AtomicReference.class).get());
    SubProtocolHandlerRegistry subProtocolHandlerRegistry = TestUtils.getPropertyValue(this.customInboundAdapter, "subProtocolHandlerRegistry", SubProtocolHandlerRegistry.class);
    assertSame(this.stompSubProtocolHandler, TestUtils.getPropertyValue(subProtocolHandlerRegistry, "defaultProtocolHandler"));
    Map<?, ?> protocolHandlers = TestUtils.getPropertyValue(subProtocolHandlerRegistry, "protocolHandlers", Map.class);
    assertEquals(3, protocolHandlers.size());
    // See warn log message.
    for (Object handler : protocolHandlers.values()) {
        assertSame(this.stompSubProtocolHandler, handler);
    }
    assertTrue(TestUtils.getPropertyValue(this.customInboundAdapter, "mergeWithDefaultConverters", Boolean.class));
    CompositeMessageConverter compositeMessageConverter = TestUtils.getPropertyValue(this.customInboundAdapter, "messageConverter", CompositeMessageConverter.class);
    List<MessageConverter> converters = compositeMessageConverter.getConverters();
    assertEquals(5, converters.size());
    assertSame(this.simpleMessageConverter, converters.get(0));
    assertSame(this.mapMessageConverter, converters.get(1));
    assertThat(converters.get(2), instanceOf(StringMessageConverter.class));
    // Test ClientWebSocketContainer parser
    assertSame(this.customInboundAdapter, TestUtils.getPropertyValue(this.clientWebSocketContainer, "messageListener"));
    assertEquals(100, TestUtils.getPropertyValue(this.clientWebSocketContainer, "sendTimeLimit"));
    assertEquals(1000, TestUtils.getPropertyValue(this.clientWebSocketContainer, "sendBufferSizeLimit"));
    assertEquals(new URI("ws://foo.bar/ws?service=user"), TestUtils.getPropertyValue(this.clientWebSocketContainer, "connectionManager.uri", URI.class));
    assertSame(this.webSocketClient, TestUtils.getPropertyValue(this.clientWebSocketContainer, "connectionManager.client"));
    assertEquals(100, TestUtils.getPropertyValue(this.clientWebSocketContainer, "connectionManager.phase"));
    WebSocketHttpHeaders headers = TestUtils.getPropertyValue(this.clientWebSocketContainer, "headers", WebSocketHttpHeaders.class);
    assertEquals("FOO", headers.getOrigin());
    assertEquals(Arrays.asList("BAR", "baz"), headers.get("FOO"));
    assertEquals(10 * 1000, TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "sendTimeLimit"));
    assertEquals(512 * 1024, TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "sendBufferSizeLimit"));
    assertEquals(new URI("ws://foo.bar"), TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "connectionManager.uri", URI.class));
    assertSame(this.webSocketClient, TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "connectionManager.client"));
    assertEquals(Integer.MAX_VALUE, TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "connectionManager.phase"));
    assertFalse(TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "connectionManager.autoStartup", Boolean.class));
    assertTrue(TestUtils.getPropertyValue(this.simpleClientWebSocketContainer, "headers", WebSocketHttpHeaders.class).isEmpty());
}
Also used : StringMessageConverter(org.springframework.messaging.converter.StringMessageConverter) WebSocketHttpHeaders(org.springframework.web.socket.WebSocketHttpHeaders) SubProtocolHandlerRegistry(org.springframework.integration.websocket.support.SubProtocolHandlerRegistry) CompositeMessageConverter(org.springframework.messaging.converter.CompositeMessageConverter) CompositeMessageConverter(org.springframework.messaging.converter.CompositeMessageConverter) MapMessageConverter(org.springframework.integration.support.converter.MapMessageConverter) MessageConverter(org.springframework.messaging.converter.MessageConverter) SimpleMessageConverter(org.springframework.integration.support.converter.SimpleMessageConverter) StringMessageConverter(org.springframework.messaging.converter.StringMessageConverter) URI(java.net.URI) Test(org.junit.Test)

Example 7 with WebSocketHttpHeaders

use of org.springframework.web.socket.WebSocketHttpHeaders in project spring-framework by spring-projects.

the class AbstractHandshakeHandler method doHandshake.

@Override
public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {
    WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHeaders());
    if (logger.isTraceEnabled()) {
        logger.trace("Processing request " + request.getURI() + " with headers=" + headers);
    }
    try {
        if (HttpMethod.GET != request.getMethod()) {
            response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
            response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET));
            if (logger.isErrorEnabled()) {
                logger.error("Handshake failed due to unexpected HTTP method: " + request.getMethod());
            }
            return false;
        }
        if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
            handleInvalidUpgradeHeader(request, response);
            return false;
        }
        if (!headers.getConnection().contains("Upgrade") && !headers.getConnection().contains("upgrade")) {
            handleInvalidConnectHeader(request, response);
            return false;
        }
        if (!isWebSocketVersionSupported(headers)) {
            handleWebSocketVersionNotSupported(request, response);
            return false;
        }
        if (!isValidOrigin(request)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return false;
        }
        String wsKey = headers.getSecWebSocketKey();
        if (wsKey == null) {
            if (logger.isErrorEnabled()) {
                logger.error("Missing \"Sec-WebSocket-Key\" header");
            }
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return false;
        }
    } catch (IOException ex) {
        throw new HandshakeFailureException("Response update failed during upgrade to WebSocket: " + request.getURI(), ex);
    }
    String subProtocol = selectProtocol(headers.getSecWebSocketProtocol(), wsHandler);
    List<WebSocketExtension> requested = headers.getSecWebSocketExtensions();
    List<WebSocketExtension> supported = this.requestUpgradeStrategy.getSupportedExtensions(request);
    List<WebSocketExtension> extensions = filterRequestedExtensions(request, requested, supported);
    Principal user = determineUser(request, wsHandler, attributes);
    if (logger.isTraceEnabled()) {
        logger.trace("Upgrading to WebSocket, subProtocol=" + subProtocol + ", extensions=" + extensions);
    }
    this.requestUpgradeStrategy.upgrade(request, response, subProtocol, extensions, user, wsHandler, attributes);
    return true;
}
Also used : WebSocketExtension(org.springframework.web.socket.WebSocketExtension) WebSocketHttpHeaders(org.springframework.web.socket.WebSocketHttpHeaders) HandshakeFailureException(org.springframework.web.socket.server.HandshakeFailureException) IOException(java.io.IOException) Principal(java.security.Principal)

Example 8 with WebSocketHttpHeaders

use of org.springframework.web.socket.WebSocketHttpHeaders in project spring-framework by spring-projects.

the class WebSocketTransport method connect.

@Override
public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
    final SettableListenableFuture<WebSocketSession> future = new SettableListenableFuture<>();
    WebSocketClientSockJsSession session = new WebSocketClientSockJsSession(request, handler, future);
    handler = new ClientSockJsWebSocketHandler(session);
    request.addTimeoutTask(session.getTimeoutTask());
    URI url = request.getTransportUrl();
    WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHandshakeHeaders());
    if (logger.isDebugEnabled()) {
        logger.debug("Starting WebSocket session on " + url);
    }
    this.webSocketClient.doHandshake(handler, headers, url).addCallback(new ListenableFutureCallback<WebSocketSession>() {

        @Override
        public void onSuccess(@Nullable WebSocketSession webSocketSession) {
        // WebSocket session ready, SockJS Session not yet
        }

        @Override
        public void onFailure(Throwable ex) {
            future.setException(ex);
        }
    });
    return future;
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) WebSocketHttpHeaders(org.springframework.web.socket.WebSocketHttpHeaders) URI(java.net.URI) WebSocketSession(org.springframework.web.socket.WebSocketSession)

Example 9 with WebSocketHttpHeaders

use of org.springframework.web.socket.WebSocketHttpHeaders in project spring-framework by spring-projects.

the class AbstractWebSocketClient method doHandshake.

@Override
public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, @Nullable WebSocketHttpHeaders headers, URI uri) {
    Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
    assertUri(uri);
    if (logger.isDebugEnabled()) {
        logger.debug("Connecting to " + uri);
    }
    HttpHeaders headersToUse = new HttpHeaders();
    if (headers != null) {
        headers.forEach((header, values) -> {
            if (values != null && !specialHeaders.contains(header.toLowerCase())) {
                headersToUse.put(header, values);
            }
        });
    }
    List<String> subProtocols = (headers != null ? headers.getSecWebSocketProtocol() : Collections.emptyList());
    List<WebSocketExtension> extensions = (headers != null ? headers.getSecWebSocketExtensions() : Collections.emptyList());
    return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions, Collections.emptyMap());
}
Also used : WebSocketHttpHeaders(org.springframework.web.socket.WebSocketHttpHeaders) HttpHeaders(org.springframework.http.HttpHeaders) WebSocketExtension(org.springframework.web.socket.WebSocketExtension)

Example 10 with WebSocketHttpHeaders

use of org.springframework.web.socket.WebSocketHttpHeaders in project spring-framework by spring-projects.

the class StandardWebSocketClientTests method setup.

@BeforeEach
public void setup() {
    this.headers = new WebSocketHttpHeaders();
    this.wsHandler = new AbstractWebSocketHandler() {
    };
    this.wsContainer = mock(WebSocketContainer.class);
    this.wsClient = new StandardWebSocketClient(this.wsContainer);
}
Also used : WebSocketContainer(jakarta.websocket.WebSocketContainer) AbstractWebSocketHandler(org.springframework.web.socket.handler.AbstractWebSocketHandler) WebSocketHttpHeaders(org.springframework.web.socket.WebSocketHttpHeaders) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

WebSocketHttpHeaders (org.springframework.web.socket.WebSocketHttpHeaders)14 URI (java.net.URI)8 Test (org.junit.jupiter.api.Test)4 HttpHeaders (org.springframework.http.HttpHeaders)4 Test (org.junit.Test)3 TextWebSocketHandler (org.springframework.web.socket.handler.TextWebSocketHandler)3 WebSocketExtension (org.springframework.web.socket.WebSocketExtension)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 MobileSecretKeyConfig (com.itrus.portal.db.MobileSecretKeyConfig)1 MobileSecretKeyConfigExample (com.itrus.portal.db.MobileSecretKeyConfigExample)1 KeySegmentationWebSocketHandler (com.itrus.portal.mobile.controller.websocket.handler.KeySegmentationWebSocketHandler)1 WebSocketContainer (jakarta.websocket.WebSocketContainer)1 IOException (java.io.IOException)1 Principal (java.security.Principal)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ExecutionException (java.util.concurrent.ExecutionException)1 JSONException (org.json.JSONException)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1 SimpleAsyncTaskExecutor (org.springframework.core.task.SimpleAsyncTaskExecutor)1