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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java

/**
 * _more_/*from  w  ww  .  ja  v a  2 s  .c om*/
 * 
 * @param file
 *            _more_
 * @param ignoreErrors
 *            _more_
 * 
 * @return _more_
 * 
 * @throws Exception
 *             _more_
 */
private byte[] readFile(String file, boolean ignoreErrors) throws Exception {
    if (new File(file).exists()) {
        return IOUtil.readBytes(IOUtil.getInputStream(file, getClass()));
    }
    if (!file.startsWith("ftp:")) {
        if (ignoreErrors) {
            return null;
        }
        throw new FileNotFoundException("Could not read file: " + file);
    }

    URL url = new URL(file);
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(url.getHost());
        ftp.login("anonymous", "password");
        ftp.setFileType(FTP.IMAGE_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if (ftp.retrieveFile(url.getPath(), bos)) {
            return bos.toByteArray();
        } else {
            throw new IOException("Unable to retrieve file:" + url);
        }
    } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) {
        System.err.println("ftp error:" + fcce);
        System.err.println(ftp.getReplyString());
        if (!ignoreErrors) {
            throw fcce;
        }
        return null;
    } catch (Exception exc) {
        if (!ignoreErrors) {
            throw exc;
        }
        return null;
    } finally {
        try {
            ftp.logout();
        } catch (Exception exc) {
        }
        try {
            ftp.disconnect();
        } catch (Exception exc) {
        }

    }
}

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

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

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

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

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

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

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

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

    return result;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();/*from w  ww  .j a v a2 s .  c  o m*/
            return client;
        } else {
            // this flowFile is going to a different destination, reset session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    // additional  
    FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    final String ftpClientConfig = ctx.getProperty(FTP_CLIENT_CONFIG_SYST).getValue();
    if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_UNIX)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    } else if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_NT)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);/*from w ww . j  a v a  2 s . c om*/
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}

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 . c om*/
            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:convcao.com.caoAgent.convcaoNeptusInteraction.java

private void Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;//from   w ww.ja  v a2 s  . c  om

    try {
        client.connect(ftpServer);
        client.login(userName, password);
        client.enterLocalPassiveMode();
        client.setFileType(FTP.BINARY_FILE_TYPE);
        fis = new FileInputStream(SourcePathDirectory + filename);
        client.changeWorkingDirectory("/" + pathDirectory);

        client.storeFile(filename, fis);

        System.out.println(
                "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename);
        client.logout();

        //Report = "File: " + filename + " Uploaded Successfully ";
    } catch (Exception exp) {
        exp.printStackTrace();
        Report = "Server Error";
        jLabel6.setText(Report);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:base.BasePlayer.AddGenome.java

static void updateEnsemblList() {
    try {//from www .ja v a  2  s.co  m

        menu = new JPopupMenu();
        area = new JTextArea();
        menuscroll = new JScrollPane();

        area.setFont(Main.menuFont);

        menu.add(menuscroll);
        //menu.setPreferredSize(new Dimension(menu.getFontMetrics(Main.menuFont).stringWidth("0000000000000000000000000000000000000000000000000")+Main.defaultFontSize*10, (int)menu.getFontMetrics(Main.menuFont).getHeight()*4));
        menu.setPreferredSize(new Dimension(300, 200));

        //area.setMaximumSize(new Dimension(300, 600));
        //area.setLineWrap(true);
        //area.setWrapStyleWord(true);
        //area.setPreferredSize(new Dimension(300,200));

        area.revalidate();
        menuscroll.getViewport().add(area);
        menu.pack();
        menu.show(AddGenome.treescroll, 0, 0);
        /*   area.addMouseListener(new MouseListener() {
                
              @Override
              public void mouseClicked(MouseEvent arg0) {
                 // TODO Auto-generated method stub
                         
              }
                
              @Override
              public void mouseEntered(MouseEvent arg0) {
                 // TODO Auto-generated method stub
                         
              }
                
              @Override
              public void mouseExited(MouseEvent arg0) {
                 // TODO Auto-generated method stub
                         
              }
                
              @Override
              public void mousePressed(MouseEvent arg0) {
                 StringBuffer buf = new StringBuffer("");
                 for(int i= 0; i<(int)(Math.random()*100); i++) {
                    buf.append("O");
                 }
                 AddGenome.area.append(buf.toString() +"\n");
                 AddGenome.area.setCaretPosition(AddGenome.area.getText().length());
                 AddGenome.area.revalidate();
                         
              }
                
              @Override
              public void mouseReleased(MouseEvent arg0) {
                 // TODO Auto-generated method stub
                         
              }
                      
           });*/

        FTPClient f = new FTPClient();
        news = new ArrayList<String[]>();
        area.append("Connecting to Ensembl...\n");
        //System.out.println("Connecting to Ensembl...");
        f.connect("ftp.ensembl.org");
        f.enterLocalPassiveMode();
        f.login("anonymous", "");
        //System.out.println("Connected.");
        area.append("Connected.\n");

        FTPFile[] files = f.listFiles("pub");
        String releasedir = "";
        String releasenro;
        for (int i = 0; i < files.length; i++) {

            if (files[i].isDirectory() && files[i].getName().contains("release")) {
                releasedir = files[i].getName();
            }
        }

        files = f.listFiles("pub/" + releasedir + "/fasta/");
        releasenro = releasedir.substring(releasedir.indexOf("-") + 1);
        area.append("Searching for new genomes");
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                FTPFile[] fastafiles = f
                        .listFiles("pub/" + releasedir + "/fasta/" + files[i].getName() + "/dna/");
                String[] urls = new String[5];
                for (int j = 0; j < fastafiles.length; j++) {
                    if (fastafiles[j].getName().contains(".dna.toplevel.")) {
                        urls[0] = "ftp://ftp.ensembl.org/pub/" + releasedir + "/fasta/" + files[i].getName()
                                + "/dna/" + fastafiles[j].getName();

                        String filePath = "/pub/" + releasedir + "/fasta/" + files[i].getName() + "/dna/"
                                + fastafiles[j].getName();
                        f.sendCommand("SIZE", filePath);
                        String reply = f.getReplyString().split("\\s+")[1];
                        urls[1] = reply;
                        break;
                    }
                }
                if (urls[0] == null) {
                    continue;
                }
                FTPFile[] annofiles = f.listFiles("pub/" + releasedir + "/gff3/" + files[i].getName());
                for (int j = 0; j < annofiles.length; j++) {
                    if (annofiles[j].getName().contains("." + releasenro + ".gff3.gz")) {
                        urls[2] = "ftp://ftp.ensembl.org/pub/" + releasedir + "/gff3/" + files[i].getName()
                                + "/" + annofiles[j].getName();
                        String filePath = "/pub/" + releasedir + "/gff3/" + files[i].getName() + "/"
                                + annofiles[j].getName();
                        f.sendCommand("SIZE", filePath);
                        String reply = f.getReplyString().split("\\s+")[1];
                        urls[3] = reply;
                        break;
                    }
                }
                if (urls[2] == null) {
                    continue;
                }
                if (files[i].getName().contains("homo_sapiens")) {
                    urls[4] = "http://hgdownload.cse.ucsc.edu/goldenPath/hg19/database/cytoBand.txt.gz";
                } else if (files[i].getName().contains("mus_musculus")) {
                    urls[4] = "http://hgdownload.cse.ucsc.edu/goldenPath/mm10/database/cytoBand.txt.gz";
                }
                String name = urls[0].substring(urls[0].lastIndexOf("/") + 1, urls[0].indexOf(".dna."));
                //System.out.print(urls[0]+"\t" +urls[1] +"\t" +urls[2] +"\t" +urls[3]);
                if (genomeHash.containsKey(name) || AddGenome.removables.contains(name)) {
                    //System.out.println(name +" already in the list.");
                    area.append(".");
                } else {
                    area.append("\nNew genome " + name + " added.\n");
                    AddGenome.area.setCaretPosition(AddGenome.area.getText().length());
                    AddGenome.area.revalidate();
                    //System.out.println("New reference " +name +" found.");
                    organisms.add(name);
                    news.add(urls);

                    if (urls[4] != null) {
                        //System.out.println(urls[0] +" " + urls[2] +" " +urls[4]);
                        URL[] newurls = { new URL(urls[0]), new URL(urls[2]), new URL(urls[4]) };
                        genomeHash.put(name, newurls);
                    } else {
                        URL[] newurls = { new URL(urls[0]), new URL(urls[2]) };
                        genomeHash.put(name, newurls);
                    }
                    Integer[] sizes = { Integer.parseInt(urls[1]), Integer.parseInt(urls[3]) };
                    sizeHash.put(name, sizes);

                }
                /*if(urls[4] != null) {
                   System.out.print("\t" +urls[4]);
                }
                System.out.println();
                */
            }

        }

        checkGenomes();
        if (news.size() > 0) {

            try {
                //File file = new File();
                FileWriter fw = new FileWriter(Main.genomeDir.getCanonicalPath() + "/ensembl_fetched.txt");
                BufferedWriter bw = new BufferedWriter(fw);

                for (int i = 0; i < news.size(); i++) {
                    for (int j = 0; j < news.get(i).length; j++) {
                        if (news.get(i)[j] == null) {
                            break;
                        }
                        if (j > 0) {
                            bw.write("\t");
                        }
                        bw.write(news.get(i)[j]);
                    }
                    bw.write("\n");
                }
                bw.close();
                fw.close();

            } catch (IOException e) {

                e.printStackTrace();
            }

        }
    } catch (Exception e) {
        Main.showError(e.getMessage(), "Error");
        e.printStackTrace();
    }

}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

private void connectButtonActionPerformed(ActionEvent evt) throws SocketException, IOException {
    String[] vehicles = controlledVehicles.split(",");
    jTextArea1.setText("");
    jTextArea1.repaint();//from  w w w  . j  a  v a  2 s. c om
    showText("Initializing Control Structures");

    try {
        startLocalStructures(vehicles);
    } catch (Exception e) {
        GuiUtils.errorMessage(getConsole(), e);
        return;
    }

    auvs = positions.keySet().size();

    showText("Initializing server connection");

    FTPClient client = new FTPClient();

    boolean PathNameCreated = false;
    try {
        client.connect("www.convcao.com", 21);
        client.login(jTextField1.getText(), new String(jPasswordField1.getPassword()));
        PathNameCreated = client.makeDirectory("/NEPTUS/" + sessionID);
        client.logout();

    } catch (IOException e) {
        jLabel6.setText("Connection Error");
        throw e;
    }

    showText("Sending session data");
    InputData initialState = new InputData();
    initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    initialState.SessionID = sessionID;
    initialState.DemoMode = "1";
    initialState.AUVs = "" + positions.keySet().size();
    String fileName = sessionID + ".txt";

    Gson gson = new Gson();
    String json = gson.toJson(initialState);

    PrintWriter writer = new PrintWriter(fileName, "UTF-8");
    writer.write(json);
    writer.close();

    if (PathNameCreated) {
        jLabel6.setText("Connection Established");
        jLabel1.setVisible(true);
        System.out.println("Uploading first file");
        upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(),
                new String(jPasswordField1.getPassword()), fileName); // send first file
        System.out.println("Uploading second file");
        String mapFxStr = FileUtil.getResourceAsFileKeepName("convcao/com/caoAgent/mapPortoSparse.txt");
        File mapFx = new File(mapFxStr);
        upload("www.convcao.com", "NEPTUS/" + sessionID, mapFx.getParent(), jTextField1.getText(),
                new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); // send sparse map
        System.out.println("Both files uploaded");
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        jTextPane1.setEditable(false);
        jTextField1.setEditable(false);
        jPasswordField1.setEditable(false);
        connectButton.setEnabled(false);
        renewButton.setEnabled(false);
    } else {
        jLabel6.setText(client.getReplyString());
        jLabel1.setVisible(false);
    }

    myDeleteFile(fileName);

    showText("ConvCAO control has started");
}

From source file:com.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java

/**
 * This method uploads the folder containing information related to a batch on a ftp server.
 * /*from w  w  w . ja  v  a2 s .  c o  m*/
 * @param batchInstance {@link BatchInstance}
 * @param batchSchemaService {@link BatchSchemaService}
 * @param batchClass {@link BatchClass}
 * @param response {@link HttpServletResponse}
 * 
 * @return {@link String} the path where file is uploaded
 */
private String uploadToFTPPath(final BatchInstance batchInstance, final BatchSchemaService batchSchemaService,
        final BatchClass batchClass, final HttpServletResponse response) {
    File zipFolder = null;
    String ftpFolderPath = null;
    String batchInstanceIdentifier = null;
    if (null != batchInstance) {
        batchInstanceIdentifier = batchInstance.getIdentifier();
    }
    File tempFolder = new File(createDownloadFolderPathName(batchInstanceIdentifier, baseFolderPath));
    tempFolder.mkdirs();
    if (tempFolder.exists()) {
        FileOutputStream fout = null;
        ZipOutputStream zout = null;
        try {
            PrintWriter writer = response.getWriter();
            response.setContentType(IUtilCommonConstants.CONTENT_TYPE_HTML);
            String zipFileName = createZipFileName(batchInstanceIdentifier);
            String zipFolderPath = EphesoftStringUtil.concatenate(baseFolderPath, File.separator, TROUBLESHOOT,
                    File.separator, zipFileName);

            String zipFilePath = EphesoftStringUtil.concatenate(zipFolderPath, File.separator, zipFileName,
                    ZIP_EXT);
            zipFolder = new File(zipFolderPath);
            zipFolder.mkdirs();
            fout = new FileOutputStream(zipFilePath);
            zout = new ZipOutputStream(fout);
            Properties properties = getFTPProperties();
            if (null != properties) {
                ftpFolderPath = EphesoftStringUtil.concatenate(TROUBLESHOOT, File.separator, zipFileName,
                        ZIP_EXT);
                FTPInformation ftpInformation = new FTPInformation(ftpServerURL, username, password,
                        properties.getProperty(UPLOAD_BASE_DIR),
                        Integer.parseInt(properties.getProperty(NUM_OF_RETRIES)),
                        properties.getProperty(DATA_TIMEOUT), zipFolderPath, TROUBLESHOOT, 2);
                try {
                    FTPClient client = new FTPClient();
                    FTPUtil.createConnection(client, ftpServerURL, username, password,
                            properties.getProperty(DATA_TIMEOUT));
                    client.disconnect();
                    copySelectedFolders(batchInstance, batchSchemaService, batchClass, tempFolder.getPath(),
                            tempFolder);
                    if (null != tempFolder.list()) {
                        FileUtils.zipDirectoryWithFullName(tempFolder.getPath(), zout);
                        FTPUtil.uploadDirectory(ftpInformation, false);
                    }
                    writer.write(copyTroubleshootingArtifacts.getFoldersNotCopied());
                } catch (SocketException socketException) {
                    LOGGER.error("Could not connect to the FTP client. Socket Exception",
                            socketException.getMessage());
                    ftpFolderPath = null;

                    // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results.
                } catch (final IOException ioException) {
                    LOGGER.error(" Invalid Credentials. Could not connect to the FTP client.",
                            ioException.getMessage());
                    ftpFolderPath = null;
                    writer.write("INVALID_CREDENTIALS");
                    response.setStatus(HttpServletResponse.SC_OK);
                    // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results.
                }
            }
        } catch (FTPDataUploadException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error occured in uploading the file to path ",
                    ftpFolderPath));
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error occured in getting writer from response.",
                    e.getMessage()));
        } catch (NumberFormatException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Exception occured in parsing number of retries.",
                    e.getMessage()));
        } finally {
            try {
                closeResources(null, zout, fout, null);
                if (tempFolder != null) {
                    FileUtils.deleteDirectoryAndContentsRecursive(tempFolder);
                }
                if (zipFolder != null) {
                    FileUtils.deleteDirectoryAndContentsRecursive(zipFolder);
                }
            } catch (IOException e) {
                LOGGER.error(EphesoftStringUtil.concatenate("Exception occured while closing outputstream.",
                        e.getMessage()));
            }
        }
    } else {
        LOGGER.error("Could not create the folder for copying the required folders.");
    }
    return ftpFolderPath;
}

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;/*from w w  w  .  jav  a  2  s.c om*/

    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;
}