Example usage for org.springframework.messaging.simp.stomp StompCommand SUBSCRIBE

List of usage examples for org.springframework.messaging.simp.stomp StompCommand SUBSCRIBE

Introduction

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

Prototype

StompCommand SUBSCRIBE

To view the source code for org.springframework.messaging.simp.stomp StompCommand SUBSCRIBE.

Click Source Link

Usage

From source file:com.codeveo.lago.bot.stomp.client.WebSocketStompSession.java

public void subscribe(String destination, String receiptId) {
    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId("sub-" + this.subscriptionIndex.getAndIncrement());
    headers.setDestination(destination);
    if (receiptId != null) {
        headers.setReceipt(receiptId);/*w w w  .java  2 s .  c  om*/
    }
    sendInternal(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(headers).build());
}

From source file:fr.jugorleans.poker.client.stomp.WebSocketStompSession.java

public void subscribe(String destination, String receiptId) {
    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId("sub" + this.subscriptionIndex.getAndIncrement());
    headers.setDestination(destination);
    if (receiptId != null) {
        headers.setReceipt(receiptId);//from ww w.  j  av  a  2 s .c  om
    }
    sendInternal(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(headers).build());
}

From source file:jp.pigumer.web.StompConfig.java

@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
    registration.setInterceptors(new ChannelInterceptorAdapter() {
        @Override//from   w ww  . j  av a2  s .co  m
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            if (accessor.getCommand() == StompCommand.SUBSCRIBE) {
                LOGGER.log(Level.INFO, String.format("%s: %s", channel, message));
            }
            return message;
        }
    });
}

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:smpp.networking.SimpleStompClient.java

public void subscribe(String destination, MessageHandler messageHandler) {

    String id = String.valueOf(this.subscriptionIndex.getAndIncrement());
    this.subscriptionHandlers.put(id, messageHandler);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId(id);/*from ww  w .j  av  a2s .co  m*/
    headers.setDestination(destination);

    Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
    byte[] bytes = encoder.encode(message);
    try {
        this.session.getRemote().sendString(new String(bytes, DEFAULT_CHARSET));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

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

@Override
public Subscription subscribe(StompHeaders stompHeaders, StompFrameHandler handler) {
    Assert.hasText(stompHeaders.getDestination(), "Destination header is required");
    Assert.notNull(handler, "StompFrameHandler must not be null");

    String subscriptionId = stompHeaders.getId();
    if (!StringUtils.hasText(subscriptionId)) {
        subscriptionId = String.valueOf(DefaultStompSession.this.subscriptionIndex.getAndIncrement());
        stompHeaders.setId(subscriptionId);
    }//from  w  ww .  j a  v a 2 s. c o  m
    checkOrAddReceipt(stompHeaders);
    Subscription subscription = new DefaultSubscription(stompHeaders, handler);

    StompHeaderAccessor accessor = createHeaderAccessor(StompCommand.SUBSCRIBE);
    accessor.addNativeHeaders(stompHeaders);
    Message<byte[]> message = createMessage(accessor, EMPTY_PAYLOAD);
    execute(message);

    return subscription;
}

From source file:org.springframework.samples.portfolio.web.tomcat.TestStompClient.java

public void subscribe(String destination, MessageHandler messageHandler) {

    String id = String.valueOf(this.subscriptionIndex.getAndIncrement());
    this.subscriptionHandlers.put(id, messageHandler);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    headers.setSubscriptionId(id);//from   w ww .j a  v a  2 s . c  o  m
    headers.setDestination(destination);

    Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
    byte[] bytes = encoder.encode(message);
    try {
        this.session.sendMessage(new TextMessage(new String(bytes, DEFAULT_CHARSET)));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

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

/**
 * Handle incoming WebSocket messages from clients.
 *///from ww  w.ja v a  2 s  . 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);
        }
    }
}