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

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

Introduction

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

Prototype

public boolean completePendingCommand() throws IOException 

Source Link

Document

There are a few FTPClient methods that do not complete the entire sequence of FTP commands to complete a transaction.

Usage

From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }/*ww  w. j  a  va  2 s. c  o  m*/
    final FTPClient ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(30);
    ftp.setControlKeepAliveReplyTimeout(30);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        ftp.connect(ftpSubscription.getFtpHost());
        _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (final IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }
    boolean error = false;
    __main: try {
        if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) {
            ftp.logout();
            error = true;
            break __main;
        }
        _log.info("Remote system is " + ftp.getSystemType());
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        //ftp.enterLocalActiveMode();
        ftp.enterLocalPassiveMode();
        //final FTPClientConfig config = new FTPClientConfig();
        ////config.setLenientFutureDates(true);
        //ftp.configure(config);
        if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) {
            ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder());
        }
        final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile());
        if (is == null) {
            _log.error("FIle not found: " + ftp.getSystemType());
        } else {
            unzip(ftpSubscription, is);
            is.close();
        }
        ftp.completePendingCommand();
    } catch (final FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (final IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException e) {
                _log.error(e);
            }
        }
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates a connection to a target host and then executes an FTP
 * request to send or receive a file to or from the target. This is fully
 * key-based, as a result, a keyfile is required for the connection to
 * successfully authenticate.//ww w.  j a v  a 2  s .  co m
 * 
 * @param sourceFile - The full path to the source file to transfer
 * @param targetFile - The full path (including file name) of the desired target file
 * @param targetHost - The target server to perform the transfer to
 * @param isUpload - <code>true</code> is the transfer is an upload, <code>false</code> if it
 *            is a download 
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeFtpConnection(final String sourceFile, final String targetFile,
        final String targetHost, final boolean isUpload) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", sourceFile);
        DEBUGGER.debug("Value: {}", targetFile);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", isUpload);
    }

    final FTPClient client = new FTPClient();
    final FTPConfig ftpConfig = appBean.getConfigData().getFtpConfig();

    if (DEBUG) {
        DEBUGGER.debug("FTPClient: {}", client);
        DEBUGGER.debug("FTPConfig: {}", ftpConfig);
    }

    try {
        client.connect(targetHost);

        if (DEBUG) {
            DEBUGGER.debug("FTPClient: {}", client);
        }

        if (!(client.isConnected())) {
            throw new IOException("Failed to authenticate to remote host with the provided information");
        }

        boolean isAuthenticated = false;

        if (StringUtils.isNotBlank(ftpConfig.getFtpAccount())) {
            isAuthenticated = client.login(
                    (StringUtils.isNotEmpty(ftpConfig.getFtpAccount())) ? ftpConfig.getFtpAccount()
                            : System.getProperty("user.name"),
                    PasswordUtils.decryptText(ftpConfig.getFtpPassword(), ftpConfig.getFtpSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        } else {
            isAuthenticated = client.login(ftpConfig.getFtpAccount(), null);
        }

        if (DEBUG) {
            DEBUGGER.debug("isAuthenticated: {}", isAuthenticated);
        }

        if (!(isAuthenticated)) {
            throw new IOException("Failed to connect to FTP server: " + targetHost);
        }

        client.enterLocalPassiveMode();

        if (!(FileUtils.getFile(sourceFile).exists())) {
            throw new IOException("File " + sourceFile + " does not exist. Skipping");
        }

        if (isUpload) {
            client.storeFile(targetFile, new FileInputStream(FileUtils.getFile(sourceFile)));
        } else {
            client.retrieveFile(sourceFile, new FileOutputStream(targetFile));
        }

        if (DEBUG) {
            DEBUGGER.debug("Reply: {}", client.getReplyCode());
            DEBUGGER.debug("Reply: {}", client.getReplyString());
        }
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if (client.isConnected()) {
                client.completePendingCommand();
                client.disconnect();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java

/**
 * Store the not-already-cached files from the given URL and return their locations.
 * //from w  w w .ja va  2 s. c  o  m
 * @param archive
 * @return Map<File, String>
 */
private Map<File, String> storeAndDecompressFiles(final Archive archive) {
    Map<File, String> result = new HashMap<File, String>();

    // Create the FTP client

    FTPClient ftpClient = retrieveFtpClient(archive.getUri());

    try {
        // Retrieve the directory listing

        List<ArchiveFile> files = retrieveFiles(archive.getUri().getPath(), ftpClient,
                archive.getExclusionExpression());

        Integer archiveNumber = -1, archiveTotal = files.size();

        logger.info("Archive with name '" + archive.getName() + "' produced " + archiveTotal + " files");

        // An empty archive typically indicates failure

        if (archiveTotal == 0)
            logger.warn("The given archive produced no entries - something probably went wrong");

        // Handle all archive files

        for (ArchiveFile archiveFile : files) {
            archiveNumber++;

            // Check whether the file already exists within the cache

            String baseUrl = (StringUtils.hasText(archive.getUri().getScheme())
                    ? archive.getUri().getScheme() + "://"
                    : "") + archive.getUri().getHost()
                    + (archive.getUri().getPort() != -1 ? ":" + archive.getUri().getPort() : "");

            if (!cacheService.isArchived(baseUrl + archiveFile.getFullPath())) {
                logger.info("Started decompressing archive " + archiveNumber + "/" + archiveTotal
                        + " with name " + archiveFile.getFullPath());

                // Write out the archive to disk so we can determine the MIME type

                File archiveFileFolder = new File(archiveFile
                        .getTranslatedPath(packagesLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!archiveFileFolder.exists())
                    archiveFileFolder.mkdirs();

                File archiveFileLocation = new File(archiveFileFolder, archiveFile.getFile().getName());

                InputStream archiveInputStream = ftpClient.retrieveFileStream(archiveFile.getFullPath());
                OutputStream archiveOutputStream = new FileOutputStream(archiveFileLocation);

                IOUtils.copy(archiveInputStream, archiveOutputStream);

                archiveInputStream.close();
                ftpClient.completePendingCommand();

                archiveOutputStream.flush();
                archiveOutputStream.close();

                // Now unpack the archive and transform each file

                InputStream compressedArchiveInputStream = new FileInputStream(archiveFileLocation);

                // Now determine the content type and create a reader in case of structured content

                MediaType archiveMediaType = autoDetectParser.getDetector()
                        .detect(new BufferedInputStream(compressedArchiveInputStream), new Metadata());

                if (!(archiveMediaType.getType().equals("application")
                        && archiveMediaType.getSubtype().equals("zip"))) {
                    logger.warn("Archive file " + archiveFile.getFullPath() + " contains " + archiveMediaType
                            + " data, which is not yet supported");

                    compressedArchiveInputStream.close();

                    continue;
                } else
                    compressedArchiveInputStream.close();

                // Create a new ZIP file from the given archive and decompress it

                ZipFile zipFile = new ZipFile(archiveFileLocation);

                File resultsLocationFolder = new File(archiveFile
                        .getTranslatedPath(resultsLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!resultsLocationFolder.exists())
                    resultsLocationFolder.mkdirs();

                File resultsLocation = new File(resultsLocationFolder,
                        stripExtension(archiveFile.getFile().getName()));

                if (!resultsLocation.exists())
                    resultsLocation.mkdirs();

                logger.info("Started processing archive with name " + archiveFile.getFullPath());

                Enumeration<? extends ZipEntry> zipEnumerator = zipFile.entries();

                while (zipEnumerator.hasMoreElements()) {
                    ZipEntry entry = zipEnumerator.nextElement();

                    // Store it locally first

                    File entryLocation = new File(resultsLocation, entry.getName());

                    try {
                        InputStream entryInputStream = zipFile.getInputStream(entry);
                        OutputStream entryOutputStream = new FileOutputStream(entryLocation);

                        IOUtils.copy(entryInputStream, entryOutputStream);

                        entryInputStream.close();
                        entryOutputStream.close();
                    } catch (IOException e) {
                        logger.error("Could not store the compressed archive entry on disk", e);

                        continue;
                    }
                }

                zipFile.close();

                // Add it to the results

                result.put(resultsLocation, baseUrl + archiveFile.getFullPath());

                logger.info("Finished processing archive with name " + archiveFile.getFullPath());
            } else if (logger.isDebugEnabled())
                logger.debug("Skipping previously processed archive with name " + archiveFile.getFullPath());
        }
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    } finally {
        try {
            if (ftpClient.isConnected())
                ftpClient.disconnect();
        } catch (IOException e) {
            logger.error("Could not disconnect the FTP client", e);
        }
    }

    return result;
}

From source file:de.ep3.ftpc.controller.portal.CrawlerDownloadController.java

@Override
public void mouseClicked(MouseEvent e) {
    CrawlerResultsItem.PreviewPanel previewPanel = (CrawlerResultsItem.PreviewPanel) e.getSource();
    CrawlerResult crawlerResult = previewPanel.getCrawlerResult();
    CrawlerFile crawlerFile = crawlerResult.getFile();

    FTPClient ftpClient = crawlerResult.getFtpClient();

    if (ftpClient.isConnected()) {
        JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadWhileConnected"), null,
                JOptionPane.ERROR_MESSAGE);
        return;//from  ww w.j  ava  2  s.c  o  m
    }

    String fileExtension = crawlerFile.getExtension();

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter chooserFilter = new FileNameExtensionFilter(
            i18n.translate("fileType", fileExtension.toUpperCase()), crawlerFile.getExtension());

    chooser.setApproveButtonText(i18n.translate("buttonSave"));
    chooser.setDialogTitle(i18n.translate("fileDownloadTo"));
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    chooser.setFileFilter(chooserFilter);
    chooser.setSelectedFile(new File(crawlerFile.getName()));

    int selection = chooser.showSaveDialog(portalFrame);

    if (selection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = chooser.getSelectedFile();

        Server relatedServer = crawlerResult.getServer();

        try {
            ftpClient.connect(relatedServer.need("server.ip"),
                    Integer.parseInt(relatedServer.need("server.port")));

            int replyCode = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new IOException(i18n.translate("crawlerServerRefused"));
            }

            if (relatedServer.has("user.name")) {
                String userName = relatedServer.get("user.name");
                String userPassword = "";

                if (relatedServer.hasTemporary("user.password")) {
                    userPassword = relatedServer.getTemporary("user.password");
                }

                boolean loggedIn = ftpClient.login(userName, userPassword);

                if (!loggedIn) {
                    throw new IOException(i18n.translate("crawlerServerAuthFail"));
                }
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            /* Download file */

            InputStream is = ftpClient.retrieveFileStream(crawlerFile.getFullName());

            if (is != null) {

                byte[] rawFile = new byte[(int) crawlerFile.getSize()];

                int i = 0;

                while (true) {
                    int b = is.read();

                    if (b == -1) {
                        break;
                    }

                    rawFile[i] = (byte) b;
                    i++;

                    /* Occasionally update the download progress */

                    if (i % 1024 == 0) {
                        int progress = Math.round((((float) i) / crawlerFile.getSize()) * 100);

                        status.add(i18n.translate("crawlerDownloadProgress", progress));
                    }
                }

                is.close();
                is = null;

                if (!ftpClient.completePendingCommand()) {
                    throw new IOException();
                }

                Files.write(fileToSave.toPath(), rawFile);
            }

            /* Logout and disconnect */

            ftpClient.logout();

            tryDisconnect(ftpClient);

            status.add(i18n.translate("crawlerDownloadDone"));
        } catch (IOException ex) {
            tryDisconnect(ftpClient);

            JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadFailed", ex.getMessage()),
                    null, JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);//from   w w w.  jav  a  2s  . c o  m
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:ServeurFTP.java

public ServeurFTP(String server10, String username10, String password10, String file10, String server20,
        String username20, String password20, String file20) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    String[] parts;/*from  ww  w .  jav  a 2s .c  o  m*/
    int port1 = 0, port2 = 0;
    FTPClient ftp1, ftp2;
    ProtocolCommandListener listener;

    server1 = server10;
    parts = server1.split(":");
    if (parts.length == 2) {
        server1 = parts[0];
        port1 = Integer.parseInt(parts[1]);
    }
    username1 = username10;
    password1 = password10;
    file1 = file10;
    server2 = server20;
    parts = server2.split(":");
    if (parts.length == 2) {
        server2 = parts[0];
        port2 = Integer.parseInt(parts[1]);
    }
    username2 = username20;
    password2 = password20;
    file2 = file20;

    listener = new PrintCommandListener(new PrintWriter(System.out), true);
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        if (port1 > 0) {
            ftp1.connect(server1, port1);
        } else {
            ftp1.connect(server1);
        }
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        if (port2 > 0) {
            ftp2.connect(server2, port2);
        } else {
            ftp2.connect(server2);
        }
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to server2
        // first, in reality, ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode.  Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

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

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

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

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

/**
 * Test CRUD for FTP server//from   w  w w. j a  v  a 2 s.  co 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();
    }
}

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

/**
 * Create a user other than "admin" who has access to a set of files. 
 * /* w ww.  java2  s.  c  o  m*/
 * Create a folder containing test.docx as user one
 * Update that file as user two.
 * Check user one can see user two's changes.
 * 
 * @throws Exception
 */
public void testTwoUserUpdate() throws Exception {
    logger.debug("Start testFTPConnect");

    final String TEST_DIR = "/Alfresco/User Homes/" + USER_ONE;

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

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

        reply = ftpTwo.getReplyCode();

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

        boolean login = ftpOne.login(USER_ONE, PASSWORD_ONE);
        assertTrue("user one login not successful", login);

        login = ftpTwo.login(USER_TWO, PASSWORD_TWO);
        assertTrue("user two login not successful", login);

        boolean success = ftpOne.changeWorkingDirectory("Alfresco");
        assertTrue("user one unable to cd to Alfreco", success);
        success = ftpOne.changeWorkingDirectory("User*Homes");
        assertTrue("user one unable to cd to User*Homes", success);
        success = ftpOne.changeWorkingDirectory(USER_ONE);
        assertTrue("user one unable to cd to " + USER_ONE, success);

        success = ftpTwo.changeWorkingDirectory("Alfresco");
        assertTrue("user two unable to cd to Alfreco", success);
        success = ftpTwo.changeWorkingDirectory("User*Homes");
        assertTrue("user two unable to cd to User*Homes", success);
        success = ftpTwo.changeWorkingDirectory(USER_ONE);
        assertTrue("user two unable to cd " + USER_ONE, success);

        // Create a file as user one
        String FILE1_CONTENT_1 = "test file 1 content";
        String FILE1_NAME = "test.docx";
        success = ftpOne.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));
        assertTrue("user one unable to append file", success);

        // Update the file as user two
        String FILE1_CONTENT_2 = "test file content updated";
        success = ftpTwo.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        assertTrue("user two unable to append file", success);

        // User one should read user2's content
        InputStream is1 = ftpOne.retrieveFileStream(FILE1_NAME);
        assertNotNull("is1 is null", is1);
        String content1 = inputStreamToString(is1);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content1);
        ftpOne.completePendingCommand();

        // User two should read user2's content
        InputStream is2 = ftpTwo.retrieveFileStream(FILE1_NAME);
        assertNotNull("is2 is null", is2);
        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftpTwo.completePendingCommand();
        logger.debug("Test finished");

    } finally {
        ftpOne.dele(TEST_DIR);
        if (ftpOne != null) {
            ftpOne.disconnect();
        }
        if (ftpTwo != null) {
            ftpTwo.disconnect();
        }
    }

}

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

/**
 * Test Setting the modification time FTP server
 *
 * @throws Exception//w ww. j a v a 2  s .  com
 */
public void testModificationTime() throws Exception {
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "ModificationTime";

    logger.debug("Start testModificationTime");

    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")));

        String pathname = "/Alfresco/User Homes" + "/" + PATH1 + "/" + PATH2 + "/" + FILE1_NAME;

        logger.debug("set modification time");
        // YYYYMMDDhhmmss Time set to 2012 August 30 12:39:05
        String olympicTime = "20120830123905";
        ftp.setModificationTime(pathname, olympicTime);

        String extractedTime = ftp.getModificationTime(pathname);
        // Feature of the commons ftp library ExtractedTime has a "status code" first and is followed by newline chars

        assertTrue("time not set correctly by explicit set time", extractedTime.contains(olympicTime));

        // 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 without setting time directly
        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();

        extractedTime = ftp.getModificationTime(pathname);

        assertFalse("time not moved on if time not explicitly set", extractedTime.contains(olympicTime));

        // 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();
    }
}