Search in sources :

Example 6 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring-framework by spring-projects.

the class StompSubProtocolHandler method sendToClient.

private void sendToClient(WebSocketSession session, StompHeaderAccessor stompAccessor, byte[] payload) {
    StompCommand command = stompAccessor.getCommand();
    try {
        byte[] bytes = this.stompEncoder.encode(stompAccessor.getMessageHeaders(), payload);
        boolean useBinary = (payload.length > 0 && !(session instanceof SockJsSession) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(stompAccessor.getContentType()));
        if (useBinary) {
            session.sendMessage(new BinaryMessage(bytes));
        } else {
            session.sendMessage(new TextMessage(bytes));
        }
    } catch (SessionLimitExceededException ex) {
        // Bad session, just get out
        throw ex;
    } catch (Throwable ex) {
        // Could be part of normal workflow (e.g. browser tab closed)
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to send WebSocket message to client in session " + session.getId(), ex);
        }
        command = StompCommand.ERROR;
    } finally {
        if (StompCommand.ERROR.equals(command)) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException ex) {
            // Ignore
            }
        }
    }
}
Also used : SockJsSession(org.springframework.web.socket.sockjs.transport.SockJsSession) SessionLimitExceededException(org.springframework.web.socket.handler.SessionLimitExceededException) IOException(java.io.IOException) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) BinaryMessage(org.springframework.web.socket.BinaryMessage) TextMessage(org.springframework.web.socket.TextMessage)

Example 7 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring-boot by spring-projects.

the class WebSocketMessagingAutoConfigurationTests method performStompSubscription.

private Object performStompSubscription(String topic) throws Throwable {
    TestPropertyValues.of("server.port:0", "spring.jackson.serialization.indent-output:true").applyTo(this.context);
    this.context.register(WebSocketMessagingConfiguration.class);
    new ServerPortInfoApplicationContextInitializer().initialize(this.context);
    this.context.refresh();
    WebSocketStompClient stompClient = new WebSocketStompClient(this.sockJsClient);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final AtomicReference<Object> result = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    StompSessionHandler handler = new StompSessionHandlerAdapter() {

        @Override
        public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            session.subscribe(topic, new StompFrameHandler() {

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    result.set(payload);
                    latch.countDown();
                }

                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return Object.class;
                }
            });
        }

        @Override
        public void handleFrame(StompHeaders headers, Object payload) {
            latch.countDown();
        }

        @Override
        public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }

        @Override
        public void handleTransportError(StompSession session, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }
    };
    stompClient.setMessageConverter(new SimpleMessageConverter());
    stompClient.connect("ws://localhost:{port}/messaging", handler, this.context.getEnvironment().getProperty("local.server.port"));
    if (!latch.await(30, TimeUnit.SECONDS)) {
        if (failure.get() != null) {
            throw failure.get();
        }
        fail("Response was not received within 30 seconds");
    }
    return result.get();
}
Also used : ServerPortInfoApplicationContextInitializer(org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer) StompFrameHandler(org.springframework.messaging.simp.stomp.StompFrameHandler) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StompHeaders(org.springframework.messaging.simp.stomp.StompHeaders) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) Type(java.lang.reflect.Type) WebSocketStompClient(org.springframework.web.socket.messaging.WebSocketStompClient) SimpleMessageConverter(org.springframework.messaging.converter.SimpleMessageConverter) StompSessionHandlerAdapter(org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)

Example 8 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring-boot by spring-projects.

the class WebSocketMessagingAutoConfigurationTests method performStompSubscription.

private Object performStompSubscription(final String topic) throws Throwable {
    EnvironmentTestUtils.addEnvironment(this.context, "server.port:0", "spring.jackson.serialization.indent-output:true");
    this.context.register(WebSocketMessagingConfiguration.class);
    new ServerPortInfoApplicationContextInitializer().initialize(this.context);
    this.context.refresh();
    WebSocketStompClient stompClient = new WebSocketStompClient(this.sockJsClient);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final AtomicReference<Object> result = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    StompSessionHandler handler = new StompSessionHandlerAdapter() {

        @Override
        public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            session.subscribe(topic, new StompFrameHandler() {

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    result.set(payload);
                    latch.countDown();
                }

                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return Object.class;
                }
            });
        }

        @Override
        public void handleFrame(StompHeaders headers, Object payload) {
            latch.countDown();
        }

        @Override
        public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }

        @Override
        public void handleTransportError(StompSession session, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }
    };
    stompClient.setMessageConverter(new SimpleMessageConverter());
    stompClient.connect("ws://localhost:{port}/messaging", handler, this.context.getEnvironment().getProperty("local.server.port"));
    if (!latch.await(30000, TimeUnit.SECONDS)) {
        if (failure.get() != null) {
            throw failure.get();
        }
        fail("Response was not received within 30 seconds");
    }
    return result.get();
}
Also used : ServerPortInfoApplicationContextInitializer(org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer) StompFrameHandler(org.springframework.messaging.simp.stomp.StompFrameHandler) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StompHeaders(org.springframework.messaging.simp.stomp.StompHeaders) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) Type(java.lang.reflect.Type) WebSocketStompClient(org.springframework.web.socket.messaging.WebSocketStompClient) SimpleMessageConverter(org.springframework.messaging.converter.SimpleMessageConverter) StompSessionHandlerAdapter(org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)

Example 9 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring-integration by spring-projects.

the class WebSocketInboundChannelAdapter method handleMessageAndSend.

@SuppressWarnings("unchecked")
private void handleMessageAndSend(Message<?> message) throws Exception {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.wrap(message);
    StompCommand stompCommand = (StompCommand) headerAccessor.getHeader("stompCommand");
    SimpMessageType messageType = headerAccessor.getMessageType();
    if ((messageType == null || SimpMessageType.MESSAGE.equals(messageType) || (SimpMessageType.CONNECT.equals(messageType) && !this.useBroker) || StompCommand.CONNECTED.equals(stompCommand) || StompCommand.RECEIPT.equals(stompCommand)) && !checkDestinationPrefix(headerAccessor.getDestination())) {
        if (SimpMessageType.CONNECT.equals(messageType)) {
            String sessionId = headerAccessor.getSessionId();
            SimpMessageHeaderAccessor connectAck = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
            connectAck.setSessionId(sessionId);
            connectAck.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
            Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAck.getMessageHeaders());
            WebSocketSession session = this.webSocketContainer.getSession(sessionId);
            this.subProtocolHandlerRegistry.findProtocolHandler(session).handleMessageToClient(session, ackMessage);
        } else if (StompCommand.CONNECTED.equals(stompCommand)) {
            this.eventPublisher.publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message));
        } else if (StompCommand.RECEIPT.equals(stompCommand)) {
            this.eventPublisher.publishEvent(new ReceiptEvent(this, (Message<byte[]>) message));
        } else {
            headerAccessor.removeHeader(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            Object payload = this.messageConverter.fromMessage(message, this.payloadType.get());
            sendMessage(getMessageBuilderFactory().withPayload(payload).copyHeaders(headerAccessor.toMap()).build());
        }
    } else {
        if (this.useBroker) {
            this.brokerHandler.handleMessage(message);
        } else if (logger.isDebugEnabled()) {
            logger.debug("Messages with non 'SimpMessageType.MESSAGE' type are ignored for sending to the " + "'outputChannel'. They have to be emitted as 'ApplicationEvent's " + "from the 'SubProtocolHandler'. Or using 'AbstractBrokerMessageHandler'(useBroker = true) " + "from server side. Received message: " + message);
        }
    }
}
Also used : ReceiptEvent(org.springframework.integration.websocket.event.ReceiptEvent) SimpMessageType(org.springframework.messaging.simp.SimpMessageType) Message(org.springframework.messaging.Message) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) SessionConnectedEvent(org.springframework.web.socket.messaging.SessionConnectedEvent) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) WebSocketSession(org.springframework.web.socket.WebSocketSession)

Example 10 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project JavaForFun by gumartinm.

the class CustomChannelInterceptor method postSend.

@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
    StompCommand command = accessor.getCommand();
    LOGGER.info("CustomChannelInterceptor postSend, StompCommand: " + command);
    LOGGER.info("CustomChannelInterceptor postSend, login: " + accessor.getLogin());
    long[] heartBeats = accessor.getHeartbeat();
    for (long heartBeat : heartBeats) {
        LOGGER.info("CustomChannelInterceptor postSend, heartBeat: " + heartBeat);
    }
    LOGGER.info("CustomChannelInterceptor postSend, destination: " + accessor.getDestination());
    LOGGER.info("CustomChannelInterceptor postSend, host: " + accessor.getHost());
    LOGGER.info("CustomChannelInterceptor postSend, message: " + accessor.getMessage());
    LOGGER.info("CustomChannelInterceptor postSend, sessionId: " + accessor.getSessionId());
    byte[] payload = (byte[]) message.getPayload();
    String stringPayload = new String(payload);
    LOGGER.info("CustomChannelInterceptor postSend, payload: " + stringPayload);
}
Also used : StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand)

Aggregations

StompCommand (org.springframework.messaging.simp.stomp.StompCommand)14 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)10 Type (java.lang.reflect.Type)2 Principal (java.security.Principal)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 ServerPortInfoApplicationContextInitializer (org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer)2 Message (org.springframework.messaging.Message)2 SimpleMessageConverter (org.springframework.messaging.converter.SimpleMessageConverter)2 StompFrameHandler (org.springframework.messaging.simp.stomp.StompFrameHandler)2 StompHeaders (org.springframework.messaging.simp.stomp.StompHeaders)2 StompSession (org.springframework.messaging.simp.stomp.StompSession)2 StompSessionHandler (org.springframework.messaging.simp.stomp.StompSessionHandler)2 StompSessionHandlerAdapter (org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)2 BinaryMessage (org.springframework.web.socket.BinaryMessage)2 TextMessage (org.springframework.web.socket.TextMessage)2 WebSocketMessage (org.springframework.web.socket.WebSocketMessage)2 WebSocketStompClient (org.springframework.web.socket.messaging.WebSocketStompClient)2 IOException (java.io.IOException)1 ByteBuffer (java.nio.ByteBuffer)1