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:com.esri.gpt.control.webharvest.validator.WAFValidator.java

@Override
public boolean checkConnection(IMessageCollector mb) {
    if (url.toLowerCase().startsWith("ftp://")) {
        FTPClient client = null;
        try {/*from  w ww  .j a va2 s.  c  o  m*/
            URL u = new URL(url);
            String host = u.getHost();
            int port = u.getPort() >= 0 ? u.getPort() : 21;
            client = new FTPClient();
            client.connect(host, port);
            CredentialProvider cp = getCredentialProvider();
            if (cp == null) {
                client.login("anonymous", "anonymous");
            } else {
                client.login(cp.getUsername(), cp.getPassword());
            }
            return true;
        } catch (MalformedURLException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestInvalidUrl");
            return false;
        } catch (IOException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestConnectionException");
            return false;
        } finally {
            if (client != null) {
                try {
                    client.disconnect();
                } catch (IOException ex) {
                }
            }
        }
    } else {
        return super.checkConnection(mb);
    }
}

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.j a v  a2s  . com
    } 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;
}

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;/* ww  w.  j  a  va  2 s. c  o m*/
    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: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 w w . j  av  a 2 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
        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:edu.stanford.epad.common.util.FTPUtil.java

public boolean sendFile(String filePath, boolean delete) throws Exception {

    String fileName = filePath;//from   w  ww.j a  v a  2  s .co m
    int slash = fileName.lastIndexOf("/");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    slash = fileName.lastIndexOf("\\");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    boolean success = true;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(ftpHost, ftpPort);
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(ftpUser, ftpPassword)) {
                if (ftpFolder != null && ftpFolder.trim().length() > 0) {
                    ftp.cwd(ftpFolder);
                    System.out.print("ftp cd: " + ftp.getReplyString());
                }
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
                FileInputStream in = new FileInputStream(filePath);
                success = ftp.storeFile(fileName, in);
                in.close();
                if (delete) {
                    File file = new File(filePath);
                    file.delete();
                }
            } else
                success = false;
        }
    } finally {
        ftp.disconnect();
    }

    return success;
}

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   w  ww .  ja  va2 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: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  a 2s . co 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:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public void send(File[] archivos) {
    try {//from w  w  w . ja v a 2s .  com
        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:com.webarch.common.net.ftp.FtpService.java

/**
 * /*from  ww  w.  ja v a 2  s . 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;
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static void getFileFtp(String user, String password, String host, int port, String fileName,
        String location) throws Exception {
    Log.info("\nretrieve " + fileName + NEW_LINE);
    FTPClient client = new FTPClient();

    client.connect(host, port); //connect to the management ftp server
    int reply = client.getReplyCode(); // check connection

    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new Exception("FTP fail to connect");
    }/* w w  w  .  ja  v  a2s . c  om*/

    if (!client.login(user, password)) { //check login
        throw new Exception("FTP fail to login");
    }

    //      FileOutputStream fos = null;
    try {
        File locationFile = new File(location);
        File dest = new File(locationFile, fileName);
        if (dest.exists()) {
            dest.delete();
        } else {
            locationFile.mkdirs();
        }
        boolean status = client.changeWorkingDirectory("/");
        Log.info("chdir-status:" + status + NEW_LINE);
        client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        client.setFileType(FTPClient.BINARY_FILE_TYPE);
        client.enterLocalActiveMode();

        InputStream in = client.retrieveFileStream(fileName);
        if (in == null) {
            Log.error("Input stream is null\n");
            throw new Exception("Fail to retrieve file " + fileName);
        }
        Thread.sleep(3000);
        saveInputStreamToFile(in, new File(location, fileName));
    } finally {
        client.disconnect();
    }

}