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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

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

    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:com.mirth.connect.connectors.file.filesystems.FtpConnection.java

public FtpConnection(String host, int port, FileSystemConnectionOptions fileSystemOptions, boolean passive,
        int timeout, FTPClient client) throws Exception {
    this.client = client;
    // This sets the timeout for read operations on data sockets. It does not affect write operations.
    client.setDataTimeout(timeout);/*from  w ww .  ja  v a  2  s .c o  m*/

    // This sets the timeout for the initial connection.
    client.setConnectTimeout(timeout);

    try {
        if (port > 0) {
            client.connect(host, port);
        } else {
            client.connect(host);
        }

        // This sets the timeout for read operations on the command socket. As per JavaDoc comments, you should only call this after the connection has been opened by connect()
        client.setSoTimeout(timeout);

        if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            throw new IOException("Ftp error: " + client.getReplyCode());
        }
        if (!client.login(fileSystemOptions.getUsername(), fileSystemOptions.getPassword())) {
            throw new IOException("Ftp error: " + client.getReplyCode());
        }
        if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
            throw new IOException("Ftp error");
        }

        initialize();

        if (passive) {
            client.enterLocalPassiveMode();
        }
    } catch (Exception e) {
        if (client.isConnected()) {
            client.disconnect();
        }
        throw e;
    }
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * @param host FTP Host name.//from  w w  w . ja v  a 2 s.  c  o  m
 * @param port FTP port.
 * @param user FTP User.
 * @param pswd FTP Password.
 * @param c    Context
 * @return Downloaded name file or blank list if something was going wrong.
 */
private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) {
    String result = "";
    FTPClient mFTPClient = null;

    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // Now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {

            // Login using username & password
            boolean status = mFTPClient.login(user, pswd);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA);
            FTPFile[] fileList = mFTPClient.listFiles();
            long timestamp = 0l;
            String nameFile = "";
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) {
                    timestamp = fileList[i].getTimestamp().getTimeInMillis();
                    nameFile = fileList[i].getName();
                }
            }
            Log.d(TAG, "File da scaricare: " + nameFile);

            mFTPClient.enterLocalActiveMode();
            File folder = new File(Constants.DIR_ROBOT_IMG);
            OutputStream outputStream = null;
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            try {
                outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                success = mFTPClient.retrieveFile(nameFile, outputStream);
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            if (success) {
                result = nameFile;
                mFTPClient.deleteFile(nameFile);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (mFTPClient != null) {
            try {
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    return result;
}

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

/**
 * Retrieve the content of a result feed URL.
 * /*from ww  w .j a v  a  2  s . 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:ch.cyberduck.core.ftp.FTPSession.java

@Override
public FTPClient connect(final HostKeyCallback callback) throws BackgroundException {
    try {//  w w w  . ja  v a2s. c  om
        final CustomTrustSSLProtocolSocketFactory f = new CustomTrustSSLProtocolSocketFactory(trust, key);

        final LoggingProtocolCommandListener listener = new LoggingProtocolCommandListener(this);
        final FTPClient client = new FTPClient(host.getProtocol(), f, f.getSSLContext()) {
            @Override
            public void disconnect() throws IOException {
                try {
                    super.disconnect();
                } finally {
                    this.removeProtocolCommandListener(listener);
                }
            }
        };
        client.addProtocolCommandListener(listener);
        this.configure(client);
        client.connect(new PunycodeConverter().convert(host.getHostname()), host.getPort());
        client.setTcpNoDelay(false);
        return client;
    } catch (IOException e) {
        throw new FTPExceptionMappingService().map(e);
    }
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

/**
 * Login into a account//from   w  ww.java2s .  c om
 *
 * @return FTPClient object or null
 * @throws IOException
 */
public FTPClient login() throws IOException {
    int reply = 0;
    FTPClient ftp = new FTPClient();
    try {
        if (port != 0)
            ftp.connect(getHost(), getPort());
        else
            ftp.connect(getHost());
        if (isAnonymous())
            ftp.login(ANONYMOUS, GUEST);
        else if (getSubAccount() != null && !getSubAccount().isEmpty())
            ftp.login(getLogin(), getPassword(), getSubAccount());
        else
            ftp.login(getLogin(), getPassword());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString()));
        if (isPassiveMode())
            ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        throw e;
    }
    return ftp;
}

From source file:com.tumblr.maximopro.iface.router.FTPHandler.java

@Override
public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException {
    byte[] encodedData = super.invoke(metaData, data);
    this.metaData = metaData;

    FTPClient ftp;
    if (enableSSL()) {
        FTPSClient ftps = new FTPSClient(isImplicit());
        ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        ftp = ftps;//from   w  ww  . j  av a  2 s  . c om
    } else {
        ftp = new FTPClient();
    }

    InputStream is = null;
    try {

        if (getTimeout() > 0) {
            ftp.setDefaultTimeout(getTimeout());
        }

        if (getBufferSize() > 0) {
            ftp.setBufferSize(getBufferSize());
        }

        if (getNoDelay()) {
            ftp.setTcpNoDelay(getNoDelay());
        }

        ftp.connect(getHostname(), getPort());

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        if (!ftp.login(getUsername(), getPassword())) {
            ftp.logout();
            ftp.disconnect();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (enableActive()) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        is = new ByteArrayInputStream(encodedData);

        String remoteFileName = getFileName(metaData);

        ftp.changeWorkingDirectory("/");
        if (createDirectoryStructure(ftp, getDirName().split("/"))) {
            ftp.storeFile(remoteFileName, is);
        } else {
            throw new MXApplicationException("iface", "cannotcreatedir");
        }

        ftp.logout();
    } catch (MXException e) {
        throw e;
    } catch (SocketException e) {
        throw new MXApplicationException("iface", "ftpsocketerror", e);
    } catch (IOException e) {
        throw new MXApplicationException("iface", "ftpioerror", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }

        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }
    }

    return null;
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downIBSA() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*  w  ww.ja  v a  2  s . c  o m*/
        FileInputStream glnCodesCsv = new FileInputStream(Constants.DIR_IBSA + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(glnCodesCsv, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("IbsaAmiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory("data");
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        System.out.println("- Connected to server " + fs + "...");
        //get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();

        List<String> list_remote_files = Arrays.asList("Konditionen.csv", "Targeting_diff.csv", "Address.csv");
        List<String> list_local_files = Arrays.asList(Constants.FILE_CUST_IBSA, Constants.FILE_TARG_IBSA,
                Constants.FILE_MOOS_ADDR);

        if (ftpFiles != null && ftpFiles.length > 0) {
            int index = 0;
            for (String remote_file : list_remote_files) {
                OutputStream os = new FileOutputStream(Constants.DIR_IBSA + "/" + list_local_files.get(index));
                System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");

                boolean done = ftp_client.retrieveFile(remote_file, os);
                if (done)
                    System.out.println("file downloaded successfully.");
                else
                    System.out.println("error.");
                os.close();
                index++;
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.thebigbang.ftpclient.FTPOperation.java

/**
 * will force keep the device turned on for all the operation duration.
 * @param params/*  w  ww . j  av  a  2s.  c  o m*/
 * @return 
 */
@SuppressLint("Wakelock")
@SuppressWarnings("deprecation")
@Override
protected Boolean doInBackground(FTPBundle... params) {
    Thread.currentThread().setName("FTPOperationWorker");
    for (final FTPBundle bundle : params) {

        FTPClient ftp = new FTPClient();
        PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client");
        try {
            // setup ftp connection:
            InetAddress addr = InetAddress.getByName(bundle.FTPServerHost);
            //set here the timeout.
            TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() {
                @Override
                public void Occurred(TimeoutException e) {
                    bundle.Exception = e;
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                    publishProgress(bundle);
                }
            });
            timeout.start();
            ftp.connect(addr, bundle.FTPServerPort);
            int reply = ftp.getReplyCode();
            timeout.Stop();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("connection refuse");
            }
            ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword);
            if (bundle.OperationType == FTPOperationType.Connect) {
                bundle.OperationStatus = FTPOperationStatus.Succed;
                publishProgress(bundle);
                continue;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            w.acquire();
            // then switch between enum of operation types.
            if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.GetData) {
                String finalFPFi = bundle.LocalFilePathName;
                // The remote filename to be downloaded.
                if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") {
                    File f = new File(bundle.LocalWorkingDirectory);
                    f.mkdirs();

                    finalFPFi = bundle.LocalWorkingDirectory + finalFPFi;
                }
                FileOutputStream fos = new FileOutputStream(finalFPFi);

                // Download file from FTP server
                String finalFileN = bundle.RemoteFilePathName;
                if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") {
                    finalFileN = bundle.RemoteWorkingDirectory + finalFileN;
                }
                boolean b = ftp.retrieveFile(finalFileN, fos);
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                fos.close();

            } else if (bundle.OperationType == FTPOperationType.SendData) {
                InputStream istr = new FileInputStream(bundle.LocalFilePathName);
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr);
                istr.close();
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
            } else if (bundle.OperationType == FTPOperationType.DeleteData) {
                throw new IOException("DeleteData is Not yet implemented");
            }

            ftp.disconnect();
            // then finish/return.
            //publishProgress(bundle);
        } catch (IOException e) {
            e.printStackTrace();
            bundle.Exception = e;
            bundle.OperationStatus = FTPOperationStatus.Failed;
        }
        try {
            w.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        publishProgress(bundle);
    }
    return true;
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from   www  .j av a  2  s  . c o  m*/
        FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("ftp_amiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        // Set working directory
        String working_dir = "ywesee_in";
        ftp_client.changeWorkingDirectory(working_dir);
        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }
        // Get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            // ... then download all csv files
            for (FTPFile f : ftpFiles) {
                String remote_file = f.getName();
                if (remote_file.endsWith("csv")) {
                    String local_file = remote_file;
                    if (remote_file.startsWith("Kunden"))
                        local_file = Constants.FILE_CUST_DESITIN;
                    if (remote_file.startsWith("Artikel"))
                        local_file = Constants.FILE_ARTICLES_DESITIN;
                    OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file);
                    System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                    boolean done = ftp_client.retrieveFile(remote_file, os);
                    if (done)
                        System.out.println("success.");
                    else
                        System.out.println("error.");
                    os.close();
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}