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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

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 {/*  ww  w .  j a  v  a 2 s  .  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:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * FTP?.//from www .  j ava 2 s .c om
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        FTPFile[] fs = ftp.listFiles();
        // ??
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                // ???
                File localFile = new File(localPath + "/" + ff.getName());
                // ?
                OutputStream is = new FileOutputStream(localFile);
                // 
                ftp.retrieveFile(ff.getName(), is);
                is.close();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java

/**
 * FTP????????//from  www .j a v  a 2s .  c  o m
 * 
 * @param addressText
 * @return FTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        FTPClient client = new FTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (FTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(FTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {//from  ww w  . j av  a 2s  . c o  m
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

/**
 * ftp?//from   w ww .jav  a  2s. c  om
 *
 * @param ftpClient
 * @return ?true?false
 * @throws Exception
 */
private boolean connect(FTPClient ftpClient) throws Exception {
    try {
        ftpClient.connect(host, port);

        // ?????
        int reply = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(reply)) {
            //ftp?
            if (ftpClient.login(username, password)) {
                setFileType(ftpClient);
                return true;
            }
        } else {
            ftpClient.disconnect();
            throw new Exception("FTP server refused connection.");
        }
    } catch (IOException e) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect(); //
            } catch (IOException e1) {
                throw new Exception("Could not disconnect from server.", e1);
            }

        }
        throw new Exception("Could not connect to server.", e);
    }
    return false;
}

From source file:com.claim.controller.FileTransferController.java

public void readFilesFromServer(String targetDirectory) {
    FTPClient ftpClient = new FTPClient();
    try {// w w  w .j av  a  2s  .  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);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        FTPFile[] ftpFiles = ftpClient.listFiles();

        if (ftpFiles != null && ftpFiles.length > 0) {
            //loop thru files
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());

                //get output stream
                OutputStream output;
                //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName());
                output = new FileOutputStream(file.getName());
                //get the file from the remote system
                ftpClient.retrieveFile(file.getName(), output);
                //close output stream
                output.close();

                //delete the file
                //ftpClient.deleteFile(file.getName());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {/*  w  ww. j a va 2  s .  c  o  m*/
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }
        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }
        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:net.paissad.jcamstream.utils.FTPUtils.java

public void estabishConnection() throws SocketException, IOException, FTPException {

    this.setFtpClient(new FTPClient());
    String errMsg;/*from www  .  j a v a 2s  .com*/

    FTPClient client = this.getFtpClient();
    PrintCommandListener listener = new PrintCommandListener(System.out);
    client.addProtocolCommandListener(listener);

    // Connects to the FTP server
    String host = this.getFtpServerHost();
    int port = this.getFtpServerPort();
    client.connect(host, port);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        client.disconnect();
        errMsg = "Unable to connect to the server " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Login to the FTP server
    String username = this.getFtpUser();
    String pass = this.getFtpPassword();
    if (!client.login(username, pass)) {
        errMsg = "Unable to login to " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Change the current directory
    String dirname = this.getFtpServerDir();
    if (!client.changeWorkingDirectory(dirname)) {

        System.out.println("Unable to change to the directory '" + dirname + "'.");
        System.out.println("Going to create the directory !");
        this.mkdirs(dirname);
        System.out.println("Creation of the directory is successful.");
    }

    client.changeWorkingDirectory(dirname);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        errMsg = "Unable to change to the directory : " + dirname;
        this.verifyReplyCode(errMsg);
    }

    client.pwd();
}

From source file:ddf.test.itests.catalog.TestFtp.java

private FTPClient createInsecureClient() throws Exception {
    FTPClient ftp = new FTPClient();

    int attempts = 0;
    while (true) {
        try {//from ww  w  . ja  v  a2  s . com
            ftp.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()));
            break;
        } catch (SocketException e) {
            // a socket exception can be thrown if the ftp server is still in the process of coming up
            // or down
            Thread.sleep(1000);
            if (attempts++ > 30) {
                throw e;
            }
        }
    }

    showServerReply(ftp);
    int connectionReply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(connectionReply)) {
        fail("FTP server refused connection: " + connectionReply);
    }

    boolean success = ftp.login(USERNAME, PASSWORD);
    showServerReply(ftp);
    if (!success) {
        fail("Could not log in to the FTP server.");
    }

    ftp.enterLocalPassiveMode();
    ftp.setControlKeepAliveTimeout(300);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    return ftp;
}

From source file:com.claim.controller.FileTransferController.java

public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception {
    FTPClient ftpClient = new FTPClient();
    int replyCode;
    boolean completed = false;
    try {// ww w  .  j a  va2s.  c  o m

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        try {
            ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
            FtpUtil.showServerReply(ftpClient);
        } catch (ConnectException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("ConnectException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (SocketException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("SocketException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("UnknownHostException: " + ex.getMessage());
            ex.printStackTrace();
        }

        replyCode = ftpClient.getReplyCode();
        FtpUtil.showServerReply(ftpClient);

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            FtpUtil.showServerReply(ftpClient);
            ftpClient.disconnect();
            Console.LOG("Exception in connecting to FTP Serve ", 0);
            throw new Exception("Exception in connecting to FTP Server");
        } else {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG("Success in connecting to FTP Serve ", 1);
        }

        try {
            boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
            FtpUtil.showServerReply(ftpClient);
            if (!success) {
                throw new Exception("Could not login to the FTP server.");
            } else {
                Console.LOG("login to the FTP server. Successfully ", 1);
            }
            //ftpClient.enterLocalPassiveMode();
        } catch (FTPConnectionClosedException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();

        // APPROACH #2: uploads second file using an OutputStream
        File files = new File(ftpObj.getFtp_directory_path());

        String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator
                + ftpObj.getFtp_report_type();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType);
        FtpUtil.showServerReply(ftpClient);

        String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp);
        FtpUtil.showServerReply(ftpClient);

        for (File file : files.listFiles()) {
            if (file.isFile()) {
                System.out.println("file ::" + file.getName());
                InputStream in = new FileInputStream(file);
                ftpClient.changeWorkingDirectory(workingDirectoryStmp);
                completed = ftpClient.storeFile(file.getName(), in);
                in.close();
                Console.LOG(
                        "  " + file.getName() + " ",
                        1);
                FtpUtil.showServerReply(ftpClient);
            }
        }
        Console.LOG(" ?... ", 1);

        //completed = ftpClient.completePendingCommand();
        FtpUtil.showServerReply(ftpClient);
        completed = true;
        ftpClient.disconnect();

    } catch (IOException ex) {
        Console.LOG(ex.getMessage(), 0);
        FtpUtil.showServerReply(ftpClient);
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            ex.printStackTrace();
        }
    }
    return completed;
}