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

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

Introduction

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

Prototype

public FTPSClient() 

Source Link

Document

Constructor for FTPSClient, calls #FTPSClient(String,boolean) .

Usage

From source file:ftp.FTPHelper.java

public void connect() throws IOException {
    if (isFtps()) {
        ftp = new FTPSClient();

    } else {/*from  www  . j  av  a  2 s .c  o m*/

        ftp = new FTPClient();
        ftp.connect(url);
        ftp.login(username, password);

    }

}

From source file:it.greenvulcano.util.remotefs.ftp.FTPSManager.java

/**
 * Create a new FTPSClient object/*ww w  .  j  a  v a 2s  .  com*/
 * 
 * @see it.greenvulcano.util.remotefs.ftp.FTPManager#createFTPClient()
 */
@Override
protected FTPClient createFTPClient() throws RemoteManagerException {
    try {
        return new FTPSClient();
    } catch (NoSuchAlgorithmException exc) {
        throw new RemoteManagerException("Error instantiating FTPSClient", exc);
    }
}

From source file:com.shadwelldacunha.byteswipe.connection.FTPSHelper.java

public FTPSHelper(String host, String username, String password, int port) {
    super(host, username, password, port);
    //TODO: Handle proxy
    this.ftps = new FTPSClient();
    //TODO: Handle set hidden files through config
    this.ftps.setListHiddenFiles(true);
}

From source file:de.aw.awlib.utils.AWRemoteFileServerHandler.java

public AWRemoteFileServerHandler(AWRemoteFileServer remoteFileServer, ExecutionListener executionListener) {
    mRemoteFileServer = remoteFileServer;
    mExecutionListener = executionListener;
    switch (remoteFileServer.getConnectionType()) {
    case SSL:/*  ww w .ja  v a2 s.c  om*/
        mClient = new FTPSClient();
        break;
    case NONSSL:
        mClient = new FTPClient();
        break;
    default:
        mClient = null;
    }
}

From source file:com.adaptris.core.ftp.ClientSettingsTest.java

@Test
public void testPreConnectSettings_FTPS() {
    FTPSClient client = new FTPSClient();
    preConnectSettings(client, FTPS.values(), createFtpsSettings());
    assertTrue(client.isEndpointCheckingEnabled());
    // Not Connected yet, so these will not be the same.
    assertFalse(client.getNeedClientAuth());
    assertFalse(client.getUseClientMode());
    assertFalse(client.getWantClientAuth());
    assertNull(client.getEnabledCipherSuites());
    assertNull(client.getEnabledProtocols());
}

From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpsFileInstance.java

@Override
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException {
    FilePathItem fpi = getFilePathItem();
    FTPClient f = new FTPSClient();
    f.connect(fpi.getHost());/*from w w w  .  j a  va2s  .co  m*/
    f.login(fpi.getUsername(), fpi.getPassword());
    return f;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * /*from   www  .  j a  v  a2s .co m*/
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

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

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

From source file:com.cloudhopper.commons.rfs.provider.FtpRemoteFileSystem.java

public void connect() throws FileSystemException {
    // make sure we don't connect twice
    if (ftp != null) {
        throw new FileSystemException("Already connected to FTP(s) server");
    }/*  ww  w  .j a v a  2 s. c  o  m*/

    // either create an SSL FTP client or normal one
    if (getProtocol() == Protocol.FTPS) {
        try {
            ftp = new FTPSClient();
        } catch (Exception e) { //} catch (NoSuchAlgorithmException e) {
            throw new FileSystemException("Unable to create FTPS client: " + e.getMessage(), e);
        }
    } else {
        ftp = new FTPClient();
    }

    //
    // connect to ftp(s) server
    //
    try {
        int reply;

        // either connect to the default port or an overridden one
        if (getURL().getPort() == null) {
            ftp.connect(getURL().getHost());
        } else {
            ftp.connect(getURL().getHost(), getURL().getPort().intValue());
        }

        // After connection attempt, check reply code to verify we're connected
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            // make sure we're definitely disconnected before we throw exception
            try {
                ftp.disconnect();
            } catch (Exception e) {
            }
            ftp = null;
            throw new FileSystemException("FTP server refused connection (replyCode=" + reply + ")");
        }

        logger.info("Connected to remote FTP server @ " + getURL().getHost() + " (not authenticated yet)");

    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Exception ex) {
            }
        }
        ftp = null;
        throw new FileSystemException("Unabled to connect to FTP server @ " + getURL().getHost(), e);
    }

    //
    // login either anonymously or with user/pass combo
    //
    try {
        boolean loggedIn = false;
        if (getURL().getUsername() == null) {
            logger.info("Logging in anonymously to FTP server");
            loggedIn = ftp.login("anonymous", "");
        } else {
            logger.info("Logging in with username and password to FTP server");
            loggedIn = ftp.login(getURL().getUsername(),
                    (getURL().getPassword() == null ? "" : getURL().getPassword()));
        }

        // did the login work?
        if (!loggedIn) {
            throw new FileSystemException("Login failed with FTP server (reply=" + ftp.getReplyString() + ")");
        }

        //
        // if we're using a secure protocol, encrypt the data channel
        //
        if (getProtocol() == Protocol.FTPS) {
            logger.info("Requesting FTP data channel to also be encrypted with SSL/TLS");
            ((FTPSClient) ftp).execPROT("P");
            // ignore if this actually worked or not -- file just fail to copy
        }

        //
        // make sure we're using binary files
        //
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            throw new FileSystemException(
                    "FTP server failed to switch to binary file mode (reply=" + ftp.getReplyString() + ")");
        }

        // should we go into passive or active mode?
        if (mode == Mode.ACTIVE) {
            ftp.enterLocalActiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new FileSystemException(
                        "FTP server failed to switch to active mode (reply=" + ftp.getReplyString() + ")");
            }
        } else if (mode == Mode.PASSIVE) {
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new FileSystemException(
                        "FTP server failed to switch to passive mode (reply=" + ftp.getReplyString() + ")");
            }
        }

        //
        // handle making or changing directories
        //
        // if the path is not empty
        if (!StringUtil.isEmpty(getURL().getPath())) {
            // recursively iterate thru directory path and attempt to create the path
            StringTokenizer path = new StringTokenizer(getURL().getPath(), "/");

            // create an array list of tokens
            ArrayList<String> pathParts = new ArrayList<String>();
            while (path.hasMoreTokens()) {
                pathParts.add(path.nextToken());
            }

            // index we'll start searching for
            int i = 0;

            // determine path of directories we're going to take
            if (pathParts.size() > 0 && pathParts.get(i).equals("~")) {
                // stay in home directory once logged in
                // just increment what we'll search from
                i = 1;
            } else {
                // change to root directory first
                if (!ftp.changeWorkingDirectory("/")) {
                    throw new FileSystemException("FTP server failed to change to root directory (reply="
                            + ftp.getReplyString() + ")");
                }
            }

            for (; i < pathParts.size(); i++) {
                // try to change to this directory
                String pathPart = pathParts.get(i);
                boolean changedDir = ftp.changeWorkingDirectory(pathPart);
                if (!changedDir) {
                    if (!mkdir) {
                        // now try to change to it again
                        if (!ftp.changeWorkingDirectory(pathPart)) {
                            throw new FileSystemException("Unable to change to directory " + getURL().getPath()
                                    + " on FTP server: " + pathPart + " does not exist");
                        }
                    } else {
                        // try to create it
                        logger.info("Making new directory on FTP server: " + pathPart);
                        if (!ftp.makeDirectory(pathPart)) {
                            throw new FileSystemException(
                                    "Unable to make directory '" + pathPart + "' on FTP server");
                        }
                        // now try to change to it again
                        if (!ftp.changeWorkingDirectory(pathPart)) {
                            throw new FileSystemException(
                                    "Unable to change to new directory '" + pathPart + "' on FTP server");
                        }
                    }
                }
            }

            // just print out our working directory
        } else {
            // staying in whatever directory we were assigned by default
            // for information purposeds, let's try to print out that dir
            String currentDir = ftp.printWorkingDirectory();
            logger.info("Current FTP working directory: " + currentDir);
        }

    } catch (FileSystemException e) {
        // make sure to disconnect, then rethrow error
        try {
            ftp.disconnect();
        } catch (Exception ex) {
        }
        ftp = null;
        throw e;
    } catch (IOException e) {
        // make sure we're definitely disconnected before we throw exception
        try {
            ftp.disconnect();
        } catch (Exception ex) {
        }
        ftp = null;
        throw new FileSystemException("Underlying IO exception with FTP server during login and setup process",
                e);
    }
}

From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);/*from  w w w . j  a v a  2 s  .  c  om*/
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:IHM.FenetreAjoutAffiche.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {//  w  ww  . j  av  a2  s  .c o m
        FileInputStream input = null;
        try {
            input = new FileInputStream(nomF);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex);
        }
        FTPSClient ftpClient = new FTPSClient();

        ftpClient.connect("iutdoua-samba.univ-lyon1.fr", 990);
        Properties props = new Properties();
        FileInputStream fichier = new FileInputStream("src/info.properties");
        props.load(fichier);
        ftpClient.login(props.getProperty("login"), props.getProperty("password"));

        System.out.println(ftpClient.getReplyString());

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

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

        String remote;

        remote = "public_html/CPOA/Site/assets/affichesFilm/" + txtNomPhoto.getText();

        boolean done = ftpClient.storeFile(remote, input);
        input.close();

        if (done) {

            System.out.println("reussi");

            this.affiche.setNom(txtNomPhoto.getText());

            etat = true;

            this.dispose();
        } else {
            System.out.println(ftpClient.getReplyString());
            this.dispose();
        }

    } catch (IOException ex) {
        Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex);
    }
}