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:dk.netarkivet.archive.bitarchive.distribute.IntegrityTests.java

@Before
public void setUp() {
    rs.setUp();//from   ww w  .ja v  a  2s .  co  m
    // new UseTestRemoteFile().setUp();

    Settings.set(ArchiveSettings.BITARCHIVE_BATCH_JOB_TIMEOUT, String.valueOf(2000));

    FileUtils.removeRecursively(WORKING);
    TestFileUtils.copyDirectoryNonCVS(ORIGINALS, WORKING);

    try {
        if (!TestInfo.UPLOADMESSAGE_TEMP_DIR.exists()) {
            TestInfo.UPLOADMESSAGE_TEMP_DIR.mkdirs();
        }

        FileUtils.removeRecursively(TestInfo.UPLOADMESSAGE_TEMP_DIR);

        TestFileUtils.copyDirectoryNonCVS(TestInfo.UPLOADMESSAGE_ORIGINALS_DIR,
                TestInfo.UPLOADMESSAGE_TEMP_DIR);
    } catch (Exception e) {
        fail("Could not setup configuration:" + e);
    }

    /** Read ftp-related settings from settings.xml. */
    final String ftpServerName = Settings.get(CommonSettings.FTP_SERVER_NAME);
    final int ftpServerPort = Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT));
    final String ftpUserName = Settings.get(CommonSettings.FTP_USER_NAME);
    final String ftpUserPassword = Settings.get(CommonSettings.FTP_USER_PASSWORD);

    /** Connect to test ftp-server. */
    theFTPClient = new FTPClient();

    /*
     * try { theFTPClient.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (IOException e) { throw new
     * IOFailure("Unable to set Transfer mode: " + e); }
     */

    try {
        theFTPClient.connect(ftpServerName, ftpServerPort);
        theFTPClient.login(ftpUserName, ftpUserPassword);
        theFTPClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    } catch (SocketException e) {
        throw new IOFailure("Connect to " + ftpServerName + " failed", e.getCause());
    } catch (IOException e) {
        throw new IOFailure("Connect to " + ftpServerName + " failed", e.getCause());
    }

    JMSConnectionMockupMQ.useJMSConnectionMockupMQ();

    TestFileUtils.copyDirectoryNonCVS(ORIGINALS_DIR, WORKING_DIR);

    bac = BitarchiveClient.getInstance(ALL_BA, ANY_BA, THE_BAMON);

    Settings.set(ArchiveSettings.BITARCHIVE_SERVER_FILEDIR, BITARCHIVE_DIR.getAbsolutePath());
    Settings.set(CommonSettings.DIR_COMMONTEMPDIR, SERVER_DIR.getAbsolutePath());
    bas = BitarchiveServer.getInstance();
    bam = BitarchiveMonitorServer.getInstance();

    /** Do not send notification by email. Print them to STDOUT. */
    Settings.set(CommonSettings.NOTIFICATIONS_CLASS, RememberNotifications.class.getName());
}

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  a  v a 2 s. c  om*/
        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:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public FTPClient getFtpClient(HashMap<String, String> params) {
    String urlServer = params.get("urlServer");
    String usuario = params.get("user");
    String pass = params.get("pass");
    //        String workingDir = params.get("workingDir");

    FTPClient ret = null;//w  w w.j a  v a  2 s  .  c o m
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(InetAddress.getByName(urlServer));
        ftpClient.login(usuario, pass);
        //Verificar conexin con el servidor.
        int reply = ftpClient.getReplyCode();
        System.out.println("Estatus de conexion FTP:" + reply);
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Conectado exitosamente");
        } else {
            System.out.println("No se pudo conectar con el servidor");
        }
        //directorio de trabajo
        //            ftpClient.changeWorkingDirectory(workingDir);
        System.out.println("Establecer carpeta de trabajo");
        //Activar que se envie cualquier tipo de archivo
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ret = ftpClient;
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}

From source file:com.buzz.buzzdata.MongoBuzz.java

private InputStream getFTPInputStream(String ftp_location) {
    InputStream retval = null;//w  w  w.  jav a  2s. com

    String server = "162.219.245.61";
    int port = 21;
    String user = "jelastic-ftp";
    String pass = "HeZCHxeefB";
    FTPClient ftpClient = new FTPClient();

    try {
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        retval = ftpClient.retrieveFileStream(ftp_location);
    } catch (IOException ex) {
        Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return retval;
}

From source file:ca.nrc.cadc.web.ServerToServerFTPTransfer.java

/**
 * Override me to for testing.
 * @return      FTPClient instance.
 */
FTPClient createFTPClient() {
    return new FTPClient();
}

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

public void uploadLocalFileFTP(String filename) {
    UPLOADFILENAME = filename;//from   w w w.j av  a 2  s .  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:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java

protected InputStream getStreamFromFTPNetwork(String imageUri, Object extra) throws IOException {
    int indexUrl = imageUri.indexOf("//") + 1;
    int indexUrlFinal = imageUri.lastIndexOf(":");
    int slash = imageUri.lastIndexOf("/");
    String ip = imageUri.substring(indexUrl + 1, indexUrlFinal);
    FTPClient client = new FTPClient();
    client.connect(ip, 20000);/*  w w w  .jav  a 2 s  .c o m*/
    client.login("anonymous", "");
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    InputStream imageStream = null;
    FTPFile[] directories = client.listFiles();
    long fileLength = (int) getFile(directories, imageUri.substring(slash + 1)).getSize();
    try {
        imageStream = client.retrieveFileStream(imageUri.substring(slash + 1));
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(imageStream);
        throw e;
    }
    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), fileLength);
}

From source file:main.TestManager.java

/**
 * Deletes all files on the server and uploads all the
 * tests from the local directory.//from w  ww .j  a  v  a 2 s .co  m
 */
public static void syncServerWithTest() {
    FTPClient ftp = new FTPClient();
    boolean error = false;
    try {
        int reply;
        String server = "zajicek.endora.cz";
        ftp.connect(server, 21);

        // After connection attempt, we check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        //Not connected successfully - inform the user
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            Debugger.println("FTP server refused connection.");
            ErrorInformer.failedSyncing();
            return;
        }
        // LOGIN
        boolean success = ftp.login("plakato", "L13nK4");
        Debugger.println("Login successful: " + success);
        if (success == false) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        ftp.enterLocalPassiveMode();
        // Get all files from the server
        FTPFile[] files = ftp.listFiles();
        System.out.println("Got files! Count: " + files.length);
        // Delete all current tests on the server to be replaced with 
        // actualized version from local directory
        for (FTPFile f : files) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                ftp.deleteFile(f.getName());
            }
        }
        // Copy the files from local folder to server
        File localFolder = new File("src/tests/");
        File[] localFiles = localFolder.listFiles();
        int failed = 0;
        for (File f : localFiles) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                Debugger.println(f.getName());
                File file = new File("src/tests/" + f.getName());
                InputStream input = new FileInputStream(file);
                if (!ftp.storeFile(f.getName(), input))
                    failed++;
                input.close();
            }
        }
        // If we failed to upload some file, inform the user
        if (failed != 0) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        // Disconnect ftp client or resolve the potential error
        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        if (error) {
            ErrorInformer.failedSyncing();
            return;
        }
    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Upload hotov");
    alert.setHeaderText(null);
    alert.setContentText("spene sa podarilo skoprova vetky testy na server!");

    alert.showAndWait();
    alert.close();
}

From source file:com.example.lista3new.SyncService.java

private boolean ftpConnect(final String host, final int port, final String username, final String password) {
    boolean status = false;
    try {//  w ww .ja  va 2  s  . c  o  m
        mFTPClient = new FTPClient();
        mFTPClient.connect(host, port);
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            status = mFTPClient.login(username, password);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();
            Log.d(TAG, "Connected");
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }

    return status;
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java

public FTPClient createFTPClient() throws GeneralSecurityException, FileNotFoundException, IOException {
    if (useFtpOverTls) {
        FTPSClient c = new FTPSClient(false);

        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
        if (trustStorePath != null) {
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword != null) {
                ts.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
            } else {
                ts.load(new FileInputStream(trustStorePath), null);
            }/*from ww w  . ja v  a  2  s . co  m*/
        } else {
            ts.load(null);
        }

        if (trustedCertificate != null) {
            InputStream certStream = new ByteArrayInputStream(trustedCertificate.getBytes());
            X509Certificate x509certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certStream);
            ts.setCertificateEntry(x509certificate.getSubjectDN().getName(), x509certificate);
        }

        c.setTrustManager(TrustManagerUtils.getDefaultTrustManager(ts));

        return c;
    }
    return new FTPClient();
}