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: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);//ww  w .ja  v  a  2 s .  co 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:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Retrieve the content of a result feed URL.
 * //from   w w  w .jav  a2s  .  c  om
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @param resultHeaders
 * @return Reader
 */
private Reader getContent(final URI uri, final String encodingOverride, final String userAgent,
        final Map<String, String> resultHeaders) {
    Reader result = null;
    String contentType = null;

    // Retrieve the feed

    try {
        InputStream inputStream = null;

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

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

                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(), "");

                    inputStream = ftpClient.retrieveFileStream(uri.getPath());
                }
            } finally {
                ftpClient.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("file")) {
            File file = new File(uri);

            if (!file.isDirectory())
                inputStream = new FileInputStream(uri.getPath());
            else
                inputStream = RSSDirectoryBuilder.build(file);
        } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
            try {
                HttpGet method = new HttpGet(uri.toString());

                if (resultHeaders != null)
                    for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                        method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
                if (userAgent != null)
                    method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

                SizeRestrictedHttpResponse response = httpClient.execute(method,
                        new SizeRestrictedResponseHandler(maximumContentLength, uri));

                try {
                    if (response != null) {
                        inputStream = new ByteArrayInputStream(response.getResponse());
                        contentType = response.getContentType() != null ? response.getContentType().getValue()
                                : null;
                    } else
                        return null;
                } catch (RuntimeException e) {
                    method.abort();

                    throw e;
                }
            } catch (IllegalArgumentException e) {
                logger.error("Invalid URL " + uri.toString() + " - not returning content", e);

                return null;
            }
        } else {
            logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed.");

            return null;
        }

        // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection)

        InputStream readerInputStream = new BufferedInputStream(inputStream);
        MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata());

        try {
            Reader reader = null;

            if (mediaType.getType().equals("application")) {
                if (mediaType.getSubtype().equals("x-gzip")) {
                    GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream);

                    if (encodingOverride != null)
                        reader = readerToBuffer(new StringBuffer(),
                                new InputStreamReader(gzipInputStream, encodingOverride), false);
                    else
                        reader = readerToBuffer(new StringBuffer(),
                                contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true)
                                        : new XmlReader(gzipInputStream, true),
                                false);

                    gzipInputStream.close();
                } else if (mediaType.getSubtype().equals("zip")) {
                    ZipFile zipFile = null;

                    // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead

                    File temporaryFile = File.createTempFile("profiler-", ".zip");

                    try {
                        FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile);
                        IOUtils.copy(readerInputStream, zipOutputStream);

                        readerInputStream.close();

                        zipOutputStream.flush();
                        zipOutputStream.close();

                        // Create a new entry and process it

                        zipFile = new ZipFile(temporaryFile);
                        Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries();

                        ZipEntry zipEntry = zipEnumeration.nextElement();

                        if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) {
                            logger.error(
                                    "ZIP files are currently expected to contain one and only one entry, which is to be a file");

                            return null;
                        }

                        // We currently only perform prolog stripping for ZIP files

                        InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));

                        if (encodingOverride != null)
                            reader = readerToBuffer(new StringBuffer(), new InputStreamReader(
                                    new BufferedInputStream(zipInputStream), encodingOverride), true);
                        else
                            result = readerToBuffer(new StringBuffer(),
                                    contentType != null
                                            ? new XmlHtmlReader(new BufferedInputStream(zipInputStream),
                                                    contentType, true)
                                            : new XmlReader(new BufferedInputStream(zipInputStream), true),
                                    true);
                    } catch (Exception e) {
                        logger.error("An error occurred during ZIP file processing", e);

                        return null;
                    } finally {
                        if (zipFile != null)
                            zipFile.close();

                        if (!temporaryFile.delete())
                            logger.error("Unable to delete temporary file");
                    }
                }
            }

            if (result == null) {
                if (encodingOverride != null)
                    result = readerToBuffer(new StringBuffer(), reader != null ? reader
                            : new InputStreamReader(readerInputStream, encodingOverride), false);
                else
                    result = readerToBuffer(new StringBuffer(),
                            reader != null ? reader
                                    : contentType != null
                                            ? new XmlHtmlReader(readerInputStream, contentType, true)
                                            : new XmlReader(readerInputStream, true),
                            false);
            }
        } catch (Exception e) {
            logger.error("An error occurred during stream processing", e);

            return null;
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        logger.error("Could not retrieve the given feed: " + e.getMessage(), e);

        return null;
    }

    return result;
}

From source file:IHM.FenetreAjoutPhoto.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {/*from ww w  .  ja v  a2s.c om*/
        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:org.isatools.isacreator.filechooser.FTPBrowser.java

public FTPBrowser(String directory, String username, String password)
        throws NoSuchAlgorithmException, IOException {
    super(FileBrowser.REMOTE_FILE_SYSTEM);
    // if protocol if ftps
    if (directory.contains("ftps")) {

        ftpClient = new FTPSClient();

    } else {//from w  ww.j a  va 2s  .  c  om
        ftpClient = new FTPClient();
    }
    connect(directory, username, password);
}

From source file:org.jevis.ftpdatasource.FTPDataSource.java

@Override
public List<InputStream> sendSampleRequest(JEVisObject channel) {
    List<InputStream> answerList = new ArrayList<InputStream>();
    try {//  w  ww .j a va2  s.co m
        if (_ssl) {
            System.out.println("ftps connection");
            _fc = new FTPSClient();
        } else {
            _fc = new FTPClient();
        }
        //            _fc.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        if (_connectionTimeout != 0) {
            _fc.setConnectTimeout(_connectionTimeout.intValue() * 1000);
        }
        if (_readTimeout != 0) {
            _fc.setDataTimeout(_readTimeout.intValue() * 1000);
        }

        _fc.connect(_serverURL, _port);
        //            _fc.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);

        if (_fc.login(_userName, _password) == false) {
            org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ERROR,
                    "No Login possible");
            //                throw new FetchingException(_id, FetchingExceptionType.CONNECTION_ERROR);
        }

        //            _fc.setFileType(FTP.BINARY_FILE_TYPE);
        //            _fc.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
        _fc.setBufferSize(1024000);

        _fc.setUseEPSVwithIPv4(false);
        _fc.enterLocalPassiveMode();

        InputStream answer = null;
        JEVisClass channelClass = channel.getJEVisClass();
        JEVisType pathType = channelClass.getType(DataCollectorTypes.Channel.FTPChannel.PATH);
        String filePath = DatabaseHelper.getObjectAsString(channel, pathType);
        JEVisType readoutType = channelClass.getType(DataCollectorTypes.Channel.FTPChannel.LAST_READOUT);
        DateTime lastReadout = DatabaseHelper.getObjectAsDate(channel, readoutType,
                DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        //            String filePath = dp.getFilePath();
        org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL,
                "SendSampleRequest2");
        List<String> fileNames = DataSourceHelper.getFTPMatchedFileNames(_fc, lastReadout, filePath);
        //        String currentFilePath = Paths.get(filePath).getParent().toString();
        org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL,
                "Nr of Matched Files " + fileNames.size());
        for (String fileName : fileNames) {
            org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL,
                    "FileInputName: " + fileName);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //                String query = Paths.get(fileName);
            org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL,
                    "FTPQuery " + fileName);
            boolean retrieveFile = _fc.retrieveFile(fileName, out);
            org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL,
                    "Request status: " + retrieveFile);
            InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
            answer = new BufferedInputStream(inputStream);
            //                InputHandler inputConverter = InputHandlerFactory.getInputConverter(answer);
            //                inputConverter.setFilePath(fileName);
            answerList.add(answer);

        }
    } catch (JEVisException ex) {
        java.util.logging.Logger.getLogger(FTPDataSource.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FTPDataSource.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    if (answerList.isEmpty()) {
        org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ERROR,
                "Cant get any data from the device");
    }

    return answerList;
}

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

protected FTPSClient createFTPSClient() throws NoSuchAlgorithmException {
    FTPSClient FTPSClient = new FTPSClient();
    FTPSClient.setConnectTimeout(connectionTimeout);

    return FTPSClient;
}

From source file:org.pepstock.jem.node.resources.impl.ftp.FtpFactory.java

/**
 * Creates and configures a FtpClient instance based on the
 * given properties./*from w  w  w  . ja v  a  2  s . c  om*/
 * 
 * @param properties the ftp client configuration properties
 * @return remote input/output steam
 * @throws JNDIException if an error occurs creating the ftp client
 */
private Object createFtpClient(Properties properties) throws JNDIException {
    // URL is mandatory
    String ftpUrlString = properties.getProperty(CommonKeys.URL);
    if (ftpUrlString == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.URL);
    }

    // creates URL objects
    // from URL string
    URL ftpUrl;
    try {
        ftpUrl = new URL(ftpUrlString);
    } catch (MalformedURLException e) {
        throw new JNDIException(NodeMessage.JEMC233E, e, ftpUrlString);
    }
    // checks scheme
    // if SSL, activates a FTPS
    if (!ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL)
            && !ftpUrl.getProtocol().equalsIgnoreCase(FTPS_PROTOCOL)) {
        throw new JNDIException(NodeMessage.JEMC137E, ftpUrl.getProtocol());
    }

    // gets port the host (from URL)
    int port = ftpUrl.getPort();
    String server = ftpUrl.getHost();

    // User id is mandatory
    String username = properties.getProperty(CommonKeys.USERID);
    if (username == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.USERID);
    }

    // password is mandatory
    String password = properties.getProperty(CommonKeys.PASSWORD);
    if (password == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.PASSWORD);
    }

    // checks if as input stream or not
    boolean asInputStream = Parser
            .parseBoolean(properties.getProperty(FtpResourceKeys.AS_INPUT_STREAM, "false"), false);

    String remoteFile = null;
    String accessMode = null;
    if (asInputStream) {
        // remote file is mandatory
        // it must be set by a data description
        remoteFile = properties.getProperty(FtpResourceKeys.REMOTE_FILE);
        if (remoteFile == null) {
            throw new JNDIException(NodeMessage.JEMC136E, FtpResourceKeys.REMOTE_FILE);
        }
        // access mode is mandatory
        // it must be set by a data description
        accessMode = properties.getProperty(FtpResourceKeys.ACTION_MODE, FtpResourceKeys.ACTION_READ);
    }

    // creates a FTPclient 
    FTPClient ftp = ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL) ? new FTPClient() : new FTPSClient();

    // checks if binary
    boolean binaryTransfer = Parser.parseBoolean(properties.getProperty(FtpResourceKeys.BINARY, "false"),
            false);

    // checks if must be restarted
    long restartOffset = Parser.parseLong(properties.getProperty(FtpResourceKeys.RESTART_OFFSET, "-1"), -1);

    // checks and sets buffer size
    int bufferSize = Parser.parseInt(properties.getProperty(FtpResourceKeys.BUFFER_SIZE, "-1"), -1);

    try {
        // reply code instance
        int reply;
        // connect to server
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();
        // if not connected for error, EXCEPTION
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new JNDIException(NodeMessage.JEMC138E, reply);
        }
        // login!!
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        // set all ftp properties
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // sets restart offset if has been set
        if (restartOffset >= 0) {
            ftp.setRestartOffset(restartOffset);
        }

        // sets buffer size
        if (bufferSize >= 0) {
            ftp.setBufferSize(bufferSize);
        }

        // if is not related to a data descritpion,
        // returns a FTP object
        if (!asInputStream) {
            return new Ftp(ftp);
        }

        // checks if is in WRITE mode
        if (accessMode.equalsIgnoreCase(FtpResourceKeys.ACTION_WRITE)) {
            // gets outputstream
            // using the file name passed by data descritpion
            OutputStream os = ftp.storeFileStream(remoteFile);
            if (os == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns outputstream
            return new FtpOutputStream(os, ftp);
        } else {
            // gest inputstream
            // using the file name passed by data descritpion
            InputStream is = ftp.retrieveFileStream(remoteFile);
            if (is == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns inputstream 
            return new FtpInputStream(is, ftp);
        }
    } catch (SocketException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    } catch (IOException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    }
}

From source file:org.runmyprocess.sec.FTP.java

/**
 * receives the object with the path to look for the file and read the configuration file
 * @param jsonObject/* ww w . ja  v  a 2  s  . co m*/
 * @param configPath
 */
@Override
public void accept(JSONObject jsonObject, String configPath) {
    try {
        LOG.log("NEW REQUEST", Level.INFO);
        Config config = new Config("configFiles" + File.separator + "FTP.config", true);//finds and reads the config file
        // get an ftpClient object
        if (client == null || jsonObject.containsKey("FTPType")) {
            if (jsonObject.getString("FTPType") == "FTP") {
                this.client = new FTPClient();
            } else if (jsonObject.getString("FTPType") == "FTPS") {
                this.client = new FTPSClient();
            }
        }
        LOG.log("NEW REQUEST CLIENT SET", Level.INFO);
        try {
            // pass directory path on server to connect
            if (!this.connect(config.getProperty("host"), jsonObject.getString("user"),
                    jsonObject.getString("password"), Integer.parseInt(config.getProperty("port")))) {
                throw new Exception("Unable to loggin to FTP");
            }
            LOG.log("Connection established...", Level.INFO);

            Task task = Task.DEFAULT;
            if (jsonObject.containsKey("task"))
                try {
                    task = Task.valueOf(jsonObject.getString("task"));
                } catch (Exception ex) {
                    //do NOTHING task not found
                }
            LOG.log(task.name(), Level.INFO);
            switch (task) {
            case PING:
                ping(jsonObject);
                break;
            case GET:
                fetchFile(jsonObject);
                break;
            case PUT:
                upload(jsonObject);
                break;
            case LIST:
                listFiles(jsonObject);
                break;
            case DELETE:
                remove(jsonObject);
                break;
            case RENAME:
                rename(jsonObject);
                break;
            case MKDIR:
                createDir(jsonObject);
                break;
            case RMDIR:
                removeDir(jsonObject);
                break;
            case DEFAULT:
                throw new Exception("Task not found");
            }

        } catch (SocketException e) {
            e.printStackTrace();
            throw new Exception(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            try {
                if (this.logged)
                    this.client.logout();
                this.client.disconnect();
                LOG.log("Disconnected", Level.INFO);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception(e);
            }
        }

    } catch (Exception e) {
        response.setData(this.FTPError(e.toString()));
        SECErrorManager errorManager = new SECErrorManager();
        errorManager.logError(e.toString(), Level.SEVERE);
        e.printStackTrace();
    }
}

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.
 *///w w w .  j a v  a 2  s.  c  om
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 o m
 * @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);
    }
}