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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

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

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

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

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

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

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

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

/**
 * @param host FTP Host name./*ww  w .ja  v a2  s .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:net.audumla.climate.bom.BOMDataLoader.java

private synchronized FTPClient getFTPClient(String host) {
    FTPClient ftp = ftpClients.get(host);
    if (ftp == null || !ftp.isAvailable() || !ftp.isConnected()) {
        ftp = new FTPClient();
        FTPClientConfig config = new FTPClientConfig();
        ftp.configure(config);/*from w  w w . j av  a  2  s.c o m*/
        try {
            ftp.setControlKeepAliveTimeout(30);
            ftp.setControlKeepAliveReplyTimeout(5);
            ftp.setDataTimeout(3000);
            ftp.setDefaultTimeout(1000);
            int reply;
            ftp.connect(host);
            LOG.debug("Connected to " + host);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                LOG.error("FTP server '" + host + "' refused connection.");
            } else {
                if (!ftp.login("anonymous", "guest")) {
                    LOG.error("Unable to login to server " + host);
                }
                ftp.setSoTimeout(60000);
                ftp.enterLocalPassiveMode();
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            }
        } catch (IOException e) {
            LOG.error("Unable to connect to " + host, e);
        }
        ftpClients.put(host, ftp);
    }
    if (!ftp.isConnected() || !ftp.isAvailable()) {
        throw new UnsupportedOperationException("Cannot connect to " + host);
    }
    return ftp;
}

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  ww w .  j  ava2 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:convcao.com.agent.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  w w  .  j  ava  2s  .  co  m*/

    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:com.rvl.android.getnzb.LocalNZB.java

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

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

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

    new Thread() {

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

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

            try {

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

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

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

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

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

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

    }.start();
}

From source file:edu.lternet.pasta.dml.download.DownloadHandler.java

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

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

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

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

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

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

                entity.setUrlContentType(contentType);
            }

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

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

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

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

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

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

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

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

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

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

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * start FTP download with specific port, user, password.
 *
 * @param hostname ftp host/*from   w w w .j  a v  a  2 s. co m*/
 * @param uri      ftp uri
 * @param user     ftp username
 * @param password ftp password
 */
public void startFtpDownload(final String hostname, final int port, final String uri, final String user,
        final String password) {

    mSpeedTestMode = SpeedTestMode.DOWNLOAD;

    mErrorDispatched = false;
    mForceCloseSocket = false;

    if (mReadExecutorService == null || mReadExecutorService.isShutdown()) {
        mReadExecutorService = Executors.newSingleThreadExecutor();
    }

    mReadExecutorService.execute(new Runnable() {

        @Override
        public void run() {

            final FTPClient ftpclient = new FTPClient();

            try {
                ftpclient.connect(hostname, port);
                ftpclient.login(user, password);
                ftpclient.enterLocalPassiveMode();
                ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

                mDownloadTemporaryPacketSize = 0;

                mTimeStart = System.currentTimeMillis();
                mTimeEnd = 0;

                if (mRepeatWrapper.isFirstDownload()) {
                    mRepeatWrapper.setFirstDownloadRepeat(false);
                    mRepeatWrapper.setStartDate(mTimeStart);
                }

                mDownloadPckSize = new BigDecimal(getFileSize(ftpclient, uri));

                if (mRepeatWrapper.isRepeatDownload()) {
                    mRepeatWrapper.updatePacketSize(mDownloadPckSize);
                }

                mFtpInputstream = ftpclient.retrieveFileStream(uri);

                if (mFtpInputstream != null) {

                    final byte[] bytesArray = new byte[SpeedTestConst.READ_BUFFER_SIZE];

                    int read;
                    while ((read = mFtpInputstream.read(bytesArray)) != -1) {
                        mDownloadTemporaryPacketSize += read;

                        if (mRepeatWrapper.isRepeatDownload()) {
                            mRepeatWrapper.updateTempPacketSize(read);
                        }

                        if (!mReportInterval) {
                            final SpeedTestReport report = mSocketInterface.getLiveDownloadReport();

                            for (int i = 0; i < mListenerList.size(); i++) {
                                mListenerList.get(i).onDownloadProgress(report.getProgressPercent(), report);
                            }
                        }

                        if (mDownloadTemporaryPacketSize == mDownloadPckSize.longValueExact()) {
                            break;
                        }
                    }

                    mFtpInputstream.close();

                    mTimeEnd = System.currentTimeMillis();

                    mReportInterval = false;
                    final SpeedTestReport report = mSocketInterface.getLiveDownloadReport();

                    for (int i = 0; i < mListenerList.size(); i++) {
                        mListenerList.get(i).onDownloadFinished(report);
                    }

                } else {

                    mReportInterval = false;
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, "cant create stream "
                            + "from uri " + uri + " with reply code : " + ftpclient.getReplyCode());
                }

                if (!mRepeatWrapper.isRepeatDownload()) {
                    closeExecutors();
                }

            } catch (IOException e) {
                //e.printStackTrace();
                mReportInterval = false;
                catchError(true, e.getMessage());
            } finally {
                mErrorDispatched = false;
                mSpeedTestMode = SpeedTestMode.NONE;
                disconnectFtp(ftpclient);
            }
        }
    });
}

From source file:ddf.test.itests.catalog.TestFtp.java

private FTPClient createInsecureClient() throws Exception {
    FTPClient ftp = new FTPClient();

    int attempts = 0;
    while (true) {
        try {/*  w w w .j a  v a 2s.  c  o  m*/
            ftp.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()));
            break;
        } catch (SocketException e) {
            // a socket exception can be thrown if the ftp server is still in the process of coming up
            // or down
            Thread.sleep(1000);
            if (attempts++ > 30) {
                throw e;
            }
        }
    }

    showServerReply(ftp);
    int connectionReply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(connectionReply)) {
        fail("FTP server refused connection: " + connectionReply);
    }

    boolean success = ftp.login(USERNAME, PASSWORD);
    showServerReply(ftp);
    if (!success) {
        fail("Could not log in to the FTP server.");
    }

    ftp.enterLocalPassiveMode();
    ftp.setControlKeepAliveTimeout(300);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    return ftp;
}

From source file:base.BasePlayer.AddGenome.java

static void updateEnsemblList() {
    try {/* w w  w .j  av a 2  s. c  o 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();
    }

}