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.web.socket.messaging.StompSubProtocolHandler.java

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

    List<Message<byte[]>> messages;
    try {
        ByteBuffer byteBuffer;
        if (webSocketMessage instanceof TextMessage) {
            byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes());
        } else if (webSocketMessage instanceof BinaryMessage) {
            byteBuffer = ((BinaryMessage) webSocketMessage).getPayload();
        } else {
            return;
        }

        BufferingStompDecoder decoder = this.decoders.get(session.getId());
        if (decoder == null) {
            throw new IllegalStateException("No decoder for session id '" + session.getId() + "'");
        }

        messages = decoder.decode(byteBuffer);
        if (messages.isEmpty()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Incomplete STOMP frame content received in session " + session + ", bufferSize="
                        + decoder.getBufferSize() + ", bufferSizeLimit=" + decoder.getBufferSizeLimit() + ".");
            }
            return;
        }
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId()
                    + ". Sending STOMP ERROR to client.", ex);
        }
        handleError(session, ex, null);
        return;
    }

    for (Message<byte[]> message : messages) {
        try {
            StompHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message,
                    StompHeaderAccessor.class);
            Assert.state(headerAccessor != null, "No StompHeaderAccessor");

            headerAccessor.setSessionId(session.getId());
            headerAccessor.setSessionAttributes(session.getAttributes());
            headerAccessor.setUser(getUser(session));
            headerAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER,
                    headerAccessor.getHeartbeat());
            if (!detectImmutableMessageInterceptor(outputChannel)) {
                headerAccessor.setImmutable();
            }

            if (logger.isTraceEnabled()) {
                logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload()));
            }

            StompCommand command = headerAccessor.getCommand();
            boolean isConnect = StompCommand.CONNECT.equals(command);
            if (isConnect) {
                this.stats.incrementConnectCount();
            } else if (StompCommand.DISCONNECT.equals(command)) {
                this.stats.incrementDisconnectCount();
            }

            try {
                SimpAttributesContextHolder.setAttributesFromMessage(message);
                boolean sent = outputChannel.send(message);

                if (sent) {
                    if (isConnect) {
                        Principal user = headerAccessor.getUser();
                        if (user != null && user != session.getPrincipal()) {
                            this.stompAuthentications.put(session.getId(), user);
                        }
                    }
                    if (this.eventPublisher != null) {
                        Principal user = getUser(session);
                        if (isConnect) {
                            publishEvent(this.eventPublisher, new SessionConnectEvent(this, message, user));
                        } else if (StompCommand.SUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionSubscribeEvent(this, message, user));
                        } else if (StompCommand.UNSUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionUnsubscribeEvent(this, message, user));
                        }
                    }
                }
            } 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 STOMP ERROR to client.", ex);
            }
            handleError(session, ex, message);
        }
    }
}

From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java

private void handleError(WebSocketSession session, Throwable ex, @Nullable Message<byte[]> clientMessage) {
    if (getErrorHandler() == null) {
        sendErrorMessage(session, ex);//from w  ww  . jav  a  2 s.c  om
        return;
    }

    Message<byte[]> message = getErrorHandler().handleClientMessageProcessingError(clientMessage, ex);
    if (message == null) {
        return;
    }

    StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
    Assert.state(accessor != null, "No StompHeaderAccessor");
    sendToClient(session, accessor, message.getPayload());
}

From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java

/**
 * Handle STOMP messages going back out to WebSocket clients.
 *///from w ww .j a  va  2  s.c  om
@Override
@SuppressWarnings("unchecked")
public void handleMessageToClient(WebSocketSession session, Message<?> message) {
    if (!(message.getPayload() instanceof byte[])) {
        if (logger.isErrorEnabled()) {
            logger.error("Expected byte[] payload. Ignoring " + message + ".");
        }
        return;
    }

    StompHeaderAccessor accessor = getStompHeaderAccessor(message);
    StompCommand command = accessor.getCommand();

    if (StompCommand.MESSAGE.equals(command)) {
        if (accessor.getSubscriptionId() == null && logger.isWarnEnabled()) {
            logger.warn("No STOMP \"subscription\" header in " + message);
        }
        String origDestination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
        if (origDestination != null) {
            accessor = toMutableAccessor(accessor, message);
            accessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
            accessor.setDestination(origDestination);
        }
    } else if (StompCommand.CONNECTED.equals(command)) {
        this.stats.incrementConnectedCount();
        accessor = afterStompSessionConnected(message, accessor, session);
        if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) {
            try {
                SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
                SimpAttributesContextHolder.setAttributes(simpAttributes);
                Principal user = getUser(session);
                publishEvent(this.eventPublisher,
                        new SessionConnectedEvent(this, (Message<byte[]>) message, user));
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        }
    }

    byte[] payload = (byte[]) message.getPayload();
    if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) {
        Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message);
        if (errorMessage != null) {
            accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class);
            Assert.state(accessor != null, "No StompHeaderAccessor");
            payload = errorMessage.getPayload();
        }
    }
    sendToClient(session, accessor, payload);
}

From source file:org.springframework.xd.dirt.integration.bus.MessageBusSupport.java

protected final Message<?> serializePayloadIfNecessary(Message<?> message, MimeType to) {
    Object originalPayload = message.getPayload();
    Object originalContentType = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
    Object contentType = originalContentType;
    if (to.equals(ALL)) {
        return message;
    } else if (to.equals(APPLICATION_OCTET_STREAM)) {
        //Pass content type as String since some transport adapters will exclude CONTENT_TYPE Header otherwise
        contentType = JavaClassMimeTypeConversion.mimeTypeFromObject(originalPayload).toString();
        Object payload = serializePayloadIfNecessary(originalPayload);
        MessageBuilder<Object> messageBuilder = MessageBuilder.withPayload(payload)
                .copyHeaders(message.getHeaders()).setHeader(MessageHeaders.CONTENT_TYPE, contentType);
        if (originalContentType != null) {
            messageBuilder.setHeader(XdHeaders.XD_ORIGINAL_CONTENT_TYPE, originalContentType);
        }/*  www . j a  v  a 2s .  co m*/
        return messageBuilder.build();
    } else {
        throw new IllegalArgumentException("'to' can only be 'ALL' or 'APPLICATION_OCTET_STREAM'");
    }
}

From source file:org.springframework.xd.dirt.integration.bus.MessageBusSupport.java

protected final Message<?> deserializePayloadIfNecessary(Message<?> message) {
    Message<?> messageToSend = message;
    Object originalPayload = message.getPayload();
    MimeType contentType = contentTypeResolver.resolve(message.getHeaders());
    Object payload = deserializePayload(originalPayload, contentType);
    if (payload != null) {
        MessageBuilder<Object> transformed = MessageBuilder.withPayload(payload)
                .copyHeaders(message.getHeaders());
        Object originalContentType = message.getHeaders().get(XdHeaders.XD_ORIGINAL_CONTENT_TYPE);
        transformed.setHeader(MessageHeaders.CONTENT_TYPE, originalContentType);
        transformed.setHeader(XdHeaders.XD_ORIGINAL_CONTENT_TYPE, null);
        messageToSend = transformed.build();
    }//w  ww .j a  va  2 s  .c o m
    return messageToSend;
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@SuppressWarnings("unchecked")
@Test//from   w  ww  . j a  v a2  s.  co m
public void testBatchingAndCompression() throws Exception {
    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    MessageBus bus = getMessageBus();
    Properties properties = new Properties();
    properties.put("deliveryMode", "NON_PERSISTENT");
    properties.put("batchingEnabled", "true");
    properties.put("batchSize", "2");
    properties.put("batchBufferLimit", "100000");
    properties.put("batchTimeout", "30000");
    properties.put("compress", "true");

    DirectChannel output = new DirectChannel();
    output.setBeanName("batchingProducer");
    bus.bindProducer("batching.0", output, properties);

    while (template.receive("xdbus.batching.0") != null) {
    }

    Log logger = spy(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.logger", Log.class));
    new DirectFieldAccessor(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor"))
            .setPropertyValue("logger", logger);
    when(logger.isTraceEnabled()).thenReturn(true);

    assertEquals(Deflater.BEST_SPEED,
            TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.level"));

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Object out = spyOn("batching.0").receive(false);
    assertThat(out, instanceOf(byte[].class));
    assertEquals("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar", new String((byte[]) out));

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    verify(logger).trace(captor.capture());
    assertThat(captor.getValue().toString(), containsString("Compressed 14 to "));

    QueueChannel input = new QueueChannel();
    input.setBeanName("batchingConsumer");
    bus.bindConsumer("batching.0", input, null);

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Message<byte[]> in = (Message<byte[]>) input.receive(10000);
    assertNotNull(in);
    assertEquals("foo", new String(in.getPayload()));
    in = (Message<byte[]>) input.receive(10000);
    assertNotNull(in);
    assertEquals("bar", new String(in.getPayload()));
    assertNull(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE));

    bus.unbindProducers("batching.0");
    bus.unbindConsumers("batching.0");
}

From source file:org.springframework.xd.dirt.module.ModuleDeployer.java

@Override
protected synchronized void handleMessageInternal(Message<?> message) throws Exception {
    String payloadString = message.getPayload().toString();
    ModuleDeploymentRequest request = this.mapper.readValue(payloadString, ModuleDeploymentRequest.class);

    if (request.isRemove()) {
        handleUndeploy(request);//from  w ww .  j ava  2s .  c o m
    } else if (request.isLaunch()) {
        Assert.isTrue(!(request instanceof CompositeModuleDeploymentRequest));
        handleLaunch(request);
    } else {
        handleDeploy(request);
    }

}

From source file:org.springframework.xd.dirt.plugins.job.JobLaunchRequestTransformer.java

@Transformer
public JobLaunchRequest toJobLaunchRequest(Message<?> message) {
    Job job;/*from w  w  w.  j av  a  2 s .co  m*/
    try {
        job = jobRegistry.getJob(jobName);
    } catch (NoSuchJobException e) {
        throw new IllegalArgumentException("The job " + jobName + " doesn't exist. Is it deployed?");
    }
    final Object payload = message.getPayload();
    JobParameters jobParameters;

    if (logger.isDebugEnabled()) {
        logger.debug(String.format(
                "JobParameters are provided as '%s'. " + "Convertering to Spring Batch JobParameters...",
                payload.getClass().getSimpleName()));
    }

    if (payload instanceof File) {
        jobParameters = jobParametersConverter.getJobParametersForFile((File) message.getPayload());
    } else if (payload instanceof String) {
        jobParameters = jobParametersConverter.getJobParametersForJsonString((String) payload);
    } else if (payload instanceof Properties) {
        jobParameters = jobParametersConverter.getJobParameters((Properties) payload);
    } else if (payload instanceof Map<?, ?>) {
        jobParameters = jobParametersConverter.getJobParametersForMap((Map) payload);
    } else if (payload instanceof Tuple) {

        final Tuple tuple = (Tuple) payload;
        final List<Object> tupleValues = tuple.getValues();

        final Map<String, Object> map = new LinkedHashMap<String, Object>(tupleValues.size());
        for (int i = 0; i < tupleValues.size(); i++) {
            map.put(tuple.getFieldNames().get(i), tupleValues.get(i));
        }

        jobParameters = jobParametersConverter.getJobParametersForMap(map);

    } else {
        throw new IllegalArgumentException(
                "This transformer does not support payloads of type " + payload.getClass().getSimpleName());
    }

    final boolean isRestart = Boolean
            .valueOf(jobParameters.getString(ExpandedJobParametersConverter.IS_RESTART_JOB_PARAMETER_KEY));

    if (job.getJobParametersIncrementer() != null && !isRestart) {
        jobParameters = job.getJobParametersIncrementer().getNext(jobParameters);
    }

    jobParameters = jobParametersConverter.removeRestartParameterIfExists(jobParameters);

    return new JobLaunchRequest(job, jobParameters);
}

From source file:org.springframework.xd.dirt.stream.FileSourceModuleTests.java

@Test
public void testFileContents() throws IOException {
    deployStream("filecontents", "file --mode=contents --dir=" + sourceDirName + " --fixedDelay=0 | sink");
    MessageTest test = new MessageTest() {

        @Override/*from w  w  w  .j a v a  2  s . c o  m*/
        public void test(Message<?> message) throws MessagingException {
            byte[] bytes = (byte[]) message.getPayload();
            assertEquals("foo", new String(bytes));
            assertEquals("foo.txt", message.getHeaders().get(FileHeaders.FILENAME, String.class));
            assertEquals(MimeType.valueOf("application/octet-stream"),
                    contentTypeResolver.resolve(message.getHeaders()));
        }
    };
    StreamTestSupport.getSinkInputChannel("filecontents").subscribe(test);
    dropFile("foo.txt");
    test.waitForCompletion(1000);
    undeployStream("filecontents");
    assertTrue(test.getMessageHandled());
}

From source file:org.springframework.xd.dirt.stream.FileSourceModuleTests.java

@Test
public void testFileContentsUpperCase() throws IOException {
    deployStream("filecontentsuppercase",
            "file --mode=CONTENTS --dir=" + sourceDirName + " --fixedDelay=0 | sink");
    MessageTest test = new MessageTest() {

        @Override//www  . j  av a 2  s . c  om
        public void test(Message<?> message) throws MessagingException {
            byte[] bytes = (byte[]) message.getPayload();
            assertEquals("foo", new String(bytes));
            assertEquals("foo.txt", message.getHeaders().get(FileHeaders.FILENAME, String.class));
            assertEquals(MimeType.valueOf("application/octet-stream"),
                    contentTypeResolver.resolve(message.getHeaders()));
        }
    };
    StreamTestSupport.getSinkInputChannel("filecontentsuppercase").subscribe(test);
    dropFile("foo.txt");
    test.waitForCompletion(3000);
    undeployStream("filecontentsuppercase");
    assertTrue(test.getMessageHandled());
}