org.springframework.messaging.simp.SimpMessageHeaderAccessor Java Examples
The following examples show how to use
org.springframework.messaging.simp.SimpMessageHeaderAccessor.
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: WebSocketConnectHandler.java From bearchoke with Apache License 2.0 | 7 votes |
@Override public void onApplicationEvent(SessionConnectEvent event) { if (log.isDebugEnabled()) { log.debug("Caught Web Socket connect event"); } MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if(user == null) { return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); if (log.isDebugEnabled()) { log.debug("Current web socket session id: " + id); } if (StringUtils.isNotBlank(id)) { repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); } // messagingTemplate.convertAndSend("/topic/friends/signin", Arrays.asList(user.getName())); }
Example #2
Source File: SimpleBrokerMessageHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #3
Source File: SendToMethodReturnValueHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void sendToUser() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; TestUser user = new TestUser(); Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null, user); this.handler.handleReturnValue(PAYLOAD, this.sendToUserReturnType, inputMessage); verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); assertNull(accessor.getSessionId()); assertNull(accessor.getSubscriptionId()); assertEquals("/user/" + user.getName() + "/dest1", accessor.getDestination()); accessor = getCapturedAccessor(1); assertNull(accessor.getSessionId()); assertNull(accessor.getSubscriptionId()); assertEquals("/user/" + user.getName() + "/dest2", accessor.getDestination()); }
Example #4
Source File: SendToMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void sendToUserDefaultDestinationSingleSession() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; TestUser user = new TestUser(); Message<?> message = createMessage(sessionId, "sub1", "/app", "/dest", user); this.handler.handleReturnValue(PAYLOAD, this.sendToUserInSessionDefaultDestReturnType, message); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); assertEquals(sessionId, accessor.getSessionId()); assertEquals("/user/" + user.getName() + "/queue/dest", accessor.getDestination()); assertEquals(MIME_TYPE, accessor.getContentType()); assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); assertEquals(this.sendToUserInSessionDefaultDestReturnType, accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); }
Example #5
Source File: SendToMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void sendToUserSessionWithoutUserName() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; Message<?> inputMessage = createMessage(sessionId, "sub1", null, null, null); this.handler.handleReturnValue(PAYLOAD, this.sendToUserReturnType, inputMessage); verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); assertEquals("/user/sess1/dest1", accessor.getDestination()); assertEquals("sess1", accessor.getSessionId()); accessor = getCapturedAccessor(1); assertEquals("/user/sess1/dest2", accessor.getDestination()); assertEquals("sess1", accessor.getSessionId()); }
Example #6
Source File: DefaultSubscriptionRegistryTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void registerSubscriptionWithSelectorNotSupported() { String sessionId = "sess01"; String subscriptionId = "subs01"; String destination = "/foo"; String selector = "headers.foo == 'bar'"; this.registry.setSelectorHeaderName(null); this.registry.registerSubscription(subscribeMessage(sessionId, subscriptionId, destination, selector)); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination(destination); accessor.setNativeHeader("foo", "bazz"); Message<?> message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap<String, String> actual = this.registry.findSubscriptions(message); assertNotNull(actual); assertEquals(1, actual.size()); assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); }
Example #7
Source File: WebsocketSinkConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
@ServiceActivator(inputChannel = Sink.INPUT) public void websocketSink(Message<?> message) { if (logger.isTraceEnabled()) { logger.trace(String.format("Handling message: %s", message)); } SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message); headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE); String messagePayload = message.getPayload().toString(); for (Channel channel : WebsocketSinkServer.channels) { if (logger.isTraceEnabled()) { logger.trace(String.format("Writing message %s to channel %s", messagePayload, channel.localAddress())); } channel.write(new TextWebSocketFrame(messagePayload)); channel.flush(); } if (traceEndpointEnabled) { addMessageToTraceRepository(message); } }
Example #8
Source File: SendToMethodReturnValueHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test // SPR-12170 public void sendToWithDestinationPlaceholders() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); Map<String, String> vars = new LinkedHashMap<>(1); vars.put("roomName", "roomA"); String sessionId = "sess1"; SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setSessionId(sessionId); accessor.setSubscriptionId("sub1"); accessor.setHeader(DESTINATION_TEMPLATE_VARIABLES_HEADER, vars); Message<?> message = MessageBuilder.createMessage(PAYLOAD, accessor.getMessageHeaders()); this.handler.handleReturnValue(PAYLOAD, this.sendToWithPlaceholdersReturnType, message); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor actual = getCapturedAccessor(0); assertEquals(sessionId, actual.getSessionId()); assertEquals("/topic/chat.message.filtered.roomA", actual.getDestination()); }
Example #9
Source File: StompSubProtocolHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #10
Source File: SimpleBrokerMessageHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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.clientOutChannel, 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 #11
Source File: SendToMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-12170 public void sendToWithDestinationPlaceholders() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); Map<String, String> vars = new LinkedHashMap<>(1); vars.put("roomName", "roomA"); String sessionId = "sess1"; SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setSessionId(sessionId); accessor.setSubscriptionId("sub1"); accessor.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars); Message<?> message = MessageBuilder.createMessage(PAYLOAD, accessor.getMessageHeaders()); this.handler.handleReturnValue(PAYLOAD, this.sendToWithPlaceholdersReturnType, message); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor actual = getCapturedAccessor(0); assertEquals(sessionId, actual.getSessionId()); assertEquals("/topic/chat.message.filtered.roomA", actual.getDestination()); }
Example #12
Source File: UserDestinationMessageHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void handleMessageWithoutActiveSession() { this.handler.setBroadcastDestination("/topic/unresolved"); 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()); Message message = captor.getValue(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(message); assertEquals("/topic/unresolved", accessor.getDestination()); assertEquals("/user/joe/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)); // Should ignore our own broadcast to brokerChannel this.handler.handleMessage(message); Mockito.verifyNoMoreInteractions(this.brokerChannel); }
Example #13
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@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 #14
Source File: UserDestinationMessageHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void handleMessageWithoutActiveSession() { this.handler.setBroadcastDestination("/topic/unresolved"); 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()); Message message = captor.getValue(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(message); assertEquals("/topic/unresolved", accessor.getDestination()); assertEquals("/user/joe/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)); // Should ignore our own broadcast to brokerChannel this.handler.handleMessage(message); Mockito.verifyNoMoreInteractions(this.brokerChannel); }
Example #15
Source File: WebSocketIntegration.java From building-microservices with Apache License 2.0 | 6 votes |
@Bean public IntegrationFlow webSocketFlow(EchoService echoService) { return (IntegrationFlowDefinition<?> integrationFlowDefinition) -> { Function<String, Object> splitter = (String messagePayload) -> { // convert the payload String echoValue = echoService.echo(messagePayload); // for each of the active WS sessions, // build a Message destined for that session containing the // input message return serverWebSocketContainer().getSessions().keySet().stream() .map(s -> MessageBuilder.withPayload(echoValue) .setHeader(SimpMessageHeaderAccessor.SESSION_ID_HEADER, s) .build()) .collect(Collectors.toList()); }; integrationFlowDefinition.split(String.class, splitter) .channel(c -> c.executor(Executors.newCachedThreadPool())) .handle(webSocketOutboundAdapter()); }; }
Example #16
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-14690 public void handleMessageFromClientWithTokenAuthentication() { ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel(); channel.addInterceptor(new AuthenticationInterceptor("[email protected]")); channel.addInterceptor(new ImmutableMessageChannelInterceptor()); TestMessageHandler messageHandler = new TestMessageHandler(); channel.subscribe(messageHandler); StompSubProtocolHandler handler = new StompSubProtocolHandler(); handler.afterSessionStarted(this.session, channel); TextMessage wsMessage = StompTextMessageBuilder.create(StompCommand.CONNECT).build(); handler.handleMessageFromClient(this.session, wsMessage, channel); assertEquals(1, messageHandler.getMessages().size()); Message<?> message = messageHandler.getMessages().get(0); Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders()); assertNotNull(user); assertEquals("[email protected]", user.getName()); }
Example #17
Source File: SubscriptionMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testHeadersPassedToMessagingTemplate() throws Exception { String sessionId = "sess1"; String subscriptionId = "subs1"; String destination = "/dest"; Message<?> inputMessage = createInputMessage(sessionId, subscriptionId, destination, null); MessageSendingOperations messagingTemplate = Mockito.mock(MessageSendingOperations.class); SubscriptionMethodReturnValueHandler handler = new SubscriptionMethodReturnValueHandler(messagingTemplate); handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage); ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class); verify(messagingTemplate).convertAndSend(eq("/dest"), eq(PAYLOAD), captor.capture()); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class); assertNotNull(headerAccessor); assertTrue(headerAccessor.isMutable()); assertEquals(sessionId, headerAccessor.getSessionId()); assertEquals(subscriptionId, headerAccessor.getSubscriptionId()); assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); }
Example #18
Source File: SendToMethodReturnValueHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void sendToDefaultDestination() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/app", "/dest", null); this.handler.handleReturnValue(PAYLOAD, this.sendToDefaultDestReturnType, inputMessage); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); assertEquals(sessionId, accessor.getSessionId()); assertEquals("/topic/dest", accessor.getDestination()); assertEquals(MIME_TYPE, accessor.getContentType()); assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); assertEquals(this.sendToDefaultDestReturnType, accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); }
Example #19
Source File: DefaultSubscriptionRegistry.java From spring-analysis-note with MIT License | 6 votes |
@Nullable private Expression getSelectorExpression(MessageHeaders headers) { Expression expression = null; if (getSelectorHeaderName() != null) { String selector = SimpMessageHeaderAccessor.getFirstNativeHeader(getSelectorHeaderName(), headers); if (selector != null) { try { expression = this.expressionParser.parseExpression(selector); this.selectorHeaderInUse = true; if (logger.isTraceEnabled()) { logger.trace("Subscription selector: [" + selector + "]"); } } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to parse selector: " + selector, ex); } } } } return expression; }
Example #20
Source File: SendToMethodReturnValueHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void sendToUserSessionWithoutUserName() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null, null); this.handler.handleReturnValue(PAYLOAD, this.sendToUserReturnType, inputMessage); verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); assertEquals("/user/sess1/dest1", accessor.getDestination()); assertEquals("sess1", accessor.getSessionId()); accessor = getCapturedAccessor(1); assertEquals("/user/sess1/dest2", accessor.getDestination()); assertEquals("sess1", accessor.getSessionId()); }
Example #21
Source File: DefaultSubscriptionRegistryTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void registerSubscriptionWithSelectorNotSupported() { String sessionId = "sess01"; String subscriptionId = "subs01"; String destination = "/foo"; String selector = "headers.foo == 'bar'"; this.registry.setSelectorHeaderName(null); this.registry.registerSubscription(subscribeMessage(sessionId, subscriptionId, destination, selector)); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination(destination); accessor.setNativeHeader("foo", "bazz"); Message<?> message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap<String, String> actual = this.registry.findSubscriptions(message); assertNotNull(actual); assertEquals(1, actual.size()); assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); }
Example #22
Source File: UserRegistryMessageHandlerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void broadcastRegistry() throws Exception { TestSimpUser simpUser1 = new TestSimpUser("joe"); TestSimpUser simpUser2 = new TestSimpUser("jane"); simpUser1.addSessions(new TestSimpSession("123")); simpUser1.addSessions(new TestSimpSession("456")); HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2)); when(this.localRegistry.getUsers()).thenReturn(simpUsers); getUserRegistryTask().run(); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(this.brokerChannel).send(captor.capture()); Message<?> message = captor.getValue(); assertNotNull(message); MessageHeaders headers = message.getHeaders(); assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers)); MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class)); remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000); assertEquals(2, remoteRegistry.getUsers().size()); assertNotNull(remoteRegistry.getUser("joe")); assertNotNull(remoteRegistry.getUser("jane")); }
Example #23
Source File: SimpleBrokerMessageHandlerTests.java From java-technology-stack with MIT License | 5 votes |
private Message<String> createConnectMessage(String sessionId, Principal user, long[] heartbeat) { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); accessor.setSessionId(sessionId); accessor.setUser(user); accessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, heartbeat); return MessageBuilder.createMessage("", accessor.getMessageHeaders()); }
Example #24
Source File: DefaultUserDestinationResolverTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
private Message<?> createMessage(SimpMessageType type, Principal user, String sessionId, String destination) { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(type); if (destination != null) { headers.setDestination(destination); } if (user != null) { headers.setUser(user); } if (sessionId != null) { headers.setSessionId(sessionId); } return MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); }
Example #25
Source File: DefaultSubscriptionRegistryTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void registerSubscriptionWithSelector() { String sessionId = "sess01"; String subscriptionId = "subs01"; String destination = "/foo"; String selector = "headers.foo == 'bar'"; this.registry.registerSubscription(subscribeMessage(sessionId, subscriptionId, destination, selector)); // First, try with selector header SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination(destination); accessor.setNativeHeader("foo", "bar"); Message<?> message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap<String, String> actual = this.registry.findSubscriptions(message); assertNotNull(actual); assertEquals(1, actual.size()); assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); // Then without actual = this.registry.findSubscriptions(createMessage(destination)); assertNotNull(actual); assertEquals(0, actual.size()); }
Example #26
Source File: SimpleBrokerMessageHandler.java From java-technology-stack with MIT License | 5 votes |
protected void sendMessageToSubscribers(@Nullable String destination, Message<?> message) { MultiValueMap<String,String> subscriptions = this.subscriptionRegistry.findSubscriptions(message); if (!subscriptions.isEmpty() && logger.isDebugEnabled()) { logger.debug("Broadcasting to " + subscriptions.size() + " sessions."); } long now = System.currentTimeMillis(); subscriptions.forEach((sessionId, subscriptionIds) -> { for (String subscriptionId : subscriptionIds) { SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); initHeaders(headerAccessor); headerAccessor.setSessionId(sessionId); headerAccessor.setSubscriptionId(subscriptionId); headerAccessor.copyHeadersIfAbsent(message.getHeaders()); headerAccessor.setLeaveMutable(true); Object payload = message.getPayload(); Message<?> reply = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders()); SessionInfo info = this.sessions.get(sessionId); if (info != null) { try { info.getClientOutboundChannel().send(reply); } catch (Throwable ex) { if (logger.isErrorEnabled()) { logger.error("Failed to send " + message, ex); } } finally { info.setLastWriteTime(now); } } } }); }
Example #27
Source File: StompSubProtocolHandler.java From java-technology-stack with MIT License | 5 votes |
/** * The simple broker produces {@code SimpMessageType.CONNECT_ACK} that's not STOMP * specific and needs to be turned into a STOMP CONNECTED frame. */ private StompHeaderAccessor convertConnectAcktoStompConnected(StompHeaderAccessor connectAckHeaders) { String name = StompHeaderAccessor.CONNECT_MESSAGE_HEADER; Message<?> message = (Message<?>) connectAckHeaders.getHeader(name); if (message == null) { throw new IllegalStateException("Original STOMP CONNECT not found in " + connectAckHeaders); } StompHeaderAccessor connectHeaders = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED); if (connectHeaders != null) { Set<String> acceptVersions = connectHeaders.getAcceptVersion(); connectedHeaders.setVersion( Arrays.stream(SUPPORTED_VERSIONS) .filter(acceptVersions::contains) .findAny() .orElseThrow(() -> new IllegalArgumentException( "Unsupported STOMP version '" + acceptVersions + "'"))); } long[] heartbeat = (long[]) connectAckHeaders.getHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER); if (heartbeat != null) { connectedHeaders.setHeartbeat(heartbeat[0], heartbeat[1]); } else { connectedHeaders.setHeartbeat(0, 0); } return connectedHeaders; }
Example #28
Source File: WebSocketConfiguration.java From haven-platform with Apache License 2.0 | 5 votes |
@Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { SimpMessageHeaderAccessor smha = SimpMessageHeaderAccessor.wrap(message); Principal user = smha.getUser(); if(user instanceof Authentication) { TempAuth auth = TempAuth.open((Authentication)user); smha.setHeader(AUTH_KEY, auth); } return message; }
Example #29
Source File: ChatController.java From springboot-learn with MIT License | 5 votes |
@MessageMapping("/chat/addUser") @SendTo(WebSocketConstants.CHAT_TOPIC) public ChatMessage addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) { headerAccessor.getSessionAttributes().put("username", chatMessage.getSender()); return chatMessage; }
Example #30
Source File: StompBrokerRelayMessageHandlerIntegrationTests.java From java-technology-stack with MIT License | 5 votes |
public static MessageExchangeBuilder send(String destination, String payload) { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); headers.setDestination(destination); Message<?> message = MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8), headers.getMessageHeaders()); return new MessageExchangeBuilder(message); }