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.eclipse.hawkbit.event.BusProtoStuffMessageConverter.java

@Override
public Object convertFromInternal(final Message<?> message, final Class<?> targetClass,
        final Object conversionHint) {
    final Object payload = message.getPayload();

    try {//from   ww w  . ja v  a2s  .  c o  m
        final Class<?> deserializeClass = ClassUtils
                .getClass(message.getHeaders().get(DEFAULT_CLASS_FIELD_NAME).toString());
        if (payload instanceof byte[]) {
            @SuppressWarnings("unchecked")
            final Schema<Object> schema = (Schema<Object>) RuntimeSchema.getSchema(deserializeClass);
            final Object deserializeEvent = schema.newMessage();
            ProtobufIOUtil.mergeFrom((byte[]) message.getPayload(), deserializeEvent, schema);
            return deserializeEvent;
        }
    } catch (final ClassNotFoundException e) {
        LOG.error("Protostuff cannot find derserialize class", e);
        throw new MessageConversionException(message, "Failed to read payload", e);
    }

    return null;
}

From source file:org.encuestame.core.test.integration.IntegrationTestCase.java

@Test
public void testTransformation() throws Exception {
    transformerInputChannel.send(new Message<String>() {
        public MessageHeaders getHeaders() {
            return new MessageHeaders(new HashMap<String, Object>());
        }//from  w w w.  j  a va2s . c o m

        public String getPayload() {
            return "original www.xebia.com message http://www.xebia.com";
        }
    });

    Message<?> transformedMessage = transformerOutputChannel.receive();
    log.debug("trams" + transformedMessage.getPayload());
    assertNotNull(transformedMessage);

    assertNotSame((String) transformedMessage.getPayload(),
            ("original www.xebia.com message http://www.xebia.com"));
    log.debug("tinyurl.com");
}

From source file:org.encuestame.core.test.integration.IntegrationTestCase.java

@Test
public void testTwitterChannel() {
    log.debug("testTwitterChannel");
    MessageChannel twitterOutChannel = this.twitterTransformedChannel;
    Message<String> twitterUpdate = new GenericMessage<String>(
            "22 Testing  http://www.google.es new Twitter samples for #springintegration "
                    + RandomStringUtils.random(2));
    log.debug("twitterOutChannel message " + twitterUpdate.getPayload());
    twitterOutChannel.send(twitterUpdate);
    log.debug("twitterOutChannel");
}

From source file:org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter.java

/**
 * Get the next result if it is available (within the timeout specified in the gateway), otherwise do nothing.
 *
 * @throws AsynchronousFailureException If there is a response and it contains a failed chunk response.
 *
 * @throws IllegalStateException if the result contains the wrong job instance id (maybe we are sharing a channel
 * and we shouldn't be)/*from  ww  w  . j av a2s  .  c  o m*/
 */
private void getNextResult() throws AsynchronousFailureException {
    Message<ChunkResponse> message = (Message<ChunkResponse>) messagingGateway.receive(replyChannel);
    if (message != null) {
        ChunkResponse payload = message.getPayload();
        if (logger.isDebugEnabled()) {
            logger.debug("Found result: " + payload);
        }
        Long jobInstanceId = payload.getJobId();
        Assert.state(jobInstanceId != null, "Message did not contain job instance id.");
        Assert.state(jobInstanceId.equals(localState.getJobId()), "Message contained wrong job instance id ["
                + jobInstanceId + "] should have been [" + localState.getJobId() + "].");
        if (payload.isRedelivered()) {
            logger.warn(
                    "Redelivered result detected, which may indicate stale state. In the best case, we just picked up a timed out message "
                            + "from a previous failed execution. In the worst case (and if this is not a restart), "
                            + "the step may now timeout.  In that case if you believe that all messages "
                            + "from workers have been sent, the business state "
                            + "is probably inconsistent, and the step will fail.");
            localState.incrementRedelivered();
        }
        localState.pushResponse(payload);
        localState.incrementActual();
        if (!payload.isSuccessful()) {
            throw new AsynchronousFailureException(
                    "Failure or interrupt detected in handler: " + payload.getMessage());
        }
    }
}

From source file:org.springframework.cloud.aws.messaging.support.converter.NotificationRequestConverter.java

@Override
public Object fromMessage(Message<?> message, Class<?> targetClass) {
    Assert.notNull(message, "message must not be null");
    Assert.notNull(targetClass, "target class must not be null");

    JsonNode jsonNode;//from   ww w  . jav  a 2  s. com
    try {
        jsonNode = this.jsonMapper.readTree(message.getPayload().toString());
    } catch (Exception e) {
        throw new MessageConversionException("Could not read JSON", e);
    }
    if (!jsonNode.has("Type")) {
        throw new MessageConversionException(
                "Payload: '" + message.getPayload() + "' does not contain a Type attribute", null);
    }

    if (!"Notification".equals(jsonNode.findValue("Type").asText())) {
        throw new MessageConversionException(
                "Payload: '" + message.getPayload() + "' is not a valid notification", null);
    }

    if (!jsonNode.has("Message")) {
        throw new MessageConversionException(
                "Payload: '" + message.getPayload() + "' does not contain a message", null);
    }

    String messagePayload = jsonNode.findPath("Message").asText();
    GenericMessage<String> genericMessage = new GenericMessage<>(messagePayload,
            getMessageAttributesAsMessageHeaders(jsonNode.findPath("MessageAttributes")));
    return new NotificationRequest(jsonNode.findPath("Subject").asText(),
            this.payloadConverter.fromMessage(genericMessage, targetClass));
}

From source file:org.springframework.cloud.aws.messaging.support.converter.ObjectMessageConverter.java

@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
    String messagePayload = message.getPayload().toString();
    byte[] rawContent = messagePayload.getBytes(this.encoding);
    if (!(Base64.isBase64(rawContent))) {
        throw new MessageConversionException("Error converting payload '" + messagePayload
                + "' because it is not a valid base64 encoded stream!", null);
    }/*from ww w  .j av  a  2s . c  om*/
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(rawContent);
    Base64InputStream base64InputStream = new Base64InputStream(byteArrayInputStream);
    Serializable result = null;
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(base64InputStream);
        result = (Serializable) objectInputStream.readObject();
    } catch (ClassNotFoundException e) {
        throw new MessageConversionException(
                "Error loading class from message payload, make sure class is in classpath!", e);
    } catch (IOException e) {
        throw new MessageConversionException("Error reading payload from binary representation", e);
    } finally {
        if (objectInputStream != null) {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                LOGGER.warn("Error closing object output stream while reading message payload", e);
            }
        }
    }

    return result;
}

From source file:org.springframework.cloud.aws.messaging.support.converter.ObjectMessageConverterTest.java

@Test
public void testToMessageAndFromMessage() throws Exception {
    String content = "stringwithspecialcharsa8";
    MySerializableClass sourceMessage = new MySerializableClass(content);
    MessageConverter messageConverter = new ObjectMessageConverter();
    Message<?> message = messageConverter.toMessage(sourceMessage, getMessageHeaders("UTF-8"));
    assertTrue(Base64.isBase64(message.getPayload().toString().getBytes("UTF-8")));
    MySerializableClass result = (MySerializableClass) messageConverter.fromMessage(message,
            MySerializableClass.class);
    assertEquals(content, result.getContent());
}

From source file:org.springframework.cloud.aws.messaging.support.converter.ObjectMessageConverterTest.java

@Test
public void testToMessageAndFromMessageWithCustomEncoding() throws Exception {
    String content = "stringwithspecialcharsa8";
    MySerializableClass sourceMessage = new MySerializableClass(content);
    MessageConverter messageConverter = new ObjectMessageConverter("ISO-8859-1");
    Message<?> message = messageConverter.toMessage(sourceMessage, getMessageHeaders("ISO-8859-1"));
    assertTrue(Base64.isBase64(message.getPayload().toString().getBytes("ISO-8859-1")));
    MySerializableClass result = (MySerializableClass) messageConverter.fromMessage(message,
            MySerializableClass.class);
    assertEquals(content, result.getContent());
}

From source file:org.springframework.cloud.consul.bus.ConsulBusIT.java

@Test
public void test003JsonToObject() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new SubtypeModule(SimpleRemoteEvent.class));
    JsonToObjectTransformer transformer = Transformers.fromJson(RemoteApplicationEvent.class,
            new Jackson2JsonObjectMapper(objectMapper));
    /*//from   ww w.ja  va 2 s. com
     * HashMap<String, Object> map = new HashMap<>(); map.put(JsonHeaders.TYPE_ID,
     * RemoteApplicationEvent.class);
     */
    Message<?> message = transformer.transform(new GenericMessage<>(JSON_PAYLOAD));
    Object payload = message.getPayload();
    assertTrue("payload is of wrong type", payload instanceof RemoteApplicationEvent);
    assertTrue("payload is of wrong type", payload instanceof SimpleRemoteEvent);
    SimpleRemoteEvent event = (SimpleRemoteEvent) payload;
    assertEquals("payload is wrong", "testMessage", event.getMessage());
}

From source file:org.springframework.cloud.contract.stubrunner.messaging.integration.StubRunnerIntegrationMessageSelector.java

@Override
public boolean accept(Message<?> message) {
    if (!headersMatch(message)) {
        return false;
    }/*  ww  w  .  j a v  a 2  s .  c o  m*/
    Object inputMessage = message.getPayload();
    JsonPaths jsonPaths = JsonToJsonPathsConverter.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
            this.groovyDsl.getInput().getMessageBody());
    DocumentContext parsedJson;
    try {
        parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
    } catch (JsonProcessingException e) {
        throw new IllegalStateException("Cannot serialize to JSON", e);
    }
    boolean matches = true;
    for (MethodBufferingJsonVerifiable path : jsonPaths) {
        matches &= matchesJsonPath(parsedJson, path);
    }
    return matches;
}