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

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

Introduction

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

Prototype

public boolean rename(String from, String to) throws IOException 

Source Link

Document

Renames a remote file.

Usage

From source file:com.globalsight.smartbox.util.FtpHelper.java

public boolean ftpRename(String p_target, String p_file) {
    FTPClient ftpClient = getFtpClient();
    if (ftpClient != null && ftpClient.isConnected()) {
        try {// w  w  w  .ja v  a2  s .c o  m
            ftpClient.rename(p_file, p_target);
        } catch (IOException e) {
            return false;
        } finally {
            closeFtpClient(ftpClient);
        }
    }

    return true;
}

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

@Override
public void rename(final String source, final String target) throws IOException {
    final FTPClient client = getClient(null);
    final boolean renameSuccessful = client.rename(source, target);
    if (!renameSuccessful) {
        throw new IOException("Failed to rename temporary file " + source + " to " + target + " due to: "
                + client.getReplyString());
    }//ww w . j ava 2 s.c o m
}

From source file:com.alexkasko.netty.ftp.FtpServerTest.java

@Test
public void test() throws IOException, InterruptedException {
    final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate(
            new ConsoleReceiver());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/* w ww.  j av a2  s  . co  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("decoder", new CrlfStringDecoder());
                    pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate));
                }

            });
    b.localAddress(2121).bind();
    FTPClient client = new FTPClient();
    //        https://issues.apache.org/jira/browse/NET-493

    client.setBufferSize(0);
    client.connect("127.0.0.1", 2121);
    assertEquals(230, client.user("anonymous"));

    // active
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    assertEquals("/", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.listFiles("/foo").length == 0);
    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    //  assertTrue(client.deleteFile("baz"));

    // passive
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    client.enterLocalPassiveMode();
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());

    //TODO make a virtual filesystem that would work with directory
    //assertTrue(client.listFiles("/foo").length==1);

    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    // client.deleteFile("baz");

    assertEquals(221, client.quit());
    try {
        client.noop();
        fail("Should throw exception");
    } catch (IOException e) {
        //expected;
    }

}

From source file:lucee.runtime.tag.Ftp.java

/**
 * rename a file on the server/*w  ww  .  j ava  2  s.  c o m*/
 * @return FTPCLient
 * @throws PageException
 * @throws IOException
 */
private FTPClient actionRename() throws PageException, IOException {
    required("existing", existing);
    required("new", _new);

    FTPClient client = getClient();
    client.rename(existing, _new);
    writeCfftp(client);

    return client;
}

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  . jav  a2  s .  c  om
    } 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 of rename case ALF-20584/*from www.  j a v  a2s  .  c  o  m*/
 * 
        
 */
public void testRenameCase() throws Exception {

    logger.debug("Start testRenameCase");

    FTPClient ftp = connectClient();

    String PATH1 = "testRenameCase";

    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 for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);

        ftp.cwd(PATH1);

        String FILE1_CONTENT_2 = "That's how it is says Pooh!";
        ftp.storeFile("FileA.txt", new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));

        assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT"));

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

        ftp.disconnect();
    }

}

From source file:org.alinous.ftp.FtpManager.java

public void rename(String sessionId, String from, String to) throws IOException {
    FTPClient ftp = this.instances.get(sessionId).getFtp();

    ftp.rename(from, to);
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 * // w ww  . ja  v a  2s  .c  om
 * @param client
 * @param src
 * @param dst
 * @return
 * @throws IOException
 */
private boolean rename(FTPClient client, Path src, Path dst) throws IOException {
    Path workDir = new Path(client.printWorkingDirectory());
    Path absoluteSrc = makeAbsolute(workDir, src);
    Path absoluteDst = makeAbsolute(workDir, dst);
    if (!exists(client, absoluteSrc)) {
        throw new IOException("Source path " + src + " does not exist");
    }
    if (exists(client, absoluteDst)) {
        throw new IOException("Destination path " + dst + " already exist, cannot rename!");
    }
    String parentSrc = absoluteSrc.getParent().toUri().toString();
    String parentDst = absoluteDst.getParent().toUri().toString();
    String from = src.getName();
    String to = dst.getName();
    if (!parentSrc.equals(parentDst)) {
        throw new IOException(
                "Cannot rename parent(source): " + parentSrc + ", parent(destination):  " + parentDst);
    }
    client.changeWorkingDirectory(parentSrc);
    boolean renamed = client.rename(from, to);
    return renamed;
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {//www  .ja v a2s  . c  om
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate).
 * Copying is done from local directory into remote ftp destination directory.
 * //from  w w w  .  j a v a 2  s .c  o  m
 * @param destPath
 * @param localSourcePath
 * @param filePattern
 * @return the number of files being copied
 * @throws IOException 
 */
public Integer syncPush(String localSourcePath, FTPClient ftpDest, String filePattern) throws IOException {
    // check for new files since the last check which need to be copied

    Integer number = 0;
    SortedMap<FileNameDate, FTPFile> destMap = fileMapByNameAndDate(ftpDest, filePattern);
    SortedMap<FileNameDate, File> sourceMap = FileUtils.fileMapByNameAndDate(localSourcePath, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (File file : sourceMap.values()) {
        logger.debug(file.getName() + ": " + new Date(file.lastModified()));

        try {
            // only copy file that don't exist yet
            if (ftpDest.listNames(file.getName()).length == 0) {
                FileInputStream fin = new FileInputStream(file);
                String tmpName = "tempFile";
                boolean rc = ftpDest.storeFile(tmpName, fin);
                fin.close();
                if (rc) {
                    rc = ftpDest.rename(tmpName, file.getName());
                    number++;
                }
                if (!rc) {
                    ftpDest.deleteFile(tmpName);
                }
            }
        } catch (Exception ex) {
            logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error  "
                    + ftpDest.getReplyString());
        }
    }
    return number;
}