Java Code Examples for org.springframework.messaging.simp.stomp.StompHeaderAccessor#setDestination()

The following examples show how to use org.springframework.messaging.simp.stomp.StompHeaderAccessor#setDestination() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EventRouter.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void sendHistoryToNewSubscriber(AbstractSubProtocolEvent ev) {
    Message<byte[]> msg = ev.getMessage();
    StompHeaderAccessor ha = StompHeaderAccessor.wrap(msg);
    String pattern = ha.getDestination();
    if(!pattern.startsWith(PREFIX)) {
        // we must send only to appropriate paths
        return;
    }
    MessageConverter messageConverter = this.simpMessagingTemplate.getMessageConverter();

    for(BusData data: buses.values()) {
        String dest = getDestination(data.getId());
        if(!this.pathMatcher.match(pattern, dest)) {
            continue;
        }
        for(Object obj: data.getEvents()) {
            StompHeaderAccessor mha = Stomp.createHeaders(ha.getSessionId(), ha.getSubscriptionId());
            mha.setDestination(dest);
            Message<?> message = messageConverter.toMessage(obj, mha.getMessageHeaders());
            clientChannel.send(message);
        }
    }
}
 
Example 2
Source File: WebSocketStompClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void sendWebSocketBinary() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/b");
	accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
	byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);

	getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class);
	verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture());
	BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
	assertNotNull(binaryMessage);
	assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0",
			new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8));
}
 
Example 3
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void brokerChannelUsedByAnnotatedMethod() {
	TestChannel channel = this.simpleBrokerContext.getBean("brokerChannel", TestChannel.class);
	SimpAnnotationMethodMessageHandler messageHandler =
			this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class);

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
	headers.setSessionId("sess1");
	headers.setSessionAttributes(new ConcurrentHashMap<>());
	headers.setDestination("/foo");
	Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

	messageHandler.handleMessage(message);

	message = channel.messages.get(0);
	headers = StompHeaderAccessor.wrap(message);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals("/bar", headers.getDestination());
	assertEquals("bar", new String((byte[]) message.getPayload()));
}
 
Example 4
Source File: UserDestinationMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleMessageFromBrokerWithoutActiveSession() {
	this.handler.setBroadcastDestination("/topic/unresolved");
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
	accessor.setSessionId("system123");
	accessor.setDestination("/topic/unresolved");
	accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo");
	accessor.setLeaveMutable(true);
	byte[] payload = "payload".getBytes(Charset.forName("UTF-8"));
	this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	// No re-broadcast
	verifyNoMoreInteractions(this.brokerChannel);
}
 
Example 5
Source File: RestTemplateXhrTransportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void connectReceiveAndCloseWithStompFrame() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/destination");
	MessageHeaders headers = accessor.getMessageHeaders();
	Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(Charset.forName("UTF-8")), headers);
	byte[] bytes = new StompEncoder().encode(message);
	TextMessage textMessage = new TextMessage(bytes);
	SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload());

	String body = "o\n" + frame.getContent() + "\n" + "c[3000,\"Go away!\"]";
	ClientHttpResponse response = response(HttpStatus.OK, body);
	connect(response);

	verify(this.webSocketHandler).afterConnectionEstablished(any());
	verify(this.webSocketHandler).handleMessage(any(), eq(textMessage));
	verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example 6
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void clientOutboundChannelUsedByAnnotatedMethod() {
	TestChannel channel = this.simpleBrokerContext.getBean("clientOutboundChannel", TestChannel.class);
	SimpAnnotationMethodMessageHandler messageHandler = this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class);

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	headers.setSessionId("sess1");
	headers.setSessionAttributes(new ConcurrentHashMap<>());
	headers.setSubscriptionId("subs1");
	headers.setDestination("/foo");
	Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();

	messageHandler.handleMessage(message);

	message = channel.messages.get(0);
	headers = StompHeaderAccessor.wrap(message);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals("/foo", headers.getDestination());
	assertEquals("bar", new String((byte[]) message.getPayload()));
}
 
Example 7
Source File: RestTemplateXhrTransportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void connectReceiveAndCloseWithStompFrame() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/destination");
	MessageHeaders headers = accessor.getMessageHeaders();
	Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(StandardCharsets.UTF_8), headers);
	byte[] bytes = new StompEncoder().encode(message);
	TextMessage textMessage = new TextMessage(bytes);
	SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload());

	String body = "o\n" + frame.getContent() + "\n" + "c[3000,\"Go away!\"]";
	ClientHttpResponse response = response(HttpStatus.OK, body);
	connect(response);

	verify(this.webSocketHandler).afterConnectionEstablished(any());
	verify(this.webSocketHandler).handleMessage(any(), eq(textMessage));
	verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example 8
Source File: StompSubProtocolHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleMessageToClientWithUserDestination() {

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
	headers.setMessageId("mess0");
	headers.setSubscriptionId("sub0");
	headers.setDestination("/queue/foo-user123");
	headers.setNativeHeader(StompHeaderAccessor.ORIGINAL_DESTINATION, "/user/queue/foo");
	Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(1, this.session.getSentMessages().size());
	WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0);
	assertTrue(((String) textMessage.getPayload()).contains("destination:/user/queue/foo\n"));
	assertFalse(((String) textMessage.getPayload()).contains(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION));
}
 
Example 9
Source File: StompSubProtocolHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleMessageToClientWithUserDestination() {

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
	headers.setMessageId("mess0");
	headers.setSubscriptionId("sub0");
	headers.setDestination("/queue/foo-user123");
	headers.setNativeHeader(StompHeaderAccessor.ORIGINAL_DESTINATION, "/user/queue/foo");
	Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(1, this.session.getSentMessages().size());
	WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0);
	assertTrue(((String) textMessage.getPayload()).contains("destination:/user/queue/foo\n"));
	assertFalse(((String) textMessage.getPayload()).contains(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION));
}
 
Example 10
Source File: WebSocketStompClientTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void sendWebSocketBinary() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/b");
	accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
	byte[] payload = "payload".getBytes(UTF_8);

	getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class);
	verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture());
	BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
	assertNotNull(binaryMessage);
	assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0",
			new String(binaryMessage.getPayload().array(), UTF_8));
}
 
Example 11
Source File: WeEventStompCommand.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public String encodeSubscribe(TopicContent topic, Long id) {
    StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
    accessor.setDestination(topic.getTopicName());
    accessor.setNativeHeader("eventId", topic.getOffset());

    accessor.setNativeHeader(StompHeaderAccessor.STOMP_ID_HEADER, Long.toString(id));
    if (!StringUtils.isBlank(topic.getGroupId())) {
        accessor.setNativeHeader("groupId", topic.getGroupId());
    }

    // keep the original SubscriptionId
    if (topic.getExtension().containsKey(WeEvent.WeEvent_SubscriptionId)) {
        accessor.setNativeHeader(WeEvent.WeEvent_SubscriptionId, topic.getExtension().get(WeEvent.WeEvent_SubscriptionId));
    }
    if (topic.getExtension().containsKey(WeEvent.WeEvent_TAG)) {
        accessor.setNativeHeader(WeEvent.WeEvent_TAG, topic.getExtension().get(WeEvent.WeEvent_TAG));
    }
    if (topic.getExtension().containsKey(WeEvent.WeEvent_EPHEMERAL)) {
        accessor.setNativeHeader(WeEvent.WeEvent_EPHEMERAL, topic.getExtension().get(WeEvent.WeEvent_EPHEMERAL));
    }
    return encodeRaw(accessor);
}
 
Example 12
Source File: StompSubProtocolHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleMessageToClientWithBinaryWebSocketMessage() {

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
	headers.setMessageId("mess0");
	headers.setSubscriptionId("sub0");
	headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
	headers.setDestination("/queue/foo");

	// Non-empty payload

	byte[] payload = new byte[1];
	Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(1, this.session.getSentMessages().size());
	WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0);
	assertTrue(webSocketMessage instanceof BinaryMessage);

	// Empty payload

	payload = EMPTY_PAYLOAD;
	message = MessageBuilder.createMessage(payload, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(2, this.session.getSentMessages().size());
	webSocketMessage = this.session.getSentMessages().get(1);
	assertTrue(webSocketMessage instanceof TextMessage);
}
 
Example 13
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private void handleOnEvent(String headerIdStr,
                           String subscriptionId,
                           WeEvent event,
                           WebSocketSession session) {
    StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
    // package the return frame
    accessor.setSubscriptionId(headerIdStr);
    accessor.setNativeHeader("subscription-id", subscriptionId);
    accessor.setMessageId(headerIdStr);
    accessor.setDestination(event.getTopic());
    accessor.setContentType(new MimeType("text", "plain", StandardCharsets.UTF_8));

    // set custom properties in header
    for (Map.Entry<String, String> custom : event.getExtensions().entrySet()) {
        accessor.setNativeHeader(custom.getKey(), custom.getValue());
    }

    // set eventId in header
    accessor.setNativeHeader(WeEventConstants.EXTENSIONS_EVENT_ID, event.getEventId());

    // payload == content
    MessageHeaders headers = accessor.getMessageHeaders();
    Message<byte[]> message = MessageBuilder.createMessage(event.getContent(), headers);
    byte[] bytes = new StompEncoder().encode(message);

    // send to remote
    send2Remote(session, new TextMessage(bytes));
}
 
Example 14
Source File: MessageBrokerConfigurationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void clientOutboundChannelUsedBySimpleBroker() {
	ApplicationContext context = loadConfig(SimpleBrokerConfig.class);

	TestChannel outboundChannel = context.getBean("clientOutboundChannel", TestChannel.class);
	SimpleBrokerMessageHandler broker = context.getBean(SimpleBrokerMessageHandler.class);

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	headers.setSessionId("sess1");
	headers.setSubscriptionId("subs1");
	headers.setDestination("/foo");
	Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

	// subscribe
	broker.handleMessage(createConnectMessage("sess1", new long[] {0,0}));
	broker.handleMessage(message);

	headers = StompHeaderAccessor.create(StompCommand.SEND);
	headers.setSessionId("sess1");
	headers.setDestination("/foo");
	message = MessageBuilder.createMessage("bar".getBytes(), headers.getMessageHeaders());

	// message
	broker.handleMessage(message);

	message = outboundChannel.messages.get(1);
	headers = StompHeaderAccessor.wrap(message);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals("/foo", headers.getDestination());
	assertEquals("bar", new String((byte[]) message.getPayload()));
}
 
Example 15
Source File: Stomp.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Send message to queue of current session
 * @param subscriptionId
 * @param dest
 * @param msg
 */
public void sendToSubscription(String subscriptionId, String dest, Object msg) {
    Assert.notNull(subscriptionId, "subscriptionId is null");
    StompHeaderAccessor sha = createHeaders(sessionId, subscriptionId);
    MessageConverter messageConverter = this.template.getMessageConverter();
    sha.setDestination("/queue/" + dest);
    Message<?> message = messageConverter.toMessage(msg, sha.getMessageHeaders());
    clientChannel.send(message);
}
 
Example 16
Source File: SimpMessagingTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void doSendWithStompHeaders() {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	accessor.setDestination("/user/queue/foo");
	Message<?> message = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());

	this.messagingTemplate.doSend("/queue/foo-user123", message);

	List<Message<byte[]>> messages = this.messageChannel.getMessages();
	Message<byte[]> sentMessage = messages.get(0);

	MessageHeaderAccessor sentAccessor = MessageHeaderAccessor.getAccessor(sentMessage, MessageHeaderAccessor.class);
	assertEquals(StompHeaderAccessor.class, sentAccessor.getClass());
	assertEquals("/queue/foo-user123", ((StompHeaderAccessor) sentAccessor).getDestination());
}
 
Example 17
Source File: UserDestinationMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleMessageFromBrokerWithActiveSession() {
	TestSimpUser simpUser = new TestSimpUser("joe");
	simpUser.addSessions(new TestSimpSession("123"));
	when(this.registry.getUser("joe")).thenReturn(simpUser);

	this.handler.setBroadcastDestination("/topic/unresolved");
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
	accessor.setSessionId("system123");
	accessor.setDestination("/topic/unresolved");
	accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo");
	accessor.setNativeHeader("customHeader", "customHeaderValue");
	accessor.setLeaveMutable(true);
	byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
	this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	Mockito.verify(this.brokerChannel).send(captor.capture());
	assertNotNull(captor.getValue());
	SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(captor.getValue());
	assertEquals("/queue/foo-user123", headers.getDestination());
	assertEquals("/user/queue/foo", headers.getFirstNativeHeader(ORIGINAL_DESTINATION));
	assertEquals("customHeaderValue", headers.getFirstNativeHeader("customHeader"));
	assertArrayEquals(payload, (byte[]) captor.getValue().getPayload());
}
 
Example 18
Source File: SimpMessagingTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void doSendWithStompHeaders() {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	accessor.setDestination("/user/queue/foo");
	Message<?> message = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());

	this.messagingTemplate.doSend("/queue/foo-user123", message);

	List<Message<byte[]>> messages = this.messageChannel.getMessages();
	Message<byte[]> sentMessage = messages.get(0);

	MessageHeaderAccessor sentAccessor = MessageHeaderAccessor.getAccessor(sentMessage, MessageHeaderAccessor.class);
	assertEquals(StompHeaderAccessor.class, sentAccessor.getClass());
	assertEquals("/queue/foo-user123", ((StompHeaderAccessor) sentAccessor).getDestination());
}
 
Example 19
Source File: WebSocketStompSession.java    From bearchoke with Apache License 2.0 4 votes vote down vote up
public void send(String destination, Object payload) {
	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
	headers.setDestination(destination);
	sendInternal((Message<byte[]>)this.messageConverter.toMessage(payload, new MessageHeaders(headers.toMap())));
}
 
Example 20
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void testDotSeparator(ApplicationContext context, boolean expectLeadingSlash) {
	MessageChannel inChannel = context.getBean("clientInboundChannel", MessageChannel.class);
	TestChannel outChannel = context.getBean("clientOutboundChannel", TestChannel.class);
	MessageChannel brokerChannel = context.getBean("brokerChannel", MessageChannel.class);

	inChannel.send(createConnectMessage("sess1", new long[] {0,0}));

	// 1. Subscribe to user destination

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	headers.setSessionId("sess1");
	headers.setSubscriptionId("subs1");
	headers.setDestination("/user/queue.q1");
	Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
	inChannel.send(message);

	// 2. Send message to user via inboundChannel

	headers = StompHeaderAccessor.create(StompCommand.SEND);
	headers.setSessionId("sess1");
	headers.setDestination("/user/sess1/queue.q1");
	message = MessageBuilder.createMessage("123".getBytes(), headers.getMessageHeaders());
	inChannel.send(message);

	assertEquals(2, outChannel.messages.size());
	Message<?> outputMessage = outChannel.messages.remove(1);
	headers = StompHeaderAccessor.wrap(outputMessage);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination());
	assertEquals("123", new String((byte[]) outputMessage.getPayload()));
	outChannel.messages.clear();

	// 3. Send message via broker channel

	SimpMessagingTemplate template = new SimpMessagingTemplate(brokerChannel);
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
	accessor.setSessionId("sess1");
	template.convertAndSendToUser("sess1", "queue.q1", "456".getBytes(), accessor.getMessageHeaders());

	assertEquals(1, outChannel.messages.size());
	outputMessage = outChannel.messages.remove(0);
	headers = StompHeaderAccessor.wrap(outputMessage);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination());
	assertEquals("456", new String((byte[]) outputMessage.getPayload()));

}