org.springframework.messaging.simp.stomp.StompHeaderAccessor Java Examples

The following examples show how to use org.springframework.messaging.simp.stomp.StompHeaderAccessor. 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: WebSocketInterceptor.java    From xechat with MIT License 7 votes vote down vote up
/**
 * 绑定用户信息
 *
 * @param message
 * @param channel
 * @return
 */
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    log.debug("进入拦截器 -> preSend");
    StompHeaderAccessor stompHeaderAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

    if (StompCommand.CONNECT.equals(stompHeaderAccessor.getCommand())) {
        User user = new User();
        user.setUserId(UUIDUtils.create());
        user.setUsername(SensitiveWordUtils.loveChina(stompHeaderAccessor.getFirstNativeHeader("username")));
        user.setAvatar(stompHeaderAccessor.getFirstNativeHeader("avatar"));
        user.setAddress(stompHeaderAccessor.getFirstNativeHeader("address"));
        user.setStatus(UserStatusConstant.ONLINE);

        stompHeaderAccessor.setUser(user);
        log.debug("绑定用户信息 -> {}", user);
    }

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

	TestChannel channel = context.getBean("clientOutboundChannel", TestChannel.class);
	SimpAnnotationMethodMessageHandler messageHandler =
			context.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 #3
Source File: StompSubProtocolHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleMessageToClientWithHeartbeatSuppressingSockJsHeartbeat() throws IOException {

	SockJsSession sockJsSession = Mockito.mock(SockJsSession.class);
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
	accessor.setHeartbeat(0, 10);
	Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(sockJsSession, message);

	verify(sockJsSession).getPrincipal();
	verify(sockJsSession).disableHeartbeat();
	verify(sockJsSession).sendMessage(any(WebSocketMessage.class));
	verifyNoMoreInteractions(sockJsSession);

	sockJsSession = Mockito.mock(SockJsSession.class);
	accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
	accessor.setHeartbeat(0, 0);
	message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(sockJsSession, message);

	verify(sockJsSession).getPrincipal();
	verify(sockJsSession).sendMessage(any(WebSocketMessage.class));
	verifyNoMoreInteractions(sockJsSession);
}
 
Example #4
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 #5
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Message<byte[]> createDisconnectMessage(WebSocketSession session) {
	StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.DISCONNECT);
	if (getHeaderInitializer() != null) {
		getHeaderInitializer().initHeaders(headerAccessor);
	}

	headerAccessor.setSessionId(session.getId());
	headerAccessor.setSessionAttributes(session.getAttributes());

	Principal user = getUser(session);
	if (user != null) {
		headerAccessor.setUser(user);
	}

	return MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders());
}
 
Example #6
Source File: StompSubProtocolErrorHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Message<byte[]> handleClientMessageProcessingError(@Nullable Message<byte[]> clientMessage, Throwable ex) {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
	accessor.setMessage(ex.getMessage());
	accessor.setLeaveMutable(true);

	StompHeaderAccessor clientHeaderAccessor = null;
	if (clientMessage != null) {
		clientHeaderAccessor = MessageHeaderAccessor.getAccessor(clientMessage, StompHeaderAccessor.class);
		if (clientHeaderAccessor != null) {
			String receiptId = clientHeaderAccessor.getReceipt();
			if (receiptId != null) {
				accessor.setReceiptId(receiptId);
			}
		}
	}

	return handleInternal(accessor, EMPTY_PAYLOAD, ex, clientHeaderAccessor);
}
 
Example #7
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void clientOutboundChannelUsedByAnnotatedMethod() {
	ApplicationContext context = loadConfig(SimpleBrokerConfig.class);

	TestChannel channel = context.getBean("clientOutboundChannel", TestChannel.class);
	SimpAnnotationMethodMessageHandler messageHandler =
			context.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 #8
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note 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 #9
Source File: UserDestinationMessageHandlerTests.java    From spring-analysis-note with MIT License 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(StandardCharsets.UTF_8);
	this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	// No re-broadcast
	verifyNoMoreInteractions(this.brokerChannel);
}
 
Example #10
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 #11
Source File: StompSubProtocolHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleMessageToClientWithSimpConnectAck() {

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

	SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
	ackAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, new long[] {15000, 15000});
	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.2\n" + "heart-beat:15000,15000\n" +
			"user-name:joe\n" + "\n" + "\u0000", actual.getPayload());
}
 
Example #12
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 #13
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 #14
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 #15
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private StompHeaderAccessor afterStompSessionConnected(Message<?> message, StompHeaderAccessor accessor,
		WebSocketSession session) {

	Principal principal = session.getPrincipal();
	if (principal != null) {
		accessor = toMutableAccessor(accessor, message);
		accessor.setNativeHeader(CONNECTED_USER_HEADER, principal.getName());
		if (this.userSessionRegistry != null) {
			String userName = getSessionRegistryUserName(principal);
			this.userSessionRegistry.registerSessionId(userName, session.getId());
		}
	}

	long[] heartbeat = accessor.getHeartbeat();
	if (heartbeat[1] > 0) {
		session = WebSocketSessionDecorator.unwrap(session);
		if (session instanceof SockJsSession) {
			((SockJsSession) session).disableHeartbeat();
		}
	}

	return accessor;
}
 
Example #16
Source File: WebSocketStompClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessageBinary() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8)));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
}
 
Example #17
Source File: WebSocketStompClientTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessageBinary() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8)));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
}
 
Example #18
Source File: WebSocketTransport.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public SendResult stompSend(TopicContent topic, WeEvent event) {
    // header id equal asyncSeq
    WeEventStompCommand stompCommand = new WeEventStompCommand();
    Long asyncSeq = (this.sequence.incrementAndGet());
    String req = stompCommand.encodeSend(asyncSeq, topic, event);
    this.sequence2Id.put(Long.toString(asyncSeq), asyncSeq);

    SendResult sendResult = new SendResult();
    sendResult.setTopic(event.getTopic());
    try {
        StompHeaderAccessor stompHeaderAccessor = getStompHeaderAccessor(stompCommand, req, asyncSeq, "publish");
        sendResult.setEventId(stompHeaderAccessor.getFirstNativeHeader("eventId"));
        sendResult.setStatus(SendResult.SendResultStatus.SUCCESS);
        log.info("publish success, event: {}, eventID: {}", event, sendResult.getEventId());
    } catch (BrokerException e) {
        if (ErrorCode.SDK_EXCEPTION_STOMP_TIMEOUT.getCode() == e.getCode()) {
            sendResult.setStatus(SendResult.SendResultStatus.TIMEOUT);
        } else {
            sendResult.setStatus(SendResult.SendResultStatus.ERROR);
        }
    }
    return sendResult;
}
 
Example #19
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	Assert.notNull(message, "Original STOMP CONNECT not found in " + connectAckHeaders);
	StompHeaderAccessor connectHeaders = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED);
	Set<String> acceptVersions = connectHeaders.getAcceptVersion();
	if (acceptVersions.contains("1.2")) {
		connectedHeaders.setVersion("1.2");
	}
	else if (acceptVersions.contains("1.1")) {
		connectedHeaders.setVersion("1.1");
	}
	else if (!acceptVersions.isEmpty()) {
		throw 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 #20
Source File: WebSocketStompClientTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void handleWebSocketMessage() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new TextMessage(text));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), UTF_8));
}
 
Example #21
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 #22
Source File: StompSubProtocolHandlerTests.java    From java-technology-stack 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 #23
Source File: RestTemplateXhrTransportTests.java    From java-technology-stack 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 #24
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private void handleUnsubscribeMessage(StompHeaderAccessor stompHeaderAccessor, WebSocketSession session) {
    String simpDestination = stompHeaderAccessor.getDestination();
    String headerIdStr = stompHeaderAccessor.getFirstNativeHeader(StompHeaderAccessor.STOMP_ID_HEADER);

    try {
        boolean result = handleUnSubscribe(session, headerIdStr);

        // send response
        StompHeaderAccessor accessor;
        if (result) {
            accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
            accessor.setDestination(simpDestination);
        } else {
            accessor = StompHeaderAccessor.create(StompCommand.ERROR);
        }
        // a unique identifier for that message and a subscription header matching the identifier of the subscription that is receiving the message.
        accessor.setReceiptId(headerIdStr);
        sendSimpleMessage(session, accessor);
    } catch (BrokerException e) {
        handleErrorMessage(session, e, headerIdStr);
    }
}
 
Example #25
Source File: AbstractAuthenticatedController.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
protected void authenticate(StompHeaderAccessor accessor) {
    String authToken = accessor.getFirstNativeHeader(ServerConstants.X_AUTH_TOKEN);

    if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
        log.debug("Header auth token: " + authToken);
    }

    if (StringUtils.isNotBlank(authToken)) {

        // set cached authenticated user back in the spring security context
        Authentication authentication = preAuthAuthenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

        if (log.isDebugEnabled()) {
            log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
        }

        SpringSecurityHelper.setAuthentication(authentication);

    }
}
 
Example #26
Source File: EventExchange.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@EventListener
public void onSessionDisConnected(SessionDisconnectEvent event) {
    Message msg = event.getMessage();
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(msg);
    String sessionId = accessor.getSessionId();

    String spaceKey = (String) webSocketSessionStore.getAttribute(sessionId, "spaceKey");

    log.debug("Session disconnect: spaceKey => {}, sessionId => {} ", spaceKey, sessionId);

    if (spaceKey == null) {
        return;
    }

    onlineWorkspaceStore.removeSession(spaceKey, sessionId);
    boolean isToBeOffline = onlineWorkspaceStore.isEmpty(spaceKey);

    if (isToBeOffline) {
        eventPublisher.publishEvent(new WorkspaceOfflineEvent(event, spaceKey));
    }

}
 
Example #27
Source File: WebSocketStompClientTests.java    From spring-analysis-note 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 #28
Source File: WeEventStompCommand.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public String encodeRaw(StompHeaderAccessor accessor, byte[] payload) {
    log.debug("encode STOMP command: {}", accessor.getCommand());

    MessageHeaders headers = accessor.getMessageHeaders();
    Message<byte[]> message = MessageBuilder.createMessage(payload != null ? payload : "".getBytes(StandardCharsets.UTF_8), headers);
    return new String((new StompEncoder()).encode(message), StandardCharsets.UTF_8);
}
 
Example #29
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 #30
Source File: WebSocketEventListener.java    From springboot-learn with MIT License 5 votes vote down vote up
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    String username = (String) headerAccessor.getSessionAttributes().get("username");
    if (username != null) {
        logger.info("User Disconnected : " + username);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(ChatMessage.MessageType.LEAVE);
        chatMessage.setSender(username);

        messagingTemplate.convertAndSend(WebSocketConstants.CHAT_TOPIC, chatMessage);
    }
}