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:org.fabric3.transport.ftp.server.host.F3FtpHostTest.java

public void testInvalidLogin() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(InetAddress.getLocalHost(), 1234);
    ftpClient.user("user");
    assertEquals(530, ftpClient.pass("password1"));
}

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();//from w w  w . j a  v a  2 s .c o m
    ftpClient.storeFile("/resource/test.dat", new ByteArrayInputStream("TEST\r\n".getBytes()));
}

From source file:org.fao.fenix.ftp.FTPTask.java

public void connectToFTP(String datasetDirectoryName) {
    FTPClient newFtpClient = new FTPClient();
    setFtpClient(newFtpClient);
    checkFTPDirectory(datasetDirectoryName);
}

From source file:org.giswater.util.UtilsFTP.java

public boolean connect() {

    boolean ok = false;
    if (client == null) {
        client = new FTPClient();
    }//from  w  w w .j  a  v  a 2s  .  c o  m

    try {
        // Connecting client
        if (port > 0) {
            client.connect(host, port);
        } else {
            client.connect(host);
        }

        // Check connection
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnect();
        } else {
            setFtpOptions();
            ok = true;
        }
    } catch (SocketException e) {
        Utils.logError(e);
        disconnect();
    } catch (IOException e) {
        Utils.logError(e);
        disconnect();
    }

    return ok;

}

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 {/*w  w  w .j  a  v  a 2  s.c om*/
            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.glassfish.common.util.admin.MapInjectionResolver.java

private void FormatUriToFile() throws IOException {
    List<String> value = parameters.get("DEFAULT");
    String uri = value.get(0);//from   w  ww . ja va2 s. co  m
    URL url = new URL(uri);
    File file = null;

    if (uri.startsWith("file:/")) {
        file = new File(url.getFile());
    } else if (uri.startsWith("http://")) {
        InputStream inStream = url.openStream();
        BufferedInputStream bufIn = new BufferedInputStream(inStream);

        file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
        if (file.exists()) {
            file.delete();
        }
        OutputStream out = new FileOutputStream(file);
        BufferedOutputStream bufOut = new BufferedOutputStream(out);
        byte buffer[] = new byte[204800];
        while (true) {
            int nRead = bufIn.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            bufOut.write(buffer, 0, nRead);
        }
        bufOut.flush();
        out.close();
        inStream.close();
    } else if (uri.startsWith("ftp://")) {
        String pattern = "^ftp://(.+?)(:.+?)?@(\\S+):(\\d+)(\\S+)$";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(uri);
        if (m.matches()) {
            String username = m.group(1);
            String password = "";
            if (m.group(2) != null) {
                password = m.group(2).replace(":", "");
            }
            String ipAddress = m.group(3);
            String port = m.group(4);
            String path = m.group(5);
            FTPClient ftp = new FTPClient();
            ftp.connect(ipAddress);
            ftp.setDefaultPort(Integer.parseInt(port));
            boolean isLogin = ftp.login(username, password);
            if (isLogin) {
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                byte[] buf = new byte[204800];
                int bufsize = 0;

                file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
                if (file.exists()) {
                    file.delete();
                }
                OutputStream ftpOut = new FileOutputStream(file);
                InputStream ftpIn = ftp.retrieveFileStream(path);
                System.out.println(ftpIn);
                while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
                    ftpOut.write(buf, 0, bufsize);
                }
                ftpOut.flush();
                ftpOut.close();
                ftpIn.close();
            } else {
                ftp.logout();
                ftp.disconnect();
            }
        } else {
            localStrings.getLocalString("IncorrectFtpAddress",
                    "The ftp address is not correct, please change another one.");
        }
    }
    if (file != null)
        parameters.set("DEFAULT", file.getAbsolutePath());
}

From source file:org.gogpsproject.parser.rinex.RinexNavigation.java

private RinexNavigationParser getFromFTP(String url) throws IOException {
    RinexNavigationParser rnp = null;/* ww  w. j a  v  a 2 s  . c om*/

    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;//from  w w  w . j a va  2  s .c o  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.greenpole.util.file.transfer.FileTransfer.java

public FileTransfer(String username, String password, String host, int portNumber)
        throws IOException, Exception {
    ftp = new FTPClient();
    int reply;/*  w  w w  .  j  a  v a  2  s. co m*/
    ftp.connect(host, portNumber);

    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        logger.info("Exception in connecting to FTP Server");
        throw new Exception("Exception in connecting to FTP Server");
    }
    logger.info("Connected to ftp server successfully - {} ", username);
    ftp.login(username, password);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.enterLocalPassiveMode();

}

From source file:org.grouter.core.readers.FtpReaderJob.java

/**
 * Use configuration parameters to create a connection to the ftp endpoint.
 * @return a FTPClient instance//  www. j  a  va2  s .  c o m
 * @throws Exception if connection problems
 */
private FTPClient initConnection() throws Exception {
    FTPClient client;
    String host = null;
    String strPort;
    try {

        Map map = node.getInBound().getEndPointContext();
        host = node.getInBound().getUri();
        strPort = (String) map.get(FTP_PORT);
        client = new FTPClient();
        int port = FTP_DEFAULT_PORT;
        if (StringUtils.isNotEmpty(strPort)) {
            port = Integer.parseInt(strPort);
            client.connect(host, port);
            int reply = client.getReplyCode();
            logger.debug("reply :" + reply);
            if (FTPReply.isPositiveCompletion(reply)) {
                logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress());
            }
        } else {
            client.connect(host, port);
            int reply = client.getReplyCode();
            logger.debug("reply :" + reply);
            if (FTPReply.isPositiveCompletion(reply)) {
                logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress());
            }

        }

        String user = (String) map.get(FTP_AUTH_USER);
        String pwd = (String) map.get(FTP_AUTH_PASSWORD);
        if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pwd)) {
            client.login(user, pwd);
            int replyCode = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("Logged into ftp server :" + host);
            }
        } else {
            client.login("anonymous", "mymail@mail.com");
            int replyCode = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("Logged into ftp server :" + host);
            }
        }
    } catch (Exception e) {
        throw new Exception("Could not establish connection with ftp endpoint using host:" + host, e);
    }
    return client;
}