Example usage for org.springframework.messaging.simp.stomp StompHeaderAccessor setUser

List of usage examples for org.springframework.messaging.simp.stomp StompHeaderAccessor setUser

Introduction

In this page you can find the example usage for org.springframework.messaging.simp.stomp StompHeaderAccessor setUser.

Prototype

public void setUser(@Nullable Principal principal) 

Source Link

Usage

From source file:org.springframework.samples.portfolio.web.standalone.StandalonePortfolioControllerTests.java

@Test
public void executeTrade() throws Exception {

    Trade trade = new Trade();
    trade.setAction(Trade.TradeAction.Buy);
    trade.setTicker("DELL");
    trade.setShares(25);/*from  w  ww.ja v  a2  s.com*/

    byte[] payload = new ObjectMapper().writeValueAsBytes(trade);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
    headers.setDestination("/app/trade");
    headers.setSessionId("0");
    headers.setUser(new TestPrincipal("fabrice"));
    headers.setSessionAttributes(new HashMap<String, Object>());
    Message<byte[]> message = MessageBuilder.withPayload(payload).setHeaders(headers).build();

    this.annotationMethodMessageHandler.handleMessage(message);

    assertEquals(1, this.tradeService.getTrades().size());
    Trade actual = this.tradeService.getTrades().get(0);

    assertEquals(Trade.TradeAction.Buy, actual.getAction());
    assertEquals("DELL", actual.getTicker());
    assertEquals(25, actual.getShares());
    assertEquals("fabrice", actual.getUsername());
}

From source file:org.springframework.samples.portfolio.web.standalone.StandalonePortfolioControllerTests.java

@Test
public void getPositions() throws Exception {

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId("0");
    headers.setDestination("/app/positions");
    headers.setSessionId("0");
    headers.setUser(new TestPrincipal("fabrice"));
    headers.setSessionAttributes(new HashMap<String, Object>());
    Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();

    this.annotationMethodMessageHandler.handleMessage(message);

    assertEquals(1, this.clientOutboundChannel.getMessages().size());
    Message<?> reply = this.clientOutboundChannel.getMessages().get(0);

    StompHeaderAccessor replyHeaders = StompHeaderAccessor.wrap(reply);
    assertEquals("0", replyHeaders.getSessionId());
    assertEquals("0", replyHeaders.getSubscriptionId());
    assertEquals("/app/positions", replyHeaders.getDestination());

    String json = new String((byte[]) reply.getPayload(), Charset.forName("UTF-8"));
    new JsonPathExpectationsHelper("$[0].company").assertValue(json, "Citrix Systems, Inc.");
    new JsonPathExpectationsHelper("$[1].company").assertValue(json, "Dell Inc.");
    new JsonPathExpectationsHelper("$[2].company").assertValue(json, "Microsoft");
    new JsonPathExpectationsHelper("$[3].company").assertValue(json, "Oracle");
}

From source file:org.springframework.samples.portfolio.web.context.ContextPortfolioControllerTests.java

@Test
public void executeTrade() throws Exception {

    Trade trade = new Trade();
    trade.setAction(Trade.TradeAction.Buy);
    trade.setTicker("DELL");
    trade.setShares(25);/*from   w ww  .j  a  v  a2  s .co  m*/

    byte[] payload = new ObjectMapper().writeValueAsBytes(trade);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
    headers.setDestination("/app/trade");
    headers.setSessionId("0");
    headers.setUser(new TestPrincipal("fabrice"));
    headers.setSessionAttributes(new HashMap<String, Object>());
    Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders());

    this.brokerChannelInterceptor.setIncludedDestinations("/user/**");
    this.brokerChannelInterceptor.startRecording();

    this.clientInboundChannel.send(message);

    Message<?> positionUpdate = this.brokerChannelInterceptor.awaitMessage(5);
    assertNotNull(positionUpdate);

    StompHeaderAccessor positionUpdateHeaders = StompHeaderAccessor.wrap(positionUpdate);
    assertEquals("/user/fabrice/queue/position-updates", positionUpdateHeaders.getDestination());

    String json = new String((byte[]) positionUpdate.getPayload(), Charset.forName("UTF-8"));
    new JsonPathExpectationsHelper("$.ticker").assertValue(json, "DELL");
    new JsonPathExpectationsHelper("$.shares").assertValue(json, 75);
}

From source file:org.springframework.samples.portfolio.web.context.ContextPortfolioControllerTests.java

@Test
public void getPositions() throws Exception {

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId("0");
    headers.setDestination("/app/positions");
    headers.setSessionId("0");
    headers.setUser(new TestPrincipal("fabrice"));
    headers.setSessionAttributes(new HashMap<String, Object>());
    Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

    this.clientOutboundChannelInterceptor.setIncludedDestinations("/app/positions");
    this.clientOutboundChannelInterceptor.startRecording();

    this.clientInboundChannel.send(message);

    Message<?> reply = this.clientOutboundChannelInterceptor.awaitMessage(5);
    assertNotNull(reply);/*from   w w w . j a v a2 s.com*/

    StompHeaderAccessor replyHeaders = StompHeaderAccessor.wrap(reply);
    assertEquals("0", replyHeaders.getSessionId());
    assertEquals("0", replyHeaders.getSubscriptionId());
    assertEquals("/app/positions", replyHeaders.getDestination());

    String json = new String((byte[]) reply.getPayload(), Charset.forName("UTF-8"));
    new JsonPathExpectationsHelper("$[0].company").assertValue(json, "Citrix Systems, Inc.");
    new JsonPathExpectationsHelper("$[1].company").assertValue(json, "Dell Inc.");
    new JsonPathExpectationsHelper("$[2].company").assertValue(json, "Microsoft");
    new JsonPathExpectationsHelper("$[3].company").assertValue(json, "Oracle");
}

From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java

/**
 * Handle incoming WebSocket messages from clients.
 *///from   ww  w .  java 2 s .c  o m
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage webSocketMessage,
        MessageChannel outputChannel) {

    try {
        Assert.isInstanceOf(TextMessage.class, webSocketMessage);
        String payload = ((TextMessage) webSocketMessage).getPayload();
        Message<?> message = this.stompMessageConverter.toMessage(payload);

        // TODO: validate size limits
        // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits

        if (logger.isTraceEnabled()) {
            logger.trace("Processing STOMP message: " + message);
        }

        try {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
            headers.setSessionId(session.getId());
            headers.setUser(session.getPrincipal());

            message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();

            if (SimpMessageType.CONNECT.equals(headers.getMessageType())) {
                handleConnect(session, message);
            }

            outputChannel.send(message);

        } catch (Throwable t) {
            logger.error("Terminating STOMP session due to failure to send message: ", t);
            sendErrorMessage(session, t);
        }

        // TODO: send RECEIPT message if incoming message has "receipt" header
        // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt

    } catch (Throwable error) {
        sendErrorMessage(session, error);
    }
}

From source file:org.springframework.messaging.simp.stomp.StompWebSocketHandler.java

/**
 * Handle incoming WebSocket messages from clients.
 *///  w  w  w  . ja v  a 2s .c o m
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) {
    try {
        String payload = textMessage.getPayload();
        Message<?> message = this.stompMessageConverter.toMessage(payload);

        // TODO: validate size limits
        // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits

        if (logger.isTraceEnabled()) {
            logger.trace("Processing STOMP message: " + message);
        }

        try {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
            headers.setSessionId(session.getId());
            headers.setUser(session.getPrincipal());
            message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();

            if (SimpMessageType.CONNECT.equals(headers.getMessageType())) {
                handleConnect(session, message);
            }

            this.dispatchChannel.send(message);

        } catch (Throwable t) {
            logger.error("Terminating STOMP session due to failure to send message: ", t);
            sendErrorMessage(session, t);
        }

        // TODO: send RECEIPT message if incoming message has "receipt" header
        // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt

    } catch (Throwable error) {
        sendErrorMessage(session, error);
    }
}

From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java

/**
 * Handle incoming WebSocket messages from clients.
 */// w  w  w.ja v  a 2s  .  c o m
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);
            Assert.state(headerAccessor != null, "No StompHeaderAccessor");

            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()));
            }

            StompCommand command = headerAccessor.getCommand();
            boolean isConnect = StompCommand.CONNECT.equals(command);
            if (isConnect) {
                this.stats.incrementConnectCount();
            } else if (StompCommand.DISCONNECT.equals(command)) {
                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) {
                        Principal user = getUser(session);
                        if (isConnect) {
                            publishEvent(this.eventPublisher, new SessionConnectEvent(this, message, user));
                        } else if (StompCommand.SUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionSubscribeEvent(this, message, user));
                        } else if (StompCommand.UNSUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionUnsubscribeEvent(this, message, user));
                        }
                    }
                }
            } 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);
        }
    }
}

From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java

private Message<byte[]> createDisconnectMessage(WebSocketSession session) {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.DISCONNECT);
    if (getHeaderInitializer() != null) {
        getHeaderInitializer().initHeaders(headerAccessor);
    }//  www . j a  va  2 s .  co m

    headerAccessor.setSessionId(session.getId());
    headerAccessor.setSessionAttributes(session.getAttributes());

    Principal user = getUser(session);
    if (user != null) {
        headerAccessor.setUser(user);
    }

    return MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders());
}