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

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

Introduction

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

Prototype

public boolean deleteFile(String pathname) throws IOException 

Source Link

Document

Deletes a file on the FTP server.

Usage

From source file:org.moxie.ftp.FTPTaskMirrorImpl.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client/*from  www . ja  v a2 s .c o m*/
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occuring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(task);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, task.getLocation());
    }
    return returnValue;
}

From source file:org.mule.modules.FtpUtils.java

public static boolean deleteFile(FTPClient client, String filePath, String fileName) {
    try {/*w ww .j  a v a2  s  .  c o  m*/
        String fullPath = createFullPath(filePath, fileName);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        if (fileExists(client, filePath, fileName)) {
            return client.deleteFile(fullPath);
        } else {
            throw new FtpLiteException("File does not exist");
        }
    } catch (IOException e) {
        disconnect(client);
        throw new FtpLiteException("Error retrieving file stream from SFTP");
    }
}

From source file:org.mule.transport.ftp.FtpMessageReceiver.java

protected void postProcess(FTPClient client, FTPFile file, MuleMessage message) throws Exception {
    if (!client.deleteFile(file.getName())) {
        throw new IOException(MessageFormat.format("Failed to delete file {0}. Ftp error: {1}", file.getName(),
                client.getReplyCode()));
    }/*from w w  w .j  a  v a2s  . c  o m*/
    if (logger.isDebugEnabled()) {
        logger.debug("Deleted processed file " + file.getName());
    }

    if (connector.isStreaming()) {
        if (!client.completePendingCommand()) {
            throw new IOException(MessageFormat.format(
                    "Failed to complete a pending command. Retrieveing file {0}. Ftp error: {1}",
                    file.getName(), client.getReplyCode()));
        }
    }
}

From source file:org.mule.transport.ftp.FtpMessageRequester.java

protected void postProcess(FTPClient client, FTPFile file, MuleMessage message) throws Exception {
    if (!connector.isStreaming()) {
        if (!client.deleteFile(file.getName())) {
            throw new IOException(MessageFormat.format("Failed to delete file {0}. Ftp error: {1}",
                    file.getName(), client.getReplyCode()));
        }//from   www  . ja v a2 s  .c  o m
        if (logger.isDebugEnabled()) {
            logger.debug("Deleted file " + file.getName());
        }
    }
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void rmR(final FTPClient ftp, final String toRm) throws IOException {
    final String cwd = ftp.printWorkingDirectory();
    // si on ne peut cd, le dossier n'existe pas
    if (ftp.changeWorkingDirectory(toRm)) {
        recurse(ftp, new ExnClosure<FTPFile, IOException>() {
            @Override/*w  w  w. jav  a2 s .  co  m*/
            public void executeChecked(FTPFile input) throws IOException {
                final boolean res;
                if (input.isDirectory())
                    res = ftp.removeDirectory(input.getName());
                else
                    res = ftp.deleteFile(input.getName());
                if (!res)
                    throw new IOException("unable to delete " + input);
            }
        }, RecursionType.DEPTH_FIRST);
    }
    ftp.changeWorkingDirectory(cwd);
    ftp.removeDirectory(toRm);
}

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 .com
 * @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;
}

From source file:org.soitoolkit.commons.mule.ftp.FtpUtil.java

/**
 * Deletes a directory with all its files and sub-directories.
 * /*from ww w .  j a  va 2 s .  c  om*/
 * @param ftpClient
 * @param path
 * @throws IOException
 */
static public void recursiveDeleteDirectory(FTPClient ftpClient, String path) throws IOException {

    logger.info("Delete directory: {}", path);

    FTPFile[] ftpFiles = ftpClient.listFiles(path);
    logger.debug("Number of files that will be deleted: {}", ftpFiles.length);

    for (FTPFile ftpFile : ftpFiles) {
        String filename = path + "/" + ftpFile.getName();
        if (ftpFile.getType() == FTPFile.FILE_TYPE) {
            boolean deleted = ftpClient.deleteFile(filename);
            logger.debug("Deleted {}? {}", filename, deleted);
        } else {
            recursiveDeleteDirectory(ftpClient, filename);
        }
    }

    boolean dirDeleted = ftpClient.deleteFile(path);
    logger.debug("Directory {} deleted: {}", path, dirDeleted);
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public boolean deleteResource(Object abstractConnection, String remoteResourcePath) throws Exception {
    long startTime = new Date().getTime();
    FTPClient FTPconnection = (FTPClient) abstractConnection;
    if (!FTPconnection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }/*ww  w  . j  a  v a 2 s  . c  o m*/

    Boolean result = true;
    List<Object> FTPconnectionObject = _checkResourcePath(FTPconnection, remoteResourcePath, "delete-resource",
            checkIsDirectory(remoteResourcePath));

    try {
        if ((Boolean) FTPconnectionObject.get(0)) {
            FTPconnection.removeDirectory(remoteResourcePath);
            log.info("The FTP sub-module deleted the directory in " + (new Date().getTime() - startTime)
                    + " ms.");
        } else {
            FTPconnection.deleteFile(remoteResourcePath);
            log.info("The FTP sub-module deleted the file in " + (new Date().getTime() - startTime) + " ms.");
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        result = false;
    }

    // if (!FTPconnection.completePendingCommand()) {
    // throw new Exception("err:FTC007: The current operation failed.");
    // }

    log.info("The FTP sub-module deleted the resource '" + remoteResourcePath + "' in "
            + (new Date().getTime() - startTime) + " ms.");

    return result;
}

From source file:s32a.CodebaseDeployer.java

/**
 * Uploads given files to ftp server./*w ww .  j  av a 2 s .c o m*/
 *
 * @param input key: desired name on server, Value: file to upload.
 */
private void uploadFiles(Map<String, File> input) {

    FTPClient client = null;
    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.userName, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        //            client.setFileType(FTP.ASCII_FILE_TYPE);

        //Creates all directories required on the server
        System.out.println("creating directories");
        client.makeDirectory("Airhockey");
        client.makeDirectory("Airhockey/Codebase");
        client.makeDirectory("Airhockey/Servers");
        client.makeDirectory("Airhockey/Codebase/s32a");
        System.out.println("default directories made");
        for (String s : directories) {
            client.makeDirectory(s);
        }

        //Uploads codebase URL
        fis = new FileInputStream(this.codebaseFile);
        boolean stored = client.storeFile("Airhockey/Codebase/codebase.properties", fis);
        //            client.completePendingCommand();
        System.out.println("Stored codebase file: " + stored);
        fis.close();

        // Removes references to all servers
        for (FTPFile f : client.listFiles("Airhockey/Servers")) {
            if (f.isFile()) {
                System.out.println("Deleting Server Listing: " + f.getName());
                client.deleteFile("/Airhockey/Servers/" + f.getName());
            }
        }

        // Uploads all class files
        System.out.println("Uploading classes");
        String defaultLoc = fs + "Airhockey" + fs + "Codebase" + fs;
        for (String dest : input.keySet()) {
            fis = new FileInputStream(input.get(dest));
            if (!client.storeFile(defaultLoc + dest, fis)) {
                System.out.println("unable to save: " + defaultLoc + dest);
            }
            fis.close();
            //                client.completePendingCommand();
        }

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:s32a.Server.Startup.FTPHandler.java

/**
 * Unregisters the server// w  ww  . j a v a  2  s  . c o  m
 * @param serverInfo The serverinfo of the server
 */
void unRegisterServer(ServerInfo serverInfo) {
    FTPClient client = null;

    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        if (!client.login(username, password)) {
            return;
        }

        boolean success = client.deleteFile(this.ftpRefLocation);
        System.out.println("dropped remote reference to file: " + success);
        client.logout();

    } catch (IOException ex) {
        showDialog("Error", "FTP: unRegisterServer IOException: " + ex.getMessage());
        //            System.out.println("IOException: " + ex.getMessage());
        //            ex.printStackTrace();
    } catch (Exception ex) {
        showDialog("Error", "FTP: CheckLogin Exception: " + ex.getMessage());
        //System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
}