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

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

Introduction

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

Prototype

public MessageHeaders getMessageHeaders() 

Source Link

Document

Return the underlying MessageHeaders instance.

Usage

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);// ww w  .  j a  v a 2  s.  c  om

    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.ja v  a2  s. co m

    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.DefaultStompSession.java

@SuppressWarnings("unchecked")
private Message<byte[]> createMessage(StompHeaderAccessor accessor, @Nullable Object payload) {
    accessor.updateSimpMessageHeadersFromStompHeaders();
    Message<byte[]> message;
    if (payload == null) {
        message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
    } else if (payload instanceof byte[]) {
        message = MessageBuilder.createMessage((byte[]) payload, accessor.getMessageHeaders());
    } else {//from  ww w. java 2  s  .co m
        message = (Message<byte[]>) getMessageConverter().toMessage(payload, accessor.getMessageHeaders());
        accessor.updateStompHeadersFromSimpMessageHeaders();
        if (message == null) {
            throw new MessageConversionException(
                    "Unable to convert payload with type='" + payload.getClass().getName() + "', contentType='"
                            + accessor.getContentType() + "', converter=[" + getMessageConverter() + "]");
        }
    }
    return message;
}

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

@Test(expected = MessageDeliveryException.class)
public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception {

    logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()");

    stopActiveMqBrokerAndAwait();//from w w w. j ava 2s  .com
    this.eventPublisher.expectBrokerAvailabilityEvent(false);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
    this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders()));
}

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

/**
 * Decode a single STOMP frame from the given {@code buffer} into a {@link Message}.
 *///  w  w w . jav  a  2s.com
@Nullable
private Message<byte[]> decodeMessage(ByteBuffer byteBuffer, @Nullable MultiValueMap<String, String> headers) {
    Message<byte[]> decodedMessage = null;
    skipLeadingEol(byteBuffer);

    // Explicit mark/reset access via Buffer base type for compatibility
    // with covariant return type on JDK 9's ByteBuffer...
    Buffer buffer = byteBuffer;
    buffer.mark();

    String command = readCommand(byteBuffer);
    if (command.length() > 0) {
        StompHeaderAccessor headerAccessor = null;
        byte[] payload = null;
        if (byteBuffer.remaining() > 0) {
            StompCommand stompCommand = StompCommand.valueOf(command);
            headerAccessor = StompHeaderAccessor.create(stompCommand);
            initHeaders(headerAccessor);
            readHeaders(byteBuffer, headerAccessor);
            payload = readPayload(byteBuffer, headerAccessor);
        }
        if (payload != null) {
            if (payload.length > 0) {
                StompCommand stompCommand = headerAccessor.getCommand();
                if (stompCommand != null && !stompCommand.isBodyAllowed()) {
                    throw new StompConversionException(stompCommand + " shouldn't have a payload: length="
                            + payload.length + ", headers=" + headers);
                }
            }
            headerAccessor.updateSimpMessageHeadersFromStompHeaders();
            headerAccessor.setLeaveMutable(true);
            decodedMessage = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
            if (logger.isTraceEnabled()) {
                logger.trace("Decoded " + headerAccessor.getDetailedLogMessage(payload));
            }
        } else {
            logger.trace("Incomplete frame, resetting input buffer...");
            if (headers != null && headerAccessor != null) {
                String name = NativeMessageHeaderAccessor.NATIVE_HEADERS;
                @SuppressWarnings("unchecked")
                MultiValueMap<String, String> map = (MultiValueMap<String, String>) headerAccessor
                        .getHeader(name);
                if (map != null) {
                    headers.putAll(map);
                }
            }
            buffer.reset();
        }
    } else {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.createForHeartbeat();
        initHeaders(headerAccessor);
        headerAccessor.setLeaveMutable(true);
        decodedMessage = MessageBuilder.createMessage(HEARTBEAT_PAYLOAD, headerAccessor.getMessageHeaders());
        if (logger.isTraceEnabled()) {
            logger.trace("Decoded " + headerAccessor.getDetailedLogMessage(null));
        }
    }

    return decodedMessage;
}

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

/**
 * Invoked when no/*from  ww  w.  j ava  2 s .  c om*/
 * {@link #setErrorHandler(StompSubProtocolErrorHandler) errorHandler}
 * is configured to send an ERROR frame to the client.
 */
private void sendErrorMessage(WebSocketSession session, Throwable error) {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
    headerAccessor.setMessage(error.getMessage());

    byte[] bytes = this.stompEncoder.encode(headerAccessor.getMessageHeaders(), EMPTY_PAYLOAD);
    try {
        session.sendMessage(new TextMessage(bytes));
    } catch (Throwable ex) {
        // Could be part of normal workflow (e.g. browser tab closed)
        logger.debug("Failed to send STOMP ERROR to client", ex);
    }
}

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

private void sendToClient(WebSocketSession session, StompHeaderAccessor stompAccessor, byte[] payload) {
    StompCommand command = stompAccessor.getCommand();
    try {/*from   w ww .  jav  a  2  s  .  c  om*/
        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
            }
        }
    }
}

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);
    }//from   w w  w  . j av  a 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());
}