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:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return//www  .  jav  a  2  s .co  m
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

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

public boolean downloadFile(String arquivo) {
    FTPConfig cf = FTPConfig.getInstance();
    FTPClient ftp = new FTPClient();
    try {/*  ww  w  . j av  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 {/*from   w  w w .  jav a2  s. c  om*/
        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;
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {/*from ww w .  j  av  a  2 s. c o m*/
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:facturacion.ftp.FtpServer.java

public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//w  ww.j  a v a2 s .c  om
        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.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1 = " + success);
        success = ftpClient.makeDirectory(hostDirServer + "/img");
        System.out.println("sucess 233 = " + success);
        success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn);
        System.out.println("sucess 3 = " + success);
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:model.ProfilModel.java

public void uploadFoto(String path) {
    String server = "localhost";
    int port = 21;
    String user = "user1";
    String pass = "itsme";

    FTPClient ftpClient = new FTPClient();
    try {/*from   ww w. j  a v  a2s .c  o  m*/

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File(path);

        String firstRemoteFile = this.user.getFoto();
        InputStream inputStream = new FileInputStream(firstLocalFile);

        System.out.println("Start uploading first file");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("The first file is uploaded successfully.");
        }
        inputStream.close();

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

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

public boolean uploadFile(File arquivo, String novoNome) {
    FTPConfig cf = FTPConfig.getInstance();

    FTPClient ftp = new FTPClient();
    try {//from   ww w . j  a va 2 s. c o m
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        //ftp.connect(server,port);
        //ftp.login(user,pass);
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        boolean done;
        try (InputStream stream = new FileInputStream(arquivo)) {
            String remoteFile = novoNome;
            System.out.println("Start uploading first file");
            done = ftp.storeFile(cf.getValue("dirFTP") + "/" + remoteFile, stream);
            stream.close();
        }
        if (done) {
            JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            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:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public void send(File[] archivos) {
    try {//from w w  w  .  ja va  2 s. c  o  m
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn = null;
        for (File actual : archivos) {
            //                String fileName = "PROCESOS_PARA_EL_IVA_VENTAS_UNICOMER.xlsx";
            buffIn = new BufferedInputStream(new FileInputStream(actual.getAbsolutePath()));//Ruta del archivo para enviar
            ftpClient.enterLocalPassiveMode();
            ftpClient.storeFile(params.get("remoteStoreFiles") + REMOTE_SEPARATOR + actual.getName(), buffIn);//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 226) {
                System.out.println("Archivo guardado exitosamente");
            } else {
                System.out.println("No se pudo guardar el archivo: " + actual.getName() + ", codigo:"
                        + ftpClient.getReplyCode());
            }
        }

        buffIn.close(); //Cerrar envio de archivos al FTP
        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
}

From source file:ftp_server.FileUpload.java

public void uploading() {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;//from ww  w  . j  a v  a2s .c om
    try {
        client.connect("shamalmahesh.net78.net");
        client.login("a9959679", "9P3IckDo");
        client.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = client.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        //            String filename = "DownloadedLook1.txt";
        String path = "D:\\jpg\\";
        //            String filename = "1.jpg";
        String filename = "appearance.jpg";
        System.out.println(path + filename);
        fis = new FileInputStream(path + filename);
        System.out.println(fis.toString());
        boolean status = client.storeFile("/public_html/testing/" + filename, fis);
        System.out.println("Status : " + status);
        System.out.println("Done!");
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.tumblr.maximopro.iface.router.FTPHandler.java

@Override
public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException {
    byte[] encodedData = super.invoke(metaData, data);
    this.metaData = metaData;

    FTPClient ftp;
    if (enableSSL()) {
        FTPSClient ftps = new FTPSClient(isImplicit());
        ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        ftp = ftps;//from ww w  .  java  2 s.  c  om
    } else {
        ftp = new FTPClient();
    }

    InputStream is = null;
    try {

        if (getTimeout() > 0) {
            ftp.setDefaultTimeout(getTimeout());
        }

        if (getBufferSize() > 0) {
            ftp.setBufferSize(getBufferSize());
        }

        if (getNoDelay()) {
            ftp.setTcpNoDelay(getNoDelay());
        }

        ftp.connect(getHostname(), getPort());

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        if (!ftp.login(getUsername(), getPassword())) {
            ftp.logout();
            ftp.disconnect();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (enableActive()) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        is = new ByteArrayInputStream(encodedData);

        String remoteFileName = getFileName(metaData);

        ftp.changeWorkingDirectory("/");
        if (createDirectoryStructure(ftp, getDirName().split("/"))) {
            ftp.storeFile(remoteFileName, is);
        } else {
            throw new MXApplicationException("iface", "cannotcreatedir");
        }

        ftp.logout();
    } catch (MXException e) {
        throw e;
    } catch (SocketException e) {
        throw new MXApplicationException("iface", "ftpsocketerror", e);
    } catch (IOException e) {
        throw new MXApplicationException("iface", "ftpioerror", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }

        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }
    }

    return null;
}