org.springframework.messaging.simp.SimpMessageType Java Examples

The following examples show how to use org.springframework.messaging.simp.SimpMessageType. 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: DefaultUserDestinationResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleMessageEncodedUserName() {
	String userName = "https://joe.openid.example.org/";

	TestSimpUser simpUser = new TestSimpUser(userName);
	simpUser.addSessions(new TestSimpSession("openid123"));
	given(this.registry.getUser(userName)).willReturn(simpUser);

	String destination = "/user/" + StringUtils.replace(userName, "/", "%2F") + "/queue/foo";

	Message<?> message = createMessage(SimpMessageType.MESSAGE, new TestPrincipal("joe"), null, destination);
	UserDestinationResult actual = this.resolver.resolveDestination(message);

	assertEquals(1, actual.getTargetDestinations().size());
	assertEquals("/queue/foo-useropenid123", actual.getTargetDestinations().iterator().next());
}
 
Example #2
Source File: DefaultUserDestinationResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-12444
public void handleMessageToOtherUser() {

	TestSimpUser otherSimpUser = new TestSimpUser("anna");
	otherSimpUser.addSessions(new TestSimpSession("456"));
	when(this.registry.getUser("anna")).thenReturn(otherSimpUser);

	TestPrincipal user = new TestPrincipal("joe");
	TestPrincipal otherUser = new TestPrincipal("anna");
	String sourceDestination = "/user/anna/queue/foo";
	Message<?> message = createMessage(SimpMessageType.MESSAGE, user, "456", sourceDestination);

	UserDestinationResult actual = this.resolver.resolveDestination(message);

	assertEquals(sourceDestination, actual.getSourceDestination());
	assertEquals(1, actual.getTargetDestinations().size());
	assertEquals("/queue/foo-user456", actual.getTargetDestinations().iterator().next());
	assertEquals("/user/queue/foo", actual.getSubscribeDestination());
	assertEquals(otherUser.getName(), actual.getUser());
}
 
Example #3
Source File: TracingChannelInterceptorTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testAfterMessageHandled() {
  Span span = mock(Span.class);
  Scope scope = mock(Scope.class);
  MessageHandler messageHandler = mock(WebSocketAnnotationMethodMessageHandler.class);
  MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi")
      .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE)
      .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION)
      .setHeader(TracingChannelInterceptor.OPENTRACING_SCOPE, scope)
      .setHeader(TracingChannelInterceptor.OPENTRACING_SPAN, span);

  TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer,
      Tags.SPAN_KIND_CLIENT);
  interceptor.afterMessageHandled(messageBuilder.build(), null, messageHandler, null);

  // Verify span is finished and scope is closed
  verify(span).finish();
  verify(scope).close();
}
 
Example #4
Source File: StompSubProtocolHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleMessageToClientWithSimpConnectAckDefaultHeartBeat() {

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
	accessor.setHeartbeat(10000, 10000);
	accessor.setAcceptVersion("1.0,1.1");
	Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());

	SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
	Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, ackAccessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, ackMessage);

	assertEquals(1, this.session.getSentMessages().size());
	TextMessage actual = (TextMessage) this.session.getSentMessages().get(0);
	assertEquals("CONNECTED\n" + "version:1.1\n" + "heart-beat:0,0\n" +
			"user-name:joe\n" + "\n" + "\u0000", actual.getPayload());
}
 
Example #5
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void clientInboundChannelSendMessage() throws Exception {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class);
	SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class);

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	TestWebSocketSession session = new TestWebSocketSession("s1");
	session.setOpen(true);
	webSocketHandler.afterConnectionEstablished(session);

	webSocketHandler.handleMessage(session,
			StompTextMessageBuilder.create(StompCommand.SEND).headers("destination:/foo").build());

	Message<?> message = channel.messages.get(0);
	StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertFalse(accessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, accessor.getMessageType());
	assertEquals("/foo", accessor.getDestination());
}
 
Example #6
Source File: SimpleBrokerMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void run() {
	long now = System.currentTimeMillis();
	for (SessionInfo info : sessions.values()) {
		if (info.getReadInterval() > 0 && (now - info.getLastReadTime()) > info.getReadInterval()) {
			handleDisconnect(info.getSessionId(), info.getUser(), null);
		}
		if (info.getWriteInterval() > 0 && (now - info.getLastWriteTime()) > info.getWriteInterval()) {
			SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
			accessor.setSessionId(info.getSessionId());
			Principal user = info.getUser();
			if (user != null) {
				accessor.setUser(user);
			}
			initHeaders(accessor);
			accessor.setLeaveMutable(true);
			MessageHeaders headers = accessor.getMessageHeaders();
			info.getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
		}
	}
}
 
Example #7
Source File: SimpleBrokerMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void readWriteIntervalCalculation() throws Exception {

	this.messageHandler.setHeartbeatValue(new long[] {1, 1});
	this.messageHandler.setTaskScheduler(this.taskScheduler);
	this.messageHandler.start();

	ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L));
	Runnable heartbeatTask = taskCaptor.getValue();
	assertNotNull(heartbeatTask);

	String id = "sess1";
	TestPrincipal user = new TestPrincipal("joe");
	Message<String> connectMessage = createConnectMessage(id, user, new long[] {10000, 10000});
	this.messageHandler.handleMessage(connectMessage);

	Thread.sleep(10);
	heartbeatTask.run();

	verify(this.clientOutboundChannel, times(1)).send(this.messageCaptor.capture());
	List<Message<?>> messages = this.messageCaptor.getAllValues();
	assertEquals(1, messages.size());
	assertEquals(SimpMessageType.CONNECT_ACK,
			messages.get(0).getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER));
}
 
Example #8
Source File: DefaultSimpUserRegistryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void addMultipleSessionIds() {
	DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry();

	TestPrincipal user = new TestPrincipal("joe");
	Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123");
	SessionConnectedEvent event = new SessionConnectedEvent(this, message, user);
	registry.onApplicationEvent(event);

	message = createMessage(SimpMessageType.CONNECT_ACK, "456");
	event = new SessionConnectedEvent(this, message, user);
	registry.onApplicationEvent(event);

	message = createMessage(SimpMessageType.CONNECT_ACK, "789");
	event = new SessionConnectedEvent(this, message, user);
	registry.onApplicationEvent(event);

	SimpUser simpUser = registry.getUser("joe");
	assertNotNull(simpUser);

	assertEquals(1, registry.getUserCount());
	assertEquals(3, simpUser.getSessions().size());
	assertNotNull(simpUser.getSession("123"));
	assertNotNull(simpUser.getSession("456"));
	assertNotNull(simpUser.getSession("789"));
}
 
Example #9
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void clientInboundChannelSendMessage() throws Exception {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class);
	SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class);

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	TestWebSocketSession session = new TestWebSocketSession("s1");
	session.setOpen(true);
	webSocketHandler.afterConnectionEstablished(session);

	TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.SEND).headers("destination:/foo").build();
	webSocketHandler.handleMessage(session, textMessage);

	Message<?> message = channel.messages.get(0);
	StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertFalse(accessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, accessor.getMessageType());
	assertEquals("/foo", accessor.getDestination());
}
 
Example #10
Source File: AbstractSubscriptionRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public final MultiValueMap<String, String> findSubscriptions(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType type = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.MESSAGE.equals(type)) {
		throw new IllegalArgumentException("Unexpected message type: " + type);
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		logger.error("No destination in " + message);
		return EMPTY_MAP;
	}

	return findSubscriptionsInternal(destination, message);
}
 
Example #11
Source File: MessageBrokerConfigurationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void brokerChannelUsedByAnnotatedMethod() {
	ApplicationContext context = loadConfig(SimpleBrokerConfig.class);

	TestChannel channel = context.getBean("brokerChannel", TestChannel.class);
	SimpAnnotationMethodMessageHandler messageHandler =
			context.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 #12
Source File: DefaultUserDestinationResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parse(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	String sourceDestination = SimpMessageHeaderAccessor.getDestination(headers);
	if (sourceDestination == null || !checkDestination(sourceDestination, this.prefix)) {
		return null;
	}
	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (messageType != null) {
		switch (messageType) {
			case SUBSCRIBE:
			case UNSUBSCRIBE:
				return parseSubscriptionMessage(message, sourceDestination);
			case MESSAGE:
				return parseMessage(headers, sourceDestination);
		}
	}
	return null;
}
 
Example #13
Source File: DefaultSimpUserRegistryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void addOneSessionId() {
	TestPrincipal user = new TestPrincipal("joe");
	Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123");
	SessionConnectedEvent event = new SessionConnectedEvent(this, message, user);

	DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry();
	registry.onApplicationEvent(event);

	SimpUser simpUser = registry.getUser("joe");
	assertNotNull(simpUser);

	assertEquals(1, registry.getUserCount());
	assertEquals(1, simpUser.getSessions().size());
	assertNotNull(simpUser.getSession("123"));
}
 
Example #14
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 #15
Source File: StompSubProtocolHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handleMessageToClientWithSimpDisconnectAck() {

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.DISCONNECT);
	Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());

	SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER, connectMessage);
	Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, ackAccessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, ackMessage);

	assertEquals(1, this.session.getSentMessages().size());
	TextMessage actual = (TextMessage) this.session.getSentMessages().get(0);
	assertEquals("ERROR\n" + "message:Session closed.\n" + "content-length:0\n" +
			"\n\u0000", actual.getPayload());
}
 
Example #16
Source File: StompSubProtocolHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleMessageToClientWithSimpDisconnectAck() {

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.DISCONNECT);
	Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());

	SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER, connectMessage);
	Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, ackAccessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, ackMessage);

	assertEquals(1, this.session.getSentMessages().size());
	TextMessage actual = (TextMessage) this.session.getSentMessages().get(0);
	assertEquals("ERROR\n" + "message:Session closed.\n" + "content-length:0\n" +
			"\n\u0000", actual.getPayload());
}
 
Example #17
Source File: StompSubProtocolHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleMessageToClientWithSimpConnectAckDefaultHeartBeat() {

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
	accessor.setHeartbeat(10000, 10000);
	accessor.setAcceptVersion("1.0");
	Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());

	SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
	Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, ackAccessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, ackMessage);

	assertEquals(1, this.session.getSentMessages().size());
	TextMessage actual = (TextMessage) this.session.getSentMessages().get(0);
	assertEquals("CONNECTED\n" + "version:1.0\n" + "heart-beat:0,0\n" +
			"user-name:joe\n" + "\n" + "\u0000", actual.getPayload());
}
 
Example #18
Source File: UserDestinationMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public Message<?> preHandle(Message<?> message) throws MessagingException {
	String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
	if (!getBroadcastDestination().equals(destination)) {
		return message;
	}
	SimpMessageHeaderAccessor accessor = getAccessor(message, SimpMessageHeaderAccessor.class);
	if (accessor.getSessionId() == null) {
		// Our own broadcast
		return null;
	}
	destination = accessor.getFirstNativeHeader(ORIGINAL_DESTINATION);
	if (logger.isTraceEnabled()) {
		logger.trace("Checking unresolved user destination: " + destination);
	}
	SimpMessageHeaderAccessor newAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
	for (String name : accessor.toNativeHeaderMap().keySet()) {
		if (NO_COPY_LIST.contains(name)) {
			continue;
		}
		newAccessor.setNativeHeader(name, accessor.getFirstNativeHeader(name));
	}
	newAccessor.setDestination(destination);
	newAccessor.setHeader(SimpMessageHeaderAccessor.IGNORE_ERROR, true); // ensure send doesn't block
	return MessageBuilder.createMessage(message.getPayload(), newAccessor.getMessageHeaders());
}
 
Example #19
Source File: DefaultUserDestinationResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleMessageWithNoUser() {
	String sourceDestination = "/user/" + "123" + "/queue/foo";
	Message<?> message = createMessage(SimpMessageType.MESSAGE, null, "123", sourceDestination);
	UserDestinationResult actual = this.resolver.resolveDestination(message);

	assertEquals(sourceDestination, actual.getSourceDestination());
	assertEquals(1, actual.getTargetDestinations().size());
	assertEquals("/queue/foo-user123", actual.getTargetDestinations().iterator().next());
	assertEquals("/user/queue/foo", actual.getSubscribeDestination());
	assertNull(actual.getUser());
}
 
Example #20
Source File: WebsocketSecurityConfiguration.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        .nullDestMatcher().authenticated()
        .simpDestMatchers("/topic/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
        // matches any destination that starts with /topic/
        // (i.e. cannot send messages directly to /topic/)
        // (i.e. cannot subscribe to /topic/messages/* to get messages sent to
        // /topic/messages-user<id>)
        .simpDestMatchers("/topic/**").authenticated()
        // message types other than MESSAGE and SUBSCRIBE
        .simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
        // catch all
        .anyMessage().denyAll();
}
 
Example #21
Source File: UserDestinationMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleMessage() {
	TestSimpUser simpUser = new TestSimpUser("joe");
	simpUser.addSessions(new TestSimpSession("123"));
	when(this.registry.getUser("joe")).thenReturn(simpUser);
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
	this.handler.handleMessage(createWith(SimpMessageType.MESSAGE, "joe", "123", "/user/joe/queue/foo"));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	Mockito.verify(this.brokerChannel).send(captor.capture());

	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(captor.getValue());
	assertEquals("/queue/foo-user123", accessor.getDestination());
	assertEquals("/user/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION));
}
 
Example #22
Source File: DefaultSimpUserRegistryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void findSubscriptions() throws Exception {
	DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry();

	TestPrincipal user = new TestPrincipal("joe");
	Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123");
	SessionConnectedEvent event = new SessionConnectedEvent(this, message, user);
	registry.onApplicationEvent(event);

	message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub1", "/match");
	SessionSubscribeEvent subscribeEvent = new SessionSubscribeEvent(this, message, user);
	registry.onApplicationEvent(subscribeEvent);

	message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub2", "/match");
	subscribeEvent = new SessionSubscribeEvent(this, message, user);
	registry.onApplicationEvent(subscribeEvent);

	message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub3", "/not-a-match");
	subscribeEvent = new SessionSubscribeEvent(this, message, user);
	registry.onApplicationEvent(subscribeEvent);

	Set<SimpSubscription> matches = registry.findSubscriptions(new SimpSubscriptionMatcher() {
		@Override
		public boolean match(SimpSubscription subscription) {
			return subscription.getDestination().equals("/match");
		}
	});

	assertEquals(2, matches.size());

	Iterator<SimpSubscription> iterator = matches.iterator();
	Set<String> sessionIds = new HashSet<>(2);
	sessionIds.add(iterator.next().getId());
	sessionIds.add(iterator.next().getId());
	assertEquals(new HashSet<>(Arrays.asList("sub1", "sub2")), sessionIds);
}
 
Example #23
Source File: StompHeaderAccessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public StompCommand updateStompCommandAsClientMessage() {
	Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), "Unexpected message type " + getMessage());
	if (getCommand() == null) {
		setHeader(COMMAND_HEADER, StompCommand.SEND);
	}
	else if (!getCommand().equals(StompCommand.SEND)) {
		throw new IllegalStateException("Unexpected STOMP command " + getCommand());
	}
	return getCommand();
}
 
Example #24
Source File: AbstractBrokerMessageHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void afterSendCompletion(
		Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {

	if (!sent) {
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
		if (SimpMessageType.DISCONNECT.equals(messageType)) {
			logger.debug("Detected unsent DISCONNECT message. Processing anyway.");
			handleMessage(message);
		}
	}
}
 
Example #25
Source File: SimpleBrokerMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void readInactivity() throws Exception {
	this.messageHandler.setHeartbeatValue(new long[] {0, 1});
	this.messageHandler.setTaskScheduler(this.taskScheduler);
	this.messageHandler.start();

	ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L));
	Runnable heartbeatTask = taskCaptor.getValue();
	assertNotNull(heartbeatTask);

	String id = "sess1";
	TestPrincipal user = new TestPrincipal("joe");
	Message<String> connectMessage = createConnectMessage(id, user, new long[] {1, 0});
	this.messageHandler.handleMessage(connectMessage);

	Thread.sleep(10);
	heartbeatTask.run();

	verify(this.clientOutChannel, atLeast(2)).send(this.messageCaptor.capture());
	List<Message<?>> messages = this.messageCaptor.getAllValues();
	assertEquals(2, messages.size());

	MessageHeaders headers = messages.get(0).getHeaders();
	assertEquals(SimpMessageType.CONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER));
	headers = messages.get(1).getHeaders();
	assertEquals(SimpMessageType.DISCONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER));
	assertEquals(id, headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER));
	assertEquals(user, headers.get(SimpMessageHeaderAccessor.USER_HEADER));
}
 
Example #26
Source File: DefaultUserDestinationResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleSubscribeNoUser() {
	String sourceDestination = "/user/queue/foo";
	Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, null, "123", sourceDestination);
	UserDestinationResult actual = this.resolver.resolveDestination(message);

	assertEquals(sourceDestination, actual.getSourceDestination());
	assertEquals(1, actual.getTargetDestinations().size());
	assertEquals("/queue/foo-user" + "123", actual.getTargetDestinations().iterator().next());
	assertEquals(sourceDestination, actual.getSubscribeDestination());
	assertNull(actual.getUser());
}
 
Example #27
Source File: DefaultUserDestinationResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleSubscribeNoUser() {
	String sourceDestination = "/user/queue/foo";
	Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, null, "123", sourceDestination);
	UserDestinationResult actual = this.resolver.resolveDestination(message);

	assertEquals(sourceDestination, actual.getSourceDestination());
	assertEquals(1, actual.getTargetDestinations().size());
	assertEquals("/queue/foo-user" + "123", actual.getTargetDestinations().iterator().next());
	assertEquals(sourceDestination, actual.getSubscribeDestination());
	assertNull(actual.getUser());
}
 
Example #28
Source File: UserDestinationMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void handleSubscribe() {
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
	this.handler.handleMessage(createWith(SimpMessageType.SUBSCRIBE, "joe", SESSION_ID, "/user/queue/foo"));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	Mockito.verify(this.brokerChannel).send(captor.capture());

	Message message = captor.getValue();
	assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(message.getHeaders()));
}
 
Example #29
Source File: UserDestinationMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void handleMessage() {
	TestSimpUser simpUser = new TestSimpUser("joe");
	simpUser.addSessions(new TestSimpSession("123"));
	given(this.registry.getUser("joe")).willReturn(simpUser);
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
	this.handler.handleMessage(createWith(SimpMessageType.MESSAGE, "joe", "123", "/user/joe/queue/foo"));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	Mockito.verify(this.brokerChannel).send(captor.capture());

	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(captor.getValue());
	assertEquals("/queue/foo-user123", accessor.getDestination());
	assertEquals("/user/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION));
}
 
Example #30
Source File: UserDestinationMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleUnsubscribe() {
	given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
	this.handler.handleMessage(createWith(SimpMessageType.UNSUBSCRIBE, "joe", "123", "/user/queue/foo"));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	Mockito.verify(this.brokerChannel).send(captor.capture());

	Message message = captor.getValue();
	assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(message.getHeaders()));
}