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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:com.omicronware.streamlet.Main.java

public static FTPClient getFtp() {
    if (client == null) {
        client = new FTPClient();
        try {/* w  w w. j a v  a  2  s  . c  om*/
            client.connect("192.168.1.2");
            client.login("streamlet", "");
        } catch (IOException ex) {
            Logger.getLogger(DownloadManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return client;
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from   www .ja v a  2  s.  c  om*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:com.symbian.driver.plugins.ftptelnet.FtpTransfer.java

/**
 * connectFTP : connects to ftp server/*from   www.j a v  a  2  s. c  om*/
 * 
 * @return boolean success/fail
 */
public boolean connectFTP() {
    if (isFTPConnected()) {
        return true;
    }
    // Connect to FTP
    try {

        // 1. create an apache client
        iFTP = new FTPClient();
        iFTP.addProtocolCommandListener(new ProtocolCommandListener() {

            public void protocolCommandSent(ProtocolCommandEvent aProtocolCommandEvent) {
                LOGGER.fine("FTP Command Send: (" + aProtocolCommandEvent.getCommand() + ") "
                        + aProtocolCommandEvent.getMessage());
            }

            public void protocolReplyReceived(ProtocolCommandEvent aProtocolCommandEvent) {
                LOGGER.fine("FTP Command Recieved: (" + aProtocolCommandEvent.getMessage() + ") Returned Code "
                        + aProtocolCommandEvent.getReplyCode());
            }
        });
        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
        iFTP.configure(conf);
        // 2. connect
        iFTP.connect(iIP, iPort);

        // 3. check connection done.
        int reply = iFTP.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFTP();
            LOGGER.log(Level.SEVERE, "FTP error: " + reply);
            return false;
        }

        // 4. Login
        if (!iFTP.login(iUserName, iPassword)) {
            LOGGER.log(Level.SEVERE, "FTP failed to login, Username: " + iUserName + " Password: " + iPassword);
            disconnectFTP();
            return false;
        } else {
            if (iPassive.equalsIgnoreCase("true")) {
                iFTP.enterLocalPassiveMode();
            }
            iFTP.setFileType(FTP.BINARY_FILE_TYPE);
            iFTP.setBufferSize(iBufferSize);
        }

    } catch (SocketException lSocketException) {
        LOGGER.log(Level.SEVERE, "Socket exception ", lSocketException);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Socket exception ", lIOException);
        return false;
    }

    LOGGER.info("FTP connection established with transport : " + iIP + ":" + iPort);

    return true;

}

From source file:com.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {// w w  w  .j ava2s. c  om
        // The executes in the IO thread!
        String sourceVar = getSourceVar(messageContext);
        InputStream src = null;
        boolean wantBase64Decode = getWantBase64Decode(messageContext);
        if (sourceVar == null) {
            src = messageContext.getMessage().getContentAsStream();
            // conditionally wrap a decoder around it
            if (wantBase64Decode) {
                src = new Base64InputStream(src);
            }
        } else {
            info.addMessage("Retrieving data from " + sourceVar);
            String sourceData = messageContext.getVariable(sourceVar);
            byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData)
                    : sourceData.getBytes(StandardCharsets.UTF_8);
            src = new ByteArrayInputStream(b);
        }
        String remoteName = getRemoteFileName(messageContext);
        remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-");

        String ftpServer = getFtpServer(messageContext);
        int ftpPort = getFtpPort(messageContext);
        String user = getFtpUser(messageContext);
        String password = getFtpPassword(messageContext);

        info.addMessage("connecting to server " + ftpServer);
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new FtpCommandListener(info));
        ftp.connect(ftpServer, ftpPort);
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("The FTP server refused the connection.");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }

        if (!ftp.login(user, password)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("Login failure");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }
        info.addMessage("logged in as " + user);

        String initialDirectory = getInitialDirectory(messageContext);
        if ((initialDirectory != null) && (!initialDirectory.equals(""))) {
            ftp.changeWorkingDirectory(initialDirectory);
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        OutputStream os = ftp.storeFileStream(remoteName);
        if (os == null) {
            // cannot open output stream
            info.addMessage("cannot open output stream to " + remoteName);
            info.setStatus("FAIL");
        } else {
            byte[] buf = new byte[2048];
            int n;
            while ((n = src.read(buf)) > 0) {
                os.write(buf, 0, n);
            }
            os.close();
            src.close();
            boolean completed = ftp.completePendingCommand();
            info.addMessage("transfer completed: " + completed);
            info.setStatus("OK");
        }

        ftp.disconnect();
        info.addMessage("All done.");
        messageContext.setVariable(varName("result"), info.toJsonString());
    } catch (java.lang.Exception exc1) {
        if (getDebug()) {
            System.out.println(ExceptionUtils.getStackTrace(exc1));
        }
        String error = exc1.toString();
        messageContext.setVariable(varName("exception"), error);
        info.setStatus("FAIL");
        info.addMessage(error);
        messageContext.setVariable(varName("result"), info.toJsonString());
        int ch = error.lastIndexOf(':');
        if (ch >= 0) {
            messageContext.setVariable(varName("error"), error.substring(ch + 2).trim());
        } else {
            messageContext.setVariable(varName("error"), error);
        }
        messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1));
        return ExecutionResult.ABORT;
    }

    return ExecutionResult.SUCCESS;
}

From source file:com.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {
    String server = properties.getValue(propServer);
    String path = properties.getValue(propPath);
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);
    String fileNamePattern = properties.getValue(propFileNamePattern);
    boolean deleteAfterLoad = Boolean.TRUE.toString().equals(properties.getValue(propDeleteAfterLoad));
    boolean truncateWhenFilesFound = Boolean.TRUE.toString()
            .equals(properties.getValue(propTruncateIndexWhenFilesFound));
    Pattern pattern = null;/* ww w.  ja v a 2s  .co  m*/
    if (fileNamePattern != null && fileNamePattern.length() > 0)
        pattern = Pattern.compile(fileNamePattern);

    String p = properties.getValue(propBuffersize);
    String xsl = properties.getValue(propXsl);
    File xmlTempResult = null;
    int bufferSize = 50;
    if (p != null && p.length() > 0)
        bufferSize = Integer.parseInt(p);
    HttpDownloader httpDownloader = client.getWebCrawlMaster().getNewHttpDownloader(true);
    FTPClient ftp = null;
    InputStream inputStream = null;
    try {
        // FTP Connection
        ftp = new FTPClient();
        checkConnect(ftp, server, login, password);
        FTPFile[] files = ftp.listFiles(path, new FtpFileInstance.FtpInstanceFileFilter(true, false, null));
        if (files == null)
            return;
        // Sort by ascendant filename
        String[] fileNames = new String[files.length];
        int i = 0;
        for (FTPFile file : files)
            fileNames[i++] = file.getName();
        Arrays.sort(fileNames);
        int ignored = 0;
        int loaded = 0;
        boolean bAlreadyTruncated = false;
        for (String fileName : fileNames) {
            String filePathName = FilenameUtils.concat(path, fileName);
            if (pattern != null)
                if (!pattern.matcher(fileName).find()) {
                    ignored++;
                    continue;
                }
            if (truncateWhenFilesFound && !bAlreadyTruncated) {
                client.deleteAll();
                bAlreadyTruncated = true;
            }
            taskLog.setInfo("Working on: " + filePathName);
            inputStream = ftp.retrieveFileStream(filePathName);
            Node xmlDoc = null;
            if (xsl != null && xsl.length() > 0) {
                xmlTempResult = File.createTempFile("ossftpfeed", ".xml");
                DomUtils.xslt(new StreamSource(inputStream), xsl, xmlTempResult);
                xmlDoc = DomUtils.readXml(new StreamSource(xmlTempResult), false);
            } else
                xmlDoc = DomUtils.readXml(new StreamSource(inputStream), false);
            client.updateXmlDocuments(xmlDoc, bufferSize, null, httpDownloader, taskLog);
            client.deleteXmlDocuments(xmlDoc, bufferSize, taskLog);
            inputStream.close();
            inputStream = null;
            if (!ftp.completePendingCommand())
                throw new SearchLibException("FTP Error");
            if (xmlTempResult != null) {
                xmlTempResult.delete();
                xmlTempResult = null;
            }
            checkConnect(ftp, server, login, password);
            if (deleteAfterLoad)
                ftp.deleteFile(filePathName);
            loaded++;
        }
        taskLog.setInfo(loaded + " file(s) loaded - " + ignored + " file(s) ignored");
    } catch (XPathExpressionException e) {
        throw new SearchLibException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SearchLibException(e);
    } catch (ParserConfigurationException e) {
        throw new SearchLibException(e);
    } catch (SAXException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    } catch (InstantiationException e) {
        throw new SearchLibException(e);
    } catch (IllegalAccessException e) {
        throw new SearchLibException(e);
    } catch (ClassNotFoundException e) {
        throw new SearchLibException(e);
    } catch (TransformerException e) {
        throw new SearchLibException(e);
    } finally {
        if (xmlTempResult != null)
            xmlTempResult.delete();
        IOUtils.close(inputStream);
        try {
            if (ftp != null)
                if (ftp.isConnected())
                    ftp.disconnect();
        } catch (IOException e) {
            Logging.warn(e);
        }
        if (httpDownloader != null)
            httpDownloader.release();
    }
}

From source file:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java

/**
 * Retrieve a file to a temporary path. This temporary path will be returned. Valid protocol
 * types: ftp, http, package or local file If a file has already be downloaded (the file is
 * existing in tmp directory) it will not be redownloaded again. Simply the path to this file
 * will be returned./*  w w w  .jav a  2s  .c o m*/
 * 
 * @param url
 *            URL to retrieve
 * @param checkAlreadyRetrieved
 *            if false, always download the file and ignore, if it is already existing
 * @return NULL on error. On success the path to the file is returned.
 */
public static File retrieve(String url, boolean checkAlreadyRetrieved) {
    if (url.indexOf("://") <= 0) {
        // Is local file
        return new File(url);
    }
    int start = url.indexOf('/') + 2;
    int end = url.indexOf('/', start);
    String serverName = url.substring(start, end);
    if (url.startsWith("package://")) {
        String filePath = url.substring(end + 1);
        String pkgPath = findPackage(serverName);
        if (pkgPath == null)
            return null;
        return new File(pkgPath, filePath);
    } else if (url.startsWith("http://")) {

        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            return tmpPath;
        }

        try {
            // Get the URL
            URL urlClass = new URL(url);
            // Open an output stream to the destination file on our local filesystem
            out = new BufferedOutputStream(new FileOutputStream(tmpPath));
            conn = urlClass.openConnection();
            in = conn.getInputStream();

            // Get the data
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
            // Done! Just clean up and get out
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                // Ignore if stream not possible to close
            }
        }
        return tmpPath;
    } else if (url.startsWith("ftp://")) {
        FTPClient client = new FTPClient();
        OutputStream outStream = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            System.out.println("Already retrieved: " + url + " to " + tmpPath.getAbsolutePath());
            return tmpPath;
        }

        try {
            // Connect to the FTP server as anonymous
            client.connect(serverName);
            client.login("anonymous", "knowrob@example.com");
            String remoteFile = url.substring(end);
            // Write the contents of the remote file to a FileOutputStream
            outStream = new FileOutputStream(tmpPath);
            client.retrieveFile(remoteFile, outStream);

        } catch (IOException ioe) {
            System.out.println("ResourceRetriever: Error communicating with FTP server: " + serverName + "\n"
                    + ioe.getMessage());
        } finally {
            try {
                outStream.close();
            } catch (IOException e1) {
                // Ignore if stream not possible to close
            }
            try {
                client.disconnect();
            } catch (IOException e) {
                System.out.println("ResourceRetriever: Problem disconnecting from FTP server: " + serverName
                        + "\n" + e.getMessage());
            }
        }
        return tmpPath;
    }
    return null;
}

From source file:adams.gui.chooser.FtpRemoteDirectorySetup.java

/**
 * Returns a new client for the host/port defined in the options.
 *
 * @return      the client//w w w  . ja va 2  s. c  om
 */
public FTPClient newClient() {
    FTPClient result;
    int reply;

    try {
        result = new FTPClient();
        result.addProtocolCommandListener(this);
        result.connect(m_Host);
        reply = result.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            getLogger().severe("FTP server refused connection: " + reply);
        } else {
            if (!result.login(m_User, m_Password.getValue())) {
                getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'");
            } else {
                if (m_UsePassiveMode)
                    result.enterLocalPassiveMode();
                if (m_UseBinaryMode)
                    result.setFileType(FTPClient.BINARY_FILE_TYPE);
            }
        }
    } catch (Exception e) {
        Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e);
        result = null;
    }

    return result;
}

From source file:com.o6Systems.utils.net.FTPModule.java

private int executeFtpCommand(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from   w  w w.ja  v a2s .  c om
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;

    // Print the command

    System.out.println("----------FTP MODULE CALL----------");

    for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
    }

    System.out.println("--------------------");
    //

    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            return 1;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        return 1;
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return error ? 1 : 0;
}

From source file:adams.scripting.connection.FTPConnection.java

/**
 * Starts up a FTP session.//from   w w  w .j  av  a2s.c om
 *
 * @return      null if OK, otherwise error message
 */
protected String connect() {
    String result;
    int reply;

    result = null;

    try {
        m_Client = new FTPClient();
        m_Client.addProtocolCommandListener(this);
        m_Client.connect(m_Host);
        reply = m_Client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            result = "FTP server refused connection: " + reply;
        } else {
            if (!m_Client.login(m_User, m_Password.getValue())) {
                result = "Failed to connect to '" + m_Host + "' as user '" + m_User + "'";
            } else {
                if (m_UsePassiveMode)
                    m_Client.enterLocalPassiveMode();
                if (m_UseBinaryMode)
                    m_Client.setFileType(FTPClient.BINARY_FILE_TYPE);
            }
        }
    } catch (Exception e) {
        result = Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ",
                e);
        m_Client = null;
    }

    return result;
}

From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }//  w  w  w .j  a v a  2s. c  om
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}