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:biz.c24.io.spring.integration.validation.C24ValidatingMessageProcessor.java

@Override
public Map<String, ?> processMessage(Message<?> message) {

    Map<String, Object> result = new HashMap<String, Object>();

    Object payload = message.getPayload();

    ComplexDataObject cdo;/*w w w  . j a va2 s . c  om*/
    try {
        cdo = (ComplexDataObject) payload;
    } catch (ClassCastException e) {
        throw new MessagingException(
                "Cannot validate payload of type [" + payload != null ? payload.getClass().getName()
                        : "null" + "]. Only ComplexDataObject is supported.",
                e);
    }

    ValidationManager manager = new ValidationManager();
    ValidationEventCollector vec = new ValidationEventCollector();
    manager.addValidationListener(vec);

    if (manager.validateByEvents(cdo)) {
        result.put(VALID, Boolean.TRUE);
    } else {
        result.put(VALID, Boolean.FALSE);
    }

    if (isAddFailEvents()) {
        result.put(FAIL_EVENTS, new ArrayList<ValidationEvent>(Arrays.asList(vec.getFailEvents())));
    }

    if (isAddPassEvents()) {
        result.put(PASS_EVENTS, new ArrayList<ValidationEvent>(Arrays.asList(vec.getPassEvents())));
    }

    if (isAddStatistics()) {
        result.put(STATISTICS, manager.getStatistics());
    }

    return result;

}

From source file:multibinder.TwoKafkaBindersApplicationTest.java

@Test
public void messagingWorks() {
    DirectChannel dataProducer = new DirectChannel();
    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka1")).bindProducer("dataIn", dataProducer,
            new ExtendedProducerProperties<>(new KafkaProducerProperties()));

    QueueChannel dataConsumer = new QueueChannel();
    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka2")).bindConsumer("dataOut",
            UUID.randomUUID().toString(), dataConsumer,
            new ExtendedConsumerProperties<>(new KafkaConsumerProperties()));

    String testPayload = "testFoo" + UUID.randomUUID().toString();
    dataProducer.send(MessageBuilder.withPayload(testPayload).build());

    Message<?> receive = dataConsumer.receive(5000);
    Assert.assertThat(receive, Matchers.notNullValue());
    Assert.assertThat(receive.getPayload(), CoreMatchers.equalTo(testPayload));
}

From source file:com.qpark.eip.core.spring.JAXBElementAwarePayloadTypeRouter.java

/**
 * Selects the most appropriate channel name matching channel identifiers
 * which are the fully qualified class names encountered while traversing
 * the payload type hierarchy. To resolve ties and conflicts (e.g.,
 * Serializable and String) it will match: 1. Type name to channel
 * identifier else... 2. Name of the subclass of the type to channel
 * identifier else... 3. Name of the Interface of the type to channel
 * identifier while also preferring direct interface over indirect subclass
 *///ww w .  j a v  a  2  s . c o m
@Override
protected List<Object> getChannelKeys(final Message<?> message) {
    if (CollectionUtils.isEmpty(this.getChannelMappings())) {
        return null;
    }
    Object o = message.getPayload();
    Class<?> type = message.getPayload().getClass();
    if (o.getClass().equals(JAXBElement.class)) {
        type = ((JAXBElement<?>) o).getDeclaredType();
    }
    boolean isArray = type.isArray();
    if (isArray) {
        type = type.getComponentType();
    }
    String closestMatch = this.findClosestMatch(type, isArray);
    return (closestMatch != null) ? Collections.<Object>singletonList(closestMatch) : null;
}

From source file:com.consol.citrus.samples.flightbooking.BookingSplitter.java

@Splitter
@Transactional//from w ww  . jav a2  s  .  c om
public Object splitMessage(Message<?> message) {
    List<Message<FlightBookingRequestMessage>> flightRequests = new ArrayList<Message<FlightBookingRequestMessage>>();

    if (!(message.getPayload() instanceof TravelBookingRequestMessage)) {
        throw new IllegalStateException("Unsupported message type: " + message.getPayload().getClass());
    }

    TravelBookingRequestMessage request = ((TravelBookingRequestMessage) message.getPayload());

    //Save customer if not already present
    if (customerDao.find(request.getCustomer().getId()) == null) {
        customerDao.persist(request.getCustomer());
    }

    for (Flight flight : request.getFlights().getFlights()) {
        //Save flight if necessary
        if (flightDao.find(flight.getFlightId()) == null) {
            flightDao.persist(flight);
        }

        FlightBookingRequestMessage flightRequest = new FlightBookingRequestMessage();
        flightRequest.setFlight(flight);
        flightRequest.setCorrelationId(request.getCorrelationId());
        flightRequest.setCustomer(request.getCustomer());
        flightRequest.setBookingId("Bx" + bookingIndex.incrementAndGet());

        MessageBuilder<FlightBookingRequestMessage> messageBuilder = MessageBuilder.withPayload(flightRequest);
        messageBuilder.copyHeaders(message.getHeaders());

        flightRequests.add(messageBuilder.build());
    }

    return flightRequests;
}

From source file:org.apilytic.currency.service.impl.DefaultTwitterService.java

/** {@inheritDoc} */
@Override//from w ww .ja  v  a2s.com
public boolean isTwitterAdapterRunning() {

    final MessagingTemplate m = new MessagingTemplate();
    final Message<String> operation = MessageBuilder.withPayload("@twitter.isRunning()").build();

    @SuppressWarnings("unchecked")
    Message<Boolean> reply = (Message<Boolean>) m.sendAndReceive(channel, operation);

    return reply.getPayload();

}

From source file:ru.asmsoft.p2p.outgoing.OutgoingChannelAdapter.java

public void send(Message<String> message) throws IOException {

    int port = (Integer) message.getHeaders().get("ip_port");
    String ip = (String) message.getHeaders().get("ip_address");
    byte[] bytesToSend = message.getPayload().getBytes();

    InetAddress IPAddress = InetAddress.getByName(ip);

    DatagramPacket sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length, IPAddress, port);
    clientSocket.send(sendPacket);//from  w  w w.ja  v a2 s.c om

}

From source file:com.consol.citrus.samples.bookstore.validation.XmlSchemaValidatingChannelInterceptor.java

/**
 * Validates the payload of the message/*w w w  .  j  a  va2s  . co m*/
 * 
 * @param message
 * @param channel
 */
public void validateSchema(Message<?> message, MessageChannel channel) {
    try {
        SAXParseException[] exceptions = xmlValidator.validate(converter.convertToSource(message.getPayload()));
        if (exceptions.length > 0) {
            StringBuilder msg = new StringBuilder("Invalid XML message on channel ");
            if (channel != null) {
                msg.append(channel.toString());
            } else {
                msg.append("<unknown>");
            }
            msg.append(":\n");
            for (SAXParseException e : exceptions) {
                msg.append("\t").append(e.getMessage());
                msg.append(" (line=").append(e.getLineNumber());
                msg.append(", col=").append(e.getColumnNumber()).append(")\n");
            }
            log.warn("XSD schema validation failed: ", msg.toString());
            throw new XmlSchemaValidationException(message, exceptions[0]);
        }
    } catch (IOException ioE) {
        throw new MessagingException("Exception applying schema validation", ioE);
    }
}

From source file:com.consol.citrus.samples.bookstore.BookStore.java

/**
 * Get the book details for a book with given isbn.
 * @param request//from ww w.  j  a  va  2s.  c  o m
 * @return
 */
public Message<GetBookDetailsResponseMessage> getBookDetails(Message<GetBookDetailsRequestMessage> request) {
    GetBookDetailsResponseMessage response = new GetBookDetailsResponseMessage();

    Book book = bookStore.get(request.getPayload().getIsbn());

    if (book == null) {
        throw new UnknownBookException(request, request.getPayload().getIsbn());
    } else {
        response.setBook(book);
    }

    return MessageBuilder.withPayload(response).build();
}

From source file:org.opencredo.couchdb.inbound.CouchDbInboundChannelAdapterTest.java

@Test
public void receiveChanges() throws Exception {

    createTestDocuments();/*from  w w w . j a v a  2  s . c  om*/

    // start the poller here to avoid polling CouchDB before it's ready
    inboundChannelAdapter.start();

    for (int i = 0; i < TEST_MESSAGES_NUMBER; i++) {
        Message<Object> message = (Message<Object>) messagingTemplate.receive();
        log.debug("received message " + message);
        assertThat(message, notNullValue());
        Object payload = message.getPayload();
        assertThat(payload, instanceOf(URI.class));
    }
}

From source file:com.consol.citrus.samples.bookstore.BookStore.java

/**
 * Get the book cover for a book with given isbn.
 * @param request/*from w  w  w.java  2 s. c  o m*/
 * @return
 */
public Message<GetBookAbstractResponseMessage> getBookAbstract(Message<GetBookAbstractRequestMessage> request) {
    GetBookAbstractResponseMessage response = new GetBookAbstractResponseMessage();

    Book book = bookStore.get(request.getPayload().getIsbn());

    if (book == null) {
        throw new UnknownBookException(request, request.getPayload().getIsbn());
    } else {
        response.setBook(book);
    }

    return MessageBuilder.withPayload(response).build();
}