Example usage for org.springframework.integration.file.support FileExistsMode FAIL

List of usage examples for org.springframework.integration.file.support FileExistsMode FAIL

Introduction

In this page you can find the example usage for org.springframework.integration.file.support FileExistsMode FAIL.

Prototype

FileExistsMode FAIL

To view the source code for org.springframework.integration.file.support FileExistsMode FAIL.

Click Source Link

Document

Raise an exception in case the file to be written already exists.

Usage

From source file:org.springframework.integration.file.FileWritingMessageHandler.java

@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
    Assert.notNull(requestMessage, "message must not be null");
    Object payload = requestMessage.getPayload();
    Assert.notNull(payload, "message payload must not be null");
    String generatedFileName = this.fileNameGenerator.generateFileName(requestMessage);
    File originalFileFromHeader = this.retrieveOriginalFileFromHeader(requestMessage);

    final File destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage);

    File tempFile = new File(destinationDirectoryToUse, generatedFileName + temporaryFileSuffix);
    File resultFile = new File(destinationDirectoryToUse, generatedFileName);

    if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFile.exists()) {
        throw new MessageHandlingException(requestMessage,
                "The destination file already exists at '" + resultFile.getAbsolutePath() + "'.");
    }/*from  w w  w .  ja  v  a2  s  . co  m*/

    final boolean ignore = FileExistsMode.IGNORE.equals(this.fileExistsMode)
            && (resultFile.exists() || (StringUtils.hasText(this.temporaryFileSuffix) && tempFile.exists()));

    if (!ignore) {

        try {
            if (payload instanceof File) {
                resultFile = this.handleFileMessage((File) payload, tempFile, resultFile);
            } else if (payload instanceof byte[]) {
                resultFile = this.handleByteArrayMessage((byte[]) payload, originalFileFromHeader, tempFile,
                        resultFile);
            } else if (payload instanceof String) {
                resultFile = this.handleStringMessage((String) payload, originalFileFromHeader, tempFile,
                        resultFile);
            } else {
                throw new IllegalArgumentException(
                        "unsupported Message payload type [" + payload.getClass().getName() + "]");
            }
        } catch (Exception e) {
            throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e);
        }

    }

    if (!this.expectReply) {
        return null;
    }

    if (resultFile != null) {
        if (originalFileFromHeader == null && payload instanceof File) {
            return MessageBuilder.withPayload(resultFile).setHeader(FileHeaders.ORIGINAL_FILE, payload);
        }
    }
    return resultFile;
}

From source file:org.springframework.integration.file.remote.RemoteFileTemplate.java

private void sendFileToRemoteDirectory(InputStream inputStream, String temporaryRemoteDirectory,
        String remoteDirectory, String fileName, Session<F> session, FileExistsMode mode) throws IOException {

    remoteDirectory = this.normalizeDirectoryPath(remoteDirectory);
    temporaryRemoteDirectory = this.normalizeDirectoryPath(temporaryRemoteDirectory);

    String remoteFilePath = remoteDirectory + fileName;
    String tempRemoteFilePath = temporaryRemoteDirectory + fileName;
    // write remote file first with temporary file extension if enabled

    String tempFilePath = tempRemoteFilePath + (this.useTemporaryFileName ? this.temporaryFileSuffix : "");

    if (this.autoCreateDirectory) {
        try {//from w  ww .  j a va 2s .c  om
            RemoteFileUtils.makeDirectories(remoteDirectory, session, this.remoteFileSeparator, this.logger);
        } catch (IllegalStateException e) {
            // Revert to old FTP behavior if recursive mkdir fails, for backwards compatibility
            session.mkdir(remoteDirectory);
        }
    }

    try {
        boolean rename = this.useTemporaryFileName;
        if (FileExistsMode.REPLACE.equals(mode)) {
            session.write(inputStream, tempFilePath);
        } else if (FileExistsMode.APPEND.equals(mode)) {
            session.append(inputStream, tempFilePath);
        } else {
            if (exists(remoteFilePath)) {
                if (FileExistsMode.FAIL.equals(mode)) {
                    throw new MessagingException(
                            "The destination file already exists at '" + remoteFilePath + "'.");
                } else {
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("File not transferred to '" + remoteFilePath + "'; already exists.");
                    }
                }
                rename = false;
            } else {
                session.write(inputStream, tempFilePath);
            }
        }
        // then rename it to its final name if necessary
        if (rename) {
            session.rename(tempFilePath, remoteFilePath);
        }
    } catch (Exception e) {
        throw new MessagingException("Failed to write to '" + tempFilePath + "' while uploading the file", e);
    } finally {
        inputStream.close();
    }
}

From source file:org.springframework.integration.ftp.dsl.FtpTests.java

@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//  w  w  w. ja  v  a2 s . com
            .execute(session -> session.list(getTargetRemoteDirectory().getName() + "/" + fileName));
    assertEquals(1, files.length);
    assertEquals(3, files[0].getSize());

    registration.destroy();
}