Search in sources :

Example 1 with WebSocketMessage

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

the class StompSubProtocolHandler method handleMessageFromClient.

/**
	 * Handle incoming WebSocket messages from clients.
	 */
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) {
    List<Message<byte[]>> messages;
    try {
        ByteBuffer byteBuffer;
        if (webSocketMessage instanceof TextMessage) {
            byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes());
        } else if (webSocketMessage instanceof BinaryMessage) {
            byteBuffer = ((BinaryMessage) webSocketMessage).getPayload();
        } else {
            return;
        }
        BufferingStompDecoder decoder = this.decoders.get(session.getId());
        if (decoder == null) {
            throw new IllegalStateException("No decoder for session id '" + session.getId() + "'");
        }
        messages = decoder.decode(byteBuffer);
        if (messages.isEmpty()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Incomplete STOMP frame content received in session " + session + ", bufferSize=" + decoder.getBufferSize() + ", bufferSizeLimit=" + decoder.getBufferSizeLimit() + ".");
            }
            return;
        }
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex);
        }
        handleError(session, ex, null);
        return;
    }
    for (Message<byte[]> message : messages) {
        try {
            StompHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
            headerAccessor.setSessionId(session.getId());
            headerAccessor.setSessionAttributes(session.getAttributes());
            headerAccessor.setUser(getUser(session));
            headerAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, headerAccessor.getHeartbeat());
            if (!detectImmutableMessageInterceptor(outputChannel)) {
                headerAccessor.setImmutable();
            }
            if (logger.isTraceEnabled()) {
                logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload()));
            }
            boolean isConnect = StompCommand.CONNECT.equals(headerAccessor.getCommand());
            if (isConnect) {
                this.stats.incrementConnectCount();
            } else if (StompCommand.DISCONNECT.equals(headerAccessor.getCommand())) {
                this.stats.incrementDisconnectCount();
            }
            try {
                SimpAttributesContextHolder.setAttributesFromMessage(message);
                boolean sent = outputChannel.send(message);
                if (sent) {
                    if (isConnect) {
                        Principal user = headerAccessor.getUser();
                        if (user != null && user != session.getPrincipal()) {
                            this.stompAuthentications.put(session.getId(), user);
                        }
                    }
                    if (this.eventPublisher != null) {
                        if (isConnect) {
                            publishEvent(new SessionConnectEvent(this, message, getUser(session)));
                        } else if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) {
                            publishEvent(new SessionSubscribeEvent(this, message, getUser(session)));
                        } else if (StompCommand.UNSUBSCRIBE.equals(headerAccessor.getCommand())) {
                            publishEvent(new SessionUnsubscribeEvent(this, message, getUser(session)));
                        }
                    }
                }
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        } catch (Throwable ex) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to send client message to application via MessageChannel" + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex);
            }
            handleError(session, ex, message);
        }
    }
}
Also used : TextMessage(org.springframework.web.socket.TextMessage) Message(org.springframework.messaging.Message) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) BinaryMessage(org.springframework.web.socket.BinaryMessage) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) ByteBuffer(java.nio.ByteBuffer) BinaryMessage(org.springframework.web.socket.BinaryMessage) BufferingStompDecoder(org.springframework.messaging.simp.stomp.BufferingStompDecoder) TextMessage(org.springframework.web.socket.TextMessage) Principal(java.security.Principal)

Example 2 with WebSocketMessage

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

the class StompSubProtocolHandlerTests method webSocketScope.

@Test
public void webSocketScope() {
    Runnable runnable = Mockito.mock(Runnable.class);
    SimpAttributes simpAttributes = new SimpAttributes(this.session.getId(), this.session.getAttributes());
    simpAttributes.setAttribute("name", "value");
    simpAttributes.registerDestructionCallback("name", runnable);
    MessageChannel testChannel = new MessageChannel() {

        @Override
        public boolean send(Message<?> message) {
            SimpAttributes simpAttributes = SimpAttributesContextHolder.currentAttributes();
            assertThat(simpAttributes.getAttribute("name"), is("value"));
            return true;
        }

        @Override
        public boolean send(Message<?> message, long timeout) {
            return false;
        }
    };
    this.protocolHandler.afterSessionStarted(this.session, this.channel);
    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
    Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
    TextMessage textMessage = new TextMessage(new StompEncoder().encode(message));
    this.protocolHandler.handleMessageFromClient(this.session, textMessage, testChannel);
    assertEquals(Collections.<WebSocketMessage<?>>emptyList(), session.getSentMessages());
    this.protocolHandler.afterSessionEnded(this.session, CloseStatus.BAD_DATA, testChannel);
    assertEquals(Collections.<WebSocketMessage<?>>emptyList(), this.session.getSentMessages());
    verify(runnable, times(1)).run();
}
Also used : MessageChannel(org.springframework.messaging.MessageChannel) TextMessage(org.springframework.web.socket.TextMessage) Message(org.springframework.messaging.Message) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) BinaryMessage(org.springframework.web.socket.BinaryMessage) SimpAttributes(org.springframework.messaging.simp.SimpAttributes) StompEncoder(org.springframework.messaging.simp.stomp.StompEncoder) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) TextMessage(org.springframework.web.socket.TextMessage) Test(org.junit.Test)

Aggregations

Message (org.springframework.messaging.Message)2 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)2 BinaryMessage (org.springframework.web.socket.BinaryMessage)2 TextMessage (org.springframework.web.socket.TextMessage)2 WebSocketMessage (org.springframework.web.socket.WebSocketMessage)2 ByteBuffer (java.nio.ByteBuffer)1 Principal (java.security.Principal)1 Test (org.junit.Test)1 MessageChannel (org.springframework.messaging.MessageChannel)1 SimpAttributes (org.springframework.messaging.simp.SimpAttributes)1 BufferingStompDecoder (org.springframework.messaging.simp.stomp.BufferingStompDecoder)1 StompEncoder (org.springframework.messaging.simp.stomp.StompEncoder)1