Example usage for org.apache.commons.net.ftp FTPClient setModificationTime

List of usage examples for org.apache.commons.net.ftp FTPClient setModificationTime

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient setModificationTime.

Prototype

public boolean setModificationTime(String pathname, String timeval) throws IOException 

Source Link

Document

Issue the FTP MFMT command (not supported by all servers) which sets the last modified time of a file.

Usage

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public String put(final FlowFile flowFile, final String path, final String filename, final InputStream content)
        throws IOException {
    final FTPClient client = getClient(flowFile);

    final String fullPath;
    if (path == null) {
        fullPath = filename;/*from w  ww .  j  a va  2 s. com*/
    } else {
        final String workingDir = setAndGetWorkingDirectory(path);
        fullPath = workingDir.endsWith("/") ? workingDir + filename : workingDir + "/" + filename;
    }

    String tempFilename = ctx.getProperty(TEMP_FILENAME).evaluateAttributeExpressions(flowFile).getValue();
    if (tempFilename == null) {
        final boolean dotRename = ctx.getProperty(DOT_RENAME).asBoolean();
        tempFilename = dotRename ? "." + filename : filename;
    }

    final boolean storeSuccessful = client.storeFile(tempFilename, content);
    if (!storeSuccessful) {
        throw new IOException("Failed to store file " + tempFilename + " to " + fullPath + " due to: "
                + client.getReplyString());
    }

    final String lastModifiedTime = ctx.getProperty(LAST_MODIFIED_TIME).evaluateAttributeExpressions(flowFile)
            .getValue();
    if (lastModifiedTime != null && !lastModifiedTime.trim().isEmpty()) {
        try {
            final DateFormat informat = new SimpleDateFormat(FILE_MODIFY_DATE_ATTR_FORMAT, Locale.US);
            final Date fileModifyTime = informat.parse(lastModifiedTime);
            final DateFormat outformat = new SimpleDateFormat(FTP_TIMEVAL_FORMAT, Locale.US);
            final String time = outformat.format(fileModifyTime);
            if (!client.setModificationTime(tempFilename, time)) {
                // FTP server probably doesn't support MFMT command
                logger.warn("Could not set lastModifiedTime on {} to {}",
                        new Object[] { flowFile, lastModifiedTime });
            }
        } catch (final Exception e) {
            logger.error("Failed to set lastModifiedTime on {} to {} due to {}",
                    new Object[] { flowFile, lastModifiedTime, e });
        }
    }
    final String permissions = ctx.getProperty(PERMISSIONS).evaluateAttributeExpressions(flowFile).getValue();
    if (permissions != null && !permissions.trim().isEmpty()) {
        try {
            int perms = numberPermissions(permissions);
            if (perms >= 0) {
                if (!client.sendSiteCommand("chmod " + Integer.toOctalString(perms) + " " + tempFilename)) {
                    logger.warn("Could not set permission on {} to {}", new Object[] { flowFile, permissions });
                }
            }
        } catch (final Exception e) {
            logger.error("Failed to set permission on {} to {} due to {}",
                    new Object[] { flowFile, permissions, e });
        }
    }

    if (!filename.equals(tempFilename)) {
        try {
            logger.debug("Renaming remote path from {} to {} for {}",
                    new Object[] { tempFilename, filename, flowFile });
            final boolean renameSuccessful = client.rename(tempFilename, filename);
            if (!renameSuccessful) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " due to: " + client.getReplyString());
            }
        } catch (final IOException e) {
            try {
                client.deleteFile(tempFilename);
                throw e;
            } catch (final IOException e1) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " and failed to delete it when attempting to clean up", e1);
            }
        }
    }

    return fullPath;
}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test Setting the modification time FTP server
 *
 * @throws Exception/* w ww  . j  a v  a2 s . co  m*/
 */
public void testModificationTime() throws Exception {
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "ModificationTime";

    logger.debug("Start testModificationTime");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        reply = ftp.cwd("/Alfresco/User Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Delete the root directory in case it was left over from a previous test run
        try {
            ftp.removeDirectory(PATH1);
        } catch (IOException e) {
            // ignore this error
        }

        // make root directory
        ftp.makeDirectory(PATH1);
        ftp.cwd(PATH1);

        // make sub-directory in new directory
        ftp.makeDirectory(PATH2);
        ftp.cwd(PATH2);

        // List the files in the new directory
        FTPFile[] files = ftp.listFiles();
        assertTrue("files not empty", files.length == 0);

        // Create a file
        String FILE1_CONTENT_1 = "test file 1 content";
        String FILE1_NAME = "testFile1.txt";
        ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));

        String pathname = "/Alfresco/User Homes" + "/" + PATH1 + "/" + PATH2 + "/" + FILE1_NAME;

        logger.debug("set modification time");
        // YYYYMMDDhhmmss Time set to 2012 August 30 12:39:05
        String olympicTime = "20120830123905";
        ftp.setModificationTime(pathname, olympicTime);

        String extractedTime = ftp.getModificationTime(pathname);
        // Feature of the commons ftp library ExtractedTime has a "status code" first and is followed by newline chars

        assertTrue("time not set correctly by explicit set time", extractedTime.contains(olympicTime));

        // Get the new file
        FTPFile[] files2 = ftp.listFiles();
        assertTrue("files not one", files2.length == 1);

        InputStream is = ftp.retrieveFileStream(FILE1_NAME);

        String content = inputStreamToString(is);
        assertEquals("Content is not as expected", content, FILE1_CONTENT_1);
        ftp.completePendingCommand();

        // Update the file contents without setting time directly
        String FILE1_CONTENT_2 = "That's how it is says Pooh!";
        ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));

        InputStream is2 = ftp.retrieveFileStream(FILE1_NAME);

        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftp.completePendingCommand();

        extractedTime = ftp.getModificationTime(pathname);

        assertFalse("time not moved on if time not explicitly set", extractedTime.contains(olympicTime));

        // now delete the file we have been using.
        assertTrue(ftp.deleteFile(FILE1_NAME));

        // negative test - file should have gone now.
        assertFalse(ftp.deleteFile(FILE1_NAME));

    } finally {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }
}