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

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

Introduction

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

Prototype

@Nullable
    public String getSubscriptionId() 

Source Link

Usage

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 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);/*  w  w w.  j a  v a  2  s.c  o  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.StompProtocolHandler.java

/**
 * Handle STOMP messages going back out to WebSocket clients.
 *//* w  w  w.j  a v a2  s.c o m*/
@Override
public void handleMessageToClient(WebSocketSession session, Message<?> message) {

    StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
    headers.setCommandIfNotSet(StompCommand.MESSAGE);

    if (StompCommand.CONNECTED.equals(headers.getCommand())) {
        // Ignore for now since we already sent it
        return;
    }

    if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no subscriptionId header: " + message);
        return;
    }

    if (!(message.getPayload() instanceof byte[])) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, expected byte[] content: " + message);
        return;
    }

    try {
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
        byte[] bytes = this.stompMessageConverter.fromMessage(message);
        session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8"))));
    } catch (Throwable t) {
        sendErrorMessage(session, t);
    } finally {
        if (StompCommand.ERROR.equals(headers.getCommand())) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException e) {
            }
        }
    }
}

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

/**
 * Handle STOMP messages going back out to WebSocket clients.
 *//*from w ww .  j a v  a2s. c o m*/
@Override
public void handleMessage(Message<?> message) {

    StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
    headers.setCommandIfNotSet(StompCommand.MESSAGE);

    if (StompCommand.CONNECTED.equals(headers.getCommand())) {
        // Ignore for now since we already sent it
        return;
    }

    String sessionId = headers.getSessionId();
    if (sessionId == null) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no sessionId header: " + message);
        return;
    }

    WebSocketSession session = this.sessions.get(sessionId);
    if (session == null) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, sessionId not found: " + message);
        return;
    }

    if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no subscriptionId header: " + message);
        return;
    }

    if (!(message.getPayload() instanceof byte[])) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, expected byte[] content: " + message);
        return;
    }

    try {
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
        byte[] bytes = this.stompMessageConverter.fromMessage(message);
        session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8"))));
    } catch (Throwable t) {
        sendErrorMessage(session, t);
    } finally {
        if (StompCommand.ERROR.equals(headers.getCommand())) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException e) {
            }
        }
    }
}

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

/**
 * Handle STOMP messages going back out to WebSocket clients.
 *///w w w . j a va2  s .  c  o  m
@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 && StompCommand.CONNECTED.equals(command)) {
            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();
        }
    }
    sendToClient(session, accessor, payload);
}