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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;//from ww  w . j  av  a2s  .c  o m
    try {
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }
        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }
        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:com.moosemorals.mediabrowser.FtpScanner.java

FtpScanner(PVR pvr, String remoteHostname) {
    this.pvr = pvr;
    this.remoteHostname = remoteHostname;

    FTPClientConfig config = new FTPClientConfig();
    config.setServerTimeZoneId(DEFAULT_TIMEZONE.getID());
    config.setServerLanguageCode("EN");

    ftp = new FTPClient();
    ftp.configure(config);//  ww w .j  ava2s  .c om
    if (debugFTP) {
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    }
    ftpRunning = new AtomicBoolean(false);

}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream2(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    File downloadFile1 = null;//  w  w  w.  j av  a  2  s .c o  m
    try {
        downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        //ftpClient.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) );
        //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD));
        //ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        boolean success;
        String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12";
        downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12");
        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
        success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12");
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12");
        InputStream is = fis;
        if (success) {
            System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf");
        } else {
            System.out.println("File #1 has been downloaded successfully. 3333");
        }
        ;
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * /*from  w w w  .j  av  a  2 s.c o  m*/
 *
 * @param remotePath ftp
 * @param fileName   ???
 * @param localPath  ???
 * @return true/false ?
 */
public boolean downloadFile(String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(remotePath);
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile file : files) {
            if (file.getName().equals(fileName)) {
                File localFile = new File(localPath + File.separator + file.getName());
                OutputStream outputStream = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), outputStream);
                outputStream.close();
            }
        }
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

private FTPClient connectMe() throws IOException {
    FTPClient ftpclient = new FTPClient();
    ftpclient.connect(configurator.host, configurator.port);

    if (ftpclient.login(configurator.username, configurator.password) == false) {
        ftpclient.logout();/*from  ww w. ja v a2 s  .  c  o m*/
        throw new IOException("Can't login to server");
    }
    int reply = ftpclient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply) == false) {
        ftpclient.disconnect();
        throw new IOException("Can't login to server");
    }

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

    if (configurator.passive) {
        ftpclient.enterLocalPassiveMode();
    } else {
        ftpclient.enterLocalActiveMode();
    }
    ftpclient.changeWorkingDirectory("/" + path);
    if (ftpclient.printWorkingDirectory().equals("/" + path) == false) {
        throw new IOException("Can't change working dir : " + "/" + path);
    }

    return ftpclient;
}

From source file:net.sf.jfilesync.plugins.net.items.TCommonsFTP_plugin.java

public TCommonsFTP_plugin() {
    ftpClient = new FTPClient();
    if (EncodingUtils.getJVMEnconding().equals("UTF-8")) {
        ftpClient.setControlEncoding("UTF-8");
    }/*w w  w.ja  va2 s  .  c om*/
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private void deleteChallengeFiles() {
    FTPClient ftp = new FTPClient();
    try {/*from w w w  . jav  a2  s . co m*/
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.changeWorkingDirectory(".well-known");
        ftp.changeWorkingDirectory("acme-challenge");

        FTPFile[] subFiles = ftp.listFiles();

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    continue;
                } else {
                    ftp.deleteFile(currentFileName);
                }
            }
        }
        ftp.changeToParentDirectory();
        ftp.removeDirectory("acme-challenge");
        ftp.changeToParentDirectory();
        ftp.removeDirectory(".well-known");
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *///from   w ww .ja  va2  s.  co  m
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

From source file:eu.prestoprime.plugin.fprint.FPrintTasks.java

@WfService(name = "fprint_upload", version = "0.8.0")
public void upload(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    logger.debug("Called " + this.getClass().getName());

    // prepare dynamic variables
    String id = dParamsString.get("id");
    String targetName = id + ".webm";
    String fileLocation = null;/*from  www .j a  v a2 s . c  o  m*/

    // prepare static variables
    String host = sParams.get("host");
    int port = Integer.parseInt(sParams.get("port"));
    String username = sParams.get("username");
    String password = sParams.get("password");
    String workdir = sParams.get("workdir");

    // retrieve AIP
    try {
        DIP dip = P4DataManager.getInstance().getDIPByID(id);
        List<String> fLocatList = dip.getAVMaterial("video/webm", "FILE");
        fileLocation = fLocatList.get(0);
    } catch (DataException | IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve the fileLocation of the Master Quality...");
    }

    logger.debug("Found video/webm location: " + fileLocation);

    // send to remote FTP folder
    FTPClient client = new FTPClient();
    try {
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                if (client.changeWorkingDirectory(workdir)) {
                    // TODO add behavior if file name is already present in
                    // remote ftp folder
                    // now OVERWRITES
                    File file = new File(fileLocation);
                    if (file.isFile()) {
                        if (client.storeFile(targetName, new FileInputStream(file))) {
                            logger.info("Stored file on server " + host + ":" + port + workdir);
                        } else {
                            throw new TaskExecutionFailedException("Cannot store file on server");
                        }
                    } else {
                        throw new TaskExecutionFailedException("Local file doesn't exist or is not acceptable");
                    }
                } else {
                    throw new TaskExecutionFailedException("Cannot browse directory " + workdir + " on server");
                }
            } else {
                throw new TaskExecutionFailedException("Username and Password not accepted by the server");
            }
        } else {
            throw new TaskExecutionFailedException(
                    "Cannot establish connection with server " + host + ":" + port);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("General exception with FTPClient");
    }

    logger.debug("Executed without errors " + this.getClass().getName());
}

From source file:AIR.Common.Web.FileFtpHandler.java

/**
 * Makes FTP call to the provided URI and retrieves contents
 *  //from w  w w .  ja  v  a 2 s  .  com
 * @param uri
 * @return ByteArrayInputStream
 * @throws FtpResourceException
 */
public static byte[] getBytes(URI uri) throws FtpResourceException {
    try {
        FTPClient ftp = new FTPClient();
        String[] credentialsAndHost = uri.getAuthority().split("@");
        String host = credentialsAndHost[1];
        String[] credentials = credentialsAndHost[0].split(":");

        ftp.connect(host);
        ftp.enterLocalPassiveMode();
        if (!ftp.login(credentials[0], credentials[1])) {
            ftp.logout();
            ftp.disconnect();
            throw new RuntimeException("FTP Authentication Failure");
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.logout();
            ftp.disconnect();
            throw new RuntimeException("FTP No reponse from server");
        }
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(uri.getPath(), output);
        output.close();
        ftp.logout();
        ftp.disconnect();
        return output.toByteArray();

    } catch (IOException ex) {
        throw new FtpResourceException(ex);
    }
}