Search in sources :

Example 1 with RemoteFileTemplate

use of org.springframework.integration.file.remote.RemoteFileTemplate in project spring-integration-samples by spring-projects.

the class SftpOutboundTransferSample method testOutbound.

@Test
public void testOutbound() throws Exception {
    final String sourceFileName = "README.md";
    final String destinationFileName = sourceFileName + "_foo";
    final ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("/META-INF/spring/integration/SftpOutboundTransferSample-context.xml", SftpOutboundTransferSample.class);
    @SuppressWarnings("unchecked") SessionFactory<LsEntry> sessionFactory = ac.getBean(CachingSessionFactory.class);
    RemoteFileTemplate<LsEntry> template = new RemoteFileTemplate<LsEntry>(sessionFactory);
    // Just the directory
    SftpTestUtils.createTestFiles(template);
    try {
        final File file = new File(sourceFileName);
        Assert.isTrue(file.exists(), String.format("File '%s' does not exist.", sourceFileName));
        final Message<File> message = MessageBuilder.withPayload(file).build();
        final MessageChannel inputChannel = ac.getBean("inputChannel", MessageChannel.class);
        inputChannel.send(message);
        Thread.sleep(2000);
        Assert.isTrue(SftpTestUtils.fileExists(template, destinationFileName), String.format("File '%s' does not exist.", destinationFileName));
        System.out.println(String.format("Successfully transferred '%s' file to a " + "remote location under the name '%s'", sourceFileName, destinationFileName));
    } finally {
        SftpTestUtils.cleanUp(template, destinationFileName);
        ac.close();
    }
}
Also used : RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) MessageChannel(org.springframework.messaging.MessageChannel) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) File(java.io.File) Test(org.junit.Test)

Example 2 with RemoteFileTemplate

use of org.springframework.integration.file.remote.RemoteFileTemplate in project spring-integration by spring-projects.

the class RemoteFileOutboundGatewayTests method testPutExists.

@Test
public void testPutExists() throws Exception {
    @SuppressWarnings("unchecked") SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class);
    @SuppressWarnings("unchecked") Session<TestLsEntry> session = mock(Session.class);
    RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<TestLsEntry>(sessionFactory) {

        @Override
        public boolean exists(String path) {
            return true;
        }
    };
    template.setRemoteDirectoryExpression(new LiteralExpression("foo/"));
    template.setBeanFactory(mock(BeanFactory.class));
    template.afterPropertiesSet();
    TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload");
    FileTransferringMessageHandler<TestLsEntry> handler = new FileTransferringMessageHandler<TestLsEntry>(sessionFactory);
    handler.setRemoteDirectoryExpression(new LiteralExpression("foo/"));
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    gw.afterPropertiesSet();
    when(sessionFactory.getSession()).thenReturn(session);
    Message<String> requestMessage = MessageBuilder.withPayload("hello").setHeader(FileHeaders.FILENAME, "bar.txt").build();
    // default (null) == REPLACE
    String path = (String) gw.handleRequestMessage(requestMessage);
    assertEquals("foo/bar.txt", path);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(session).write(any(InputStream.class), captor.capture());
    assertEquals("foo/bar.txt.writing", captor.getValue());
    verify(session).rename("foo/bar.txt.writing", "foo/bar.txt");
    gw.setFileExistsMode(FileExistsMode.FAIL);
    try {
        path = (String) gw.handleRequestMessage(requestMessage);
        fail("Exception expected");
    } catch (Exception e) {
        assertThat(e.getMessage(), containsString("The destination file already exists"));
    }
    gw.setFileExistsMode(FileExistsMode.REPLACE);
    path = (String) gw.handleRequestMessage(requestMessage);
    assertEquals("foo/bar.txt", path);
    captor = ArgumentCaptor.forClass(String.class);
    verify(session, times(2)).write(any(InputStream.class), captor.capture());
    assertEquals("foo/bar.txt.writing", captor.getValue());
    verify(session, times(2)).rename("foo/bar.txt.writing", "foo/bar.txt");
    gw.setFileExistsMode(FileExistsMode.APPEND);
    path = (String) gw.handleRequestMessage(requestMessage);
    assertEquals("foo/bar.txt", path);
    captor = ArgumentCaptor.forClass(String.class);
    verify(session).append(any(InputStream.class), captor.capture());
    assertEquals("foo/bar.txt", captor.getValue());
    gw.setFileExistsMode(FileExistsMode.IGNORE);
    path = (String) gw.handleRequestMessage(requestMessage);
    assertEquals("foo/bar.txt", path);
    // no more writes/appends
    verify(session, times(2)).write(any(InputStream.class), anyString());
    verify(session, times(1)).append(any(InputStream.class), anyString());
}
Also used : RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) FileTransferringMessageHandler(org.springframework.integration.file.remote.handler.FileTransferringMessageHandler) InputStream(java.io.InputStream) LiteralExpression(org.springframework.expression.common.LiteralExpression) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) IOException(java.io.IOException) BeanFactory(org.springframework.beans.factory.BeanFactory) Test(org.junit.Test)

Example 3 with RemoteFileTemplate

use of org.springframework.integration.file.remote.RemoteFileTemplate in project spring-integration by spring-projects.

the class RemoteFileOutboundGatewayTests method testPut.

@Test
public void testPut() throws Exception {
    @SuppressWarnings("unchecked") SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class);
    @SuppressWarnings("unchecked") Session<TestLsEntry> session = mock(Session.class);
    RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<TestLsEntry>(sessionFactory) {

        @Override
        public boolean exists(String path) {
            return false;
        }
    };
    template.setRemoteDirectoryExpression(new LiteralExpression("foo/"));
    template.setBeanFactory(mock(BeanFactory.class));
    template.afterPropertiesSet();
    TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload");
    FileTransferringMessageHandler<TestLsEntry> handler = new FileTransferringMessageHandler<TestLsEntry>(sessionFactory);
    handler.setRemoteDirectoryExpressionString("'foo/'");
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    gw.afterPropertiesSet();
    when(sessionFactory.getSession()).thenReturn(session);
    Message<String> requestMessage = MessageBuilder.withPayload("hello").setHeader(FileHeaders.FILENAME, "bar.txt").build();
    String path = (String) gw.handleRequestMessage(requestMessage);
    assertEquals("foo/bar.txt", path);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(session).write(any(InputStream.class), captor.capture());
    assertEquals("foo/bar.txt.writing", captor.getValue());
    verify(session).rename("foo/bar.txt.writing", "foo/bar.txt");
}
Also used : RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) FileTransferringMessageHandler(org.springframework.integration.file.remote.handler.FileTransferringMessageHandler) InputStream(java.io.InputStream) LiteralExpression(org.springframework.expression.common.LiteralExpression) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) BeanFactory(org.springframework.beans.factory.BeanFactory) Test(org.junit.Test)

Example 4 with RemoteFileTemplate

use of org.springframework.integration.file.remote.RemoteFileTemplate in project spring-integration by spring-projects.

the class FtpTests method testFtpOutboundFlow.

@Test
public void testFtpOutboundFlow() {
    IntegrationFlow flow = f -> f.handle(Ftp.outboundAdapter(sessionFactory(), FileExistsMode.FAIL).useTemporaryFileName(false).fileNameExpression("headers['" + FileHeaders.FILENAME + "']").remoteDirectory("ftpTarget"));
    IntegrationFlowRegistration registration = this.flowContext.registration(flow).register();
    String fileName = "foo.file";
    Message<ByteArrayInputStream> message = MessageBuilder.withPayload(new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8))).setHeader(FileHeaders.FILENAME, fileName).build();
    registration.getInputChannel().send(message);
    RemoteFileTemplate<FTPFile> template = new RemoteFileTemplate<>(sessionFactory());
    FTPFile[] files = template.execute(session -> session.list(getTargetRemoteDirectory().getName() + "/" + fileName));
    assertEquals(1, files.length);
    assertEquals(3, files[0].getSize());
    registration.destroy();
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) IntegrationFlow(org.springframework.integration.dsl.IntegrationFlow) Autowired(org.springframework.beans.factory.annotation.Autowired) Assert.assertThat(org.junit.Assert.assertThat) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) FtpInboundFileSynchronizingMessageSource(org.springframework.integration.ftp.inbound.FtpInboundFileSynchronizingMessageSource) SpringRunner(org.springframework.test.context.junit4.SpringRunner) RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) Matchers.isOneOf(org.hamcrest.Matchers.isOneOf) FtpStreamingMessageSource(org.springframework.integration.ftp.inbound.FtpStreamingMessageSource) EnableIntegration(org.springframework.integration.config.EnableIntegration) IntegrationFlowRegistration(org.springframework.integration.dsl.context.IntegrationFlowContext.IntegrationFlowRegistration) FtpTestSupport(org.springframework.integration.ftp.FtpTestSupport) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) FTPFile(org.apache.commons.net.ftp.FTPFile) Matchers.containsString(org.hamcrest.Matchers.containsString) FileCopyUtils(org.springframework.util.FileCopyUtils) QueueChannel(org.springframework.integration.channel.QueueChannel) RunWith(org.junit.runner.RunWith) FileHeaders(org.springframework.integration.file.FileHeaders) IntegrationFlowContext(org.springframework.integration.dsl.context.IntegrationFlowContext) FileExistsMode(org.springframework.integration.file.support.FileExistsMode) TestUtils(org.springframework.integration.test.util.TestUtils) MessageSource(org.springframework.integration.core.MessageSource) MessageBuilder(org.springframework.integration.support.MessageBuilder) Pollers(org.springframework.integration.dsl.Pollers) IntegrationFlows(org.springframework.integration.dsl.IntegrationFlows) Message(org.springframework.messaging.Message) FtpRemoteFileTemplate(org.springframework.integration.ftp.session.FtpRemoteFileTemplate) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileOutputStream(java.io.FileOutputStream) Matchers(org.hamcrest.Matchers) AbstractRemoteFileOutboundGateway(org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway) IOException(java.io.IOException) Test(org.junit.Test) ApplicationContext(org.springframework.context.ApplicationContext) File(java.io.File) Assert.assertNull(org.junit.Assert.assertNull) FileReader(java.io.FileReader) GenericMessage(org.springframework.messaging.support.GenericMessage) Assert.assertEquals(org.junit.Assert.assertEquals) StandardIntegrationFlow(org.springframework.integration.dsl.StandardIntegrationFlow) InputStream(java.io.InputStream) RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) FtpRemoteFileTemplate(org.springframework.integration.ftp.session.FtpRemoteFileTemplate) ByteArrayInputStream(java.io.ByteArrayInputStream) IntegrationFlowRegistration(org.springframework.integration.dsl.context.IntegrationFlowContext.IntegrationFlowRegistration) FTPFile(org.apache.commons.net.ftp.FTPFile) IntegrationFlow(org.springframework.integration.dsl.IntegrationFlow) StandardIntegrationFlow(org.springframework.integration.dsl.StandardIntegrationFlow) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 5 with RemoteFileTemplate

use of org.springframework.integration.file.remote.RemoteFileTemplate in project spring-integration-samples by spring-projects.

the class SftpTestUtils method createTestFiles.

public static void createTestFiles(RemoteFileTemplate<LsEntry> template, final String... fileNames) {
    if (template != null) {
        final ByteArrayInputStream stream = new ByteArrayInputStream("foo".getBytes());
        template.execute((SessionCallback<LsEntry, Void>) session -> {
            try {
                session.mkdir("si.sftp.sample");
            } catch (Exception e) {
                assertThat(e.getMessage(), containsString("failed to create"));
            }
            for (int i = 0; i < fileNames.length; i++) {
                stream.reset();
                session.write(stream, "si.sftp.sample/" + fileNames[i]);
            }
            return null;
        });
    }
}
Also used : Assert.assertThat(org.junit.Assert.assertThat) ByteArrayInputStream(java.io.ByteArrayInputStream) SftpATTRS(com.jcraft.jsch.SftpATTRS) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) Matchers.containsString(org.hamcrest.Matchers.containsString) RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) SessionCallback(org.springframework.integration.file.remote.SessionCallback) ChannelSftp(com.jcraft.jsch.ChannelSftp) ByteArrayInputStream(java.io.ByteArrayInputStream) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException)

Aggregations

RemoteFileTemplate (org.springframework.integration.file.remote.RemoteFileTemplate)11 Test (org.junit.Test)10 Matchers.containsString (org.hamcrest.Matchers.containsString)9 InputStream (java.io.InputStream)7 File (java.io.File)6 BeanFactory (org.springframework.beans.factory.BeanFactory)6 IOException (java.io.IOException)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 LiteralExpression (org.springframework.expression.common.LiteralExpression)5 List (java.util.List)4 Assert.assertThat (org.junit.Assert.assertThat)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)3 Assert.assertEquals (org.junit.Assert.assertEquals)3 GenericMessage (org.springframework.messaging.support.GenericMessage)3 ChannelSftp (com.jcraft.jsch.ChannelSftp)2 LsEntry (com.jcraft.jsch.ChannelSftp.LsEntry)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2