Search in sources :

Example 1 with FileExistsMode

use of org.springframework.integration.file.support.FileExistsMode in project spring-integration by spring-projects.

the class FtpTests method testFtpMgetFlow.

@Test
@SuppressWarnings("unchecked")
public void testFtpMgetFlow() {
    QueueChannel out = new QueueChannel();
    IntegrationFlow flow = f -> f.handle(Ftp.outboundGateway(sessionFactory(), AbstractRemoteFileOutboundGateway.Command.MGET, "payload").options(AbstractRemoteFileOutboundGateway.Option.RECURSIVE).fileExistsMode(FileExistsMode.IGNORE).filterExpression("name matches 'subFtpSource|.*1.txt'").localDirectoryExpression("'" + getTargetLocalDirectoryName() + "' + #remoteDirectory").localFilenameExpression("#remoteFileName.replaceFirst('ftpSource', 'localTarget')")).channel(out);
    IntegrationFlowRegistration registration = this.flowContext.registration(flow).register();
    String dir = "ftpSource/";
    registration.getInputChannel().send(new GenericMessage<>(dir + "*"));
    Message<?> result = out.receive(10_000);
    assertNotNull(result);
    List<File> localFiles = (List<File>) result.getPayload();
    // should have filtered ftpSource2.txt
    assertEquals(2, localFiles.size());
    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"), Matchers.containsString(dir));
    }
    assertThat(localFiles.get(1).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"), Matchers.containsString(dir + "subFtpSource"));
    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) QueueChannel(org.springframework.integration.channel.QueueChannel) IntegrationFlowRegistration(org.springframework.integration.dsl.context.IntegrationFlowContext.IntegrationFlowRegistration) List(java.util.List) IntegrationFlow(org.springframework.integration.dsl.IntegrationFlow) StandardIntegrationFlow(org.springframework.integration.dsl.StandardIntegrationFlow) Matchers.containsString(org.hamcrest.Matchers.containsString) FTPFile(org.apache.commons.net.ftp.FTPFile) File(java.io.File) Test(org.junit.Test)

Example 2 with FileExistsMode

use of org.springframework.integration.file.support.FileExistsMode in project spring-integration by spring-projects.

the class AbstractRemoteFileOutboundGateway method get.

/**
 * Copy a remote file to the configured local directory.
 * @param message the message.
 * @param session the session.
 * @param remoteDir the remote directory.
 * @param remoteFilePath the remote file path.
 * @param remoteFilename the remote file name.
 * @param fileInfoParam the remote file info; if null we will execute an 'ls' command
 * first.
 * @return The file.
 * @throws IOException Any IOException.
 */
protected File get(Message<?> message, Session<F> session, String remoteDir, String remoteFilePath, String remoteFilename, F fileInfoParam) throws IOException {
    F fileInfo = fileInfoParam;
    if (fileInfo == null) {
        F[] files = session.list(remoteFilePath);
        if (files == null) {
            throw new MessagingException("Session returned null when listing " + remoteFilePath);
        }
        if (files.length != 1 || files[0] == null || isDirectory(files[0]) || isLink(files[0])) {
            throw new MessagingException(remoteFilePath + " is not a file");
        }
        fileInfo = files[0];
    }
    File localFile = new File(generateLocalDirectory(message, remoteDir), generateLocalFileName(message, remoteFilename));
    FileExistsMode fileExistsMode = this.fileExistsMode;
    boolean appending = FileExistsMode.APPEND.equals(fileExistsMode);
    boolean exists = localFile.exists();
    boolean replacing = FileExistsMode.REPLACE.equals(fileExistsMode) || (exists && FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode) && localFile.lastModified() != getModified(fileInfo));
    if (!exists || appending || replacing) {
        OutputStream outputStream;
        String tempFileName = localFile.getAbsolutePath() + this.remoteFileTemplate.getTemporaryFileSuffix();
        File tempFile = new File(tempFileName);
        if (appending) {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile, true));
        } else {
            outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
        }
        if (replacing) {
            localFile.delete();
        }
        try {
            session.read(remoteFilePath, outputStream);
        } catch (Exception e) {
            /* Some operation systems acquire exclusive file-lock during file processing
				and the file can't be deleted without closing streams before.
				*/
            outputStream.close();
            tempFile.delete();
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new MessagingException("Failure occurred while copying from remote to local directory", e);
            }
        } finally {
            try {
                outputStream.close();
            } catch (Exception ignored2) {
            // Ignore it
            }
        }
        if (!appending && !tempFile.renameTo(localFile)) {
            throw new MessagingException("Failed to rename local file");
        }
        if (this.options.contains(Option.PRESERVE_TIMESTAMP) || FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode)) {
            localFile.setLastModified(getModified(fileInfo));
        }
        if (this.options.contains(Option.DELETE)) {
            boolean result = session.remove(remoteFilePath);
            if (!result) {
                logger.error("Failed to delete: " + remoteFilePath);
            } else if (logger.isDebugEnabled()) {
                logger.debug(remoteFilePath + " deleted");
            }
        }
    } else if (FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Local file '" + localFile + "' has the same modified timestamp, ignored");
        }
        if (this.command.equals(Command.MGET)) {
            localFile = null;
        }
    } else if (!FileExistsMode.IGNORE.equals(fileExistsMode)) {
        throw new MessageHandlingException(message, "Local file " + localFile + " already exists");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Existing file skipped: " + localFile);
        }
        if (this.command.equals(Command.MGET)) {
            localFile = null;
        }
    }
    return localFile;
}
Also used : MessagingException(org.springframework.messaging.MessagingException) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) IOException(java.io.IOException) PartialSuccessException(org.springframework.integration.support.PartialSuccessException) FileNotFoundException(java.io.FileNotFoundException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) FileOutputStream(java.io.FileOutputStream) FileExistsMode(org.springframework.integration.file.support.FileExistsMode) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 IOException (java.io.IOException)2 FileExistsMode (org.springframework.integration.file.support.FileExistsMode)2 BufferedOutputStream (java.io.BufferedOutputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 StandardCharsets (java.nio.charset.StandardCharsets)1 List (java.util.List)1 Matcher (java.util.regex.Matcher)1 FTPFile (org.apache.commons.net.ftp.FTPFile)1 Matchers (org.hamcrest.Matchers)1 Matchers.containsString (org.hamcrest.Matchers.containsString)1 Matchers.equalTo (org.hamcrest.Matchers.equalTo)1 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)1 Matchers.isOneOf (org.hamcrest.Matchers.isOneOf)1 Assert.assertEquals (org.junit.Assert.assertEquals)1