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

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

Introduction

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

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

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

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {//  w ww  . jav a 2s.com
        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();
        }
    }
}

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

public void downZurRose() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {//from   w  w  w .  j  a  v a  2 s .  c  o  m
        FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/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("P_ywesee")) {
                    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 + "...");

        String[] working_dir = { "ywesee out", "../ywesee in" };

        for (int i = 0; i < working_dir.length; ++i) {
            // Set working directory
            ftp_client.changeWorkingDirectory(working_dir[i]);
            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("Artikelstamm"))
                            local_file = Constants.CSV_FILE_DISPO_ZR;
                        OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + 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();
        }
    }
}

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 w  w .  j  ava  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.cladonia.xngreditor.URLUtilities.java

public static InputStream open(URL url) throws IOException {
    //        System.out.println( "URLUtilities.open( "+url+")");
    InputStream stream = null;/* w  ww .jav a2s  . c o m*/

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("http") || protocol.equals("https")) {
        try {
            DefaultAuthenticator authenticator = Main.getDefaultAuthenticator();

            URL newURL = new URL(URLUtilities.toString(url));

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(
                        new PasswordAuthentication(username, password.toCharArray()));
            }

            stream = newURL.openStream();

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(null);
            }
        } catch (Exception e) {
            //            System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage());
            // try it with webdav
            WebdavResource webdav = createWebdavResource(toString(url), username, password);

            stream = webdav.getMethodData(toString(url));

            webdav.close();
        }
    } else if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        try {
            //               System.out.println( "Connecting to: "+host+" ...");

            client = new FTPClient();
            client.connect(host);

            //               System.out.println( "Connected.");

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                //                  System.out.println( "Could not connect.");
                client.disconnect();
                throw new IOException("FTP Server \"" + host + "\" refused connection.");
            }

            //               System.out.println( "Logging in using: "+username+", "+password+" ...");

            if (!client.login(username, password)) {
                //                  System.out.println( "Could not log in.");
                // TODO bring up login dialog?
                client.disconnect();

                throw new IOException("Could not login to FTP Server \"" + host + "\".");
            }

            //               System.out.println( "Logged in.");

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

            //               System.out.println( "Opening file \""+url.getFile()+"\" ...");

            stream = client.retrieveFileStream(url.getFile());
            //               System.out.println( "File opened.");

            //               System.out.println( "Disconnecting ...");
            client.disconnect();
            //               System.out.println( "Disconnected.");

        } catch (IOException e) {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                } catch (IOException f) {
                    // do nothing
                    e.printStackTrace();
                }
            }

            throw new IOException("Could not connect to FTP Server \"" + host + "\".");
        }

    } else if (protocol.equals("file")) {
        stream = url.openStream();
    } else {

        //unknown protocol but try anyways
        try {
            stream = url.openStream();
        } catch (IOException ioe) {

            throw new IOException("The \"" + protocol + "\" protocol is not supported.");
        }
    }

    return stream;
}

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

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

    try {// w  w  w .j  a  va 2 s  . c  om
        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:edu.lternet.pasta.dml.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * /*w  w w . j  av  a 2  s. c o m*/
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:com.hackengine_er.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//from   www  .  j av  a  2s  . c  om
        client.connect(Configuration.FTPClient());
        if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

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

/**
 * //from   w  w w  .ja  v a 2  s.  c o 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:com.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//from   w  ww.  jav  a2  s  .c o m
        client.connect(Initialize.FTPClient());
        if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

From source file:com.rvl.android.getnzb.LocalNZB.java

public void uploadLocalFileFTP(String filename) {
    UPLOADFILENAME = filename;//from  w w  w.j a  v  a 2 s .  c o  m

    UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server.");

    SharedPreferences prefs = GetNZB.preferences;
    if (prefs.getString("FTPHostname", "") == "") {
        uploadDialogHandler.sendEmptyMessage(0);
        Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.",
                Toast.LENGTH_LONG).show();
        return;
    }

    new Thread() {

        public void run() {
            SharedPreferences prefs = GetNZB.preferences;
            FTPClient ftp = new FTPClient();

            String replycode = "";
            String FTPHostname = prefs.getString("FTPHostname", "");
            String FTPUsername = prefs.getString("FTPUsername", "anonymous");
            String FTPPassword = prefs.getString("FTPPassword", "my@email.address");
            String FTPPort = prefs.getString("FTPPort", "21");
            String FTPUploadPath = prefs.getString("FTPUploadPath", "~/");
            if (!FTPUploadPath.matches("$/")) {
                Log.d(Tags.LOG, "Adding trailing slash");
                FTPUploadPath += "/";
            }
            String targetFile = FTPUploadPath + UPLOADFILENAME;

            try {

                ftp.connect(FTPHostname, Integer.parseInt(FTPPort));
                if (ftp.login(FTPUsername, FTPPassword)) {

                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    ftp.enterLocalPassiveMode();
                    File file = new File(getFilesDir() + "/" + UPLOADFILENAME);
                    BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file));
                    Log.d(Tags.LOG, "Saving file to:" + targetFile);
                    if (ftp.storeFile(targetFile, buffIn)) {
                        Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: "
                                + Integer.toString(ftp.getReplyCode()));

                        isUploadedFTP = true;
                    } else {
                        Log.d(Tags.LOG, "FTP: Could not upload file  Replycode: "
                                + Integer.toString(ftp.getReplyCode()));
                        FTPErrorCode = Integer.toString(ftp.getReplyCode());
                        isUploadedFTP = false;
                    }

                    buffIn.close();
                    ftp.logout();
                    ftp.disconnect();

                } else {
                    Log.d(Tags.LOG, "No ftp login");
                }
            } catch (SocketException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            } catch (IOException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            }
            if (isUploadedFTP) {
                removeLocalNZBFile(UPLOADFILENAME);
            }

            UPLOADFILENAME = "";
            uploadDialogHandlerFTP.sendEmptyMessage(0);
        }

    }.start();
}