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

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

Introduction

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

Prototype

public InputStream retrieveFileStream(String remote) throws IOException 

Source Link

Document

Returns an InputStream from which a named file from the server can be read.

Usage

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

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }//w w  w  . java2 s . c  om
    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: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   w ww  .j a va 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: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  .java  2 s .co 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: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);//  w  w  w  .java 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: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.j av a 2 s  . 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:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileSystem.java

@Override
public InputStream readFromFile(Path path) throws XenonException {
    LOGGER.debug("newInputStream path = {}", path);

    assertIsOpen();//w ww.j  a  v a2 s  .c  o  m
    Path absPath = toAbsolutePath(path);
    assertPathExists(absPath);
    assertPathIsFile(absPath);

    // Since FTP connections can only do a single thing a time, we need a
    // new FTPClient to handle the stream.
    FTPClient newClient = adaptor.connect(getLocation(), credential);
    newClient.enterLocalPassiveMode();

    try {
        InputStream in = newClient.retrieveFileStream(absPath.toString());

        checkClientReply(newClient, "Failed to read from path: " + absPath.toString());

        return new TransferClientInputStream(in, new CloseableClient(newClient));
    } catch (IOException e) {
        throw new XenonException(ADAPTOR_NAME, "Failed to read from path: " + absPath);
    }
}

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

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

From source file:org.apache.activemq.blob.FTPBlobDownloadStrategy.java

public InputStream getInputStream(ActiveMQBlobMessage message) throws IOException, JMSException {
    url = message.getURL();// www.  jav a  2  s  .  co  m
    final FTPClient ftp = createFTP();
    String path = url.getPath();
    String workingDir = path.substring(0, path.lastIndexOf("/"));
    String file = path.substring(path.lastIndexOf("/") + 1);
    ftp.changeWorkingDirectory(workingDir);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

    InputStream input = new FilterInputStream(ftp.retrieveFileStream(file)) {

        public void close() throws IOException {
            in.close();
            ftp.quit();
            ftp.disconnect();
        }
    };

    return input;
}