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

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

Introduction

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

Prototype

public boolean logout() throws IOException 

Source Link

Document

Logout of the FTP server by sending the QUIT command.

Usage

From source file:ftp.search.Index.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {//  w  w  w.  j ava  2s .  c o m
        // TODO add your handling code here:
        Class.forName("com.mysql.jdbc.Driver");
        String uid = "root";
        String pwd = "clever";
        String dbURL = "jdbc:mysql://localhost:3306/ftp";
        Connection conn = DriverManager.getConnection(dbURL, uid, pwd);
        Statement statement = conn.createStatement();
        FTPClient ftpClient = new FTPClient();
        String ftp = jTextField1.getText();
        int port = 21;
        try {
            ftpClient.connect(ftp, port);
            int a = ftpClient.getConnectTimeout();
            ftpClient.login("anonymous", "");
            // lists files and directories in the current working directory
            insertFiles(ftp, "/", statement, ftpClient);

            JOptionPane.showMessageDialog(this, "Files Indexed Successfully");
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException ex) {
            Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.zxy.commons.net.ftp.FtpUtils.java

/**
 * FTP handle//from w  w  w.  j a  v  a2 s .  co  m
 * 
 * @param <T> return object type
 * @param ftpConfig ftp config
 * @param callback ftp callback
 * @return value
*/
public static <T> T ftpHandle(FtpConfig ftpConfig, FtpCallback<T> callback) {
    FTPClient client = null;
    if (ftpConfig.isFtps() && ftpConfig.getSslContext() != null) {
        client = new FTPSClient(ftpConfig.getSslContext());
    } else if (ftpConfig.isFtps()) {
        client = new FTPSClient();
    } else {
        client = new FTPClient();
    }

    client.configure(ftpConfig.getFtpClientConfig());
    try {
        //            client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        client.connect(ftpConfig.getHost(), ftpConfig.getPort());
        client.setConnectTimeout(ftpConfig.getConnectTimeoutMs());
        client.setControlKeepAliveTimeout(ftpConfig.getKeepAliveTimeoutSeconds());
        if (!Strings.isNullOrEmpty(ftpConfig.getUsername())) {
            client.login(ftpConfig.getUsername(), ftpConfig.getPassword());
        }
        LOGGER.trace("Connected to {}, reply: {}", ftpConfig.getHost(), client.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            throw new NetException("FTP server refused connection.");
        }
        return callback.process(client);
    } catch (Exception e) {
        throw new NetException(e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
            try {
                client.disconnect();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
        }
    }
}

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

@Nullable
private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite,
        @NonNls final String directory, final ProgressIndicator indicator) {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(30 * 1000);//from www  . j a  va2  s  .  c o  m
    try {
        indicator.setText("Connecting to server...");
        ftp.connect(ftpSite);
        indicator.setText("Connected to server");

        if (!ftp.login("anonymous", "anonymous@jetbrains.com")) {
            return "Failed to login";
        }
        indicator.setText("Logged in");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "FTP server refused connection: " + reply;
        }
        if (!ftp.changeWorkingDirectory(directory)) {
            return "Failed to change directory";
        }

        // else won't work behind FW
        ftp.enterLocalPassiveMode();

        if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) {
            return "Failed to switch to binary mode";
        }

        indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")");
        FileInputStream readStream = new FileInputStream(reportPath);
        try {
            if (!ftp.storeFile(reportPath.getName(), readStream)) {
                return "Failed to upload file";
            }
        } catch (IOException e) {
            return "Error during transfer: " + e.getMessage();
        } finally {
            readStream.close();
        }
        ftp.logout();
        return null;
    } catch (IOException e) {
        return "Failed to upload: " + e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getFileInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {/*  w w  w . j a va 2  s  . co  m*/
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //ftpClient.enterLocalPassiveMode();
        // crear directorio
        //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta));
        //System.out.println("File #1 has been downloaded successfully. 1");
        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12");
        //InputStream is = fis;
        System.out.println("File ruta=" + "1/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

        if (is == null)
            System.out.println("File #1 es null");
        else
            System.out.println("File #1 no es null");

        //return ftpClient.retrieveFileStream(remote_file_ruta);
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * ?FTP?.//from   ww w.j av a 2 s  .c  o m
 * 
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public boolean ftpUploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("UTF-8");
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(path);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        // 
        ftp.storeFile(filename, input);
        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

From source file:dk.netarkivet.common.distribute.IntegrityTestsFTP.java

public void testWrongChecksumThrowsError() throws Exception {
    Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.FTPRemoteFile");
    RemoteFile rf = RemoteFileFactory.getInstance(testFile2, true, false, true);
    // upload error to ftp server
    File temp = File.createTempFile("foo", "bar");
    FTPClient client = new FTPClient();
    client.connect(Settings.get(CommonSettings.FTP_SERVER_NAME),
            Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT)));
    client.login(Settings.get(CommonSettings.FTP_USER_NAME), Settings.get(CommonSettings.FTP_USER_PASSWORD));
    Field field = FTPRemoteFile.class.getDeclaredField("ftpFileName");
    field.setAccessible(true);/*from  ww w .  j  a v a 2 s. c o  m*/
    String filename = (String) field.get(rf);
    client.storeFile(filename, new ByteArrayInputStream("foo".getBytes()));
    client.logout();
    try {
        rf.copyTo(temp);
        fail("Should throw exception on wrong checksum");
    } catch (IOFailure e) {
        // expected
    }
    assertFalse("Destination file should not exist", temp.exists());
}

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 {/*from w w w  .  j  a v a  2  s .c o m*/
        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:com.microsoft.azuretools.utils.WebAppUtils.java

public static void deployArtifact(String artifactName, String artifactPath, PublishingProfile pp,
        boolean toRoot, IProgressIndicator indicator) throws IOException {
    FTPClient ftp = null;
    InputStream input = null;//from w  w  w  . j  a  v a 2 s .  com
    try {
        if (indicator != null)
            indicator.setText("Connecting to FTP server...");

        ftp = getFtpConnection(pp);

        if (indicator != null)
            indicator.setText("Uploading the application...");
        input = new FileInputStream(artifactPath);
        if (toRoot) {
            WebAppUtils.removeFtpDirectory(ftp, ftpWebAppsPath + "ROOT", indicator);
            ftp.deleteFile(ftpWebAppsPath + "ROOT.war");
            ftp.storeFile(ftpWebAppsPath + "ROOT.war", input);
        } else {
            WebAppUtils.removeFtpDirectory(ftp, ftpWebAppsPath + artifactName, indicator);
            ftp.deleteFile(artifactName + ".war");
            boolean success = ftp.storeFile(ftpWebAppsPath + artifactName + ".war", input);
            if (!success) {
                int rc = ftp.getReplyCode();
                throw new IOException("FTP client can't store the artifact, reply code: " + rc);
            }
        }
        if (indicator != null)
            indicator.setText("Logging out of FTP server...");
        ftp.logout();
    } finally {
        if (input != null)
            input.close();
        if (ftp != null && ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}

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 w w  w. j  a  va2s . 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.webarch.common.net.ftp.FtpService.java

/**
 * /*ww  w  .ja  v  a  2s .  c o m*/
 *
 * @param remotePath ftp
 * @param fileName   ???
 * @param localPath  ???
 * @return true/false ?
 */
public boolean downloadFile(String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(remotePath);
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile file : files) {
            if (file.getName().equals(fileName)) {
                File localFile = new File(localPath + File.separator + file.getName());
                OutputStream outputStream = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), outputStream);
                outputStream.close();
            }
        }
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}