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

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

Introduction

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

Prototype

public int getReplyCode() 

Source Link

Document

Returns the integer value of the reply code of the last FTP reply.

Usage

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

/**
 * Start FTP upload.//from  w  w  w .  ja  v  a  2 s  .c  o m
 *
 * @param hostname      ftp host
 * @param port          ftp port
 * @param uri           upload uri
 * @param fileSizeOctet file size in octet
 * @param user          username
 * @param password      password
 */
public void startFtpUpload(final String hostname, final int port, final String uri, final int fileSizeOctet,
        final String user, final String password) {

    mSpeedTestMode = SpeedTestMode.UPLOAD;

    mUploadFileSize = new BigDecimal(fileSizeOctet);
    mForceCloseSocket = false;
    mErrorDispatched = false;

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

    mWriteExecutorService.execute(new Runnable() {
        @Override
        public void run() {

            final FTPClient ftpClient = new FTPClient();
            final RandomGen randomGen = new RandomGen();

            RandomAccessFile uploadFile = null;

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

                byte[] fileContent = new byte[] {};

                if (mSocketInterface.getUploadStorageType() == UploadStorageType.RAM_STORAGE) {
                    /* generate a file with size of fileSizeOctet octet */
                    fileContent = randomGen.generateRandomArray(fileSizeOctet);
                } else {
                    uploadFile = randomGen.generateRandomFile(fileSizeOctet);
                    uploadFile.seek(0);
                }

                mFtpOutputstream = ftpClient.storeFileStream(uri);

                if (mFtpOutputstream != null) {

                    mUploadTempFileSize = 0;

                    final int uploadChunkSize = mSocketInterface.getUploadChunkSize();

                    final int step = fileSizeOctet / uploadChunkSize;
                    final int remain = fileSizeOctet % uploadChunkSize;

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

                    if (mRepeatWrapper.isFirstUpload()) {
                        mRepeatWrapper.setFirstUploadRepeat(false);
                        mRepeatWrapper.setStartDate(mTimeStart);
                    }

                    if (mRepeatWrapper.isRepeatUpload()) {
                        mRepeatWrapper.updatePacketSize(mUploadFileSize);
                    }

                    if (mForceCloseSocket) {
                        SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "");
                    } else {
                        for (int i = 0; i < step; i++) {

                            final byte[] chunk = SpeedTestUtils.readUploadData(
                                    mSocketInterface.getUploadStorageType(), fileContent, uploadFile,
                                    mUploadTempFileSize, uploadChunkSize);

                            mFtpOutputstream.write(chunk, 0, uploadChunkSize);

                            mUploadTempFileSize += uploadChunkSize;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(uploadChunkSize);
                            }

                            if (!mReportInterval) {

                                final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

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

                        if (remain != 0) {

                            final byte[] chunk = SpeedTestUtils.readUploadData(
                                    mSocketInterface.getUploadStorageType(), fileContent, uploadFile,
                                    mUploadTempFileSize, remain);

                            mFtpOutputstream.write(chunk, 0, remain);

                            mUploadTempFileSize += remain;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(remain);
                            }
                        }
                        if (!mReportInterval) {
                            final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                            for (int j = 0; j < mListenerList.size(); j++) {
                                mListenerList.get(j).onUploadProgress(SpeedTestConst.PERCENT_MAX.floatValue(),
                                        report);

                            }
                        }
                        mTimeEnd = System.currentTimeMillis();
                    }
                    mFtpOutputstream.close();

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

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

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

                } else {
                    mReportInterval = false;
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "cant create stream "
                            + "from uri " + uri + " with reply code : " + ftpClient.getReplyCode());
                }
            } catch (SocketTimeoutException e) {
                //e.printStackTrace();
                mReportInterval = false;
                mErrorDispatched = true;
                if (!mForceCloseSocket) {
                    SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, false,
                            SpeedTestConst.SOCKET_WRITE_ERROR);
                } else {
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                }
                closeSocket();
                closeExecutors();
            } catch (IOException e) {
                //e.printStackTrace();
                mReportInterval = false;
                mErrorDispatched = true;
                SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                closeExecutors();
            } finally {
                mErrorDispatched = false;
                mSpeedTestMode = SpeedTestMode.NONE;
                disconnectFtp(ftpClient);
                if (uploadFile != null) {
                    try {
                        uploadFile.close();
                        randomGen.deleteFile();
                    } catch (IOException e) {
                        //e.printStackTrace();
                    }
                }
            }
        }
    });
}

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

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

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

        @Override//from   w  ww.  j av a2 s  .c o m
        public void checkConnection() throws IOException {
            return;
        }

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

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

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

        @Override
        public void close() {
        }

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

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

private void login(Credential credential, FTPClient ftp) throws XenonException {
    try {/*w ww  .j  a va  2 s  .c o m*/
        loginWithCredentialOrDefault(ftp, credential);
        int replyCode = ftp.getReplyCode();
        verifyLoginSuccess(replyCode);
    } catch (XenonException | IOException e) {
        throw new XenonException(getName(), "Failed to login", e);
    }
}

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

private void checkClientReply(FTPClient client, String message) throws XenonException {

    int replyCode = client.getReplyCode();
    String replyString = client.getReplyString();

    if (replyCode >= 100 && replyCode < 300) {
        return;// w ww  .j av a2  s.com
    }

    throw new XenonException(ADAPTOR_NAME, message, new IOException(replyString));
}

From source file:nz.co.jsrsolutions.ds3.provider.CMEEodDataProvider.java

public CMEEodDataProvider(String hostname, String basePath, CMEEodDataProviderExchangeDescriptor[] descriptors)
        throws EodDataProviderException {

    _hostname = hostname;/*from w  ww  .jav a  2  s . c o m*/
    _basePath = basePath;
    _descriptors = descriptors;

    FTPClient ftp = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftp.configure(config);
    boolean error = false;
    try {
        int reply;
        ftp.connect(_hostname);
        _logger.info("Connected to " + _hostname);
        _logger.info(ftp.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            _logger.error("FTP server refused connection.");
            throw new EodDataProviderException("FTP server refused connection.");
        }

        boolean result = ftp.login("anonymous", "jsr@argusat.com");

        result = ftp.changeWorkingDirectory(_basePath);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            _logger.error(reply);
            throw new EodDataProviderException("Failed to cd into " + _basePath);
        }

        for (CMEEodDataProviderExchangeDescriptor descriptor : _descriptors) {

            OutputStream output = new ByteArrayOutputStream();

            String modificationTime = ftp.getModificationTime(descriptor.getFilename());

            // 213 20131202235804\r\n

            result = ftp.retrieveFile(descriptor.getFilename(), output);

            output.close();
        }

        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:org.alfresco.bm.file.FtpTestFileService.java

/**
 * Provides a safe (connected) FTP client
 *///from   www. j  a  va  2  s  . c  o  m
private FTPClient getFTPClient() throws IOException {
    // Connect to the FTP server
    FTPClient ftp = new FTPClient();

    // Connect and login 
    ftp.connect(ftpHost, ftpPort);
    if (!ftp.login(ftpUsername, ftpPassword)) {
        throw new IOException("FTP credentials rejected.");
    }

    if (ftpLocalPassiveMode) {
        ftp.enterLocalPassiveMode();
    }

    // Settings for the FTP channel
    ftp.setControlKeepAliveTimeout(300);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.setAutodetectUTF8(false);
    int reply = ftp.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IOException("FTP server refused connection.");
    }

    // Done
    return ftp;
}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Simple test that connects to the inbuilt ftp server and logs on
 * /*from w w w.j  a  va2 s  .  com*/
 * @throws Exception
 */
public void testFTPConnect() throws Exception {
    logger.debug("Start testFTPConnect");

    FTPClient ftp = connectClient();
    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login not successful", login);
    } finally {
        ftp.disconnect();
    }
}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Simple negative test that connects to the inbuilt ftp server and attempts to 
 * log on with the wrong password.//from   w  w w. j av a  2s  .  com
 * 
 * @throws Exception
 */
public void testFTPConnectNegative() throws Exception {
    logger.debug("Start testFTPConnectNegative");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, "garbage");
        assertFalse("admin login successful", login);

        // now attempt to list the files and check that the command does not 
        // succeed
        FTPFile[] files = ftp.listFiles();

        assertNotNull(files);
        assertTrue(files.length == 0);
        reply = ftp.getReplyCode();

        assertTrue(FTPReply.isNegativePermanent(reply));

    } finally {
        ftp.disconnect();
    }
}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test CWD for FTP server/* w w  w .ja  va 2s .  co  m*/
 * 
 * @throws Exception
 */
public void testCWD() throws Exception {
    logger.debug("Start testCWD");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        FTPFile[] files = ftp.listFiles();
        reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        assertTrue(files.length == 1);

        boolean foundAlfresco = false;
        for (FTPFile file : files) {
            logger.debug("file name=" + file.getName());
            assertTrue(file.isDirectory());

            if (file.getName().equalsIgnoreCase("Alfresco")) {
                foundAlfresco = true;
            }
        }
        assertTrue(foundAlfresco);

        // Change to Alfresco Dir that we know exists
        reply = ftp.cwd("/Alfresco");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // relative path with space char
        reply = ftp.cwd("Data Dictionary");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // non existant absolute
        reply = ftp.cwd("/Garbage");
        assertTrue(FTPReply.isNegativePermanent(reply));

        reply = ftp.cwd("/Alfresco/User Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Wild card
        reply = ftp.cwd("/Alfresco/User*Homes");
        assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply));

        //            // Single char pattern match
        //            reply = ftp.cwd("/Alfre?co");
        //            assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply));

        // two level folder
        reply = ftp.cwd("/Alfresco/Data Dictionary");
        assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply));

        // go up one
        reply = ftp.cwd("..");
        assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply));

        reply = ftp.pwd();
        ftp.getStatus();

        assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply));

        // check we are at the correct point in the tree
        reply = ftp.cwd("Data Dictionary");
        assertTrue(FTPReply.isPositiveCompletion(reply));

    } finally {
        ftp.disconnect();
    }

}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test CRUD for FTP server/*ww  w .  ja  v  a  2 s.c o  m*/
 *
 * @throws Exception
 */
public void testCRUD() throws Exception {
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "Second part";

    logger.debug("Start testFTPCRUD");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        reply = ftp.cwd("/Alfresco/User Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Delete the root directory in case it was left over from a previous test run
        try {
            ftp.removeDirectory(PATH1);
        } catch (IOException e) {
            // ignore this error
        }

        // make root directory
        ftp.makeDirectory(PATH1);
        ftp.cwd(PATH1);

        // make sub-directory in new directory
        ftp.makeDirectory(PATH2);
        ftp.cwd(PATH2);

        // List the files in the new directory
        FTPFile[] files = ftp.listFiles();
        assertTrue("files not empty", files.length == 0);

        // Create a file
        String FILE1_CONTENT_1 = "test file 1 content";
        String FILE1_NAME = "testFile1.txt";
        ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));

        // Get the new file
        FTPFile[] files2 = ftp.listFiles();
        assertTrue("files not one", files2.length == 1);

        InputStream is = ftp.retrieveFileStream(FILE1_NAME);

        String content = inputStreamToString(is);
        assertEquals("Content is not as expected", content, FILE1_CONTENT_1);
        ftp.completePendingCommand();

        // Update the file contents
        String FILE1_CONTENT_2 = "That's how it is says Pooh!";
        ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));

        InputStream is2 = ftp.retrieveFileStream(FILE1_NAME);

        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftp.completePendingCommand();

        // now delete the file we have been using.
        assertTrue(ftp.deleteFile(FILE1_NAME));

        // negative test - file should have gone now.
        assertFalse(ftp.deleteFile(FILE1_NAME));

    } finally {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }
}