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.mozilla.SUTAgentAndroid.service.DoCommand.java

public String FTPGetFile(String sServer, String sSrcFileName, String sDstFileName, OutputStream out) {
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    String sRet = sErrorPrefix + "FTP Get failed for " + sSrcFileName;
    String strRet = "";
    int reply = 0;
    FileOutputStream outStream = null;
    String sTmpDstFileName = fixFileName(sDstFileName);

    FTPClient ftp = new FTPClient();
    try {/*  w  w w  .ja  va  2 s . co m*/
        ftp.connect(sServer);
        reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            ftp.login("anonymous", "b@t.com");
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                ftp.enterLocalPassiveMode();
                if (ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
                    File dstFile = new File(sTmpDstFileName);
                    outStream = new FileOutputStream(dstFile);
                    FTPFile[] ftpFiles = ftp.listFiles(sSrcFileName);
                    if (ftpFiles.length > 0) {
                        long lFtpSize = ftpFiles[0].getSize();
                        if (lFtpSize <= 0)
                            lFtpSize = 1;

                        InputStream ftpIn = ftp.retrieveFileStream(sSrcFileName);
                        while ((nRead = ftpIn.read(buffer)) != -1) {
                            lTotalRead += nRead;
                            outStream.write(buffer, 0, nRead);
                            strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received "
                                    + ((lTotalRead * 100) / lFtpSize) + "% completed";
                            out.write(strRet.getBytes());
                            out.flush();
                        }
                        ftpIn.close();
                        @SuppressWarnings("unused")
                        boolean bRet = ftp.completePendingCommand();
                        outStream.flush();
                        outStream.close();
                        strRet = ftp.getReplyString();
                        reply = ftp.getReplyCode();
                    } else {
                        strRet = sRet;
                    }
                }
                ftp.logout();
                ftp.disconnect();
                sRet = "\n" + strRet;
            } else {
                ftp.disconnect();
                System.err.println("FTP server refused login.");
            }
        } else {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        }
    } catch (SocketException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    } catch (IOException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    }
    return (sRet);
}

From source file:GestoSAT.GestoSAT.java

@Schedule(dayOfWeek = "Sun-Sat", month = "*", hour = "22", dayOfMonth = "*", year = "*", minute = "0", second = "0", persistent = true)
public void generarCopia() {

    // http://chuwiki.chuidiang.org/index.php?title=Backup_de_MySQL_con_Java
    try {/*from   w  w w .j a va  2s. co  m*/
        Process p = Runtime.getRuntime().exec("mysqldump -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3)
                + " -h " + mySQL.elementAt(0) + " -P " + mySQL.elementAt(1) + " gestosat");

        InputStream is = p.getInputStream();
        FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql");
        byte[] buffer = new byte[1000];

        int leido = is.read(buffer);
        while (leido > 0) {
            fos.write(buffer, 0, leido);
            leido = is.read(buffer);
        }
        fos.close();

        //http://www.javamexico.org/blogs/lalo200/pequeno_ejemplo_para_subir_un_archivo_ftp_con_la_libreria_commons_net
        FTPClient clienteFTP = new FTPClient();

        // Lanza excepcin si el servidor no existe
        clienteFTP.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1)));

        if (clienteFTP.login(confSeg.elementAt(2), confSeg.elementAt(3))) {

            clienteFTP.setFileType(FTP.BINARY_FILE_TYPE);
            BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql"));
            clienteFTP.enterLocalPassiveMode();
            clienteFTP.storeFile("backupGestoSAT.sql", buffIn);
            buffIn.close();
            clienteFTP.logout();
            clienteFTP.disconnect();
        } else
            System.out.println("Error de conexin FTP");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:GestoSAT.GestoSAT.java

public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo)
        throws Exception {
    FileReader file;/*  w w  w  .j  a v  a2s  . c om*/
    try {
        this.iva = Math.abs(iva);

        BufferedImage image = null;
        byte[] imageByte;

        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(logo.split(",")[1]);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();

        // write the image to a file
        File outputfile = new File("logo");
        String formato = logo.split("/")[1].split(";")[0];
        ImageIO.write(image, formato, outputfile);

        // MySQL
        if (mySQL.elementAt(0).equals(this.mySQL.elementAt(0))) {
            if (!mySQL.elementAt(1).equals(this.mySQL.elementAt(1))
                    && !mySQL.elementAt(2).equals(this.mySQL.elementAt(2))
                    && (!mySQL.elementAt(3).equals(this.mySQL.elementAt(3))
                            || !mySQL.elementAt(0).equals(""))) {
                Class.forName("com.mysql.jdbc.Driver");
                this.con.close();
                this.con = DriverManager.getConnection("jdbc:mysql://" + mySQL.elementAt(0) + ":"
                        + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user="
                        + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3));

                this.mySQL.set(0, mySQL.elementAt(0));
                this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "");
                this.mySQL.set(2, mySQL.elementAt(2));
                this.mySQL.set(3, mySQL.elementAt(3));
            }
        } else {
            // Comprobar que pass != ""
            Process pGet = Runtime.getRuntime()
                    .exec("mysqldump -u " + this.mySQL.elementAt(2) + " -p" + this.mySQL.elementAt(3) + " -h "
                            + this.mySQL.elementAt(0) + " -P " + this.mySQL.elementAt(1) + " gestosat");

            InputStream is = pGet.getInputStream();
            FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql");
            byte[] bufferOut = new byte[1000];

            int leido = is.read(bufferOut);
            while (leido > 0) {
                fos.write(bufferOut, 0, leido);
                leido = is.read(bufferOut);
            }
            fos.close();

            Class.forName("com.mysql.jdbc.Driver");
            this.con.close();
            this.con = DriverManager.getConnection(
                    "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1)))
                            + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3));

            this.mySQL.set(0, mySQL.elementAt(0));
            this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "");
            this.mySQL.set(2, mySQL.elementAt(2));
            this.mySQL.set(3, mySQL.elementAt(3));

            Process pPut = Runtime.getRuntime()
                    .exec("mysql -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h "
                            + mySQL.elementAt(0) + " -P " + Math.abs(Integer.parseInt(mySQL.elementAt(1)))
                            + " gestosat");

            OutputStream os = pPut.getOutputStream();
            FileInputStream fis = new FileInputStream("backupGestoSAT.sql");
            byte[] bufferIn = new byte[1000];

            int escrito = fis.read(bufferIn);
            while (escrito > 0) {
                os.write(bufferIn, 0, leido);
                escrito = fis.read(bufferIn);
            }

            os.flush();
            os.close();
            fis.close();
        }

        // FTP

        FTPClient cliente = new FTPClient();
        if (!confSeg.elementAt(3).equals("")) {
            cliente.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1)));

            if (cliente.login(confSeg.elementAt(2), confSeg.elementAt(3))) {
                cliente.setFileType(FTP.BINARY_FILE_TYPE);
                BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql"));
                cliente.enterLocalPassiveMode();
                cliente.storeFile("backupGestoSAT.sql", buffIn);
                buffIn.close();
                cliente.logout();
                cliente.disconnect();

                this.confSeg = confSeg;
            } else
                return false;
        }

        File archConf = new File("confGestoSAT");
        BufferedWriter bw = new BufferedWriter(new FileWriter(archConf));
        bw.write(this.mySQL.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.mySQL.elementAt(1))) + ";"
                + this.mySQL.elementAt(2) + ";" + this.mySQL.elementAt(3) + ";" + this.confSeg.elementAt(0)
                + ";" + Math.abs(Integer.parseInt(this.confSeg.elementAt(1))) + ";" + this.confSeg.elementAt(2)
                + ";" + this.confSeg.elementAt(3) + ";" + Math.abs(iva));
        bw.close();

        return true;
    } catch (Exception ex) {
        file = new FileReader("confGestoSAT");
        BufferedReader b = new BufferedReader(file);
        String cadena;
        cadena = b.readLine();
        String[] valores = cadena.split(";");

        this.mySQL.add(valores[0]);
        this.mySQL.add(Math.abs(Integer.parseInt(valores[1])) + "");
        this.mySQL.add(valores[2]);
        this.mySQL.add(valores[3]);
        con.close();
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager
                .getConnection("jdbc:mysql://" + this.mySQL.elementAt(0) + ":" + this.mySQL.elementAt(1)
                        + "/gestosat?user=" + this.mySQL.elementAt(2) + "&password=" + this.mySQL.elementAt(3));

        this.confSeg.add(valores[4]);
        this.confSeg.add(Math.abs(Integer.parseInt(valores[5])) + "");
        this.confSeg.add(valores[6]);
        this.confSeg.add(valores[7]);

        file.close();
        Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }/*from   ww w  .j  a  v a 2 s .c  o  m*/
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToFTPserver(final Activity activity, final Handler handler,
        final String latestVideoFile_filename, final String latestVideoFile_absolutepath,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doVideoFTP starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FTP);

    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // FTP; connect preferences here!
            ///* w  ww.  j a  v  a  2 s.co  m*/
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
            String ftpHostName = prefs.getString("defaultFTPhostPreference", null);
            String ftpUsername = prefs.getString("defaultFTPusernamePreference", null);
            String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null);

            // use name of local file.
            String ftpRemoteFtpFilename = latestVideoFile_filename;

            // FTP
            FTPClient ftpClient = new FTPClient();
            InetAddress uploadhost = null;
            try {

                uploadhost = InetAddress.getByName(ftpHostName);
            } catch (UnknownHostException e1) {
                // If DNS resolution fails then abort immediately - show
                // dialog to
                // inform user first.
                e1.printStackTrace();
                Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed.");
                uploadhost = null;
            }

            if (uploadhost == null) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean connected = false;

            try {
                ftpClient.connect(uploadhost);
                connected = true;

            } catch (SocketException e) {
                e.printStackTrace();
                connected = false;

            } catch (UnknownHostException e) {
                //
                e.printStackTrace();
                connected = false;
            } catch (IOException e) {
                //
                e.printStackTrace();
                connected = false;
            }

            if (!connected) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean reply = false;
            try {

                reply = ftpClient.login(ftpUsername, ftpPassword);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp.login - video uploading failed.");
            }

            // check the reply code here
            // If we cant login, abort after showing user a dialog.
            if (!reply) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    //
                    e.printStackTrace();
                }

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();
                    }
                }, 0);

                return;
            }

            // Set File type to binary
            try {
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (IOException e) {
                //
                e.printStackTrace();
                // keep going?!
            }

            // BEYOND HERE DONT USE DIALOGS!

            // Construct the input stream to send to Ftp server, from the
            // local
            // video file on the sd card
            BufferedInputStream buffIn = null;
            File file = new File(latestVideoFile_absolutepath);

            try {
                buffIn = new BufferedInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on local video file - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                return;
            }

            ftpClient.enterLocalPassiveMode();

            try {
                // UPLOAD THE LOCAL VIDEO FILE.
                ftpClient.storeFile(ftpRemoteFtpFilename, buffIn);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on storeFile - video uploading failed.");

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                buffIn.close();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on buff.close - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.logout();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp logout - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp disconnect - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }

            if (emailAddress != null && ftpHostName != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_));

                }
            }, 0);

        }
    });

    t.start();

    return t;
}

From source file:base.BasePlayer.Main.java

static String getNewFile(String server, String folder, String oldfile) {
    String minfile = "";
    try {//from   w  ww.j  ava  2s  .  co m

        String filename = oldfile;
        FTPClient f = new FTPClient();
        f.connect(server);
        f.enterLocalPassiveMode();
        f.login("anonymous", "");
        FTPFile[] files = f.listFiles(folder);
        int left = 0, right = filename.length() - 1, distance = 0;
        int mindistance = 100;

        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().endsWith(".gff3.gz")) {
                distance = 0;
                right = Math.min(filename.length(), files[i].getName().length());
                left = 0;

                while (left < right) {
                    if (filename.charAt(left) != files[i].getName().charAt(left)) {
                        distance++;
                    }
                    left++;
                }
                distance += Math.abs(filename.length() - files[i].getName().length());
                if (distance < mindistance) {
                    mindistance = distance;
                    minfile = files[i].getName();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return minfile;
}

From source file:com.ibm.cics.ca1y.Emit.java

/**
 * Get the contents of a file from an FTP server.
 * //  w  w  w. j  a v  a  2 s .  co  m
 * @param filename
 *            -
 * @param server
 *            -
 * @param useraname
 *            -
 * @param userpassword
 *            -
 * @param transfer
 *            -
 * @param mode
 *            -
 * @param epsv
 *            -
 * @param protocol
 *            -
 * @param trustmgr
 *            -
 * @param datatimeout
 *            -
 * @param proxyserver
 *            -
 * @param proxyusername
 *            -
 * @param proxypassword
 *            -
 * @param anonymouspassword
 *            -
 * @return byte[] representing the retrieved file, null otherwise.
 */
private static byte[] getFileUsingFTP(String filename, String server, String username, String userpassword,
        String transfer, String mode, String epsv, String protocol, String trustmgr, String datatimeout,
        String proxyserver, String proxyusername, String proxypassword, String anonymouspassword) {

    FTPClient ftp;

    if (filename == null || server == null)
        return null;
    int port = 0;
    if (server != null) {
        String parts[] = server.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (Exception _ex) {
            }
        }
    }

    int proxyport = 0;
    if (proxyserver != null) {
        String parts[] = proxyserver.split(":");

        if (parts.length == 2) {
            proxyserver = parts[0];

            try {
                proxyport = Integer.parseInt(parts[1]);

            } catch (Exception _ex) {
            }
        }
    }

    if (username == null) {
        username = "anonymous";

        if (userpassword == null)
            userpassword = anonymouspassword;
    }

    if (protocol == null) {
        if (proxyserver != null)
            ftp = new FTPHTTPClient(proxyserver, proxyport, proxyusername, proxypassword);
        else
            ftp = new FTPClient();

    } else {
        FTPSClient ftps = null;

        if ("true".equalsIgnoreCase(protocol)) {
            ftps = new FTPSClient(true);

        } else if ("false".equalsIgnoreCase(protocol)) {
            ftps = new FTPSClient(false);

        } else if (protocol != null) {
            String parts[] = protocol.split(",");

            if (parts.length == 1)
                ftps = new FTPSClient(protocol);
            else
                ftps = new FTPSClient(parts[0], Boolean.parseBoolean(parts[1]));
        }

        ftp = ftps;

        if ("all".equalsIgnoreCase(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());

        } else if ("valid".equalsIgnoreCase(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());

        } else if ("none".equalsIgnoreCase(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (datatimeout != null) {
        try {
            ftp.setDataTimeout(Integer.parseInt(datatimeout));

        } catch (Exception _ex) {
            ftp.setDataTimeout(-1);
        }
    }

    if (port <= 0) {
        port = ftp.getDefaultPort();
    }

    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();

        sb.append(Emit.messages.getString("FTPAboutToGetFileFromServer")).append(" - ").append("file name:")
                .append(filename).append(",server:").append(server).append(":").append(port)
                .append(",username:").append(username).append(",userpassword:")
                .append(userpassword != null && !"anonymous".equals(username) ? "<obscured>" : userpassword)
                .append(",transfer:").append(transfer).append(",mode:").append(mode).append(",epsv:")
                .append(epsv).append(",protocol:").append(protocol).append(",trustmgr:").append(trustmgr)
                .append(",datatimeout:").append(datatimeout).append(",proxyserver:").append(proxyserver)
                .append(":").append(proxyport).append(",proxyusername:").append(proxyusername)
                .append(",proxypassword:").append(proxypassword != null ? "<obscured>" : null);

        logger.fine(sb.toString());
    }

    try {
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer"));
            return null;
        }

    } catch (IOException _ex) {
        logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer"));

        if (ftp.isConnected())
            try {
                ftp.disconnect();
            } catch (IOException _ex2) {
            }

        return null;
    }

    ByteArrayOutputStream output;
    try {
        if (!ftp.login(username, userpassword)) {
            ftp.logout();
            logger.warning(Emit.messages.getString("FTPServerRefusedLoginCredentials"));
            return null;
        }
        if ("binary".equalsIgnoreCase(transfer)) {
            ftp.setFileType(2);
        } else {
            ftp.setFileType(0);
        }

        if ("localactive".equalsIgnoreCase(mode)) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4("true".equalsIgnoreCase(epsv));
        output = new ByteArrayOutputStream();
        ftp.retrieveFile(filename, output);
        output.close();
        ftp.noop();
        ftp.logout();

    } catch (IOException _ex) {
        logger.warning(Emit.messages.getString("FTPFailedToTransferFile"));

        if (ftp.isConnected())
            try {
                ftp.disconnect();
            } catch (IOException _ex2) {
            }
        return null;
    }

    return output.toByteArray();
}

From source file:net.yacy.grid.io.assets.FTPStorageFactory.java

public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread)
        throws IOException {
    this.server = server;
    this.username = username == null ? "" : username;
    this.password = password == null ? "" : password;
    this.port = port;
    this.deleteafterread = deleteafterread;

    this.ftpClient = new Storage<byte[]>() {

        @Override/*from www.j a  va2 s.c  o  m*/
        public void checkConnection() throws IOException {
            return;
        }

        private FTPClient initConnection() throws IOException {
            FTPClient ftp = new FTPClient();
            ftp.setDataTimeout(3000);
            ftp.setConnectTimeout(20000);
            if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) {
                ftp.connect(FTPStorageFactory.this.server);
            } else {
                ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port);
            }
            ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("bad connection to ftp server: " + reply);
            }
            if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("login failure");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(8192);
            return ftp;
        }

        @Override
        public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException {
            long t0 = System.currentTimeMillis();
            FTPClient ftp = initConnection();
            try {
                long t1 = System.currentTimeMillis();
                String file = cdPath(ftp, path);
                long t2 = System.currentTimeMillis();
                ftp.enterLocalPassiveMode();
                boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset));
                long t3 = System.currentTimeMillis();
                if (!success)
                    throw new IOException("storage to path " + path + " was not successful (storeFile=false)");
                Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = "
                        + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2));
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return FTPStorageFactory.this;
        }

        @Override
        public Asset<byte[]> load(String path) throws IOException {
            FTPClient ftp = initConnection();
            ByteArrayOutputStream baos = null;
            byte[] b = null;
            try {
                String file = cdPath(ftp, path);
                baos = new ByteArrayOutputStream();
                ftp.retrieveFile(file, baos);
                b = baos.toByteArray();
                if (FTPStorageFactory.this.deleteafterread)
                    try {
                        boolean deleted = ftp.deleteFile(file);
                        FTPFile[] remaining = ftp.listFiles();
                        if (remaining.length == 0) {
                            ftp.cwd("/");
                            if (path.startsWith("/"))
                                path = path.substring(1);
                            int p = path.indexOf('/');
                            if (p > 0)
                                path = path.substring(0, p);
                            ftp.removeDirectory(path);
                        }
                    } catch (Throwable e) {
                        Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e);
                    }
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return new Asset<byte[]>(FTPStorageFactory.this, b);
        }

        @Override
        public void close() {
        }

        private String cdPath(FTPClient ftp, String path) throws IOException {
            int success_code = ftp.cwd("/");
            if (success_code >= 300)
                throw new IOException("cannot cd into " + path + ": " + success_code);
            if (path.length() == 0 || path.equals("/"))
                return "";
            if (path.charAt(0) == '/')
                path = path.substring(1); // we consider that all paths are absolute to / (home)
            int p;
            while ((p = path.indexOf('/')) > 0) {
                String dir = path.substring(0, p);
                int code = ftp.cwd(dir);
                if (code >= 300) {
                    // path may not exist, try to create the path
                    boolean success = ftp.makeDirectory(dir);
                    if (!success)
                        throw new IOException("unable to create directory " + dir + " for path " + path);
                    code = ftp.cwd(dir);
                    if (code >= 300)
                        throw new IOException("unable to cwd into directory " + dir + " for path " + path);
                }
                path = path.substring(p + 1);
            }
            return path;
        }
    };
}

From source file:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileAdaptor.java

private void loginWithCredentialOrDefault(FTPClient ftp, Credential credential) throws IOException {
    String password = "";
    String user = "anonymous";
    if (credential instanceof PasswordCredential) {
        PasswordCredential passwordCredential = (PasswordCredential) credential;
        password = new String(passwordCredential.getPassword());
        user = passwordCredential.getUsername();
    }//from ww  w  .  j  a v a  2s  .  co  m
    ftp.login(user, password);
}

From source file:no.imr.sea2data.stox.InstallerUtil.java

public static Boolean retrieveFromFTP(String ftpPath, String outFile, FTPFileFilter filter) {
    try {// ww w  .jav a  2 s . com
        FTPClient ftpClient = new FTPClient();
        // pass directory path on server to connect
        if (ftpPath == null) {
            return false;
        }
        ftpPath = ftpPath.replace("ftp://", "");
        String[] s = ftpPath.split("/", 2);
        if (s.length != 2) {
            return false;
        }
        String server = s[0];
        String subPath = s[1];
        ftpClient.setConnectTimeout(5000);
        ftpClient.connect(server);
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        if (!ftpClient.login("anonymous", "")) {
            return false;
        }
        ftpClient.enterLocalPassiveMode(); // bug : mac doesnt allow ftp server connect through through local firewall - thus use passive server
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            try {
                String path = subPath + "/";
                FTPFile[] files = ftpClient.listFiles(path, filter);
                Optional<FTPFile> opt = Arrays.stream(files)
                        .sorted((f1, f2) -> Integer.compare(f1.getName().length(), f2.getName().length()))
                        .findFirst();
                if (opt.isPresent()) {
                    ftpClient.retrieveFile(path + opt.get().getName(), fos);
                }
            } finally {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return true;
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}