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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:ch.sdi.core.impl.ftp.FtpExecutor.java

/**
 * @throws SdiException/*from   ww w . j av a2  s  .co m*/
 * @throws IOException
 */
public void connectAndLogin() throws SdiException, IOException {
    if (!myInitialized) {
        initBySpringContext();
    } // if !initialized

    try {
        if (myProtocol == null) {
            if (myProxyHost != null) {
                myLog.debug("Using HTTP proxy server: " + myProxyHost);
                myFtp = new FTPHTTPClient(myProxyHost, myProxyPort, myProxyUser, myProxyPassword);
            } else {
                myLog.debug("Using simple FTPClient");
                myFtp = new FTPClient();
            }
        } else {
            FTPSClient ftps;
            if (myProtocol.equals("true")) {
                myLog.debug("Using FTPSClient with implicite SSL");
                ftps = new FTPSClient(true);
            } else if (myProtocol.equals("false")) {
                myLog.debug("Using FTPSClient with no implicite SSL");
                ftps = new FTPSClient(false);
            } else {
                String prot[] = myProtocol.split(",");
                if (prot.length == 1) { // Just protocol
                    myLog.debug("Using FTPSClient with protocol " + myProtocol);
                    ftps = new FTPSClient(myProtocol);
                } else { // protocol,true|false
                    myLog.debug("Using FTPSClient with " + prot[0] + " and " + prot[1]);
                    ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
                }
            }
            myFtp = ftps;
            if ("all".equals(myTrustmgr)) {
                myLog.debug("Using AcceptAllTrustManager");
                ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
            } else if ("valid".equals(myTrustmgr)) {
                myLog.debug("Using ValidateServerCertificateTrustManager");
                ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
            } else if ("none".equals(myTrustmgr)) {
                myLog.debug("Setting TrustManager to null");
                ftps.setTrustManager(null);
            } else {
                myLog.debug("Using no TrustManager at all");
            }
        }

        if (myKeepAliveTimeout >= 0) {
            myLog.debug("Setting KeepAliveTimeout to " + myKeepAliveTimeout);
            myFtp.setControlKeepAliveTimeout(myKeepAliveTimeout);
        }
        if (myControlKeepAliveReplyTimeout >= 0) {
            myLog.debug("Setting ControlKeepAliveReplyTimeout to " + myControlKeepAliveReplyTimeout);
            myFtp.setControlKeepAliveReplyTimeout(myControlKeepAliveReplyTimeout);
        }

        // intercept commands and write it to our logger
        myPrintCommandToLoggerListener = new PrintCommandToLoggerListener(myLog);
        PrintWriter writer = myPrintCommandToLoggerListener.getPrintWriter();
        myFtp.addProtocolCommandListener(new PrintCommandListener(writer, true, '\n', true));
        //            myFtp.addProtocolCommandListener( new PrintCommandListener( new PrintWriter( System.out ), true ) );

        try {
            int reply;
            if (myPort > 0) {
                myLog.debug("Connecting to " + myServer + ":" + myPort);
                myFtp.connect(myServer, myPort);
            } else {
                myLog.debug("Connecting to " + myServer + " (default port)");
                myFtp.connect(myServer);
            }

            myLog.debug("Connected to " + myServer + " on " + (myPort > 0 ? myPort : myFtp.getDefaultPort()));

            // After connection attempt, you should check the reply code to verify success.
            reply = myFtp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                myFtp.disconnect();
                throw createFtpException("FTP server refused connection.");
            }
        } catch (IOException e) {
            throw createFtpException("Could not connect to server.", e);
        }

        if (!myFtp.login(myUsername, myPassword)) {
            myFtp.logout();
            throw createFtpException("Problems on login");
        }

        myLog.debug("Remote system is " + myFtp.getSystemType());
        myFtp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are behind firewalls these days.
        if (myLocalActive) {
            myFtp.enterLocalActiveMode();
        } else {
            myFtp.enterLocalPassiveMode();
        }

        myFtp.setUseEPSVwithIPv4(myUseEpsvWithIPv4);
    } finally {
        myPrintCommandToLoggerListener.flushRest();
    }
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public void getFile(String remoteFile, File localFile) throws Exception {

    FTPClient ftpClient = new FTPClient();
    OutputStream outputStream = null;
    try {//from   w w w. ja  va  2s.c o  m
        ftpClient.connect(ftpHost, ftpPort);
        ftpClient.enterLocalPassiveMode();
        if (ftpUser != null && ftpUser.length() > 0)
            ftpClient.login(ftpUser, ftpPassword);
        else
            ftpClient.login("anonymous", "");
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        boolean commandOK = ftpClient.completePendingCommand();
        //boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        //if (!success) {
        //   throw new Exception("Error retrieving remote file: " + remoteFile);
        //}   
    } finally {
        outputStream.close();
        ftpClient.disconnect();
    }
}

From source file:ch.sdi.core.impl.ftp.FTPClientExample.java

/**
*
*//* w  w w.j a  v  a 2 s. com*/
private void run() throws Throwable {
    if (myProtocol == null) {
        if (myProxyHost != null) {
            myLog.debug("Using HTTP proxy server: " + myProxyHost);
            myFtp = new FTPHTTPClient(myProxyHost, myProxyPort, myProxyUser, myProxyPassword);
        } else {
            myFtp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (myProtocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (myProtocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = myProtocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(myProtocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        myFtp = ftps;
        if ("all".equals(myTrustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(myTrustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(myTrustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (myPrintHash) {
        myFtp.setCopyStreamListener(createListener());
    }
    if (myKeepAliveTimeout >= 0) {
        myFtp.setControlKeepAliveTimeout(myKeepAliveTimeout);
    }
    if (myControlKeepAliveReplyTimeout >= 0) {
        myFtp.setControlKeepAliveReplyTimeout(myControlKeepAliveReplyTimeout);
    }
    myFtp.setListHiddenFiles(myHidden);

    // intercept commands and write it to our logger
    myPrintCommandToLoggerListener = new PrintCommandToLoggerListener(myLog);
    PrintWriter writer = myPrintCommandToLoggerListener.getPrintWriter();
    myFtp.addProtocolCommandListener(new PrintCommandListener(writer, true, '\n', true));
    //        myFtp.addProtocolCommandListener( new PrintCommandListener( new PrintWriter( System.out ), true ) );

    try {
        int reply;
        if (myPort > 0) {
            myFtp.connect(myServer, myPort);
        } else {
            myFtp.connect(myServer);
        }

        myLog.debug("Connected to " + myServer + " on " + (myPort > 0 ? myPort : myFtp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = myFtp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            myFtp.disconnect();
            throw new Exception("FTP server refused connection.");
        }
    } catch (IOException e) {
        if (myFtp.isConnected()) {
            try {
                myFtp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        throw new Exception("Could not connect to server.", e);
    }

    try {
        if (!myFtp.login(myUsername, myPassword)) {
            myFtp.logout();
            throw createFtpException("Problems on login");
        }

        myLog.debug("Remote system is " + myFtp.getSystemType());

        if (myBinaryTransfer) {
            myFtp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            myFtp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (myLocalActive) {
            myFtp.enterLocalActiveMode();
        } else {
            myFtp.enterLocalPassiveMode();
        }

        myFtp.setUseEPSVwithIPv4(myUseEpsvWithIPv4);

        if (myStoreFile) {
            InputStream input;

            input = new FileInputStream(myLocal);

            myFtp.storeFile(myRemote, input);

            input.close();
        } else if (myListFiles) {
            if (myLenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                myFtp.configure(config);
            }

            for (FTPFile f : myFtp.listFiles(myRemote)) {
                myLog.debug(f.getRawListing());
                myLog.debug(f.toFormattedString());
            }
        } else if (myMlsd) {
            for (FTPFile f : myFtp.mlistDir(myRemote)) {
                myLog.debug(f.getRawListing());
                myLog.debug(f.toFormattedString());
            }
        } else if (myMlst) {
            FTPFile f = myFtp.mlistFile(myRemote);
            if (f != null) {
                myLog.debug(f.toFormattedString());
            }
        } else if (myListNames) {
            for (String s : myFtp.listNames(myRemote)) {
                myLog.debug(s);
            }
        } else if (myFeat) {
            // boolean feature check
            if (myRemote != null) { // See if the command is present
                if (myFtp.hasFeature(myRemote)) {
                    myLog.debug("Has feature: " + myRemote);
                } else {
                    if (FTPReply.isPositiveCompletion(myFtp.getReplyCode())) {
                        myLog.debug("FEAT " + myRemote + " was not detected");
                    } else {
                        throw createFtpException("Command failed");
                    }
                }

                // Strings feature check
                String[] features = myFtp.featureValues(myRemote);
                if (features != null) {
                    for (String f : features) {
                        myLog.debug("FEAT " + myRemote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(myFtp.getReplyCode())) {
                        myLog.warn("FEAT " + myRemote + " is not present");
                    } else {
                        throw createFtpException("Command failed");
                    }
                }
            } else {
                if (myFtp.features()) {
                    // Command listener has already printed the output
                } else {
                    throw createFtpException("Command failed");
                }
            }
        } else if (myDoCommand != null) {
            if (myFtp.doCommand(myDoCommand, myRemote)) {
                // Command listener has already printed the output
            } else {
                throw createFtpException("Command failed");
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(myLocal);

            myFtp.retrieveFile(myRemote, output);

            output.close();
        }

        myFtp.noop(); // check that control connection is working OK

        myFtp.logout();
    } catch (FTPConnectionClosedException e) {
        throw createFtpException("Server closed connection.");
    } catch (IOException e) {
        throw createFtpException("IOException caught");
    } finally {
        myPrintCommandToLoggerListener.flushRest();

        if (myFtp.isConnected()) {
            try {
                myFtp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

}

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

private FTPClient initFtpClient() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(host, port);/*ww  w.ja v  a2s.  c o  m*/
    ftpClient.login(username, password);

    // Sets Binary File Type for ZIP File.
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    // Set Buffer Size to speed up download/upload file.
    ftpClient.setBufferSize(102400);

    return ftpClient;
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

public static ArrayList<String> performDirectoryListing(String downloadURL,
        BackgroundTaskStatusProviderSupportingExternalCall status) {
    if (status == null)
        status = new BackgroundTaskConsoleLogger("downloading: " + downloadURL, "please wait", false);
    String server, remote;//from   ww  w  .j  a v a  2s . c o  m

    runIdx++;
    final int thisRun = runIdx;

    server = downloadURL.substring("ftp://".length());
    remote = server.substring(server.indexOf("/") + "/".length());
    server = server.substring(0, server.indexOf("/"));

    ArrayList<String> result = null;

    final FTPClient ftp;
    ThreadSafeOptions tso;
    synchronized (host2ftp) {
        if (!host2ftp.containsKey(server)) {
            ThreadSafeOptions ttt = new ThreadSafeOptions();
            ttt.setParam(0, new FTPClient());
            host2ftp.put(server, ttt);
        }
        tso = host2ftp.get(server);
        ftp = (FTPClient) tso.getParam(0, null);
    }
    status.setCurrentStatusValue(0);

    try {
        result = listFiles(status, downloadURL, server, remote, ftp);
        status.setCurrentStatusText2("Finished: " + downloadURL);

        BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() {
            public void run() {
                try {
                    synchronized (GUIhelper.class) {
                        if (runIdx == thisRun) {
                            System.out.println("Disconnect FTP connection");
                            ftp.disconnect();
                        }
                    }
                } catch (Exception err) {
                    ErrorMsg.addErrorMessage(err);
                }
            }
        });
    } catch (Exception e) {
        ErrorMsg.addErrorMessage(e);
    }
    return result;
}

From source file:net.sourceforge.dvb.projectx.xinput.ftp.XInputFileImpl.java

/**
 * Opens XInputFile for random access//  ww  w.ja  v  a  2 s  .c  o  m
 * 
 * @param mode
 *          Access mode as in RandomAccessFile
 * @throws IOException
 */
public void randomAccessOpen(String mode) throws IOException {

    if (isopen) {
        throw new IllegalStateException("XInputFile is already open!");
    }

    if (mode.compareTo("r") != 0) {
        throw new IllegalStateException("Illegal access mode for FileType.FTP");
    }

    boolean ret = false;

    client = new FTPClient();
    client.connect(ftpVO.getServer(), ftpVO.getPortasInteger()); //void
    if (debug)
        System.out.println("rAO connect " + client.getReplyString());

    ret = client.login(ftpVO.getUser(), ftpVO.getPassword()); //bool
    if (debug)
        System.out.println("rAO login " + ret + " / " + client.getReplyString());

    ret = client.changeWorkingDirectory(ftpVO.getDirectory()); //bool
    if (debug)
        System.out.println("rAO cwd " + ret + " / " + client.getReplyString());

    ret = client.setFileType(FTP.BINARY_FILE_TYPE); //bool
    if (debug)
        System.out.println("rAO binary " + ret + " / " + client.getReplyString());

    client.enterLocalPassiveMode(); //void
    if (debug)
        System.out.println("rAO PASV " + client.getReplyString());

    String[] commands = getUserFTPCommand();

    for (int i = 0; i < commands.length; i++) {
        if (commands[i] != null && commands[i].length() > 0) {
            client.sendCommand(commands[i]); //bool
            if (debug)
                System.out.println("rAO cmd " + client.getReplyString());
        }
    }

    isopen = true;
}

From source file:EscribirCorreo.java

private void SubirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubirActionPerformed
    //Codigo para subir archivo         
    String localfile = subir1Field.getText();
    String server = "51.254.137.26";
    String username = "proyecto";
    String password = "proyecto";
    String destinationfile = nombre;
    try {/*w w w  . j a v a  2s  .  co m*/
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        InputStream in = new FileInputStream(localfile);
        ftp.setFileType(ftp.BINARY_FILE_TYPE);
        ftp.storeFile(destinationfile, in);
        JOptionPane.showMessageDialog(null, "Archivo subido correctamente", "Subido!",
                JOptionPane.INFORMATION_MESSAGE);
        if (archivos == null) {
            archivos = "http://51.254.137.26/proyecto/" + destinationfile;
        } else {
            archivos = archivos + "#http://51.254.137.26/proyecto/" + destinationfile;
        }
        in.close();
        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Retrieve the content of a result feed URL.
 * //from   ww w .  jav  a2 s  .  c om
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @param resultHeaders
 * @return Reader
 */
private Reader getContent(final URI uri, final String encodingOverride, final String userAgent,
        final Map<String, String> resultHeaders) {
    Reader result = null;
    String contentType = null;

    // Retrieve the feed

    try {
        InputStream inputStream = null;

        if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) {
            FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

            try {
                ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

                if (StringUtils.hasText(uri.getUserInfo())) {
                    if (uri.getUserInfo().contains(":"))
                        ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                                uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
                    else
                        ftpClient.login(uri.getUserInfo(), "");

                    inputStream = ftpClient.retrieveFileStream(uri.getPath());
                }
            } finally {
                ftpClient.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("file")) {
            File file = new File(uri);

            if (!file.isDirectory())
                inputStream = new FileInputStream(uri.getPath());
            else
                inputStream = RSSDirectoryBuilder.build(file);
        } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
            try {
                HttpGet method = new HttpGet(uri.toString());

                if (resultHeaders != null)
                    for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                        method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
                if (userAgent != null)
                    method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

                SizeRestrictedHttpResponse response = httpClient.execute(method,
                        new SizeRestrictedResponseHandler(maximumContentLength, uri));

                try {
                    if (response != null) {
                        inputStream = new ByteArrayInputStream(response.getResponse());
                        contentType = response.getContentType() != null ? response.getContentType().getValue()
                                : null;
                    } else
                        return null;
                } catch (RuntimeException e) {
                    method.abort();

                    throw e;
                }
            } catch (IllegalArgumentException e) {
                logger.error("Invalid URL " + uri.toString() + " - not returning content", e);

                return null;
            }
        } else {
            logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed.");

            return null;
        }

        // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection)

        InputStream readerInputStream = new BufferedInputStream(inputStream);
        MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata());

        try {
            Reader reader = null;

            if (mediaType.getType().equals("application")) {
                if (mediaType.getSubtype().equals("x-gzip")) {
                    GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream);

                    if (encodingOverride != null)
                        reader = readerToBuffer(new StringBuffer(),
                                new InputStreamReader(gzipInputStream, encodingOverride), false);
                    else
                        reader = readerToBuffer(new StringBuffer(),
                                contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true)
                                        : new XmlReader(gzipInputStream, true),
                                false);

                    gzipInputStream.close();
                } else if (mediaType.getSubtype().equals("zip")) {
                    ZipFile zipFile = null;

                    // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead

                    File temporaryFile = File.createTempFile("profiler-", ".zip");

                    try {
                        FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile);
                        IOUtils.copy(readerInputStream, zipOutputStream);

                        readerInputStream.close();

                        zipOutputStream.flush();
                        zipOutputStream.close();

                        // Create a new entry and process it

                        zipFile = new ZipFile(temporaryFile);
                        Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries();

                        ZipEntry zipEntry = zipEnumeration.nextElement();

                        if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) {
                            logger.error(
                                    "ZIP files are currently expected to contain one and only one entry, which is to be a file");

                            return null;
                        }

                        // We currently only perform prolog stripping for ZIP files

                        InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));

                        if (encodingOverride != null)
                            reader = readerToBuffer(new StringBuffer(), new InputStreamReader(
                                    new BufferedInputStream(zipInputStream), encodingOverride), true);
                        else
                            result = readerToBuffer(new StringBuffer(),
                                    contentType != null
                                            ? new XmlHtmlReader(new BufferedInputStream(zipInputStream),
                                                    contentType, true)
                                            : new XmlReader(new BufferedInputStream(zipInputStream), true),
                                    true);
                    } catch (Exception e) {
                        logger.error("An error occurred during ZIP file processing", e);

                        return null;
                    } finally {
                        if (zipFile != null)
                            zipFile.close();

                        if (!temporaryFile.delete())
                            logger.error("Unable to delete temporary file");
                    }
                }
            }

            if (result == null) {
                if (encodingOverride != null)
                    result = readerToBuffer(new StringBuffer(), reader != null ? reader
                            : new InputStreamReader(readerInputStream, encodingOverride), false);
                else
                    result = readerToBuffer(new StringBuffer(),
                            reader != null ? reader
                                    : contentType != null
                                            ? new XmlHtmlReader(readerInputStream, contentType, true)
                                            : new XmlReader(readerInputStream, true),
                            false);
            }
        } catch (Exception e) {
            logger.error("An error occurred during stream processing", e);

            return null;
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        logger.error("Could not retrieve the given feed: " + e.getMessage(), e);

        return null;
    }

    return result;
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public boolean sendFile(String filePath, boolean delete) throws Exception {

    String fileName = filePath;//  w w  w. j  a v  a 2 s  .  c  o m
    int slash = fileName.lastIndexOf("/");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    slash = fileName.lastIndexOf("\\");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    boolean success = true;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(ftpHost, ftpPort);
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(ftpUser, ftpPassword)) {
                if (ftpFolder != null && ftpFolder.trim().length() > 0) {
                    ftp.cwd(ftpFolder);
                    System.out.print("ftp cd: " + ftp.getReplyString());
                }
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
                FileInputStream in = new FileInputStream(filePath);
                success = ftp.storeFile(fileName, in);
                in.close();
                if (delete) {
                    File file = new File(filePath);
                    file.delete();
                }
            } else
                success = false;
        }
    } finally {
        ftp.disconnect();
    }

    return success;
}

From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java

public void download(RunFileTransferEntity runFileTransferEntity) {
    log.debug("Start FTPUtil download");

    File filecheck = new File(runFileTransferEntity.getOutFilePath());
    if (!(filecheck.exists() && filecheck.isDirectory())
            && !(runFileTransferEntity.getOutFilePath().contains("hdfs://"))) {
        log.error("Invalid output file path. Please provide valid output file path.");
        throw new RuntimeException("Invalid output path");
    }/*from  w  ww.j  a  va  2s  .c  o m*/
    boolean fail_if_exist = false;
    FTPClient ftpClient = new FTPClient();
    int retryAttempt = runFileTransferEntity.getRetryAttempt();
    int attemptCount = 1;
    int i = 0;
    boolean login = false;
    boolean done = false;
    for (i = 0; i < retryAttempt; i++) {
        try {
            log.info("Connection attempt: " + (i + 1));
            if (runFileTransferEntity.getTimeOut() != 0)
                ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut());
            log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n"
                    + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno"
                    + runFileTransferEntity.getPortNo());
            ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo());

            login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword());

            if (!login) {
                log.error("Invalid FTP details provided. Please provide correct FTP details.");
                throw new FTPUtilException("Invalid FTP details");
            }
            ftpClient.enterLocalPassiveMode();
            if (runFileTransferEntity.getEncoding() != null)
                ftpClient.setControlEncoding(runFileTransferEntity.getEncoding());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (runFileTransferEntity.getOutFilePath().contains("hdfs://")) {
                log.debug("Processing for HDFS output path");
                String outputPath = runFileTransferEntity.getOutFilePath();
                String s1 = outputPath.substring(7, outputPath.length());
                String s2 = s1.substring(0, s1.indexOf("/"));
                File f = new File("/tmp");
                if (!f.exists()) {
                    f.mkdir();
                }

                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + "\\" + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                    outputStream.close();
                } else {
                    if (!(isfile.exists() && !isfile.isDirectory())) {
                        OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        throw new RuntimeException("File already exists");
                    }
                }

                Configuration conf = new Configuration();
                conf.set("fs.defaultFS", "hdfs://" + s2);
                FileSystem hdfsFileSystem = FileSystem.get(conf);

                String s = outputPath.substring(7, outputPath.length());
                String hdfspath = s.substring(s.indexOf("/"), s.length());

                Path local = new Path("/tmp/" + file_name);
                Path hdfs = new Path(hdfspath);
                hdfsFileSystem.copyFromLocalFile(local, hdfs);

            } else {
                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), (outputStream));
                    outputStream.close();
                } else {

                    if (!(isfile.exists() && !isfile.isDirectory())) {

                        OutputStream outputStream = new FileOutputStream(
                                runFileTransferEntity.getOutFilePath().replaceAll(
                                        Matcher.quoteReplacement("\\"), "/") + File.separatorChar + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        Log.error("File already exits");
                        throw new FTPUtilException("File already exists");

                    }

                }
            }
        } catch (Exception e) {
            log.error("error while transferring the file", e);
            if (!login) {
                log.error("Login ");

                throw new FTPUtilException("Invalid FTP details");
            }
            if (fail_if_exist) {
                log.error("File already exists ");
                throw new FTPUtilException("File already exists");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                Log.error("Exception occured during sleep");
            } catch (Error err) {
                log.error("fatal error", e);
                throw new FTPUtilException(err);
            }
            continue;
        }

        break;

    }

    if (i == runFileTransferEntity.getRetryAttempt()) {

        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();

            }
        } catch (Exception e) {

            Log.error("Exception while closing the ftp client", e);
        }
        if (runFileTransferEntity.getFailOnError())
            throw new FTPUtilException("File transfer failed ");

    }

    log.debug("Finished FTPUtil download");

}