Search in sources :

Example 1 with SimpAttributes

use of org.springframework.messaging.simp.SimpAttributes 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")).isEqualTo("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);
    assertThat(session.getSentMessages()).isEqualTo(Collections.<WebSocketMessage<?>>emptyList());
    this.protocolHandler.afterSessionEnded(this.session, CloseStatus.BAD_DATA, testChannel);
    assertThat(this.session.getSentMessages()).isEqualTo(Collections.<WebSocketMessage<?>>emptyList());
    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.jupiter.api.Test)

Example 2 with SimpAttributes

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

the class StompSubProtocolHandler method handleMessageToClient.

/**
 * Handle STOMP messages going back out to WebSocket clients.
 */
@Override
@SuppressWarnings("unchecked")
public void handleMessageToClient(WebSocketSession session, Message<?> message) {
    if (!(message.getPayload() instanceof byte[])) {
        if (logger.isErrorEnabled()) {
            logger.error("Expected byte[] payload. Ignoring " + message + ".");
        }
        return;
    }
    StompHeaderAccessor accessor = getStompHeaderAccessor(message);
    StompCommand command = accessor.getCommand();
    if (StompCommand.MESSAGE.equals(command)) {
        if (accessor.getSubscriptionId() == null && logger.isWarnEnabled()) {
            logger.warn("No STOMP \"subscription\" header in " + message);
        }
        String origDestination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
        if (origDestination != null) {
            accessor = toMutableAccessor(accessor, message);
            accessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
            accessor.setDestination(origDestination);
        }
    } else if (StompCommand.CONNECTED.equals(command)) {
        this.stats.incrementConnectedCount();
        accessor = afterStompSessionConnected(message, accessor, session);
        if (this.eventPublisher != null) {
            try {
                SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
                SimpAttributesContextHolder.setAttributes(simpAttributes);
                Principal user = getUser(session);
                publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user));
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        }
    }
    byte[] payload = (byte[]) message.getPayload();
    if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) {
        Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message);
        if (errorMessage != null) {
            accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class);
            Assert.state(accessor != null, "No StompHeaderAccessor");
            payload = errorMessage.getPayload();
        }
    }
    Runnable task = OrderedMessageChannelDecorator.getNextMessageTask(message);
    if (task != null) {
        Assert.isInstanceOf(ConcurrentWebSocketSessionDecorator.class, session);
        ((ConcurrentWebSocketSessionDecorator) session).setMessageCallback(m -> task.run());
    }
    sendToClient(session, accessor, payload);
}
Also used : SimpAttributes(org.springframework.messaging.simp.SimpAttributes) ConcurrentWebSocketSessionDecorator(org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) Principal(java.security.Principal)

Example 3 with SimpAttributes

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

the class StompSubProtocolHandler method afterSessionEnded.

@Override
public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) {
    this.decoders.remove(session.getId());
    Message<byte[]> message = createDisconnectMessage(session);
    SimpAttributes simpAttributes = SimpAttributes.fromMessage(message);
    try {
        SimpAttributesContextHolder.setAttributes(simpAttributes);
        if (this.eventPublisher != null) {
            Principal user = getUser(session);
            publishEvent(this.eventPublisher, new SessionDisconnectEvent(this, message, session.getId(), closeStatus, user));
        }
        outputChannel.send(message);
    } finally {
        this.stompAuthentications.remove(session.getId());
        SimpAttributesContextHolder.resetAttributes();
        simpAttributes.sessionCompleted();
    }
}
Also used : SimpAttributes(org.springframework.messaging.simp.SimpAttributes) Principal(java.security.Principal)

Aggregations

SimpAttributes (org.springframework.messaging.simp.SimpAttributes)3 Principal (java.security.Principal)2 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)2 Test (org.junit.jupiter.api.Test)1 Message (org.springframework.messaging.Message)1 MessageChannel (org.springframework.messaging.MessageChannel)1 StompCommand (org.springframework.messaging.simp.stomp.StompCommand)1 StompEncoder (org.springframework.messaging.simp.stomp.StompEncoder)1 BinaryMessage (org.springframework.web.socket.BinaryMessage)1 TextMessage (org.springframework.web.socket.TextMessage)1 WebSocketMessage (org.springframework.web.socket.WebSocketMessage)1 ConcurrentWebSocketSessionDecorator (org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator)1