Search in sources :

Example 96 with SimpMessageHeaderAccessor

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

the class TestServerConfig method clientOutboundChannel.

@Bean
public AbstractSubscribableChannel clientOutboundChannel() {
    DirectChannel directChannel = new DirectChannel();
    directChannel.addInterceptor(new ChannelInterceptor() {

        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
            headers.setLeaveMutable(true);
            return MessageBuilder.createMessage(message.getPayload(), headers.getMessageHeaders());
        }
    });
    return directChannel;
}
Also used : MessageChannel(org.springframework.messaging.MessageChannel) Message(org.springframework.messaging.Message) DirectChannel(org.springframework.integration.channel.DirectChannel) ChannelInterceptor(org.springframework.messaging.support.ChannelInterceptor) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) Bean(org.springframework.context.annotation.Bean)

Example 97 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project BootForum by chipolaris.

the class WebSocketEventsListener method handleSessionUnsubscribeEvent.

@EventListener
private void handleSessionUnsubscribeEvent(SessionUnsubscribeEvent event) {
    Message<byte[]> message = event.getMessage();
    // https://stackoverflow.com/questions/54330744/spring-boot-websocket-how-to-get-notified-on-client-subscriptions
    SimpMessageHeaderAccessor simpMessageHeaderAccessor = SimpMessageHeaderAccessor.wrap(message);
    String username = "Anonymous";
    Principal user = event.getUser();
    if (user != null) {
        username = user.getName();
    }
    String subscriptionId = simpMessageHeaderAccessor.getSubscriptionId();
    Map<String, Object> sessionAttributes = simpMessageHeaderAccessor.getSessionAttributes();
    String simpDestination = (String) sessionAttributes.get(subscriptionId);
    boolean removeResult = chatManager.removeSubscribedUser(simpDestination, username);
    if (removeResult) {
        logger.info(String.format("User %s unsubscribes from simpDestination: %s", username, simpDestination));
        this.template.convertAndSend(simpDestination, new RoomMessage(username, "leave", System.currentTimeMillis(), null));
    } else {
        logger.info(String.format("A session from user %s unsubscribes to simpDestination: %s", username, simpDestination));
    }
}
Also used : RoomMessage(com.github.chipolaris.bootforum.messaging.RoomMessage) Principal(java.security.Principal) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) EventListener(org.springframework.context.event.EventListener)

Example 98 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project activiti-cloud by Activiti.

the class GraphQLBrokerMessageHandlerTest method simpHeaderAccessor.

private SimpMessageHeaderAccessor simpHeaderAccessor(WebSocketSession session) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setDestination(destination);
    headerAccessor.setSessionId(session.getId());
    headerAccessor.setSessionAttributes(session.getAttributes());
    headerAccessor.setUser(session.getPrincipal());
    headerAccessor.setLeaveMutable(true);
    return headerAccessor;
}
Also used : SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Example 99 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project activiti-cloud by Activiti.

the class GraphQLBrokerMessageHandlerTest method connectionInitMessage.

private Message<GraphQLMessage> connectionInitMessage(String operationId, String sessionId) {
    SimpMessageHeaderAccessor headerAccessor = simpHeaderAccessor(mockWebSocketSession(sessionId));
    headerAccessor.setHeader(StompHeaderAccessor.HEART_BEAT_HEADER, new long[] { 0, 5000 });
    GraphQLMessage payload = new GraphQLMessage(operationId, GraphQLMessageType.CONNECTION_INIT);
    return MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
}
Also used : GraphQLMessage(org.activiti.cloud.services.notifications.graphql.ws.api.GraphQLMessage) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Example 100 with SimpMessageHeaderAccessor

use of org.springframework.messaging.simp.SimpMessageHeaderAccessor in project activiti-cloud by Activiti.

the class GraphQLBrokerSubProtocolHandler method handleMessageFromClient.

@Override
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> message, MessageChannel outputChannel) throws Exception {
    if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        GraphQLMessage sourceMessage = objectMapper.reader().forType(GraphQLMessage.class).readValue(textMessage.getPayload());
        try {
            SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
            headerAccessor.setDestination(destination);
            headerAccessor.setSessionId(session.getId());
            headerAccessor.setSessionAttributes(session.getAttributes());
            headerAccessor.setUser(getUser(session));
            headerAccessor.setLeaveMutable(true);
            Message<GraphQLMessage> decodedMessage = MessageBuilder.createMessage(sourceMessage, headerAccessor.getMessageHeaders());
            headerAccessor.setHeader(GRAPHQL_MESSAGE_TYPE, sourceMessage.getType().toString());
            if (logger.isTraceEnabled()) {
                logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload()));
            }
            boolean isConnect = GraphQLMessageType.CONNECTION_INIT.equals(sourceMessage.getType());
            if (isConnect) {
                this.stats.incrementConnectCount();
                // Let's inject connectionParams into headers
                Optional.ofNullable(sourceMessage.getPayload()).ifPresent(map -> {
                    map.entrySet().forEach(e -> {
                        headerAccessor.setHeader(e.getKey(), e.getValue());
                    });
                });
                // inject client KA interval
                Integer kaInterval = Optional.ofNullable(headerAccessor.getHeader(KA_INTERVAL_HEADER)).map(v -> Integer.parseInt(v.toString())).orElse(DEFAULT_KA_INTERVAL);
                headerAccessor.setHeader(StompHeaderAccessor.HEART_BEAT_HEADER, new long[] { 0, kaInterval });
            } else if (GraphQLMessageType.CONNECTION_TERMINATE.equals(sourceMessage.getType())) {
                this.stats.incrementDisconnectCount();
            } else if (GraphQLMessageType.START.equals(sourceMessage.getType())) {
                this.stats.incrementStartCount();
            } else if (GraphQLMessageType.STOP.equals(sourceMessage.getType())) {
                this.stats.incrementStopCount();
            }
            try {
                SimpAttributesContextHolder.setAttributesFromMessage(decodedMessage);
                boolean sent = outputChannel.send(decodedMessage);
                if (sent) {
                    if (isConnect) {
                        Principal user = headerAccessor.getUser();
                        if (user != null && user != session.getPrincipal()) {
                            this.graphqlAuthentications.put(session.getId(), user);
                        }
                    }
                    if (this.eventPublisher != null) {
                        if (isConnect) {
                            publishEvent(new GraphQLSessionConnectEvent(this, decodedMessage, getUser(session)));
                        } else if (GraphQLMessageType.START.equals(sourceMessage.getType())) {
                            publishEvent(new GraphQLSessionSubscribeEvent(this, decodedMessage, getUser(session)));
                        } else if (GraphQLMessageType.STOP.equals(sourceMessage.getType())) {
                            publishEvent(new GraphQLSessionUnsubscribeEvent(this, decodedMessage, getUser(session)));
                        }
                    }
                }
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        } catch (Throwable ex) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to send client message to application via MessageChannel" + " in session " + session.getId() + ". Sending CONNECTION_ERROR to client.", ex);
            }
            sendErrorMessage(session, ex, sourceMessage);
        }
    }
    return;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ScheduledFuture(java.util.concurrent.ScheduledFuture) SessionLimitExceededException(org.springframework.web.socket.handler.SessionLimitExceededException) LoggerFactory(org.slf4j.LoggerFactory) SimpAttributesContextHolder(org.springframework.messaging.simp.SimpAttributesContextHolder) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) SubProtocolHandler(org.springframework.web.socket.messaging.SubProtocolHandler) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) WebSocketSession(org.springframework.web.socket.WebSocketSession) CloseStatus(org.springframework.web.socket.CloseStatus) GraphQLMessage(org.activiti.cloud.services.notifications.graphql.ws.api.GraphQLMessage) TextMessage(org.springframework.web.socket.TextMessage) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) Nullable(org.springframework.lang.Nullable) Message(org.springframework.messaging.Message) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Logger(org.slf4j.Logger) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) SimpMessageType(org.springframework.messaging.simp.SimpMessageType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) MessageChannel(org.springframework.messaging.MessageChannel) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) ApplicationEvent(org.springframework.context.ApplicationEvent) List(java.util.List) Principal(java.security.Principal) GraphQLMessageType(org.activiti.cloud.services.notifications.graphql.ws.api.GraphQLMessageType) Gauge(com.codahale.metrics.annotation.Gauge) Optional(java.util.Optional) Collections(java.util.Collections) MessageBuilder(org.springframework.messaging.support.MessageBuilder) GraphQLMessage(org.activiti.cloud.services.notifications.graphql.ws.api.GraphQLMessage) TextMessage(org.springframework.web.socket.TextMessage) Principal(java.security.Principal) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Aggregations

SimpMessageHeaderAccessor (org.springframework.messaging.simp.SimpMessageHeaderAccessor)198 Test (org.junit.jupiter.api.Test)103 Message (org.springframework.messaging.Message)50 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)19 TextMessage (org.springframework.web.socket.TextMessage)16 MessageHeaders (org.springframework.messaging.MessageHeaders)15 Principal (java.security.Principal)13 MessageChannel (org.springframework.messaging.MessageChannel)11 GraphQLMessage (org.activiti.cloud.services.notifications.graphql.ws.api.GraphQLMessage)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 LinkedHashMap (java.util.LinkedHashMap)7 HashMap (java.util.HashMap)6 TestPrincipal (org.springframework.core.testfixture.security.TestPrincipal)6 List (java.util.List)5 SimpMessageType (org.springframework.messaging.simp.SimpMessageType)5 Map (java.util.Map)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 SimpMessagingTemplate (org.springframework.messaging.simp.SimpMessagingTemplate)4 RoomMessage (com.github.chipolaris.bootforum.messaging.RoomMessage)3 CountDownLatch (java.util.concurrent.CountDownLatch)3