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

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

Introduction

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

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Closes the connection to the FTP server and restores connection parameters to the default values.

Usage

From source file:net.audumla.climate.bom.BOMDataLoader.java

private synchronized FTPClient getFTPClient(String host) {
    FTPClient ftp = ftpClients.get(host);
    if (ftp == null || !ftp.isAvailable() || !ftp.isConnected()) {
        ftp = new FTPClient();
        FTPClientConfig config = new FTPClientConfig();
        ftp.configure(config);/*ww  w  .  j av  a2s  .c o m*/
        try {
            ftp.setControlKeepAliveTimeout(30);
            ftp.setControlKeepAliveReplyTimeout(5);
            ftp.setDataTimeout(3000);
            ftp.setDefaultTimeout(1000);
            int reply;
            ftp.connect(host);
            LOG.debug("Connected to " + host);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                LOG.error("FTP server '" + host + "' refused connection.");
            } else {
                if (!ftp.login("anonymous", "guest")) {
                    LOG.error("Unable to login to server " + host);
                }
                ftp.setSoTimeout(60000);
                ftp.enterLocalPassiveMode();
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            }
        } catch (IOException e) {
            LOG.error("Unable to connect to " + host, e);
        }
        ftpClients.put(host, ftp);
    }
    if (!ftp.isConnected() || !ftp.isAvailable()) {
        throw new UnsupportedOperationException("Cannot connect to " + host);
    }
    return ftp;
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from   w  w w.  j  a  v a2 s.  c  o m*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {//w w w . j ava2 s .co  m
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java

/**
 * This method uploads the folder containing information related to a batch on a ftp server.
 * //  ww w  .ja  v a 2  s .  co  m
 * @param batchInstance {@link BatchInstance}
 * @param batchSchemaService {@link BatchSchemaService}
 * @param batchClass {@link BatchClass}
 * @param response {@link HttpServletResponse}
 * 
 * @return {@link String} the path where file is uploaded
 */
private String uploadToFTPPath(final BatchInstance batchInstance, final BatchSchemaService batchSchemaService,
        final BatchClass batchClass, final HttpServletResponse response) {
    File zipFolder = null;
    String ftpFolderPath = null;
    String batchInstanceIdentifier = null;
    if (null != batchInstance) {
        batchInstanceIdentifier = batchInstance.getIdentifier();
    }
    File tempFolder = new File(createDownloadFolderPathName(batchInstanceIdentifier, baseFolderPath));
    tempFolder.mkdirs();
    if (tempFolder.exists()) {
        FileOutputStream fout = null;
        ZipOutputStream zout = null;
        try {
            PrintWriter writer = response.getWriter();
            response.setContentType(IUtilCommonConstants.CONTENT_TYPE_HTML);
            String zipFileName = createZipFileName(batchInstanceIdentifier);
            String zipFolderPath = EphesoftStringUtil.concatenate(baseFolderPath, File.separator, TROUBLESHOOT,
                    File.separator, zipFileName);

            String zipFilePath = EphesoftStringUtil.concatenate(zipFolderPath, File.separator, zipFileName,
                    ZIP_EXT);
            zipFolder = new File(zipFolderPath);
            zipFolder.mkdirs();
            fout = new FileOutputStream(zipFilePath);
            zout = new ZipOutputStream(fout);
            Properties properties = getFTPProperties();
            if (null != properties) {
                ftpFolderPath = EphesoftStringUtil.concatenate(TROUBLESHOOT, File.separator, zipFileName,
                        ZIP_EXT);
                FTPInformation ftpInformation = new FTPInformation(ftpServerURL, username, password,
                        properties.getProperty(UPLOAD_BASE_DIR),
                        Integer.parseInt(properties.getProperty(NUM_OF_RETRIES)),
                        properties.getProperty(DATA_TIMEOUT), zipFolderPath, TROUBLESHOOT, 2);
                try {
                    FTPClient client = new FTPClient();
                    FTPUtil.createConnection(client, ftpServerURL, username, password,
                            properties.getProperty(DATA_TIMEOUT));
                    client.disconnect();
                    copySelectedFolders(batchInstance, batchSchemaService, batchClass, tempFolder.getPath(),
                            tempFolder);
                    if (null != tempFolder.list()) {
                        FileUtils.zipDirectoryWithFullName(tempFolder.getPath(), zout);
                        FTPUtil.uploadDirectory(ftpInformation, false);
                    }
                    writer.write(copyTroubleshootingArtifacts.getFoldersNotCopied());
                } catch (SocketException socketException) {
                    LOGGER.error("Could not connect to the FTP client. Socket Exception",
                            socketException.getMessage());
                    ftpFolderPath = null;

                    // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results.
                } catch (final IOException ioException) {
                    LOGGER.error(" Invalid Credentials. Could not connect to the FTP client.",
                            ioException.getMessage());
                    ftpFolderPath = null;
                    writer.write("INVALID_CREDENTIALS");
                    response.setStatus(HttpServletResponse.SC_OK);
                    // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results.
                }
            }
        } catch (FTPDataUploadException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error occured in uploading the file to path ",
                    ftpFolderPath));
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error occured in getting writer from response.",
                    e.getMessage()));
        } catch (NumberFormatException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Exception occured in parsing number of retries.",
                    e.getMessage()));
        } finally {
            try {
                closeResources(null, zout, fout, null);
                if (tempFolder != null) {
                    FileUtils.deleteDirectoryAndContentsRecursive(tempFolder);
                }
                if (zipFolder != null) {
                    FileUtils.deleteDirectoryAndContentsRecursive(zipFolder);
                }
            } catch (IOException e) {
                LOGGER.error(EphesoftStringUtil.concatenate("Exception occured while closing outputstream.",
                        e.getMessage()));
            }
        }
    } else {
        LOGGER.error("Could not create the folder for copying the required folders.");
    }
    return ftpFolderPath;
}

From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

/**
 * ftp?/*from  w w w .j a va2s  . c  o m*/
 *
 * @param ftpClient
 * @return ?true?false
 * @throws Exception
 */
private boolean connect(FTPClient ftpClient) throws Exception {
    try {
        ftpClient.connect(host, port);

        // ?????
        int reply = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(reply)) {
            //ftp?
            if (ftpClient.login(username, password)) {
                setFileType(ftpClient);
                return true;
            }
        } else {
            ftpClient.disconnect();
            throw new Exception("FTP server refused connection.");
        }
    } catch (IOException e) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect(); //
            } catch (IOException e1) {
                throw new Exception("Could not disconnect from server.", e1);
            }

        }
        throw new Exception("Could not connect to server.", e);
    }
    return false;
}

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

/**
 * Test an archive connection by logging onto the given URL and retrieving a directory listing.
 * //from  w  w  w.java2s  . com
 * @param uri
 * @return boolean
 */
public boolean testConnection(final URI uri) {
    if (!uri.getScheme().equalsIgnoreCase("ftp") && !uri.getScheme().equalsIgnoreCase("ftps")) {
        logger.error("Archive URL " + uri + " using protocol '" + uri.getScheme() + "' is not supported");

        return false;
    }

    FTPClient ftpClient = retrieveFtpClient(uri);

    if (ftpClient != null) {
        try {
            logger.info("Retrieving testing content for archive with URI " + uri);

            // Retrieve a file listing

            ftpClient.listFiles(uri.getPath());

            // Disconnect the client

            ftpClient.disconnect();
        } catch (IOException e) {
            logger.error("Could not perform all FTP operations during archive testing", e);

            return false;
        }

        return true;
    } else
        return false;
}

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public List<String> getFilesExists(List<String> fileNames) {
    List<String> ret = new ArrayList<String>();
    try {/*from www  .  j  ava  2  s .co  m*/
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn;
        ftpClient.enterLocalPassiveMode();
        for (String nombre : fileNames) {
            buffIn = new BufferedInputStream(ftpClient
                    .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 150) {
                System.out.println("Archivo obtenido exitosamente");
                buffIn.close();
                ret.add(nombre);
            } else {
                System.out.println(
                        "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode());
            }
        }

        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}

From source file:com.mendhak.gpslogger.senders.ftp.Ftp.java

public static boolean Upload(String server, String username, String password, int port, boolean useFtps,
        String protocol, boolean implicit, InputStream inputStream, String fileName) {
    FTPClient client = null;

    try {//ww w . j ava 2 s  . com
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

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

    try {
        Utilities.LogDebug("Connecting to FTP");
        client.connect(server, port);

        Utilities.LogDebug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();

            Utilities.LogDebug("Uploading file to FTP server");

            FTPFile[] existingDirectory = client.listFiles("GPSLogger");

            if (existingDirectory.length <= 0) {
                client.makeDirectory("GPSLogger");
            }

            client.changeWorkingDirectory("GPSLogger");
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            if (result) {
                Utilities.LogDebug("Successfully FTPd file");
            } else {
                Utilities.LogDebug("Failed to FTP file");
            }

        } else {
            Utilities.LogDebug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        Utilities.LogError("Could not connect or upload to FTP server.", e);
    } finally {
        try {
            Utilities.LogDebug("Logging out of FTP server");
            client.logout();

            Utilities.LogDebug("Disconnecting from FTP server");
            client.disconnect();
        } catch (Exception e) {
            Utilities.LogError("Could not logout or disconnect", e);
        }
    }

    return true;
}

From source file:br.com.tiagods.util.FTPDownload.java

public boolean downloadFile(String arquivo) {
    FTPConfig cf = FTPConfig.getInstance();
    FTPClient ftp = new FTPClient();
    try {/*  w ww.  j a v  a  2s .  c  o  m*/
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        String remoteFile1 = cf.getValue("dirFTP") + "/" + arquivo;
        novoArquivo = new File(System.getProperty("java.io.tmpdir") + "/" + arquivo);
        try (OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(novoArquivo))) {
            boolean success = ftp.retrieveFile(remoteFile1, outputStream1);
            if (success) {
                return true;
            }
        }
        return false;
    } catch (IOException e) {
        System.out.println("Erro = " + e.getMessage());
        return false;
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:net.audumla.climate.bom.BOMDataLoader.java

private boolean storeFTPFile(String host, String location, OutputStream os) {
    FTPClient ftp = getFTPClient(host);
    try {//  w ww. j  a  v a  2s. com
        if (getFTPFile(host, location) != null) {
            synchronized (ftp) {
                IOUtils.copy(ftp.retrieveFileStream(location), os);
            }
        } else {
            return false;
        }
    } catch (IOException ex) {
        LOG.warn("Unable to load file " + location + " FTP Reply -> " + ftp.getReplyCode(), ex);
        return false;
    } finally {
        try {
            os.close();
        } catch (Exception ex) {
            LOG.error("Unknown error encountered storing file " + location, ex);
        }
    }
    LOG.info("Retrieved remote FTP content - " + "ftp://" + host + location);
    try {
        if (!ftp.completePendingCommand()) {
            ftp.logout();
            ftp.disconnect();
        }
    } catch (Exception ex) {
        LOG.error("Unknown error encountered storing file " + location, ex);
    }
    return true;
}