Example usage for org.springframework.messaging Message getHeaders

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

Introduction

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

Prototype

MessageHeaders getHeaders();

Source Link

Document

Return message headers for the message (never null but may be empty).

Usage

From source file:org.springframework.integration.jms.ChannelPublishingJmsMessageListenerTests.java

private void startBackgroundReplier(final PollableChannel channel) {
    new SimpleAsyncTaskExecutor().execute(() -> {
        Message<?> request = channel.receive(50000);
        Message<?> reply = new GenericMessage<String>(((String) request.getPayload()).toUpperCase());
        ((MessageChannel) request.getHeaders().getReplyChannel()).send(reply, 5000);
    });//from w w w.  java 2 s  .c o  m
}

From source file:org.springframework.integration.jms.JmsOutboundGateway.java

private Object sendAndReceiveWithContainer(Message<?> requestMessage) throws JMSException {
    Connection connection = this.createConnection(); // NOSONAR - closed in ConnectionFactoryUtils.
    Session session = null;/*from   w  w  w . ja va 2 s. c  o m*/
    Destination replyTo = this.replyContainer.getReplyDestination();
    try {
        session = this.createSession(connection);

        // convert to JMS Message
        Object objectToSend = requestMessage;
        if (this.extractRequestPayload) {
            objectToSend = requestMessage.getPayload();
        }
        javax.jms.Message jmsRequest = this.messageConverter.toMessage(objectToSend, session);

        // map headers
        this.headerMapper.fromHeaders(requestMessage.getHeaders(), jmsRequest);

        jmsRequest.setJMSReplyTo(replyTo);
        connection.start();
        if (logger.isDebugEnabled()) {
            logger.debug("ReplyTo: " + replyTo);
        }

        Integer priority = new IntegrationMessageHeaderAccessor(requestMessage).getPriority();
        if (priority == null) {
            priority = this.priority;
        }
        Destination requestDestination = this.determineRequestDestination(requestMessage, session);

        Object reply = null;
        if (this.correlationKey == null) {
            /*
             * Remove any existing correlation id that was mapped from the inbound message
             * (it will be restored in the reply by normal ARPMH header processing).
             */
            jmsRequest.setJMSCorrelationID(null);
            reply = doSendAndReceiveAsyncDefaultCorrelation(requestDestination, jmsRequest, session, priority);
        } else {
            reply = doSendAndReceiveAsync(requestDestination, jmsRequest, session, priority);
        }
        /*
         * Remove the gateway's internal correlation Id to avoid conflicts with an upstream
         * gateway.
         */
        if (reply instanceof javax.jms.Message) {
            ((javax.jms.Message) reply).setJMSCorrelationID(null);
        }
        return reply;
    } finally {
        JmsUtils.closeSession(session);
        ConnectionFactoryUtils.releaseConnection(connection, this.connectionFactory, true);
    }
}

From source file:org.springframework.integration.jms.JmsOutboundGateway.java

private javax.jms.Message sendAndReceiveWithoutContainer(Message<?> requestMessage) throws JMSException {
    Connection connection = this.createConnection(); // NOSONAR - closed in ConnectionFactoryUtils.
    Session session = null;/*from   w ww  . j  a va 2  s . co  m*/
    Destination replyTo = null;
    try {
        session = this.createSession(connection);

        // convert to JMS Message
        Object objectToSend = requestMessage;
        if (this.extractRequestPayload) {
            objectToSend = requestMessage.getPayload();
        }
        javax.jms.Message jmsRequest = this.messageConverter.toMessage(objectToSend, session);

        // map headers
        this.headerMapper.fromHeaders(requestMessage.getHeaders(), jmsRequest);

        replyTo = this.determineReplyDestination(requestMessage, session);
        jmsRequest.setJMSReplyTo(replyTo);
        connection.start();
        if (logger.isDebugEnabled()) {
            logger.debug("ReplyTo: " + replyTo);
        }

        Integer priority = new IntegrationMessageHeaderAccessor(requestMessage).getPriority();
        if (priority == null) {
            priority = this.priority;
        }
        javax.jms.Message replyMessage = null;
        Destination requestDestination = this.determineRequestDestination(requestMessage, session);
        if (this.correlationKey != null) {
            replyMessage = doSendAndReceiveWithGeneratedCorrelationId(requestDestination, jmsRequest, replyTo,
                    session, priority);
        } else if (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic) {
            replyMessage = doSendAndReceiveWithTemporaryReplyToDestination(requestDestination, jmsRequest,
                    replyTo, session, priority);
        } else {
            replyMessage = doSendAndReceiveWithMessageIdCorrelation(requestDestination, jmsRequest, replyTo,
                    session, priority);
        }
        return replyMessage;
    } finally {
        JmsUtils.closeSession(session);
        this.deleteDestinationIfTemporary(replyTo);
        ConnectionFactoryUtils.releaseConnection(connection, this.connectionFactory, true);
    }
}

From source file:org.springframework.integration.kafka.support.ProducerConfiguration.java

public void send(final Message<?> message) throws Exception {
    final V v = getPayload(message);

    String topic = message.getHeaders().get("topic", String.class);
    if (message.getHeaders().containsKey("messageKey")) {
        producer.send(new KeyedMessage<K, V>(topic, getKey(message), v));
    } else {//from  w  w  w.j a  v  a2  s.co m
        producer.send(new KeyedMessage<K, V>(topic, v));
    }
}

From source file:org.springframework.integration.kafka.support.ProducerConfiguration.java

@SuppressWarnings("unchecked")
private K getKey(final Message<?> message) throws Exception {
    final Object key = message.getHeaders().get("messageKey");

    if (producerMetadata.getKeyEncoder().getClass().isAssignableFrom(DefaultEncoder.class)) {
        return (K) getByteStream(key);
    }/*from   w w  w .j a v  a2 s.c  om*/

    return message.getHeaders().get("messageKey", producerMetadata.getKeyClassType());
}

From source file:org.springframework.integration.samples.filesplit.Application.java

/**
 * Rename the input file after success/failure.
 *
 * @return the flow.//  w  ww  .  ja  v  a  2 s  .  co  m
 */
@Bean
public MethodInterceptor afterMailAdvice() {
    return invocation -> {
        Message<?> message = (Message<?>) invocation.getArguments()[0];
        MessageHeaders headers = message.getHeaders();
        File originalFile = headers.get(FileHeaders.ORIGINAL_FILE, File.class);
        try {
            invocation.proceed();
            originalFile.renameTo(new File(originalFile.getAbsolutePath() + headers.get(EMAIL_SUCCESS_SUFFIX)));
        } catch (Exception e) {
            originalFile.renameTo(new File(
                    originalFile.getAbsolutePath() + headers.get(EMAIL_SUCCESS_SUFFIX) + ".email.failed"));
        }
        return null;
    };
}

From source file:org.springframework.integration.samples.rest.service.EmployeeSearchService.java

/**
 * The API <code>getEmployee()</code> looks up the mapped in coming message header's id param
 * and fills the return object with the appropriate employee details. The return
 * object is wrapped in Spring Integration Message with response headers filled in.
 * This example shows the usage of URL path variables and how the service act on
 * those variables.//from   w  w w  .j  av  a  2s .  c  o m
 * @param inMessage
 * @return an instance of <code>{@link Message}</code> that wraps <code>{@link EmployeeList}</code>
 */
@Secured("ROLE_REST_HTTP_USER")
public Message<EmployeeList> getEmployee(Message<?> inMessage) {

    EmployeeList employeeList = new EmployeeList();
    Map<String, Object> responseHeaderMap = new HashMap<String, Object>();

    try {
        MessageHeaders headers = inMessage.getHeaders();
        String id = (String) headers.get("employeeId");
        boolean isFound;
        if (id.equals("1")) {
            employeeList.getEmployee().add(new Employee(1, "John", "Doe"));
            isFound = true;
        } else if (id.equals("2")) {
            employeeList.getEmployee().add(new Employee(2, "Jane", "Doe"));
            isFound = true;
        } else if (id.equals("0")) {
            employeeList.getEmployee().add(new Employee(1, "John", "Doe"));
            employeeList.getEmployee().add(new Employee(2, "Jane", "Doe"));
            isFound = true;
        } else {
            isFound = false;
        }
        if (isFound) {
            setReturnStatusAndMessage("0", "Success", employeeList, responseHeaderMap);
        } else {
            setReturnStatusAndMessage("2", "Employee Not Found", employeeList, responseHeaderMap);
        }

    } catch (Exception e) {
        setReturnStatusAndMessage("1", "System Error", employeeList, responseHeaderMap);
        logger.error("System error occured :" + e);
    }
    Message<EmployeeList> message = new GenericMessage<EmployeeList>(employeeList, responseHeaderMap);
    return message;
}

From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java

@Test
public void testStream() {
    Session<?> session = spy(this.sessionFactory.getSession());
    session.close();//from  www .  j a v  a2 s. c  o  m

    String dir = "sftpSource/";
    this.inboundGetStream.send(new GenericMessage<Object>(dir + " sftpSource1.txt"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);
    assertEquals("source1", result.getPayload());
    assertEquals("sftpSource/", result.getHeaders().get(FileHeaders.REMOTE_DIRECTORY));
    assertEquals(" sftpSource1.txt", result.getHeaders().get(FileHeaders.REMOTE_FILE));
    verify(session).close();
}

From source file:org.springframework.integration.store.PersistentMessageGroup.java

@Override
public int getSequenceSize() {
    if (size() == 0) {
        return 0;
    } else {//w ww.j  a  va2  s.  c om
        Message<?> message = getOne();
        if (message != null) {
            Integer sequenceSize = message.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE,
                    Integer.class);
            return (sequenceSize != null ? sequenceSize : 0);
        } else {
            return 0;
        }
    }
}

From source file:org.springframework.integration.support.json.EmbeddedJsonHeadersMessageMapper.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w  .ja  v  a  2 s . c  o m*/
public byte[] fromMessage(Message<?> message) throws Exception {
    Map<String, Object> headersToEncode = this.allHeaders ? message.getHeaders()
            : pruneHeaders(message.getHeaders());

    if (this.rawBytes && message.getPayload() instanceof byte[]) {
        return fromBytesPayload((byte[]) message.getPayload(), headersToEncode);
    } else {
        Message<?> messageToEncode = message;

        if (!this.allHeaders) {
            if (!headersToEncode.containsKey(MessageHeaders.ID)) {
                headersToEncode.put(MessageHeaders.ID, MessageHeaders.ID_VALUE_NONE);
            }
            if (!headersToEncode.containsKey(MessageHeaders.TIMESTAMP)) {
                headersToEncode.put(MessageHeaders.TIMESTAMP, -1L);
            }

            messageToEncode = new MutableMessage<>(message.getPayload(), headersToEncode);
        }

        return this.objectMapper.writeValueAsBytes(messageToEncode);
    }
}