Search in sources :

Example 46 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project spring-framework by spring-projects.

the class DefaultSimpUserRegistry method onApplicationEvent.

@Override
public void onApplicationEvent(ApplicationEvent event) {
    AbstractSubProtocolEvent subProtocolEvent = (AbstractSubProtocolEvent) event;
    Message<?> message = subProtocolEvent.getMessage();
    SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
    String sessionId = accessor.getSessionId();
    if (event instanceof SessionSubscribeEvent) {
        LocalSimpSession session = this.sessions.get(sessionId);
        if (session != null) {
            String id = accessor.getSubscriptionId();
            String destination = accessor.getDestination();
            session.addSubscription(id, destination);
        }
    } else if (event instanceof SessionConnectedEvent) {
        Principal user = subProtocolEvent.getUser();
        if (user == null) {
            return;
        }
        String name = user.getName();
        if (user instanceof DestinationUserNameProvider) {
            name = ((DestinationUserNameProvider) user).getDestinationUserName();
        }
        synchronized (this.sessionLock) {
            LocalSimpUser simpUser = this.users.get(name);
            if (simpUser == null) {
                simpUser = new LocalSimpUser(name);
                this.users.put(name, simpUser);
            }
            LocalSimpSession session = new LocalSimpSession(sessionId, simpUser);
            simpUser.addSession(session);
            this.sessions.put(sessionId, session);
        }
    } else if (event instanceof SessionDisconnectEvent) {
        synchronized (this.sessionLock) {
            LocalSimpSession session = this.sessions.remove(sessionId);
            if (session != null) {
                LocalSimpUser user = session.getUser();
                user.removeSession(sessionId);
                if (!user.hasSessions()) {
                    this.users.remove(user.getName());
                }
            }
        }
    } else if (event instanceof SessionUnsubscribeEvent) {
        LocalSimpSession session = this.sessions.get(sessionId);
        if (session != null) {
            String subscriptionId = accessor.getSubscriptionId();
            session.removeSubscription(subscriptionId);
        }
    }
}
Also used : Principal(java.security.Principal) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) DestinationUserNameProvider(org.springframework.messaging.simp.user.DestinationUserNameProvider)

Example 47 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project spring-framework by spring-projects.

the class SubscriptionMethodReturnValueHandler method createHeaders.

private MessageHeaders createHeaders(String sessionId, String subscriptionId, MethodParameter returnType) {
    SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    if (getHeaderInitializer() != null) {
        getHeaderInitializer().initHeaders(accessor);
    }
    accessor.setSessionId(sessionId);
    accessor.setSubscriptionId(subscriptionId);
    accessor.setHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER, returnType);
    accessor.setLeaveMutable(true);
    return accessor.getMessageHeaders();
}
Also used : SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Example 48 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project spring-framework by spring-projects.

the class StompBrokerRelayMessageHandler method handleMessageInternal.

@Override
protected void handleMessageInternal(Message<?> message) {
    String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
    if (!isBrokerAvailable()) {
        if (sessionId == null || SYSTEM_SESSION_ID.equals(sessionId)) {
            throw new MessageDeliveryException("Message broker not active. Consider subscribing to " + "receive BrokerAvailabilityEvent's from an ApplicationListener Spring bean.");
        }
        StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler != null) {
            handler.sendStompErrorFrameToClient("Broker not available.");
            handler.clearConnection();
        } else {
            StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
            if (getHeaderInitializer() != null) {
                getHeaderInitializer().initHeaders(accessor);
            }
            accessor.setSessionId(sessionId);
            accessor.setUser(SimpMessageHeaderAccessor.getUser(message.getHeaders()));
            accessor.setMessage("Broker not available.");
            MessageHeaders headers = accessor.getMessageHeaders();
            getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
        }
        return;
    }
    StompHeaderAccessor stompAccessor;
    StompCommand command;
    MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
    if (accessor == null) {
        throw new IllegalStateException("No header accessor (not using the SimpMessagingTemplate?): " + message);
    } else if (accessor instanceof StompHeaderAccessor) {
        stompAccessor = (StompHeaderAccessor) accessor;
        command = stompAccessor.getCommand();
    } else if (accessor instanceof SimpMessageHeaderAccessor) {
        stompAccessor = StompHeaderAccessor.wrap(message);
        command = stompAccessor.getCommand();
        if (command == null) {
            command = stompAccessor.updateStompCommandAsClientMessage();
        }
    } else {
        throw new IllegalStateException("Unexpected header accessor type " + accessor.getClass() + " in " + message);
    }
    if (sessionId == null) {
        if (!SimpMessageType.MESSAGE.equals(stompAccessor.getMessageType())) {
            if (logger.isErrorEnabled()) {
                logger.error("Only STOMP SEND supported from within the server side. Ignoring " + message);
            }
            return;
        }
        sessionId = SYSTEM_SESSION_ID;
        stompAccessor.setSessionId(sessionId);
    }
    String destination = stompAccessor.getDestination();
    if (command != null && command.requiresDestination() && !checkDestinationPrefix(destination)) {
        return;
    }
    if (StompCommand.CONNECT.equals(command)) {
        if (logger.isDebugEnabled()) {
            logger.debug(stompAccessor.getShortLogMessage(EMPTY_PAYLOAD));
        }
        stompAccessor = (stompAccessor.isMutable() ? stompAccessor : StompHeaderAccessor.wrap(message));
        stompAccessor.setLogin(this.clientLogin);
        stompAccessor.setPasscode(this.clientPasscode);
        if (getVirtualHost() != null) {
            stompAccessor.setHost(getVirtualHost());
        }
        StompConnectionHandler handler = new StompConnectionHandler(sessionId, stompAccessor);
        this.connectionHandlers.put(sessionId, handler);
        this.stats.incrementConnectCount();
        this.tcpClient.connect(handler);
    } else if (StompCommand.DISCONNECT.equals(command)) {
        StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring DISCONNECT in session " + sessionId + ". Connection already cleaned up.");
            }
            return;
        }
        stats.incrementDisconnectCount();
        handler.forward(message, stompAccessor);
    } else {
        StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("No TCP connection for session " + sessionId + " in " + message);
            }
            return;
        }
        handler.forward(message, stompAccessor);
    }
}
Also used : SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessageHeaders(org.springframework.messaging.MessageHeaders) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Example 49 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project spring-framework by spring-projects.

the class SimpleBrokerMessageHandler method handleMessageInternal.

@Override
protected void handleMessageInternal(Message<?> message) {
    MessageHeaders headers = message.getHeaders();
    SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
    String destination = SimpMessageHeaderAccessor.getDestination(headers);
    String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
    Principal user = SimpMessageHeaderAccessor.getUser(headers);
    updateSessionReadTime(sessionId);
    if (!checkDestinationPrefix(destination)) {
        return;
    }
    if (SimpMessageType.MESSAGE.equals(messageType)) {
        logMessage(message);
        sendMessageToSubscribers(destination, message);
    } else if (SimpMessageType.CONNECT.equals(messageType)) {
        logMessage(message);
        long[] clientHeartbeat = SimpMessageHeaderAccessor.getHeartbeat(headers);
        long[] serverHeartbeat = getHeartbeatValue();
        this.sessions.put(sessionId, new SessionInfo(sessionId, user, clientHeartbeat, serverHeartbeat));
        SimpMessageHeaderAccessor connectAck = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
        initHeaders(connectAck);
        connectAck.setSessionId(sessionId);
        connectAck.setUser(SimpMessageHeaderAccessor.getUser(headers));
        connectAck.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
        connectAck.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, serverHeartbeat);
        Message<byte[]> messageOut = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAck.getMessageHeaders());
        getClientOutboundChannel().send(messageOut);
    } else if (SimpMessageType.DISCONNECT.equals(messageType)) {
        logMessage(message);
        handleDisconnect(sessionId, user, message);
    } else if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
        logMessage(message);
        this.subscriptionRegistry.registerSubscription(message);
    } else if (SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
        logMessage(message);
        this.subscriptionRegistry.unregisterSubscription(message);
    }
}
Also used : SimpMessageType(org.springframework.messaging.simp.SimpMessageType) Message(org.springframework.messaging.Message) MessageHeaders(org.springframework.messaging.MessageHeaders) Principal(java.security.Principal) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Example 50 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project spring-framework by spring-projects.

the class SimpleBrokerMessageHandler method handleDisconnect.

private void handleDisconnect(String sessionId, Principal user, Message<?> origMessage) {
    this.sessions.remove(sessionId);
    this.subscriptionRegistry.unregisterAllSubscriptions(sessionId);
    SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
    accessor.setSessionId(sessionId);
    accessor.setUser(user);
    if (origMessage != null) {
        accessor.setHeader(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER, origMessage);
    }
    initHeaders(accessor);
    Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
    getClientOutboundChannel().send(message);
}
Also used : SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Aggregations

SimpMessageHeaderAccessor (org.springframework.messaging.simp.SimpMessageHeaderAccessor)54 Test (org.junit.Test)34 Message (org.springframework.messaging.Message)14 MessageHeaders (org.springframework.messaging.MessageHeaders)5 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)5 TextMessage (org.springframework.web.socket.TextMessage)5 MessageChannel (org.springframework.messaging.MessageChannel)3 MessageDeliveryException (org.springframework.messaging.MessageDeliveryException)3 TestPrincipal (org.springframework.messaging.simp.TestPrincipal)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 HttpRequestHandler (org.springframework.web.HttpRequestHandler)3 Principal (java.security.Principal)2 LinkedHashMap (java.util.LinkedHashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 MissingCsrfTokenException (org.springframework.security.web.csrf.MissingCsrfTokenException)2 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 MessageSendingOperations (org.springframework.messaging.core.MessageSendingOperations)1