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

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

Introduction

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

Prototype

public boolean changeWorkingDirectory(String pathname) throws IOException 

Source Link

Document

Change the current working directory of the FTP session.

Usage

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

/**
 * Runs the task./*from  w ww.j a  v a2s.c o 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;//ww w.  j a  va  2s  .  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.compiere.model.MMediaServer.java

/**
 *    (Re-)Deploy all media//from ww w . j av  a 2  s.c om
 *    @param media array of media to deploy
 *    @return true if deployed
 */
public boolean deploy(MMedia[] media) {
    // Check whether the host is our example localhost, we will not deploy locally, but this is no error
    if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
        log.warning("You have not defined your own server, we will not really deploy to localhost!");
        return true;
    }

    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getIP_Address());
        if (ftp.login(getUserName(), getPassword()))
            log.info("Connected to " + getIP_Address() + " as " + getUserName());
        else {
            log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
        return false;
    }

    boolean success = true;
    String cmd = null;
    //   List the files in the directory
    try {
        cmd = "cwd";
        ftp.changeWorkingDirectory(getFolder());
        //
        cmd = "list";
        String[] fileNames = ftp.listNames();
        log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);

        /*
        FTPFile[] files = ftp.listFiles();
        log.config("Number of files in " + getFolder() + ": " + files.length);
        for (int i = 0; i < files.length; i++)
           log.fine(files[i].getTimestamp() + " \t" + files[i].getName());*/
        //
        cmd = "bin";
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //
        for (int i = 0; i < media.length; i++) {
            if (!media[i].isSummary()) {
                log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                MImage thisImage = media[i].getImage();

                // Open the file and output streams
                byte[] buffer = thisImage.getData();
                ByteArrayInputStream is = new ByteArrayInputStream(buffer);

                String fileName = media[i].get_ID() + media[i].getExtension();
                cmd = "put " + fileName;
                ftp.storeFile(fileName, is);
                is.close();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
        success = false;
    }
    //   Logout from the FTP Server and disconnect
    try {
        cmd = "logout";
        ftp.logout();
        cmd = "disconnect";
        ftp.disconnect();
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
    }
    ftp = null;
    return success;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/** 
 * ?//from   www  . j a v a2 s  .  c o  m
 * <p>??</p>
 *
 * @author  covito
 * @param ftp
 * @param path
 * @param mkdir true?
 * @return
 */
protected boolean dealDocPath(FTPClient ftp, String path, boolean mkdir) {
    String doc = path.substring(0, path.indexOf("/"));
    try {
        boolean success = ftp.changeWorkingDirectory(rootWorkingDirectory + "/" + doc);
        if (!success) {
            if (mkdir) {
                ftp.mkd(rootWorkingDirectory + "/" + doc);
                return ftp.changeWorkingDirectory(rootWorkingDirectory + "/" + doc);
            }
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

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()
 * //w w w .j a  va  2  s  .  co  m
 * @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.gogpsproject.parser.rinex.RinexNavigation.java

private RinexNavigationParser getFromFTP(String url) throws IOException {
    RinexNavigationParser rnp = null;/*w  ww  .  ja va2 s.  c o m*/

    String origurl = url;
    if (negativeChache.containsKey(url)) {
        if (System.currentTimeMillis() - negativeChache.get(url).getTime() < 60 * 60 * 1000) {
            throw new FileNotFoundException("cached answer");
        } else {
            negativeChache.remove(url);
        }
    }

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File rnf = new File(RNP_CACHE, filename);

    if (!rnf.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

            // 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 null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                negativeChache.put(origurl, new Date());
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            rnp = new RinexNavigationParser(uis, rnf);
            rnp.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + rnf);
        rnp = new RinexNavigationParser(rnf);
        rnp.init();
    }
    return rnp;
}

From source file:org.gogpsproject.parser.sp3.SP3Navigation.java

private SP3Parser getFromFTP(String url) throws IOException {
    SP3Parser sp3p = null;/*ww w.java 2s .  co m*/

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File sp3f = new File(SP3_CACHE, filename);

    if (!sp3f.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

            // 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 null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            sp3p = new SP3Parser(uis, sp3f);
            sp3p.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + sp3f);
        sp3p = new SP3Parser(sp3f);
        sp3p.init();
    }
    return sp3p;
}

From source file:org.jboss.ejb3.examples.ch06.filetransfer.FileTransferBean.java

@Override
public void cd(final String directory) {
    // Get the client
    final FTPClient client = this.getClient();

    // Exec cd/*from w w  w  . ja  v a 2s . c om*/
    try {
        // Exec cd
        client.changeWorkingDirectory(directory);

        // Check reply for success
        this.checkLastOperation();
    } catch (final Exception e) {
        throw new FileTransferException("Could not change working directory to \"" + directory + "\"", e);
    }

    // Set the pwd (used upon activation)
    log.info("cd > " + directory);
    this.setPresentWorkingDirectory(directory);
}

From source file:org.jevis.commons.driver.DataSourceHelper.java

public static List<String> getFTPMatchedFileNames(FTPClient fc, DateTime lastReadout, String filePath) {
    filePath = filePath.replace("\\", "/");
    String[] pathStream = getPathTokens(filePath);

    String startPath = "";
    if (filePath.startsWith("/")) {
        startPath = "/";
    }// w  w w .j  av a2  s .co  m

    List<String> folderPathes = getMatchingPathes(startPath, pathStream, new ArrayList<String>(), fc,
            lastReadout, new DateTimeFormatterBuilder());
    //        System.out.println("foldersize,"+folderPathes.size());
    List<String> fileNames = new ArrayList<String>();

    if (folderPathes.isEmpty()) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Cant find suitable folder on the device");
        return fileNames;
    }

    //        String fileName = null;
    String fileNameScheme = pathStream[pathStream.length - 1];
    String currentfolder = null;
    try {
        for (String folder : folderPathes) {
            //                fc.changeWorkingDirectory(folder);
            //                System.out.println("currentFolder,"+folder);
            currentfolder = folder;
            //                for (FTPFile file : fc.listFiles(folder)) {
            //                    System.out.println(file.getName());
            //                }
            fc.changeWorkingDirectory(folder);
            for (FTPFile file : fc.listFiles()) {
                //                    org.apache.log4j.Logger.getLogger(Launcher.class.getName()).log(org.apache.log4j.Level.ALL, "CurrentFileName: " + fileName);
                //                    fileName = removeFoler(fileName, folder);
                if (file.getTimestamp().compareTo(lastReadout.toGregorianCalendar()) < 0) {
                    continue;
                }
                boolean match = false;
                System.out.println(file.getName());
                if (DataSourceHelper.containsTokens(fileNameScheme)) {
                    boolean matchDate = matchDateString(file.getName(), fileNameScheme);
                    DateTime folderTime = getFileTime(folder + file.getName(), pathStream);
                    boolean isLater = folderTime.isAfter(lastReadout);
                    if (matchDate && isLater) {
                        match = true;
                    }
                } else {
                    Pattern p = Pattern.compile(fileNameScheme);
                    Matcher m = p.matcher(file.getName());
                    match = m.matches();
                }
                if (match) {
                    fileNames.add(folder + file.getName());
                }
            }
        }
    } catch (IOException ex) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                ex.getMessage());
    } catch (Exception ex) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Error while searching a matching file");
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Folder: " + currentfolder);
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "FileName: " + fileNameScheme);
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                ex.getMessage());
    }
    if (folderPathes.isEmpty()) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Cant find suitable files on the device");
    }
    //        System.out.println("filenamesize"+fileNames.size());
    return fileNames;
}

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);//  ww w  . j  a  v a2 s.  co 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);
        }
    }

}