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.kafka.support.ProducerConfiguration.java

@SuppressWarnings("unchecked")
private V getPayload(final Message<?> message) throws Exception {
    if (producerMetadata.getValueEncoder().getClass().isAssignableFrom(DefaultEncoder.class)) {
        return (V) getByteStream(message.getPayload());
    } else if (message.getPayload().getClass().isAssignableFrom(producerMetadata.getValueClassType())) {
        return producerMetadata.getValueClassType().cast(message.getPayload());
    }//from w w w  .  ja  va 2 s .  co m

    throw new Exception("Message payload type is not matching with what is configured");
}

From source file:org.springframework.integration.mqtt.MqttAdapterTests.java

@Test
public void testInboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);/*from w w  w . j  a v a  2  s .c  o  m*/
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);

    factory = spy(factory);
    final IMqttClient client = mock(IMqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());

    final AtomicBoolean connectCalled = new AtomicBoolean();
    final AtomicBoolean failConnection = new AtomicBoolean();
    final CountDownLatch waitToFail = new CountDownLatch(1);
    final CountDownLatch failInProcess = new CountDownLatch(1);
    final CountDownLatch goodConnection = new CountDownLatch(2);
    final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
    willAnswer(invocation -> {
        if (failConnection.get()) {
            failInProcess.countDown();
            waitToFail.await(10, TimeUnit.SECONDS);
            throw reconnectException;
        }
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        goodConnection.countDown();
        return null;
    }).given(client).connect(any(MqttConnectOptions.class));

    final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
    willAnswer(invocation -> {
        callback.set(invocation.getArgument(0));
        return null;
    }).given(client).setCallback(any(MqttCallback.class));

    given(client.isConnected()).willReturn(true);

    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory,
            "baz", "fix");
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.setBeanFactory(mock(BeanFactory.class));
    ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
    final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
    willAnswer(invocation -> {
        events.add(invocation.getArgument(0));
        return null;
    }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
    adapter.setApplicationEventPublisher(applicationEventPublisher);
    adapter.setRecoveryInterval(500);
    adapter.afterPropertiesSet();
    adapter.start();

    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());

    MqttMessage message = new MqttMessage("qux".getBytes());
    callback.get().messageArrived("baz", message);
    Message<?> outMessage = outputChannel.receive(0);
    assertNotNull(outMessage);
    assertEquals("qux", outMessage.getPayload());

    MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());

    // lose connection and make first reconnect fail
    failConnection.set(true);
    RuntimeException e = new RuntimeException("foo");
    adapter.connectionLost(e);

    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), e);

    assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
    waitToFail.countDown();
    failConnection.set(false);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), reconnectException);

    // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
    assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
    int n = 0;
    while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
        event = events.poll(10, TimeUnit.SECONDS);
    }
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    taskScheduler.destroy();
}

From source file:org.springframework.integration.samples.advance.testing.jms.JmsMockTests.java

/**
 * This test verifies that a message received on a polling JMS inbound channel adapter is
 * routed to the designated channel and that the message payload is as expected
 *
 * @throws JMSException//from ww w. j av a 2 s  .c  om
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testReceiveMessage() throws JMSException, InterruptedException, IOException {
    String msg = "hello";

    boolean sent = verifyJmsMessageReceivedOnOutputChannel(msg, outputChannel, new CountDownHandler() {

        @Override
        protected void verifyMessage(Message<?> message) {
            assertEquals("hello", message.getPayload());
        }
    });
    assertTrue("message not sent to expected output channel", sent);
}

From source file:org.springframework.integration.samples.advance.testing.jms.JmsMockTests.java

/**
 * This test verifies that a message received on a polling JMS inbound channel adapter is
 * routed to the errorChannel and that the message payload is the expected exception
 *
 * @throws JMSException//  w ww  .  j a v a 2  s  . c  om
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public void testReceiveInvalidMessage() throws JMSException, IOException, InterruptedException {
    String msg = "whoops";
    boolean sent = verifyJmsMessageReceivedOnOutputChannel(msg, invalidMessageChannel, new CountDownHandler() {

        @Override
        protected void verifyMessage(Message<?> message) {
            assertEquals("invalid payload", message.getPayload());
        }

    });
    assertTrue("message not sent to expected output channel", sent);
}

From source file:org.springframework.integration.samples.tcpclientserver.TcpServerCustomSerializerTest.java

@Test
public void testHappyPath() {

    // add a listener to this channel, otherwise there is not one defined
    // the reason we use a listener here is so we can assert truths on the
    // message and/or payload
    SubscribableChannel channel = (SubscribableChannel) incomingServerChannel;
    channel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override//from  ww w  . j  a  v a  2  s  . com
        protected Object handleRequestMessage(Message<?> requestMessage) {
            CustomOrder payload = (CustomOrder) requestMessage.getPayload();

            // we assert during the processing of the messaging that the
            // payload is just the content we wanted to send without the
            // framing bytes (STX/ETX)
            assertEquals(123, payload.getNumber());
            assertEquals("PINGPONG02", payload.getSender());
            assertEquals("You got it to work!", payload.getMessage());
            return requestMessage;
        }
    });

    String sourceMessage = "123PINGPONG02000019You got it to work!";

    // use the java socket API to make the connection to the server
    Socket socket = null;
    Writer out = null;
    BufferedReader in = null;

    try {
        socket = new Socket("localhost", this.serverConnectionFactory.getPort());
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        out.write(sourceMessage);
        out.flush();

        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuffer str = new StringBuffer();

        int c;
        while ((c = in.read()) != -1) {
            str.append((char) c);
        }

        String response = str.toString();
        assertEquals(sourceMessage, response);

    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        fail(String.format("Test (port: %s) ended with an exception: %s",
                this.serverConnectionFactory.getPort(), e.getMessage()));
    } finally {
        try {
            socket.close();
            out.close();
            in.close();

        } catch (Exception e) {
            // swallow exception
        }

    }
}

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

@Test
public void testInt2866LocalDirectoryExpressionGET() {
    Session<?> session = this.sessionFactory.getSession();
    String dir = "sftpSource/";
    long modified = setModifiedOnSource1();
    this.inboundGet.send(new GenericMessage<Object>(dir + " sftpSource1.txt"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);//  w ww.j a va  2 s .  co m
    File localFile = (File) result.getPayload();
    assertThat(localFile.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir.toUpperCase()));
    assertPreserved(modified, localFile);

    dir = "sftpSource/subSftpSource/";
    this.inboundGet.send(new GenericMessage<Object>(dir + "subSftpSource1.txt"));
    result = this.output.receive(1000);
    assertNotNull(result);
    localFile = (File) result.getPayload();
    assertThat(localFile.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir.toUpperCase()));
    Session<?> session2 = this.sessionFactory.getSession();
    assertSame(TestUtils.getPropertyValue(session, "targetSession.jschSession"),
            TestUtils.getPropertyValue(session2, "targetSession.jschSession"));
}

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

@Test
@SuppressWarnings("unchecked")
public void testInt2866LocalDirectoryExpressionMGET() {
    String dir = "sftpSource/";
    long modified = setModifiedOnSource1();
    this.inboundMGet.send(new GenericMessage<Object>(dir + "*.txt"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);//from www .j a va  2 s .c o  m
    List<File> localFiles = (List<File>) result.getPayload();

    assertThat(localFiles.size(), Matchers.greaterThan(0));

    boolean assertedModified = false;
    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
        if (file.getPath().contains("localTarget1")) {
            assertedModified = assertPreserved(modified, file);
        }
    }
    assertTrue(assertedModified);

    dir = "sftpSource/subSftpSource/";
    this.inboundMGet.send(new GenericMessage<Object>(dir + "*.txt"));
    result = this.output.receive(1000);
    assertNotNull(result);
    localFiles = (List<File>) result.getPayload();

    assertThat(localFiles.size(), Matchers.greaterThan(0));

    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
    }
}

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

@Test
@SuppressWarnings("unchecked")
public void testInt3172LocalDirectoryExpressionMGETRecursive() throws IOException {
    String dir = "sftpSource/";
    long modified = setModifiedOnSource1();
    File secondRemote = new File(getSourceRemoteDirectory(), "sftpSource2.txt");
    secondRemote.setLastModified(System.currentTimeMillis() - 1_000_000);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);//from ww  w.  java2s. co  m
    List<File> localFiles = (List<File>) result.getPayload();
    assertEquals(3, localFiles.size());

    boolean assertedModified = false;
    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
        if (file.getPath().contains("localTarget1")) {
            assertedModified = assertPreserved(modified, file);
        }
    }
    assertTrue(assertedModified);
    assertThat(localFiles.get(2).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir + "subSftpSource"));

    File secondTarget = new File(getTargetLocalDirectory() + File.separator + "sftpSource", "localTarget2.txt");
    ByteArrayOutputStream remoteContents = new ByteArrayOutputStream();
    ByteArrayOutputStream localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondRemote, remoteContents);
    FileUtils.copyFile(secondTarget, localContents);
    String localAsString = new String(localContents.toByteArray());
    assertEquals(new String(remoteContents.toByteArray()), localAsString);
    long oldLastModified = secondRemote.lastModified();
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream("junk".getBytes()), secondRemote);
    long newLastModified = secondRemote.lastModified();
    secondRemote.setLastModified(oldLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals(localAsString, new String(localContents.toByteArray()));
    secondRemote.setLastModified(newLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals("junk", new String(localContents.toByteArray()));
    // restore the remote file contents
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream(localAsString.getBytes()), secondRemote);
}

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

@Test
@SuppressWarnings("unchecked")
public void testInt3172LocalDirectoryExpressionMGETRecursiveFiltered() {
    String dir = "sftpSource/";
    this.inboundMGetRecursiveFiltered.send(new GenericMessage<Object>(dir + "*"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);/*from  w w  w.  j a  va2 s.  c  o m*/
    List<File> localFiles = (List<File>) result.getPayload();
    // should have filtered sftpSource2.txt
    assertEquals(2, localFiles.size());

    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
    }
    assertThat(localFiles.get(1).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir + "subSftpSource"));

}

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

@Test
public void testInt3088MPutNotRecursive() throws Exception {
    Session<?> session = sessionFactory.getSession();
    session.close();//w w w . j  a v  a  2  s .  c o m
    session = TestUtils.getPropertyValue(session, "targetSession", Session.class);
    ChannelSftp channel = spy(TestUtils.getPropertyValue(session, "channel", ChannelSftp.class));
    new DirectFieldAccessor(session).setPropertyValue("channel", channel);

    String dir = "sftpSource/";
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    while (output.receive(0) != null) {
        // drain
    }
    this.inboundMPut.send(new GenericMessage<File>(getSourceLocalDirectory()));
    @SuppressWarnings("unchecked")
    Message<List<String>> out = (Message<List<String>>) this.output.receive(1000);
    assertNotNull(out);
    assertEquals(2, out.getPayload().size());
    assertThat(out.getPayload().get(0), not(equalTo(out.getPayload().get(1))));
    assertThat(out.getPayload().get(0),
            anyOf(equalTo("sftpTarget/localSource1.txt"), equalTo("sftpTarget/localSource2.txt")));
    assertThat(out.getPayload().get(1),
            anyOf(equalTo("sftpTarget/localSource1.txt"), equalTo("sftpTarget/localSource2.txt")));
    verify(channel).chmod(384, "sftpTarget/localSource1.txt"); // 384 = 600 octal
    verify(channel).chmod(384, "sftpTarget/localSource2.txt");
}