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

The following examples show how to use org.springframework.messaging.simp.stomp.StompHeaderAccessor#wrap() . 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: 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 2
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 3
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 4
Source File: WebSocketEventListener.java    From code with Apache License 2.0 6 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);
        try {
            redisTemplate.opsForSet().remove(onlineUsers, username);
            redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }
}
 
Example 5
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 6
Source File: EventExchange.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@EventListener
public void onSessionConnected(SessionConnectEvent event) {
    Message msg = event.getMessage();
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(msg);
    String sessionId = accessor.getSessionId();

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

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

    if (spaceKey == null) {
        return;
    }

    boolean isToBeOnline = onlineWorkspaceStore.isEmpty(spaceKey);
    onlineWorkspaceStore.addSession(spaceKey, sessionId);

    if (isToBeOnline) {
        eventPublisher.publishEvent(new WorkspaceOnlineEvent(event, spaceKey));
    }
}
 
Example 7
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 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: WebSocketEventListener.java    From springboot-websocket-demo with Apache License 2.0 6 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);
        try {
            redisTemplate.opsForSet().remove(onlineUsers, username);
            redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }
}
 
Example 10
Source File: StompSubProtocolHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void handleMessageFromClient() {

	TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.STOMP).headers(
			"login:guest", "passcode:guest", "accept-version:1.1,1.0", "heart-beat:10000,10000").build();

	this.protocolHandler.afterSessionStarted(this.session, this.channel);
	this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);

	verify(this.channel).send(this.messageCaptor.capture());
	Message<?> actual = this.messageCaptor.getValue();
	assertNotNull(actual);

	assertEquals("s1", SimpMessageHeaderAccessor.getSessionId(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getSessionAttributes(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getUser(actual.getHeaders()));
	assertEquals("joe", SimpMessageHeaderAccessor.getUser(actual.getHeaders()).getName());
	assertNotNull(SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));
	assertArrayEquals(new long[] {10000, 10000}, SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));

	StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(actual);
	assertEquals(StompCommand.STOMP, stompAccessor.getCommand());
	assertEquals("guest", stompAccessor.getLogin());
	assertEquals("guest", stompAccessor.getPasscode());
	assertArrayEquals(new long[] {10000, 10000}, stompAccessor.getHeartbeat());
	assertEquals(new HashSet<>(Arrays.asList("1.1","1.0")), stompAccessor.getAcceptVersion());
	assertEquals(0, this.session.getSentMessages().size());
}
 
Example 11
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private StompHeaderAccessor getStompHeaderAccessor(Message<?> message) {
	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor instanceof StompHeaderAccessor) {
		return (StompHeaderAccessor) accessor;
	}
	else {
		StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(message);
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
		if (SimpMessageType.CONNECT_ACK.equals(messageType)) {
			stompAccessor = convertConnectAcktoStompConnected(stompAccessor);
		}
		else if (SimpMessageType.DISCONNECT_ACK.equals(messageType)) {
			String receipt = getDisconnectReceipt(stompAccessor);
			if (receipt != null) {
				stompAccessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
				stompAccessor.setReceiptId(receipt);
			}
			else {
				stompAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
				stompAccessor.setMessage("Session closed.");
			}
		}
		else if (SimpMessageType.HEARTBEAT.equals(messageType)) {
			stompAccessor = StompHeaderAccessor.createForHeartbeat();
		}
		else if (stompAccessor.getCommand() == null || StompCommand.SEND.equals(stompAccessor.getCommand())) {
			stompAccessor.updateStompCommandAsServerMessage();
		}
		return stompAccessor;
	}
}
 
Example 12
Source File: WebSocketEventListener.java    From code with Apache License 2.0 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("/topic/public", chatMessage);
    }
}
 
Example 13
Source File: StompSubProtocolHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleMessageFromClient() {

	TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.CONNECT).headers(
			"login:guest", "passcode:guest", "accept-version:1.1,1.0", "heart-beat:10000,10000").build();

	this.protocolHandler.afterSessionStarted(this.session, this.channel);
	this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);

	verify(this.channel).send(this.messageCaptor.capture());
	Message<?> actual = this.messageCaptor.getValue();
	assertNotNull(actual);

	assertEquals("s1", SimpMessageHeaderAccessor.getSessionId(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getSessionAttributes(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getUser(actual.getHeaders()));
	assertEquals("joe", SimpMessageHeaderAccessor.getUser(actual.getHeaders()).getName());
	assertNotNull(SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));
	assertArrayEquals(new long[] {10000, 10000}, SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));

	StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(actual);
	assertEquals(StompCommand.CONNECT, stompAccessor.getCommand());
	assertEquals("guest", stompAccessor.getLogin());
	assertEquals("guest", stompAccessor.getPasscode());
	assertArrayEquals(new long[] {10000, 10000}, stompAccessor.getHeartbeat());
	assertEquals(new HashSet<>(Arrays.asList("1.1","1.0")), stompAccessor.getAcceptVersion());
	assertEquals(0, this.session.getSentMessages().size());
}
 
Example 14
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void clientOutboundChannelUsedBySimpleBroker() {
	TestChannel channel = this.simpleBrokerContext.getBean("clientOutboundChannel", TestChannel.class);
	SimpleBrokerMessageHandler broker = this.simpleBrokerContext.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(message);

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

	// message
	broker.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 5 votes vote down vote up
@Test
public void handleMessageFromClient() {

	TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.CONNECT).headers(
			"login:guest", "passcode:guest", "accept-version:1.1,1.0", "heart-beat:10000,10000").build();

	this.protocolHandler.afterSessionStarted(this.session, this.channel);
	this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);

	verify(this.channel).send(this.messageCaptor.capture());
	Message<?> actual = this.messageCaptor.getValue();
	assertNotNull(actual);

	assertEquals("s1", SimpMessageHeaderAccessor.getSessionId(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getSessionAttributes(actual.getHeaders()));
	assertNotNull(SimpMessageHeaderAccessor.getUser(actual.getHeaders()));
	assertEquals("joe", SimpMessageHeaderAccessor.getUser(actual.getHeaders()).getName());
	assertNotNull(SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));
	assertArrayEquals(new long[] {10000, 10000}, SimpMessageHeaderAccessor.getHeartbeat(actual.getHeaders()));

	StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(actual);
	assertEquals(StompCommand.CONNECT, stompAccessor.getCommand());
	assertEquals("guest", stompAccessor.getLogin());
	assertEquals("guest", stompAccessor.getPasscode());
	assertArrayEquals(new long[] {10000, 10000}, stompAccessor.getHeartbeat());
	assertEquals(new HashSet<>(Arrays.asList("1.1","1.0")), stompAccessor.getAcceptVersion());
	assertEquals(0, this.session.getSentMessages().size());
}
 
Example 16
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
protected StompHeaderAccessor toMutableAccessor(StompHeaderAccessor headerAccessor, Message<?> message) {
	return (headerAccessor.isMutable() ? headerAccessor : StompHeaderAccessor.wrap(message));
}
 
Example 17
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()));

}
 
Example 18
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
private void handleSingleMessage(Message<byte[]> msg, WebSocketSession session) {
    StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(msg);
    if (stompHeaderAccessor.isHeartbeat()) {
        log.debug("heart beat from client: {}", session.getId());
        return;
    }

    StompCommand stompCommand = stompHeaderAccessor.getCommand();
    if (stompCommand == null) {
        log.error("miss command in stomp header, close session");
        this.closeSession(session);
        return;
    }

    log.info("session id: {} stomp header: {} payload.length: {}", session.getId(), stompHeaderAccessor.getMessageHeaders(), msg.getPayload().length);
    switch (stompCommand) {
        case CONNECT:
            handleConnectMessage(stompHeaderAccessor, session);
            break;

        case DISCONNECT:
            handleDisconnectMessage(stompHeaderAccessor, session);
            break;

        case SEND:
            handleSendMessage(stompHeaderAccessor, msg, session);
            break;

        case SUBSCRIBE:
            handleSubscribeMessage(stompHeaderAccessor, session);
            break;

        case UNSUBSCRIBE:
            handleUnsubscribeMessage(stompHeaderAccessor, session);
            break;

        default:
            handleDefaultMessage(stompHeaderAccessor, session);
            break;
    }
}
 
Example 19
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
protected StompHeaderAccessor toMutableAccessor(StompHeaderAccessor headerAccessor, Message<?> message) {
	return (headerAccessor.isMutable() ? headerAccessor : StompHeaderAccessor.wrap(message));
}
 
Example 20
Source File: StompSubProtocolHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
protected StompHeaderAccessor toMutableAccessor(StompHeaderAccessor headerAccessor, Message<?> message) {
	return (headerAccessor.isMutable() ? headerAccessor : StompHeaderAccessor.wrap(message));
}