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.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void sendOnlyViewExpression() throws Exception {
    QueueChannel requestChannel = new QueueChannel();
    HttpRequestHandlingController controller = new HttpRequestHandlingController(false);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    Expression viewExpression = new SpelExpressionParser().parseExpression("'baz'");
    controller.setViewExpression(viewExpression);
    controller.afterPropertiesSet();// w  w  w.  j  a  va  2s  .c  o m
    controller.start();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("hello".getBytes());

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");

    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals("baz", modelAndView.getViewName());
    assertEquals(0, modelAndView.getModel().size());
    Message<?> requestMessage = requestChannel.receive(0);
    assertNotNull(requestMessage);
    assertEquals("hello", requestMessage.getPayload());
}

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void requestReply() throws Exception {
    DirectChannel requestChannel = new DirectChannel();
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
        @Override// w w w.  ja  va  2  s . c om
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return requestMessage.getPayload().toString().toUpperCase();
        }
    };
    requestChannel.subscribe(handler);
    HttpRequestHandlingController controller = new HttpRequestHandlingController(true);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.setViewName("foo");
    controller.afterPropertiesSet();
    controller.start();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");
    request.setContent("hello".getBytes()); //For Spring 3.0.7.RELEASE the Content must be set,

    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals("foo", modelAndView.getViewName());
    assertEquals(1, modelAndView.getModel().size());
    Object reply = modelAndView.getModel().get("reply");
    assertNotNull(reply);
    assertEquals("HELLO", reply);
}

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void requestReplyWithCustomReplyKey() throws Exception {
    DirectChannel requestChannel = new DirectChannel();
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
        @Override//w w  w  .  j a v a2 s . c om
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return requestMessage.getPayload().toString().toUpperCase();
        }
    };
    requestChannel.subscribe(handler);
    HttpRequestHandlingController controller = new HttpRequestHandlingController(true);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.setViewName("foo");
    controller.setReplyKey("myReply");
    controller.afterPropertiesSet();
    controller.start();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("howdy".getBytes());

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");

    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals("foo", modelAndView.getViewName());
    assertEquals(1, modelAndView.getModel().size());
    assertNull(modelAndView.getModel().get("reply"));
    Object reply = modelAndView.getModel().get("myReply");
    assertEquals("HOWDY", reply);
}

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void requestReplyWithFullMessageInModel() throws Exception {
    DirectChannel requestChannel = new DirectChannel();
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
        @Override/*from   w  ww  . ja  v a 2s .  c o m*/
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return requestMessage.getPayload().toString().toUpperCase();
        }
    };
    requestChannel.subscribe(handler);
    HttpRequestHandlingController controller = new HttpRequestHandlingController(true);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.setViewName("foo");
    controller.setExtractReplyPayload(false);
    controller.afterPropertiesSet();
    controller.start();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("abc".getBytes());

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");

    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals("foo", modelAndView.getViewName());
    assertEquals(1, modelAndView.getModel().size());
    Object reply = modelAndView.getModel().get("reply");
    assertNotNull(reply);
    assertTrue(reply instanceof Message<?>);
    assertEquals("ABC", ((Message<?>) reply).getPayload());
}

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void shutDown() throws Exception {
    DirectChannel requestChannel = new DirectChannel();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
        @Override/*  www . ja  va2s . c o  m*/
        protected Object handleRequestMessage(Message<?> requestMessage) {
            try {
                latch2.countDown();
                // hold up an active thread so we can verify the count and that it completes ok
                latch1.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return requestMessage.getPayload().toString().toUpperCase();
        }
    };
    requestChannel.subscribe(handler);
    final HttpRequestHandlingController controller = new HttpRequestHandlingController(true);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.setViewName("foo");
    controller.afterPropertiesSet();
    controller.start();

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("hello".getBytes());

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");

    MockHttpServletResponse response = new MockHttpServletResponse();
    final AtomicInteger active = new AtomicInteger();
    final AtomicBoolean expected503 = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            // wait for the active thread
            latch2.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
        }
        // start the shutdown
        active.set(controller.beforeShutdown());
        try {
            MockHttpServletResponse response1 = new MockHttpServletResponse();
            controller.handleRequest(request, response1);
            expected503.set(response1.getStatus() == HttpStatus.SERVICE_UNAVAILABLE.value());
            latch1.countDown();
        } catch (Exception e) {
            LogFactory.getLog(getClass()).error("Async handleRequest failed", e);
        }
    });
    ModelAndView modelAndView = controller.handleRequest(request, response);
    // verify we get a 503 after shutdown starts
    assertEquals(1, active.get());
    assertTrue(expected503.get());
    // verify the active request still processed ok
    assertEquals("foo", modelAndView.getViewName());
    assertEquals(1, modelAndView.getModel().size());
    Object reply = modelAndView.getModel().get("reply");
    assertNotNull(reply);
    assertEquals("HELLO", reply);
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@Test
//   @Repeat(1000) // INT-3722
public void gatewayIntegrationTest() throws Exception {
    final List<String> connectionIds = new ArrayList<String>();
    final AtomicBoolean okToRun = new AtomicBoolean(true);
    Executors.newSingleThreadExecutor().execute(() -> {
        while (okToRun.get()) {
            Message<?> m = inbound.receive(1000);
            if (m != null) {
                connectionIds.add((String) m.getHeaders().get(IpHeaders.CONNECTION_ID));
                replies.send(MessageBuilder.withPayload("foo:" + new String((byte[]) m.getPayload()))
                        .copyHeaders(m.getHeaders()).build());
            }/*from  ww  w  . jav a 2  s  .c  o m*/
        }
    });
    TestingUtilities.waitListening(serverCf, null);
    new DirectFieldAccessor(this.clientGatewayCf).setPropertyValue("port", this.serverCf.getPort());

    this.toGateway.send(new GenericMessage<>("Hello, world!"));
    Message<?> m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world!", new String((byte[]) m.getPayload()));

    BlockingQueue<?> connections = TestUtils.getPropertyValue(this.gatewayCF, "pool.available",
            BlockingQueue.class);
    // wait until the connection is returned to the pool
    int n = 0;
    while (n++ < 100 && connections.size() == 0) {
        Thread.sleep(100);
    }

    // assert we use the same connection from the pool
    toGateway.send(new GenericMessage<String>("Hello, world2!"));
    m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world2!", new String((byte[]) m.getPayload()));

    assertEquals(2, connectionIds.size());
    assertEquals(connectionIds.get(0), connectionIds.get(1));

    okToRun.set(false);
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@SuppressWarnings("unchecked")
@Test //INT-3722/*from  ww w. j a va2  s  .co  m*/
public void testGatewayRelease() throws Exception {
    TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0);
    in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    final TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(in);
    final AtomicInteger count = new AtomicInteger(2);
    in.registerListener(message -> {
        if (!(message instanceof ErrorMessage)) {
            if (count.decrementAndGet() < 1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            handler.handleMessage(message);
        }
        return false;
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    TestingUtilities.waitListening(in, null);
    int port = in.getPort();
    TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port);
    out.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 2);
    final TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(cache);
    QueueChannel outputChannel = new QueueChannel();
    gate.setOutputChannel(outputChannel);
    gate.setBeanFactory(mock(BeanFactory.class));
    gate.afterPropertiesSet();
    Log logger = spy(TestUtils.getPropertyValue(gate, "logger", Log.class));
    new DirectFieldAccessor(gate).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(new Answer<Void>() {

        private final CountDownLatch latch = new CountDownLatch(2);

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            String log = invocation.getArgument(0);
            if (log.startsWith("Response")) {
                Executors.newSingleThreadScheduledExecutor()
                        .execute(() -> gate.handleMessage(new GenericMessage<>("bar")));
                // hold up the first thread until the second has added its pending reply
                latch.await(10, TimeUnit.SECONDS);
            } else if (log.startsWith("Added")) {
                latch.countDown();
            }
            return null;
        }
    }).when(logger).debug(anyString());
    gate.start();
    gate.handleMessage(new GenericMessage<String>("foo"));
    Message<byte[]> result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("foo", new String(result.getPayload()));
    result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("bar", new String(result.getPayload()));
    handler.stop();
    gate.stop();
    verify(logger, never()).error(anyString());
}

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);
    });//  w w  w. jav  a 2  s  .co  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;//  w w w. j  av a2s .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;// w w w .j a  v  a2 s . c  o 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);
    }
}