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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java

/**
 * Runs the task./*from ww w .  j  a  v a2  s. co  m*/
 *
 * @throws BuildException if the task fails or is not configured
 *         correctly.
 */
@Override
public void execute() throws BuildException {
    checkAttributes();

    FTPClient ftp = null;

    try {
        log("Opening FTP connection to " + server, Project.MSG_VERBOSE);

        ftp = new FTPClient();
        if (this.isConfigurationSet) {
            ftp = FTPConfigurator.configure(ftp, this);
        }

        ftp.setRemoteVerificationEnabled(enableRemoteVerification);

        if (this.proxyServer != null) {

            // Connect through an FTP proxy.

            // Get FTP proxy credentials (optional).
            String proxyUserId;
            char[] proxyPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.proxyServer, this.proxyPort,
                        this.proxyUserid, this.proxyPassword, RequestorType.PROXY);
                if (pa == null) {
                    proxyUserId = null;
                    proxyPassword = null;
                } else {
                    proxyUserId = pa.getUserName();
                    if (proxyUserId == null)
                        throw new BuildException("Proxy user ID missing");
                    proxyPassword = pa.getPassword();
                    if (proxyPassword == null)
                        throw new BuildException("Proxy password missing");
                }
            }

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the FTP proxy.
            this.log("Opening FTP connection to proxy server \"" + this.proxyServer + "\" on port "
                    + this.proxyPort, Project.MSG_VERBOSE);
            ftp.connect(this.proxyServer, this.proxyPort);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection to proxy server failed: " + ftp.getReplyString());
            }
            this.log("connected to proxy server", Project.MSG_VERBOSE);

            // Authenticate with the FTP proxy (optional).
            if (proxyUserId != null) {
                this.log("logging in to FTP proxy server", Project.MSG_VERBOSE);
                if (!ftp.login(proxyUserId, new String(proxyPassword))) {
                    throw new BuildException("Could not login to FTP proxy server");
                }
            }

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            String userid2 = serverUserId + '@' + this.server;
            if (this.port != FTP2.DEFAULT_FTP_PORT)
                userid2 += ":" + this.port;
            if (this.account == null ? !ftp.login(userid2, new String(serverPassword))
                    : !ftp.login(userid2, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.log("login succeeded", Project.MSG_VERBOSE);
        } else {

            // Direct connection to remote FTP server.

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the remote FTP server.
            this.log("Opening FTP connection to " + this.server, Project.MSG_VERBOSE);
            ftp.connect(this.server, this.port);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection failed: " + ftp.getReplyString());
            }
            this.log("connected", Project.MSG_VERBOSE);

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            if (this.account == null ? !ftp.login(serverUserId, new String(serverPassword))
                    : !ftp.login(serverUserId, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.log("login succeeded", Project.MSG_VERBOSE);
        }

        if (binary) {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        } else {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        }

        if (passive) {
            log("entering passive mode", Project.MSG_VERBOSE);
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString());
            }
        }

        // If an initial command was configured then send it.
        // Some FTP servers offer different modes of operation,
        // E.G. switching between a UNIX file system mode and
        // a legacy file system.
        if (this.initialSiteCommand != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.this.initialSiteCommand);
                }
            }, "initial site command: " + this.initialSiteCommand);
        }

        // For a unix ftp server you can set the default mask for all files
        // created.

        if (umask != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, "umask " + umask);
                }
            }, "umask " + umask);
        }

        // If the action is MK_DIR, then the specified remote
        // directory is the directory to create.

        if (action == MK_DIR) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    makeRemoteDir(lftp, remotedir);
                }
            }, remotedir);
        } else if (action == SITE_CMD) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.this.siteCommand);
                }
            }, "Site Command: " + this.siteCommand);
        } else {
            if (remotedir != null) {
                log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE);
                ftp.changeWorkingDirectory(remotedir);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString());
                }
            }
            if (newerOnly && timeDiffAuto) {
                // in this case we want to find how much time span there is between local
                // and remote
                timeDiffMillis = getTimeDiff(ftp);
            }
            log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
            transferFiles(ftp);
        }

    } catch (IOException ex) {
        throw new BuildException("error during FTP transfer: " + ex, ex);
    } finally {
        if (ftp != null && ftp.isConnected()) {
            try {
                log("disconnecting", Project.MSG_VERBOSE);
                ftp.logout();
                ftp.disconnect();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/*w  w  w.  j a  v a  2 s . co  m*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.codice.alliance.nsili.source.NsiliSource.java

/**
 * Uses FTPClient to obtain the IOR string from the provided URL via FTP.
 *///w  ww.j a v  a  2  s. co  m
private void getIorStringFromFtpSource() {
    URI uri = null;
    try {
        uri = new URI(iorUrl);
    } catch (URISyntaxException e) {
        LOGGER.error("{} : Invalid URL specified for IOR string: {} {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Invalid URL specified for IOR string: {}", id, iorUrl, e);
    }

    FTPClient ftpClient = new FTPClient();
    try {
        if (uri.getPort() > 0) {
            ftpClient.connect(uri.getHost(), uri.getPort());
        } else {
            ftpClient.connect(uri.getHost());
        }

        if (!ftpClient.login(serverUsername, serverPassword)) {
            LOGGER.error("{} : FTP server log in unsuccessful.", id);
        } else {
            int timeoutMsec = clientTimeout * 1000;
            ftpClient.setConnectTimeout(timeoutMsec);
            ftpClient.setControlKeepAliveReplyTimeout(timeoutMsec);
            ftpClient.setDataTimeout(timeoutMsec);

            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            InputStream inputStream = ftpClient.retrieveFileStream(uri.getPath());

            iorString = IOUtils.toString(inputStream, StandardCharsets.ISO_8859_1.name());
            //Remove leading/trailing whitespace as the CORBA init can't handle that.
            iorString = iorString.trim();
        }
    } catch (Exception e) {
        LOGGER.warn("{} : Error retrieving IOR file for {}. {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Error retrieving IOR file for {}.", id, iorUrl, e);
    }
}

From source file:org.ecoinformatics.datamanager.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * //from  w  w  w .j a  va2 s  .c om
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {//from www.  j av a 2  s  .  co  m
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}

From source file:org.fabric3.transport.ftp.server.host.F3FtpHostTest.java

public void testStor() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(InetAddress.getLocalHost(), 1234);
    ftpClient.user("user");
    ftpClient.pass("password");
    ftpClient.enterLocalPassiveMode();
    ftpClient.storeFile("/resource/test.dat", new ByteArrayInputStream("TEST\r\n".getBytes()));
}

From source file:org.gitools.datasources.obo.OBOStream.java

public OBOStream(URL baseUrl) throws IOException {
    this.baseUrl = baseUrl;

    // Workaround for FTP problem connecting ftp.geneontology.org with URL.openStream()
    if (baseUrl.getProtocol().equalsIgnoreCase("ftp")) {
        FTPClient ftp = new FTPClient();
        if (baseUrl.getPort() != -1) {
            ftp.connect(baseUrl.getHost(), baseUrl.getPort());
        } else {//from ww w  .j  a va  2 s.co  m
            ftp.connect(baseUrl.getHost());
        }
        ftp.login("anonymous", "");
        ftp.enterLocalPassiveMode();
        ftp.setControlKeepAliveTimeout(60);
        InputStream is = ftp.retrieveFileStream(baseUrl.getPath());
        this.reader = new BufferedReader(new InputStreamReader(is));
    } else {
        this.reader = new BufferedReader(new InputStreamReader(baseUrl.openStream()));
    }

    this.linePos = 0;
}

From source file:org.jason.mapmaker.server.service.ShapefileMetadataServiceImpl.java

private List<String> getRemoteFilenames(String url, String directory) {

    FTPClient ftp = new FTPClient();
    List<String> filenameList = new ArrayList<String>();

    try {/* w w  w .  ja va  2 s  .  c o m*/
        int reply;
        ftp.connect(url);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.out.println("FTP connection failed for " + url);
        }
        ftp.enterLocalPassiveMode();
        ftp.login("anonymous", "");
        FTPFile[] files = ftp.listFiles(directory);
        for (FTPFile f : files) {
            filenameList.add(f.getName());
        }

        ftp.logout();

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return filenameList;
}

From source file:org.jnode.protocol.ftp.FTPURLConnection.java

/**
 * @see java.net.URLConnection#getInputStream()
 *//*from   w w  w  . j a  va  2 s. c  o m*/
public InputStream getInputStream() throws IOException {
    FTPClient client = new FTPClient();
    client.connect(host);
    String replyString = client.getReplyString();
    int replyCode = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        client.disconnect();
        throw new IOException(replyString);
    }
    if (!client.login(username, password)) {
        replyString = client.getReplyString();
        client.logout();
        throw new IOException(replyString);
    }
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        client.retrieveFile(path, os);
        client.logout();
    } finally {
        client.disconnect();
    }
    return new ByteArrayInputStream(os.toByteArray());
}

From source file:org.jumpmind.metl.core.runtime.resource.FtpDirectory.java

protected FTPClient createClient() {
    FTPClient ftpClient = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftpClient.configure(config);/*from  ww  w  . j a  v a2  s . c  o m*/

    if (connectTimeout != null) {
        ftpClient.setConnectTimeout(connectTimeout);
    }

    try {
        if (port != null) {
            ftpClient.connect(hostname, port);
        } else {
            ftpClient.connect(hostname);
        }

        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RuntimeException(
                    String.format("Failed to connect to %s.  Recevied a reply code of %d", hostname, reply));
        }

        if (isNotBlank(username)) {
            if (!ftpClient.login(username, password)) {
                throw new AuthenticationException();
            }
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        if (isNotBlank(basePath)) {
            ftpClient.changeWorkingDirectory(basePath);
        }
        return ftpClient;
    } catch (Exception e) {
        close();
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new IoException(e);
        }
    }

}