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

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

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient 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.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {/* w ww  .j a v  a 2s  . c  o  m*/
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        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;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.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();
        }
    }
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {//from ww  w. j  av a2 s  . c  o m
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private Boolean downloadFile(String server, int portNumber, String user, String password, String filename,
        File localFile) throws IOException {
    FTPClient ftp = null;

    try {/*from   www. jav  a  2  s .  c om*/
        ftp = new FTPClient();
        ftp.setBufferSize(1024 * 1024);
        ftp.connect(server, portNumber);
        Log.d(NAME, "Connected. Reply: " + ftp.getReplyString());
        if (!ftp.login(user, password)) {
            return false;
        }
        Log.d(NAME, "Logged in");
        if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
            return false;
        }
        Log.d(NAME, "Downloading");
        ftp.enterLocalPassiveMode();

        OutputStream outputStream = null;
        boolean success = false;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
            success = ftp.retrieveFile(filename, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }

        return success;
    } finally {
        if (ftp != null) {
            ftp.logout();
            ftp.disconnect();
        }
    }
}

From source file:com.claim.controller.FileTransferController.java

public void readFilesFromServer(String targetDirectory) {
    FTPClient ftpClient = new FTPClient();
    try {/* w  ww.j  a  v  a2s  .  c  o  m*/

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
        ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        FTPFile[] ftpFiles = ftpClient.listFiles();

        if (ftpFiles != null && ftpFiles.length > 0) {
            //loop thru files
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());

                //get output stream
                OutputStream output;
                //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName());
                output = new FileOutputStream(file.getName());
                //get the file from the remote system
                ftpClient.retrieveFile(file.getName(), output);
                //close output stream
                output.close();

                //delete the file
                //ftpClient.deleteFile(file.getName());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * /*from   w  w  w . j  av  a2  s . co  m*/
 * @throws UnknownHostException
 *         If the hostname cannot be resolved.
 *         
 * @throws SocketException
 *         If the socket timeout could not be set.
 *         
 * @throws FTPConnectionClosedException
 *         If the connection is closed by the server.
 *         
 * @throws LoginFailedException
 *         If the login fails.
 *         
 * @throws DirectoryChangeFailedException
 *         If changing to the directory provided by the internet
 *         archive fails.
 *         
 * @throws CopyStreamException
 *         If an I/O error occurs while in the middle of
 *         transferring a file.
 *         
 * @throws IOException
 *         If an I/O error occurs while sending a command or
 *         receiving a reply from the server
 *         
 * @throws IllegalStateException
 *          If the contribution object is not ready to upload
 *          (no username, password, server, etc. set)
 *          or if java's xml parser is configured badly
 */

public void upload()
        throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException,
        DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException {

    final int NUM_XML_FILES = 2;
    final String META_XML_SUFFIX = "_meta.xml";
    final String FILES_XML_SUFFIX = "_files.xml";

    final String username = getUsername();
    final String password = getPassword();

    if (getFtpServer() == null) {
        throw new IllegalStateException("ftp server not set");
    }
    if (getFtpPath() == null) {
        throw new IllegalStateException("ftp path not set");
    }
    if (username == null) {
        throw new IllegalStateException("username not set");
    }
    if (password == null) {
        throw new IllegalStateException("password not set");
    }

    // calculate total number of files and bytes

    final String metaXmlString = serializeDocument(getMetaDocument());
    final String filesXmlString = serializeDocument(getFilesDocument());

    final byte[] metaXmlBytes = metaXmlString.getBytes();
    final byte[] filesXmlBytes = filesXmlString.getBytes();

    final int metaXmlLength = metaXmlBytes.length;
    final int filesXmlLength = filesXmlBytes.length;

    final Collection files = getFiles();

    final int totalFiles = NUM_XML_FILES + files.size();

    final String[] fileNames = new String[totalFiles];
    final long[] fileSizes = new long[totalFiles];

    final String metaXmlName = getIdentifier() + META_XML_SUFFIX;
    fileNames[0] = metaXmlName;
    fileSizes[0] = metaXmlLength;

    final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX;
    fileNames[1] = filesXmlName;
    fileSizes[1] = filesXmlLength;

    int j = 2;
    for (Iterator i = files.iterator(); i.hasNext();) {
        final File f = (File) i.next();
        fileNames[j] = f.getRemoteFileName();
        fileSizes[j] = f.getFileSize();
        j++;
    }

    // init the progress mapping
    for (int i = 0; i < fileSizes.length; i++) {
        _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i]));
        _totalUploadSize += fileSizes[i];
    }

    FTPClient ftp = new FTPClient();

    try {
        // first connect

        if (isCancelled()) {
            return;
        }
        ftp.enterLocalPassiveMode();

        if (isCancelled()) {
            return;
        }
        ftp.connect(getFtpServer());

        final int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RefusedConnectionException(getFtpServer() + "refused FTP connection");
        }
        // now login
        if (isCancelled()) {
            return;
        }
        if (!ftp.login(username, password)) {
            throw new LoginFailedException();
        }

        try {

            // try to change the directory
            if (!ftp.changeWorkingDirectory(getFtpPath())) {
                // if changing fails, make the directory
                if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }

                // now change directory, if it fails again bail
                if (isCancelled()) {
                    return;
                }
                if (!ftp.changeWorkingDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }
            }

            if (isCancelled()) {
                return;
            }
            connected();

            // upload xml files
            uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp);

            uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp);

            // now switch to binary mode
            if (isCancelled()) {
                return;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // upload contributed files
            for (final Iterator i = files.iterator(); i.hasNext();) {
                final File f = (File) i.next();

                uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp);
            }
        } catch (InterruptedIOException ioe) {
            // we've been requested to cancel
            return;
        } finally {
            ftp.logout(); // we don't care if logging out fails
        }
    } finally {
        try {
            ftp.disconnect();
        } catch (IOException e) {
        } // don't care if disconnecting fails
    }

    // now tell the Internet Archive that we're done
    if (isCancelled()) {
        return;
    }
    checkinStarted();

    if (isCancelled()) {
        return;
    }
    checkin();

    if (isCancelled()) {
        return;
    }
    checkinCompleted();
}

From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

/**
 * FTPClient/*from ww  w .  j a  v a  2s.  c  o m*/
 *
 * @throws Exception
 */
private FTPClient getFTPClient() throws Exception {
    if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {
        return ftpClientThreadLocal.get();
    } else {
        FTPClient ftpClient = new FTPClient(); //FtpClient
        ftpClient.setControlEncoding(encoding); //

        connect(ftpClient); //ftp?

        //passive?
        if (passiveMode) {
            ftpClient.enterLocalPassiveMode();
        }
        setFileType(ftpClient); //

        try {
            ftpClient.setSoTimeout(clientTimeout);
        } catch (SocketException e) {
            throw new Exception("Set timeout error.", e);
        }
        ftpClientThreadLocal.set(ftpClient);
        return ftpClient;
    }
}

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 ww .  ja v a 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:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

private FTPClient connect() {
    final FTPClient connection = new FTPClient();
    try {//from  ww w .  j  a v  a 2s  .c  om
        connection.setAutodetectUTF8(true);
        connection.connect(url.getHost(), port);
        connection.enterLocalActiveMode();
        if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) {
            throw new SourceException(
                    String.format("Cannot login as anonymous user, reason %s", connection.getReplyString()));
        }
        if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        connection.enterLocalPassiveMode();
        connection.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (final IOException e) {
        disconnect(connection);
        throw new SourceException(e);
    }
    return connection;
}

From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java

public void conectarFTP(Archivo archivo) {
    FTPClient client = new FTPClient();
    /*String sFTP = "127.0.0.1";
    String sUser = "tae";/*from   w w w .j  av a 2 s  .com*/
    String sPassword = "tae";*/
    String sFTP = buscarParametros(FTP_SERVER);
    String sUser = buscarParametros(FTP_USER);
    String sPassword = buscarParametros(FTP_PASSWORD);
    ///////////////////////////////////
    //String[] lista;
    try {
        client.connect(sFTP);
        boolean login = client.login(sUser, sPassword);
        System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory());
        client.setFileType(FTP.BINARY_FILE_TYPE);
        BufferedInputStream buffIn = null;
        buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre()));
        client.enterLocalPassiveMode();
        StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta.
        int i = 0;
        String nombre = "";
        while (tokens.hasMoreTokens()) {
            if (i == 1) {
                nombre = tokens.nextToken();
                i++;
            } else {
                i++;
            }
        }
        client.storeFile(nombre, buffIn);
        buffIn.close();
        /*lista = client.listNames();
        for (String lista1 : lista) {
        System.out.println(lista1);
        }*/
        //client.changeWorkingDirectory("\\done");
        //System.out.println("2. Working Directory: " + client.printWorkingDirectory());
        client.logout();
        client.disconnect();
        System.out.println("Termin de conectarme al FTP!!");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

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

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

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

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

    return ftpclient;
}