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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:com.logic.test.FTPSLogic.java

public static void main(String[] args) {
    String serverAdress = "62.2.176.167";
    String username = "RLSFTPRead";
    String password = "ftp4rls";
    int port = 990;
    FTPSClient ftpsClient = new FTPSClient("TLS", true);
    String remoteFile = "REM - Persons Extract.csv";
    File localFile = new File("Persons Extract.csv");

    try {/*from   w w w  .  j ava2 s  .c o m*/
        TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        //ftpsClient.setTrustManager(trustManager[0]);
        //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //kmf.init(null, null);
        //KeyManager km = kmf.getKeyManagers()[0];

        //ftpsClient.setKeyManager(km);
        ftpsClient.setBufferSize(1024 * 1024);
        ftpsClient.setConnectTimeout(100000);
        ftpsClient.connect(InetAddress.getByName(serverAdress), port);
        ftpsClient.setSoTimeout(100000);

        if (ftpsClient.login(username, password)) {
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.changeWorkingDirectory("/");
            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpsClient.enterLocalPassiveMode();

            //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile));
            for (FTPFile file : ftpsClient.listFiles()) {
                System.out.println("Nom " + file.getName());
            }

        }
    } catch (SocketException e) {
        ;
    } catch (UnknownHostException e) {
        ;
    } catch (IOException e) {
        ;
    } catch (Exception e) {
        ;
    } finally {
        try {
            ftpsClient.logout();
        } catch (Exception e2) {
        }

        try {
            ftpsClient.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:examples.ftp.FTPSExample.java

public static final void main(String[] args) throws NoSuchAlgorithmException {
    int base = 0;
    boolean storeFile = false, binaryTransfer = false, error = false;
    String server, username, password, remote, local;
    String protocol = "SSL"; // SSL/TLS
    FTPSClient ftps;

    for (base = 0; base < args.length; base++) {
        if (args[base].startsWith("-s"))
            storeFile = true;/*from   w  ww . j a  v a  2s  .  c om*/
        else if (args[base].startsWith("-b"))
            binaryTransfer = true;
        else
            break;
    }

    if ((args.length - base) != 5) {
        System.err.println(USAGE);
        System.exit(1);
    }

    server = args[base++];
    username = args[base++];
    password = args[base++];
    remote = args[base++];
    local = args[base];

    ftps = new FTPSClient(protocol);

    ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

    try {
        int reply;

        ftps.connect(server);
        System.out.println("Connected to " + server + ".");

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftps.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftps.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftps.isConnected()) {
            try {
                ftps.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        ftps.setBufferSize(1000);

        if (!ftps.login(username, password)) {
            ftps.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftps.getSystemName());

        if (binaryTransfer)
            ftps.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftps.enterLocalPassiveMode();

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftps.storeFile(remote, input);

            input.close();
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftps.retrieveFile(remote, output);

            output.close();
        }

        ftps.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftps.isConnected()) {
            try {
                ftps.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:IHM.FenetreAjoutAffiche.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {//from  www.j ava 2  s . com
        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);
    }
}

From source file:IHM.FenetreAjoutPhoto.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {//w  ww. ja va 2  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")); // on tablit les paramtre de connexion et on fournit les identifiants

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

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

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

        String remote = null;

        if (this.radioBtnPhoto.isSelected()) //si l'utilisateur beut choisir une photo classique on choisit le bon rpertoire d'arriver
        {
            remote = "public_html/CPOA/Site/assets/photos/" + txtNomPhoto.getText();

            this.laPhoto.setTypePhoto(1);

        } else if ((this.radioBtnPhotoP.isSelected())) // de mme si c'est une photo de profil
        {
            remote = "public_html/CPOA/Site/assets/photoProfil/" + txtNomPhoto.getText();
            this.laPhoto.setTypePhoto(2);
        }

        boolean done = ftpClient.storeFile(remote, input); // on upload la photo
        input.close();

        if (done) // on teste si le transfert est russi
        {

            System.out.println("reussi");

            this.laPhoto.setNomPhoto(txtNomPhoto.getText());

            this.laPhoto.setLieu(txtLieu.getText());

            String dateD = txtAnneeD.getText() + "-" + txtMoisD.getText() + "-" + txtJourD.getText();
            this.laPhoto.setDatePhoto(dateD);

            etat = true;

            this.dispose();
        } else {
            System.out.println(ftpClient.getReplyString()); // on affiche la rponse du serveur si le transfert est rat
            this.dispose();
        }

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

From source file:ddf.test.itests.catalog.TestFtp.java

private FTPSClient createSecureClient(boolean setKeystore) throws Exception {
    FTPSClient ftps = new FTPSClient();

    if (setKeystore) {
        KeyManager keyManager = KeyManagerUtils.createClientKeyManager(
                new File(System.getProperty("javax.net.ssl.keyStore")),
                System.getProperty("javax.net.ssl.keyStorePassword"));
        ftps.setKeyManager(keyManager);/* w w  w  .  j av a2s .  c o m*/
    }

    int attempts = 0;
    while (true) {
        try {
            ftps.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()));
            break;
        } catch (SocketException e) {
            // a socket exception can be thrown if the ftp server is still in the process of coming up
            // or down
            Thread.sleep(1000);
            if (attempts++ > 30) {
                throw e;
            }
        }
    }

    showServerReply(ftps);
    int connectionReply = ftps.getReplyCode();
    if (!FTPReply.isPositiveCompletion(connectionReply)) {
        fail("FTP server refused connection: " + connectionReply);
    }

    boolean success = ftps.login(USERNAME, PASSWORD);
    showServerReply(ftps);
    if (!success) {
        fail("Could not log in to the FTP server.");
    }

    ftps.enterLocalPassiveMode();
    ftps.setControlKeepAliveTimeout(300);
    ftps.setFileType(FTP.BINARY_FILE_TYPE);

    return ftps;
}

From source file:org.mule.transport.ftps.FtpsConnector.java

/**
 * Passive mode is OFF by default. The value is taken from the connector
 * settings. In case there are any overriding properties set on the endpoint,
 * those will be used./*from  ww  w. j  ava 2s .c o m*/
 *
 * @see #setPassive(boolean)
 */
public void enterActiveOrPassiveMode(FTPSClient client, ImmutableEndpoint endpoint) {
    // well, no endpoint URI here, as we have to use the most common denominator
    // in API :(
    final String passiveString = (String) endpoint.getProperty(FtpsConnector.PROPERTY_PASSIVE_MODE);
    if (passiveString == null) {
        // try the connector properties then
        if (isPassive()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP passive mode");
            }
            client.enterLocalPassiveMode();
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP active mode");
            }
            client.enterLocalActiveMode();
        }
    } else {
        // override with endpoint's definition
        final boolean passiveMode = Boolean.valueOf(passiveString).booleanValue();
        if (passiveMode) {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP passive mode (endpoint override)");
            }
            client.enterLocalPassiveMode();
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Entering FTP active mode (endpoint override)");
            }
            client.enterLocalActiveMode();
        }
    }
}

From source file:org.wso2.iot.agent.services.FileDownloadService.java

/**
 * This method downloads the file using sftp client.
 *
 * @param operation      - operation object.
 * @param host           - host address.
 * @param ftpUserName    - ftp user name.
 * @param ftpPassword    - ftp password.
 * @param savingLocation - location in the device to save the file.
 * @param fileName       - name of the file to download.
 * @param serverPort     - ftp server port.
 * @param fileDirectory  - the directory of the file in FTP server.
 * @throws AndroidAgentException - Android agent exception.
 *//*from   ww  w  . java 2s  .c  o m*/
private void downloadFileUsingFTPSClient(Operation operation, String host, String ftpUserName,
        String ftpPassword, String savingLocation, String fileName, int serverPort, String fileDirectory)
        throws AndroidAgentException {
    FTPSClient ftpsClient = new FTPSClient();
    FileOutputStream fileOutputStream = null;
    OutputStream outputStream = null;
    String response;
    try {
        ftpsClient.connect(host, serverPort);
        if (ftpsClient.login(ftpUserName, ftpPassword)) {
            ftpsClient.enterLocalPassiveMode();
            ftpsClient.execPROT("P");
            fileOutputStream = new FileOutputStream(savingLocation + File.separator + fileName);
            outputStream = new BufferedOutputStream(fileOutputStream);
            ftpsClient.changeWorkingDirectory(fileDirectory);
            if (ftpsClient.retrieveFile(fileName, outputStream)) {
                response = "File uploaded to the device successfully ( " + fileName + " ).";
                operation.setStatus(resources.getString(R.string.operation_value_completed));
            } else {
                response = "File uploaded to the device not completed ( " + fileName + " ).";
                operation.setStatus(resources.getString(R.string.operation_value_error));
            }
        } else {
            response = ftpUserName + " - FTP login failed.";
            operation.setStatus(resources.getString(R.string.operation_value_error));
        }
        operation.setOperationResponse(response);
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e);
    } finally {
        try {
            if (ftpsClient.isConnected()) {
                ftpsClient.logout();
                ftpsClient.disconnect();
            }
        } catch (IOException ignored) {
        }
        cleanupStreams(null, outputStream, null, fileOutputStream, null, null, null, null);
    }
}

From source file:org.wso2.iot.agent.services.FileUploadService.java

/**
 * File upload operation using an FTPS explicit TLS client.
 *
 * @param operation       - operation object.
 * @param host            - host name.// ww w .  j  a v a 2  s.c  om
 * @param ftpUserName     - ftp user name.
 * @param ftpPassword     - ftp password.
 * @param uploadDirectory - ftp directory to upload file.
 * @param fileLocation    - local file location.
 * @param serverPort      - ftp port to connect.
 * @throws AndroidAgentException - AndroidAgent exception.
 */
private void uploadFileUsingFTPSClient(Operation operation, String host, String ftpUserName, String ftpPassword,
        String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException {
    FTPSClient ftpsClient = new FTPSClient();
    String fileName = null;
    InputStream inputStream = null;
    Boolean loginResult = false;
    String response;
    try {
        File file = new File(fileLocation);
        fileName = file.getName();
        ftpsClient.connect(host, serverPort);
        ftpsClient.enterLocalPassiveMode();
        loginResult = ftpsClient.login(ftpUserName, ftpPassword);
        ftpsClient.execPROT("P");
        inputStream = new FileInputStream(file);
        ftpsClient.changeWorkingDirectory(uploadDirectory);
        if (ftpsClient.storeFile(fileName, inputStream)) {
            response = "File uploaded from the device completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_completed));
        } else {
            response = "File uploaded from the device not completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_error));
        }
        operation.setOperationResponse(response);
    } catch (IOException e) {
        if (!loginResult) {
            response = ftpUserName + " - FTP login failed.";
        } else {
            response = fileTransferExceptionCause(e, fileName);
        }
        handleOperationError(operation, response, e, resources);
    } finally {
        try {
            if (ftpsClient.isConnected()) {
                ftpsClient.logout();
                ftpsClient.disconnect();
            }
        } catch (IOException ignored) {
        }
        cleanupStreams(inputStream, null, null, null, null, null, null, null);
    }
}