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

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

Introduction

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

Prototype

public boolean isConnected() 

Source Link

Document

Returns true if the client is currently connected to a server.

Usage

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

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {/*  w  w w  .j  a  v  a2 s. co  m*/
        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();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) {
            for (FTPFile ftpFile : ftpClient.listFiles()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setName(ftpFile.getName());
                fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                fileInfo.setIsDirectory(ftpFile.isDirectory());
                fileInfo.setSize(ftpFile.getSize());
                fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                fileInfos.add(fileInfo);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
    // }
    return fileInfos;
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {/*from  www .  j  a v a2s .  co m*/
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}

From source file:boosta.artem.services.FTPResultReader.java

public void readResult() {
    String server = "62.210.82.210";
    int port = 55021;
    String user = "misha_p";
    String pass = "GfhjkM1983";

    FTPClient ftpClient = new FTPClient();
    try {//  ww w .  j  a  v  a  2s .  co m

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

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String remoteFile = Main.remote_out_path;
        System.out.println(remoteFile);
        //String remoteFile = "/results/ttgenerate.txt";
        String downlFile = Main.file_name;
        System.out.println(downlFile);
        File downloadFile = new File(downlFile);
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));

        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        outputStream.close();

        if (success) {
            System.out.println(" ?   FTP!!!");
        } else {
            System.out.println("  ?   TFP!!!");
        }

    } catch (IOException ex) {
        System.out.println("   ? FTP  !!!");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println(" ? ?? ? FTP!!!");
        }
    }
}

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

private void deleteChallengeFiles() {
    FTPClient ftp = new FTPClient();
    try {//from  w ww.  ja v a 2s .c om
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.changeWorkingDirectory(".well-known");
        ftp.changeWorkingDirectory("acme-challenge");

        FTPFile[] subFiles = ftp.listFiles();

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    continue;
                } else {
                    ftp.deleteFile(currentFileName);
                }
            }
        }
        ftp.changeToParentDirectory();
        ftp.removeDirectory("acme-challenge");
        ftp.changeToParentDirectory();
        ftp.removeDirectory(".well-known");
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:be.thomasmore.controller.FileController.java

public String uploadFile() throws IOException {
    String server = "logic.sinners.be";
    int port = 21;
    String user = "logic_java";
    String pass = "scoretracker";

    FTPClient ftpClient = new FTPClient();
    try {//from w w w  .jav  a2s.  co  m
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        String firstRemoteFile = getFileName(part);
        InputStream inputStream = part.getInputStream();

        System.out.println("Bestand uploaden");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("Het bestand is succesvol upgeload.");
            statusMessage = "De gegevens werden succesvol ingeladen.";
        }

    } catch (IOException ex) {
        System.out.println("Fout: " + ex.getMessage());
        statusMessage = "Er is een fout opgetreden: " + ex.getMessage();
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
     //De bestandsnaam uit het bestand (part) halen
     String fileName = getFileName(part);
     System.out.println("***** fileName: " + fileName);
            
     String basePath = "C:" + File.separator + "data" + File.separator;
            
     File outputFilePath = new File(basePath + fileName);
            
     //Streams aanmaken om het upgeloade bestand naar de destination te kopiren
     InputStream inputStream = null;
     OutputStream outputStream = null;
     try {
     inputStream = part.getInputStream();
     outputStream = new FileOutputStream(outputFilePath);
            
     int read = 0;
     final byte[] bytes = new byte[1024];
     while ((read = inputStream.read(bytes)) != -1) {
     outputStream.write(bytes, 0, read);
     }
     statusMessage = "De gegevens werden succesvol ingeladen.";
     } catch (IOException e) {
     e.printStackTrace();
     statusMessage = "Er is een fout opgetreden.";
     } finally {
     if (outputStream != null) {
     outputStream.close();
     }
     if (inputStream != null) {
     inputStream.close();
     }
     }*/
    leesExcel();

    return null;
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile)
        throws IOException, Exception {
    FTPClient ftp = new FTPClient();
    try {/* w  ww  .j a v a2  s.c  om*/
        int reply = 0;
        boolean replyB = false;
        ftp.connect(theServer);
        System.out.print(ftp.getReplyString());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        } else {
            ftp.login("anonymous", "anonymous");
            replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to login to " + theServer);
            }
            OutputStream output = new FileOutputStream(theLocalFile);
            replyB = ftp.retrieveFile(theServerFile, output);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to retrieve " + theServerFile);
            }
        }
        ftp.logout();
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage());
        throw rethrownExp;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignore) {
                // do nothing
            }
        }
    }
}

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 w  w  .  j  a  v a 2 s.  c om
        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:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

private static ArrayList<String> listFiles(final BackgroundTaskStatusProviderSupportingExternalCall status,
        String downloadURL, String server, String remotePath, final FTPClient ftp) {
    String username;/* ww w .j  ava 2s  .c om*/
    String password;
    username = "anonymous@" + server;
    password = "anonymous";

    final ObjectRef myoutputstream = new ObjectRef();

    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText1("Command: " + arg0.getMessage());
        }

        public void protocolReplyReceived(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText2("Message: " + arg0.getMessage());
            if (myoutputstream.getObject() != null) {
                String msg = arg0.getMessage();
                if (msg.indexOf("Opening BINARY mode") >= 0) {
                    if (msg.indexOf("(") > 0) {
                        msg = msg.substring(msg.indexOf("(") + "(".length());
                        if (msg.indexOf(" ") > 0) {
                            msg = msg.substring(0, msg.indexOf(" "));
                            try {
                                long max = Long.parseLong(msg);
                                MyOutputStream os = (MyOutputStream) myoutputstream.getObject();
                                os.setMaxBytes(max);
                            } catch (Exception e) {
                                System.out.println(
                                        "Could not determine file length for detailed progress information");
                            }
                        }
                    }
                }
            }
        }
    });

    System.out.println("FTP LIST DIRECTORY: " + downloadURL);

    try {
        if (ftp.isConnected()) {
            status.setCurrentStatusText2("Using open FTP connection");
            System.out.println("Reusing open FTP connection");
        } else {
            ftp.connect(server);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                status.setCurrentStatusText1("Can't connect to FTP server");
                status.setCurrentStatusText2("ERROR");
                return new ArrayList<String>();
            }
            if (!ftp.login("anonymous", "anonymous")) {
                if (!ftp.login(username, password)) {
                    ftp.disconnect();
                    status.setCurrentStatusText1("Can't login to FTP server");
                    status.setCurrentStatusText2("ERROR");
                    return new ArrayList<String>();
                }
            }
            status.setCurrentStatusText1("Set Binary Transfer Mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            status.setCurrentStatusText2("Activate Passive Transfer Mode");
            ftp.enterLocalPassiveMode();
        }
        status.setCurrentStatusText1("Start download...");
        status.setCurrentStatusText2("Please Wait.");

        ftp.setRemoteVerificationEnabled(false);

        FTPFile[] res = ftp.listFiles(remotePath);

        ArrayList<String> result = new ArrayList<String>();

        for (FTPFile r : res) {
            result.add(r.getName());
        }

        return result;
    } catch (Exception err) {
        ErrorMsg.addErrorMessage(err);
        if (ftp != null && ftp.isConnected()) {
            try {
                System.out.println("Disconnect FTP connection (following error condition)");
                ftp.disconnect();
            } catch (Exception err2) {
                ErrorMsg.addErrorMessage(err2);
            }
        }
        return new ArrayList<String>();
    }
}

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 {// www.j a v  a  2s .  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:net.siegmar.japtproxy.fetcher.FetcherFtp.java

/**
 * {@inheritDoc}//from  w w  w .  j  a v a2  s  . c o  m
 */
@Override
public FetchedResourceFtp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final FTPClient ftpClient = new FTPClient();
    ftpClient.setSoTimeout(socketTimeout);
    ftpClient.setDataTimeout(dataTimeout);

    try {
        final String host = targetResource.getHost();
        final String resourceName = targetResource.getPath();

        LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName);

        ftpClient.connect(host);
        ftpClient.enterLocalPassiveMode();

        if (!ftpClient.login("anonymous", "japt-proxy")) {
            throw new IOException("Can't login to FTP server");
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        final FTPFile[] files = ftpClient.listFiles(resourceName);

        if (files.length == 0) {
            throw new ResourceUnavailableException("Resource '" + resourceName + "' not found");
        }

        if (files.length > 1) {
            throw new IOException("Multiple files found");
        }

        final FTPFile file = files[0];

        final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file);
        fetchedResourceFtp
                .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis());

        return fetchedResourceFtp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceFtp
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }

        throw e;
    }
}