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:models.LocalIndexer.java

public LocalIndexer(String ftp_addr) {
    //        documents_queue = new LinkedList();        
    ftp_address = ftp_addr;
    ftpClient = new FTPClient();
}

From source file:com.esri.gpt.control.webharvest.validator.WAFValidator.java

@Override
public boolean checkConnection(IMessageCollector mb) {
    if (url.toLowerCase().startsWith("ftp://")) {
        FTPClient client = null;// w ww  . j  a  v a2  s  .c o  m
        try {
            URL u = new URL(url);
            String host = u.getHost();
            int port = u.getPort() >= 0 ? u.getPort() : 21;
            client = new FTPClient();
            client.connect(host, port);
            CredentialProvider cp = getCredentialProvider();
            if (cp == null) {
                client.login("anonymous", "anonymous");
            } else {
                client.login(cp.getUsername(), cp.getPassword());
            }
            return true;
        } catch (MalformedURLException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestInvalidUrl");
            return false;
        } catch (IOException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestConnectionException");
            return false;
        } finally {
            if (client != null) {
                try {
                    client.disconnect();
                } catch (IOException ex) {
                }
            }
        }
    } else {
        return super.checkConnection(mb);
    }
}

From source file:com.starr.smartbuilds.service.FileService.java

public String getFile(Build build, ServletContext sc)
        throws FileNotFoundException, IOException, ParseException {

    /*if (fileName == null || fileName.equals("") || fileText == null || fileText.equals("")) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     } else {/*from  w  w w. jav  a2  s.c  o  m*/
     try {*/
    String path = sc.getRealPath("/");
    System.out.println(path);
    File dir = new File(path + "/builds");
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();
    }

    String fileName = path + "/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
    File fileBuild = new File(fileName);
    if (!fileBuild.exists() || fileBuild.isDirectory()) {
        String file_data = buildService.buildData(build, buildService.parseBlocks(build.getBlocks()));
        fileBuild.createNewFile();
        FileOutputStream fos = new FileOutputStream(fileBuild, false);
        fos.write(file_data.getBytes());
        fos.close();
    }

    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    try {
        client.connect("itelit.ftp.ukraine.com.ua");
        client.login("itelit_dor", "154896");

        // Create an InputStream of the file to be uploaded
        fis = new FileInputStream(fileBuild.getAbsolutePath());

        // Store file to server
        client.storeFile("builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json", fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*} catch (IOException ex) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     }
     }*/
    return "http://dor.it-elit.org/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
}

From source file:hd3gtv.storage.AbstractFileBridgeFtp.java

public AbstractFileBridgeFtp(StorageConfigurator configurator) throws IOException {
    this.configurator = configurator;
    ftpclient = new FTPClient();
    reconnect();/* w ww.java  2  s.  c o m*/

    if (configurator.path.equals("/") == false) {
        if (configurator.path.startsWith("/") == false) {
            configurator.path = "/" + configurator.path;
        }
        if (configurator.path.endsWith("/")) {
            configurator.path = configurator.path.substring(0, configurator.path.length() - 1);
        }

        root_path = configurator.path;
    } else {
        root_path = "/";
    }

    file = getRandomFtpFile(configurator.path);

    if (file == null) {
        throw new IOException("Can't found root path");
    }

    path = "/";
}

From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java

@Override
public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from www  . j a  va2  s.  c  o  m
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return//ww  w . jav  a 2s. co m
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java

/**
 * {@inheritDoc}/*www.  jav  a2 s  .c  o  m*/
 */
@Override
public FetchedResourceFtp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final FTPClient ftpClient = new FTPClient();
    ftpClient.setSoTimeout(socketTimeout);
    ftpClient.setDataTimeout(dataTimeout);

    try {
        final String host = targetResource.getHost();
        final String resourceName = targetResource.getPath();

        LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName);

        ftpClient.connect(host);
        ftpClient.enterLocalPassiveMode();

        if (!ftpClient.login("anonymous", "japt-proxy")) {
            throw new IOException("Can't login to FTP server");
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        final FTPFile[] files = ftpClient.listFiles(resourceName);

        if (files.length == 0) {
            throw new ResourceUnavailableException("Resource '" + resourceName + "' not found");
        }

        if (files.length > 1) {
            throw new IOException("Multiple files found");
        }

        final FTPFile file = files[0];

        final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file);
        fetchedResourceFtp
                .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis());

        return fetchedResourceFtp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceFtp
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }

        throw e;
    }
}

From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java

public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName,
        String originalFileName) {
    if (logger.isDebugEnabled()) {
        logger.debug("SampleUploadCluster.process called");
    }//w  ww.  j  a  v a 2  s. c o m
    FTPClient ftp = new FTPClient();
    OutputStream out = null;
    File file = new File(sourceRepositoryPath + "/" + maskingFileName);
    FileInputStream fin = null;
    BufferedInputStream bin = null;
    String storeFileName = null;
    String server = "?IP";//??  ? . ex) 210.25.3.21
    try {
        ftp.connect(server);
        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            storeFileName = maskingFileName
                    + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            ftp.login("testId",
                    "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length()));
            if (logger.isDebugEnabled()) {
                logger.debug(server + " connect success !!! ");
            }
            ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/");
            out = ftp.storeFileStream(storeFileName);
            FileCopyUtils.copy(fin, out);
            if (logger.isDebugEnabled()) {
                logger.debug(" cluster success !!! ");
            }
        } else {
            ftp.disconnect();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (bin != null)
                bin.close();
            ftp.logout();
            out = null;
            bin = null;
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}

From source file:co.nubetech.hiho.mapreduce.OracleLoadMapper.java

protected void setup(Mapper.Context context) throws IOException, InterruptedException {

    String ip = context.getConfiguration().get(HIHOConf.ORACLE_FTP_ADDRESS);
    String portno = context.getConfiguration().get(HIHOConf.ORACLE_FTP_PORT);
    String usr = context.getConfiguration().get(HIHOConf.ORACLE_FTP_USER);
    String pwd = context.getConfiguration().get(HIHOConf.ORACLE_FTP_PASSWORD);
    String dir = context.getConfiguration().get(HIHOConf.ORACLE_EXTERNAL_TABLE_DIR);
    logger.debug("ip is " + ip);
    logger.debug("port, usr, password are " + portno + ", " + usr + ", " + pwd + "," + dir);
    if (ftpClient == null) {
        ftpClient = new FTPClient();
    }/* w  w  w .  j  av  a 2  s  . c  om*/

    ftpClient.connect(ip, Integer.parseInt(portno));
    logger.debug("Found connection");
    ftpClient.login(usr, pwd);
    logger.debug("Logged in to remote server");
    ftpClient.changeWorkingDirectory(dir);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
}

From source file:com.netsteadfast.greenstep.util.FtpClientUtils.java

public FtpClientUtils() {
    ftpClient = new FTPClient();
    ftpClient.setBufferSize(100000);
}