Example usage for org.springframework.messaging Message getPayload

List of usage examples for org.springframework.messaging Message getPayload

Introduction

In this page you can find the example usage for org.springframework.messaging Message getPayload.

Prototype

T getPayload();

Source Link

Document

Return the message payload.

Usage

From source file:org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.java

@Override
public void handleMessage(Message<?> message) throws MessagingException {
    String destination = getDestination(message);
    if (destination == null) {
        return;//www .j a v  a 2  s  .  c  o m
    }
    String lookupDestination = getLookupDestination(destination);
    if (lookupDestination == null) {
        return;
    }
    MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getMutableAccessor(message);
    headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, lookupDestination);
    headerAccessor.setLeaveMutable(true);
    message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders());

    if (logger.isDebugEnabled()) {
        logger.debug("Searching methods to handle " + headerAccessor.getShortLogMessage(message.getPayload())
                + ", lookupDestination='" + lookupDestination + "'");
    }

    handleMessageInternal(message, lookupDestination);
    headerAccessor.setImmutable();
}

From source file:org.springframework.messaging.simp.handler.SimpleBrokerMessageHandler.java

protected void sendMessageToSubscribers(String destination, Message<?> message) {
    MultiValueMap<String, String> subscriptions = this.subscriptionRegistry.findSubscriptions(message);
    for (String sessionId : subscriptions.keySet()) {
        for (String subscriptionId : subscriptions.get(sessionId)) {

            SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
            headers.setSessionId(sessionId);
            headers.setSubscriptionId(subscriptionId);

            Object payload = message.getPayload();
            Message<?> clientMessage = MessageBuilder.withPayloadAndHeaders(payload, headers).build();
            try {
                this.messageChannel.send(clientMessage);
            } catch (Throwable ex) {
                logger.error("Failed to send message to destination=" + destination + ", sessionId=" + sessionId
                        + ", subscriptionId=" + subscriptionId, ex);
            }/*w  w  w  .  j  a  v a  2 s .  c  o m*/
        }
    }
}

From source file:org.springframework.messaging.simp.handler.UserDestinationMessageHandler.java

@Override
public void handleMessage(Message<?> message) throws MessagingException {

    SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
    SimpMessageType messageType = headers.getMessageType();
    String destination = headers.getDestination();

    if (!SimpMessageType.MESSAGE.equals(messageType)) {
        return;/*  w  w  w  .  j a  v  a  2s  .c o m*/
    }

    if (!checkDestination(destination)) {
        return;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Processing message to destination " + destination);
    }

    UserDestinationParser destinationParser = new UserDestinationParser(destination);
    String user = destinationParser.getUser();

    if (user == null) {
        if (logger.isErrorEnabled()) {
            logger.error("Ignoring message, expected destination pattern \"" + this.destinationPrefix
                    + "{userId}/**\": " + destination);
        }
        return;
    }

    for (String sessionId : this.userQueueSuffixResolver.getUserQueueSuffixes(user)) {

        String targetDestination = destinationParser.getTargetDestination(sessionId);
        headers.setDestination(targetDestination);
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();

        if (logger.isTraceEnabled()) {
            logger.trace("Sending message to resolved target destination " + targetDestination);
        }
        this.messagingTemplate.send(targetDestination, message);
    }
}

From source file:org.springframework.messaging.simp.stomp.DefaultStompSession.java

private void execute(Message<byte[]> message) {
    if (logger.isTraceEnabled()) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (accessor != null) {
            logger.trace("Sending " + accessor.getDetailedLogMessage(message.getPayload()));
        }/*  w  ww .jav a2 s  . c om*/
    }
    TcpConnection<byte[]> conn = this.connection;
    Assert.state(conn != null, "Connection closed");
    try {
        conn.send(message).get();
    } catch (ExecutionException ex) {
        throw new MessageDeliveryException(message, ex.getCause());
    } catch (Throwable ex) {
        throw new MessageDeliveryException(message, ex);
    }
}

From source file:org.springframework.messaging.simp.stomp.DefaultStompSession.java

@Override
public void handleMessage(Message<byte[]> message) {
    StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
    Assert.state(accessor != null, "No StompHeaderAccessor");

    accessor.setSessionId(this.sessionId);
    StompCommand command = accessor.getCommand();
    Map<String, List<String>> nativeHeaders = accessor.getNativeHeaders();
    StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(nativeHeaders);
    boolean isHeartbeat = accessor.isHeartbeat();
    if (logger.isTraceEnabled()) {
        logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
    }/* www  .j ava2 s  .  c o m*/

    try {
        if (StompCommand.MESSAGE.equals(command)) {
            DefaultSubscription subscription = this.subscriptions.get(stompHeaders.getSubscription());
            if (subscription != null) {
                invokeHandler(subscription.getHandler(), message, stompHeaders);
            } else if (logger.isDebugEnabled()) {
                logger.debug("No handler for: " + accessor.getDetailedLogMessage(message.getPayload())
                        + ". Perhaps just unsubscribed?");
            }
        } else {
            if (StompCommand.RECEIPT.equals(command)) {
                String receiptId = stompHeaders.getReceiptId();
                ReceiptHandler handler = this.receiptHandlers.get(receiptId);
                if (handler != null) {
                    handler.handleReceiptReceived();
                } else if (logger.isDebugEnabled()) {
                    logger.debug(
                            "No matching receipt: " + accessor.getDetailedLogMessage(message.getPayload()));
                }
            } else if (StompCommand.CONNECTED.equals(command)) {
                initHeartbeatTasks(stompHeaders);
                this.version = stompHeaders.getFirst("version");
                this.sessionFuture.set(this);
                this.sessionHandler.afterConnected(this, stompHeaders);
            } else if (StompCommand.ERROR.equals(command)) {
                invokeHandler(this.sessionHandler, message, stompHeaders);
            } else if (!isHeartbeat && logger.isTraceEnabled()) {
                logger.trace("Message not handled.");
            }
        }
    } catch (Throwable ex) {
        this.sessionHandler.handleException(this, command, stompHeaders, message.getPayload(), ex);
    }
}

From source file:org.springframework.messaging.simp.stomp.DefaultStompSession.java

private void invokeHandler(StompFrameHandler handler, Message<byte[]> message, StompHeaders stompHeaders) {
    if (message.getPayload().length == 0) {
        handler.handleFrame(stompHeaders, null);
        return;//ww w  . j  av a2  s . c o  m
    }
    Type payloadType = handler.getPayloadType(stompHeaders);
    Class<?> resolvedType = ResolvableType.forType(payloadType).resolve();
    if (resolvedType == null) {
        throw new MessageConversionException("Unresolvable payload type [" + payloadType
                + "] from handler type [" + handler.getClass() + "]");
    }
    Object object = getMessageConverter().fromMessage(message, resolvedType);
    if (object == null) {
        throw new MessageConversionException("No suitable converter for payload type [" + payloadType
                + "] from handler type [" + handler.getClass() + "]");
    }
    handler.handleFrame(stompHeaders, object);
}

From source file:org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler.java

@Override
public void handleMessage(Message<?> message) {

    StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
    String sessionId = headers.getSessionId();
    String destination = headers.getDestination();
    StompCommand command = headers.getCommand();
    SimpMessageType messageType = headers.getMessageType();

    if (!this.running) {
        if (logger.isTraceEnabled()) {
            logger.trace("STOMP broker relay not running. Ignoring message id=" + headers.getId());
        }//ww  w.  ja v  a  2 s  .com
        return;
    }

    if (SimpMessageType.MESSAGE.equals(messageType)) {
        sessionId = (sessionId == null) ? STOMP_RELAY_SYSTEM_SESSION_ID : sessionId;
        headers.setSessionId(sessionId);
        command = (command == null) ? StompCommand.SEND : command;
        headers.setCommandIfNotSet(command);
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
    }

    if (headers.getCommand() == null) {
        logger.error("Ignoring message, no STOMP command: " + message);
        return;
    }
    if (sessionId == null) {
        logger.error("Ignoring message, no sessionId: " + message);
        return;
    }

    try {
        if (checkDestinationPrefix(command, destination)) {

            if (logger.isTraceEnabled()) {
                logger.trace("Processing message: " + message);
            }

            if (SimpMessageType.CONNECT.equals(messageType)) {
                headers.setHeartbeat(0, 0); // TODO: disable for now
                message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
                RelaySession session = new RelaySession(sessionId);
                this.relaySessions.put(sessionId, session);
                session.open(message);
            } else if (SimpMessageType.DISCONNECT.equals(messageType)) {
                RelaySession session = this.relaySessions.remove(sessionId);
                if (session == null) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Session already removed, sessionId=" + sessionId);
                    }
                    return;
                }
                session.forward(message);
            } else {
                RelaySession session = this.relaySessions.get(sessionId);
                if (session == null) {
                    logger.warn("Session id=" + sessionId + " not found. Ignoring message: " + message);
                    return;
                }
                session.forward(message);
            }
        }
    } catch (Throwable t) {
        logger.error("Failed to handle message " + message, t);
    }
}

From source file:org.springframework.messaging.simp.stomp.StompEncoder.java

/**
 * Encodes the given STOMP {@code message} into a {@code byte[]}
 * @param message the message to encode//from www.  j a v a2s  .c  o  m
 * @return the encoded message
 */
public byte[] encode(Message<byte[]> message) {
    return encode(message.getHeaders(), message.getPayload());
}

From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java

/**
 * Handle incoming WebSocket messages from clients.
 *///from w  w w. j av a 2 s  . c  o  m
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage webSocketMessage,
        MessageChannel outputChannel) {

    try {
        Assert.isInstanceOf(TextMessage.class, webSocketMessage);
        String payload = ((TextMessage) webSocketMessage).getPayload();
        Message<?> message = this.stompMessageConverter.toMessage(payload);

        // TODO: validate size limits
        // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits

        if (logger.isTraceEnabled()) {
            logger.trace("Processing STOMP message: " + message);
        }

        try {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
            headers.setSessionId(session.getId());
            headers.setUser(session.getPrincipal());

            message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();

            if (SimpMessageType.CONNECT.equals(headers.getMessageType())) {
                handleConnect(session, message);
            }

            outputChannel.send(message);

        } catch (Throwable t) {
            logger.error("Terminating STOMP session due to failure to send message: ", t);
            sendErrorMessage(session, t);
        }

        // TODO: send RECEIPT message if incoming message has "receipt" header
        // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt

    } catch (Throwable error) {
        sendErrorMessage(session, error);
    }
}

From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java

/**
 * Handle STOMP messages going back out to WebSocket clients.
 */// w  w w. ja va2  s .co m
@Override
public void handleMessageToClient(WebSocketSession session, Message<?> message) {

    StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
    headers.setCommandIfNotSet(StompCommand.MESSAGE);

    if (StompCommand.CONNECTED.equals(headers.getCommand())) {
        // Ignore for now since we already sent it
        return;
    }

    if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no subscriptionId header: " + message);
        return;
    }

    if (!(message.getPayload() instanceof byte[])) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, expected byte[] content: " + message);
        return;
    }

    try {
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
        byte[] bytes = this.stompMessageConverter.fromMessage(message);
        session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8"))));
    } catch (Throwable t) {
        sendErrorMessage(session, t);
    } finally {
        if (StompCommand.ERROR.equals(headers.getCommand())) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException e) {
            }
        }
    }
}