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:de.l3s.dlg.ncbikraken.ftp.NcbiFTPClient.java

public static void getMedline(MedlineFileType type) {
    FileOutputStream out = null;//w  ww  . j  av  a  2 s .c om
    FTPClient ftp = new FTPClient();
    try {
        // Connection String
        LOGGER.info("Connecting to FTP server " + SERVER_NAME);
        ftp.connect(SERVER_NAME);
        ftp.login("anonymous", "");
        ftp.cwd(BASELINE_PATH);
        ftp.cwd(type.getServerPath());

        try {
            ftp.pasv();
        } catch (IOException e) {
            LOGGER.error(
                    "Can not access the passive mode. Maybe a problem with your (Windows) firewall. Just try to run as administrator: \nnetsh advfirewall set global StatefulFTP disable");
            return;
        }

        for (FTPFile file : ftp.listFiles()) {
            if (file.isFile()) {
                File meshF = new File(file.getName());
                LOGGER.debug("Downloading file: " + SERVER_NAME + ":" + BASELINE_PATH + "/"
                        + type.getServerPath() + "/" + meshF.getName());
                out = new FileOutputStream(Configuration.INSTANCE.getMedlineDir() + File.separator + meshF);
                ftp.retrieveFile(meshF.getName(), out);
                out.flush();
                out.close();
            }
        }

    } catch (IOException ioe) {
        LOGGER.error(ioe.getMessage());

    } finally {
        IOUtils.closeQuietly(out);
        try {
            ftp.disconnect();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

}

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 {//from  w  ww .  j a  v  a  2  s  . 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:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Disconnects the SSH session, if necessary.
 *
 * @param client   the client to disconnect
 *///from   www  .  ja v a2  s  .c  o  m
protected void disconnect(FTPClient client) {
    if (client != null) {
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (Exception e) {
                Utils.handleException(this, "Failed to disconnect!", e);
            }
        }
    }
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure.
 * /*w w w.j a  v  a  2  s  .  c  o  m*/
 * @param sourceDirectoryPath the directory to be uploaded
 * @param destDirName the path on ftp where directory will be uploaded
 * @param numberOfRetryCounter number of attempts to be made for uploading the directory
 * @throws FTPDataUploadException if an error occurs while uploading the file
 * @throws IOException if an error occurs while making the ftp connection
 * @throws SocketException if an error occurs while making the ftp connection
 */
public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData)
        throws FTPDataUploadException, SocketException, IOException {
    boolean isValid = true;
    if (ftpInformation.getSourceDirectoryPath() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DIR);
        throw new FTPDataUploadException(VAR_SOURCE_DIR);
    }
    if (ftpInformation.getDestDirName() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DES);
        throw new FTPDataUploadException(VAR_SOURCE_DES);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String destDirName = ftpInformation.getDestDirName();
        String destinationDirectory = ftpInformation.getUploadBaseDir();
        if (destDirName != null && !destDirName.isEmpty()) {
            String uploadBaseDir = ftpInformation.getUploadBaseDir();
            if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) {
                destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        destDirName);
            } else {
                destinationDirectory = destDirName;
            }

        }
        FileInputStream fis = null;
        try {
            createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(),
                    ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut());

            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Upload...");
            } else {
                LOGGER.info("Invalid Connection to FTP server. Disconnecting Client");
                client.disconnect();
                isValid = false;
                throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client");
            }
            if (isValid) {

                // code changed for keeping the control connection busy.
                client.setControlKeepAliveTimeout(300);
                client.setFileType(FTP.BINARY_FILE_TYPE);
                createFtpDirectoryTree(client, destinationDirectory);
                // client.makeDirectory(destinationDirectory);
                if (deleteExistingFTPData) {
                    deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData);
                }
                File file = new File(ftpInformation.getSourceDirectoryPath());
                if (file.isDirectory()) {
                    String[] fileList = file.list();
                    for (String fileName : fileList) {
                        String inputFile = EphesoftStringUtil
                                .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName);
                        File checkFile = new File(inputFile);
                        if (checkFile.isFile()) {
                            LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName));
                            fis = new FileInputStream(inputFile);
                            try {
                                client.storeFile(fileName, fis);
                            } catch (IOException e) {
                                int retryCounter = ftpInformation.getNumberOfRetryCounter();
                                LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-",
                                        (retryCounter + 1)));
                                if (retryCounter < ftpInformation.getNumberOfRetries()) {
                                    retryCounter = retryCounter + 1;
                                    uploadDirectory(ftpInformation, deleteExistingFTPData);
                                } else {
                                    LOGGER.error("Error in uploading the file to FTP server");
                                }
                            } finally {
                                try {
                                    if (fis != null) {
                                        fis.close();
                                    }
                                } catch (IOException e) {
                                    LOGGER.info(EphesoftStringUtil
                                            .concatenate("Could not close stream for file.", inputFile));
                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("File does not exist..");
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Disconnecting from FTP server....", e);
            }
        }
    }
}

From source file:ca.nrc.cadc.web.ServerToServerFTPTransfer.java

public void send(final OutputStreamWrapper outputStreamWrapper, final String filename) throws IOException {
    final FTPClient ftpClient = connect();
    ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();/*from   w w  w  .j a v a  2 s . c  o m*/

    try {
        final OutputStream outputStream = ftpClient.storeFileStream(filename);

        outputStreamWrapper.write(outputStream);

        outputStream.flush();
        outputStream.close();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
}

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

/**
 * ftp/*w  ww  .  ja v  a2  s . c o m*/
 *
 * @throws Exception
 */
public void disconnect() throws Exception {
    try {
        FTPClient ftpClient = getFTPClient();
        ftpClient.logout();
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
            ftpClient = null;
        }
    } catch (IOException e) {
        throw new Exception("Could not disconnect from server.", e);
    }
}

From source file:com.discursive.jccook.net.FTPExample.java

public void start() throws IOException {

    FTPClient client = new FTPClient();
    OutputStream outStream = null;

    try {/*from   ww  w.j a  va 2s.c o  m*/
        client.connect("ftp.ibiblio.org");
        client.login("anonymous", "");

        String remoteFile = "/pub/micro/commodore/schematics/computers/c64/c64bus.gif";
        outStream = new FileOutputStream("c64bus.gif");

        client.retrieveFile(remoteFile, outStream);
    } catch (IOException ioe) {
        System.out.println("Error communicating with FTP server.");
    } finally {
        IOUtils.closeQuietly(outStream);
        try {
            client.disconnect();
        } catch (IOException e) {
            System.out.println("Problem disconnecting from FTP server");
        }
    }

    secondExample();

}

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

public FTPFile getFTPFile(String host, String location) throws IOException {
    FTPClient ftp = getFTPClient(host);
    try {//from  www.j a  v a  2  s  . c o  m
        synchronized (ftp) {
            FTPFile[] files = ftp.listFiles(location);
            if (files.length > 0) {
                return files[0];
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        try {
            ftp.logout();
            ftp.disconnect();
        } catch (Exception ex) {
            LOG.error("Failure to close connection", ex);
        }
        throw new UnsupportedOperationException(
                "Error locating File " + host + location + " FTP Code -> " + ftp.getReplyCode(), e);
    } finally {
        /*            if (!ftp.completePendingCommand()) {
        ftp.logout();
        ftp.disconnect();
                    }
                    ftp.disconnect();
        */
    }
}

From source file:com.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {/*w ww .j a v  a2 s. c  o m*/
        // The executes in the IO thread!
        String sourceVar = getSourceVar(messageContext);
        InputStream src = null;
        boolean wantBase64Decode = getWantBase64Decode(messageContext);
        if (sourceVar == null) {
            src = messageContext.getMessage().getContentAsStream();
            // conditionally wrap a decoder around it
            if (wantBase64Decode) {
                src = new Base64InputStream(src);
            }
        } else {
            info.addMessage("Retrieving data from " + sourceVar);
            String sourceData = messageContext.getVariable(sourceVar);
            byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData)
                    : sourceData.getBytes(StandardCharsets.UTF_8);
            src = new ByteArrayInputStream(b);
        }
        String remoteName = getRemoteFileName(messageContext);
        remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-");

        String ftpServer = getFtpServer(messageContext);
        int ftpPort = getFtpPort(messageContext);
        String user = getFtpUser(messageContext);
        String password = getFtpPassword(messageContext);

        info.addMessage("connecting to server " + ftpServer);
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new FtpCommandListener(info));
        ftp.connect(ftpServer, ftpPort);
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("The FTP server refused the connection.");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }

        if (!ftp.login(user, password)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("Login failure");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }
        info.addMessage("logged in as " + user);

        String initialDirectory = getInitialDirectory(messageContext);
        if ((initialDirectory != null) && (!initialDirectory.equals(""))) {
            ftp.changeWorkingDirectory(initialDirectory);
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        OutputStream os = ftp.storeFileStream(remoteName);
        if (os == null) {
            // cannot open output stream
            info.addMessage("cannot open output stream to " + remoteName);
            info.setStatus("FAIL");
        } else {
            byte[] buf = new byte[2048];
            int n;
            while ((n = src.read(buf)) > 0) {
                os.write(buf, 0, n);
            }
            os.close();
            src.close();
            boolean completed = ftp.completePendingCommand();
            info.addMessage("transfer completed: " + completed);
            info.setStatus("OK");
        }

        ftp.disconnect();
        info.addMessage("All done.");
        messageContext.setVariable(varName("result"), info.toJsonString());
    } catch (java.lang.Exception exc1) {
        if (getDebug()) {
            System.out.println(ExceptionUtils.getStackTrace(exc1));
        }
        String error = exc1.toString();
        messageContext.setVariable(varName("exception"), error);
        info.setStatus("FAIL");
        info.addMessage(error);
        messageContext.setVariable(varName("result"), info.toJsonString());
        int ch = error.lastIndexOf(':');
        if (ch >= 0) {
            messageContext.setVariable(varName("error"), error.substring(ch + 2).trim());
        } else {
            messageContext.setVariable(varName("error"), error);
        }
        messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1));
        return ExecutionResult.ABORT;
    }

    return ExecutionResult.SUCCESS;
}

From source file:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java

/**
 * Retrieve a file to a temporary path. This temporary path will be returned. Valid protocol
 * types: ftp, http, package or local file If a file has already be downloaded (the file is
 * existing in tmp directory) it will not be redownloaded again. Simply the path to this file
 * will be returned./*from  w w w .  ja  v a2 s .c  o m*/
 * 
 * @param url
 *            URL to retrieve
 * @param checkAlreadyRetrieved
 *            if false, always download the file and ignore, if it is already existing
 * @return NULL on error. On success the path to the file is returned.
 */
public static File retrieve(String url, boolean checkAlreadyRetrieved) {
    if (url.indexOf("://") <= 0) {
        // Is local file
        return new File(url);
    }
    int start = url.indexOf('/') + 2;
    int end = url.indexOf('/', start);
    String serverName = url.substring(start, end);
    if (url.startsWith("package://")) {
        String filePath = url.substring(end + 1);
        String pkgPath = findPackage(serverName);
        if (pkgPath == null)
            return null;
        return new File(pkgPath, filePath);
    } else if (url.startsWith("http://")) {

        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            return tmpPath;
        }

        try {
            // Get the URL
            URL urlClass = new URL(url);
            // Open an output stream to the destination file on our local filesystem
            out = new BufferedOutputStream(new FileOutputStream(tmpPath));
            conn = urlClass.openConnection();
            in = conn.getInputStream();

            // Get the data
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
            // Done! Just clean up and get out
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                // Ignore if stream not possible to close
            }
        }
        return tmpPath;
    } else if (url.startsWith("ftp://")) {
        FTPClient client = new FTPClient();
        OutputStream outStream = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            System.out.println("Already retrieved: " + url + " to " + tmpPath.getAbsolutePath());
            return tmpPath;
        }

        try {
            // Connect to the FTP server as anonymous
            client.connect(serverName);
            client.login("anonymous", "knowrob@example.com");
            String remoteFile = url.substring(end);
            // Write the contents of the remote file to a FileOutputStream
            outStream = new FileOutputStream(tmpPath);
            client.retrieveFile(remoteFile, outStream);

        } catch (IOException ioe) {
            System.out.println("ResourceRetriever: Error communicating with FTP server: " + serverName + "\n"
                    + ioe.getMessage());
        } finally {
            try {
                outStream.close();
            } catch (IOException e1) {
                // Ignore if stream not possible to close
            }
            try {
                client.disconnect();
            } catch (IOException e) {
                System.out.println("ResourceRetriever: Problem disconnecting from FTP server: " + serverName
                        + "\n" + e.getMessage());
            }
        }
        return tmpPath;
    }
    return null;
}