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:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }//from  w ww .ja  v a  2 s .c  om
    final FTPClient ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(30);
    ftp.setControlKeepAliveReplyTimeout(30);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        ftp.connect(ftpSubscription.getFtpHost());
        _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (final IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }
    boolean error = false;
    __main: try {
        if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) {
            ftp.logout();
            error = true;
            break __main;
        }
        _log.info("Remote system is " + ftp.getSystemType());
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        //ftp.enterLocalActiveMode();
        ftp.enterLocalPassiveMode();
        //final FTPClientConfig config = new FTPClientConfig();
        ////config.setLenientFutureDates(true);
        //ftp.configure(config);
        if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) {
            ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder());
        }
        final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile());
        if (is == null) {
            _log.error("FIle not found: " + ftp.getSystemType());
        } else {
            unzip(ftpSubscription, is);
            is.close();
        }
        ftp.completePendingCommand();
    } catch (final FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (final IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException e) {
                _log.error(e);
            }
        }
    }
}

From source file:com.claim.support.FtpUtil.java

public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) {
    FTPClient ftpClient = new FTPClient();
    InputStream inputStream = null;
    try {/*from   w ww .j  av  a2 s .  c  o m*/
        FtpProperties properties = new ResourcesProperties().loadFTPProperties();
        ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
        ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        File secondLocalFile = new File(direcPath);
        String secondRemoteFile = "WorkshopDay2.docx";
        inputStream = new FileInputStream(secondLocalFile);
        System.out.println("Start uploading second file");
        OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
        byte[] bytesIn = new byte[4096];
        int read = 0;
        while ((read = inputStream.read(bytesIn)) != -1) {
            outputStream.write(bytesIn, 0, read);
        }
        inputStream.close();
        outputStream.close();
        boolean completed = ftpClient.completePendingCommand();
        if (completed) {
            System.out.println("The second file is uploaded successfully.");
        }
    } 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:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);/* w  ww .  j ava  2 s .  co  m*/
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java

public void conectarFTP(Archivo archivo) {
    FTPClient client = new FTPClient();
    /*String sFTP = "127.0.0.1";
    String sUser = "tae";/*from  w  w  w .j  a va  2s.  c o m*/
    String sPassword = "tae";*/
    String sFTP = buscarParametros(FTP_SERVER);
    String sUser = buscarParametros(FTP_USER);
    String sPassword = buscarParametros(FTP_PASSWORD);
    ///////////////////////////////////
    //String[] lista;
    try {
        client.connect(sFTP);
        boolean login = client.login(sUser, sPassword);
        System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory());
        client.setFileType(FTP.BINARY_FILE_TYPE);
        BufferedInputStream buffIn = null;
        buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre()));
        client.enterLocalPassiveMode();
        StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta.
        int i = 0;
        String nombre = "";
        while (tokens.hasMoreTokens()) {
            if (i == 1) {
                nombre = tokens.nextToken();
                i++;
            } else {
                i++;
            }
        }
        client.storeFile(nombre, buffIn);
        buffIn.close();
        /*lista = client.listNames();
        for (String lista1 : lista) {
        System.out.println(lista1);
        }*/
        //client.changeWorkingDirectory("\\done");
        //System.out.println("2. Working Directory: " + client.printWorkingDirectory());
        client.logout();
        client.disconnect();
        System.out.println("Termin de conectarme al FTP!!");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:facturacion.ftp.FtpServer.java

public static int sendTokenInputStream(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//from ww w . j ava2  s. c  o  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.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
        System.out.println(hostDirServer);
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1133 = " + success);
        //showServerReply(ftpClient);
        success = ftpClient.makeDirectory(hostDirServer + "/token");
        /*
        System.out.println("sucess 1 = "+success);
        success = ftpClient.makeDirectory("casa111");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/usr/erp/token/casa");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/casa2");
        System.out.println("sucess 1 = "+success);
        */
        success = ftpClient.storeFile(hostDirServer + "/token/" + fileNameServer, buffIn);
        //success = ftpClient.storeFile("prueba", buffIn);
        System.out.println("sucess 2 = " + success);
        //return (success)? 1:0;
    } 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:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java

/**
 * _more_/*from ww  w . j  av  a 2s  .c  om*/
 * 
 * @param file
 *            _more_
 * @param ignoreErrors
 *            _more_
 * 
 * @return _more_
 * 
 * @throws Exception
 *             _more_
 */
private byte[] readFile(String file, boolean ignoreErrors) throws Exception {
    if (new File(file).exists()) {
        return IOUtil.readBytes(IOUtil.getInputStream(file, getClass()));
    }
    if (!file.startsWith("ftp:")) {
        if (ignoreErrors) {
            return null;
        }
        throw new FileNotFoundException("Could not read file: " + file);
    }

    URL url = new URL(file);
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(url.getHost());
        ftp.login("anonymous", "password");
        ftp.setFileType(FTP.IMAGE_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if (ftp.retrieveFile(url.getPath(), bos)) {
            return bos.toByteArray();
        } else {
            throw new IOException("Unable to retrieve file:" + url);
        }
    } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) {
        System.err.println("ftp error:" + fcce);
        System.err.println(ftp.getReplyString());
        if (!ignoreErrors) {
            throw fcce;
        }
        return null;
    } catch (Exception exc) {
        if (!ignoreErrors) {
            throw exc;
        }
        return null;
    } finally {
        try {
            ftp.logout();
        } catch (Exception exc) {
        }
        try {
            ftp.disconnect();
        } catch (Exception exc) {
        }

    }
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/*w  w w .  ja v  a2  s  .c o m*/
            inputStream = new FileInputStream(file);
            ftpClient.connect(ftpInfo.get("host"), 21);
            ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            path = ftpInfo.get("path") + path;
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream2(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    File downloadFile1 = null;/* ww w  .  j ava  2s  .  com*/
    try {
        downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        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.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) );
        //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD));
        //ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        boolean success;
        String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12";
        downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12");
        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
        success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12");
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12");
        InputStream is = fis;
        if (success) {
            System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf");
        } else {
            System.out.println("File #1 has been downloaded successfully. 3333");
        }
        ;
        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:fr.acxio.tools.agia.ftp.FTPUploadTasklet.java

@Override
public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception {
    FTPClient aClient = ftpClientFactory.getFtpClient();

    RegexFilenameFilter aFilter = new RegexFilenameFilter();
    aFilter.setRegex(regexFilename);//from w w  w.  j ava2s  .c o  m

    try {
        File aLocalDir = new File(localBaseDir);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Listing : {} ({}) for upload to [{}]", localBaseDir, regexFilename,
                    aClient.getRemoteAddress().toString());
        }

        File[] aLocalFiles = aLocalDir.listFiles(aFilter);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("  {} file(s) found", aLocalFiles.length);
        }

        for (File aLocalFile : aLocalFiles) {

            if (sContribution != null) {
                sContribution.incrementReadCount();
            }

            URI aRemoteFile = new URI(remoteBaseDir).resolve(aLocalFile.getName());
            InputStream aInputStream;
            aInputStream = new FileInputStream(aLocalFile);
            try {

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info(" Uploading : {} => {}", aLocalFile.getAbsolutePath(),
                            aRemoteFile.toASCIIString());
                }

                aClient.storeFile(aRemoteFile.toASCIIString(), aInputStream);

                if (sContribution != null) {
                    sContribution.incrementWriteCount(1);
                }
            } finally {
                aInputStream.close();
            }
        }
    } finally {
        aClient.logout();
        aClient.disconnect();
    }

    return RepeatStatus.FINISHED;
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

private void Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;/*from w w w.j a  v a2 s  .c o m*/

    try {
        client.connect(ftpServer);
        client.login(userName, password);
        client.enterLocalPassiveMode();
        client.setFileType(FTP.BINARY_FILE_TYPE);
        fis = new FileInputStream(SourcePathDirectory + filename);
        client.changeWorkingDirectory("/" + pathDirectory);

        client.storeFile(filename, fis);

        System.out.println(
                "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename);
        client.logout();

        //Report = "File: " + filename + " Uploaded Successfully ";
    } catch (Exception exp) {
        exp.printStackTrace();
        Report = "Server Error";
        jLabel6.setText(Report);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}