Example usage for org.apache.commons.net.ftp FTPFile getName

List of usage examples for org.apache.commons.net.ftp FTPFile getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Return the name of the file.

Usage

From source file:onl.area51.gfs.mapviewer.action.ImportGribAction.java

private void selectDestName(FTPClient client, FTPFile remoteFile) throws Exception {
    SwingUtilities.invokeLater(() -> {
        // Default to the remote file name
        fileChooser.setSelectedFile(new File(remoteFile.getName()));

        if (fileChooser.showSaveDialog(Main.getFrame()) == JFileChooser.APPROVE_OPTION) {
            File localFile = fileChooser.getSelectedFile();

            ProgressDialog.copy(remoteFile.getName(), remoteFile.getSize(),
                    () -> client.retrieveFileStream(remoteFile.getName()), () -> {
                        Main.setStatus("Disconnecting, transfer complete.");
                        SwingUtils.executeTask(client::close);
                        OpenGribAction.getInstance().open(localFile);
                    }, () -> {/*from   w w w  . jav a2 s  .c om*/
                        Main.setStatus("Disconnecting, transfer failed");
                        SwingUtils.executeTask(client::close);
                    }, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } else {
            Main.setStatus("Disconnecting, no transfer performed.");
            SwingUtils.executeTask(client::close);
        }

    });
}

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

/**
 * Does a listing of files on the FTP server
 *///from ww w.j  a  v  a2 s.  c om
@Override
protected List<FileData> listRemoteFiles() {
    // Get a list of files from the FTP server
    FTPClient ftp = null;
    FTPFile[] ftpFiles = new FTPFile[0];
    try {
        ftp = getFTPClient();
        if (!ftp.changeWorkingDirectory(ftpPath)) {
            throw new IOException("Failed to change directory (leading '/' could be a problem): " + ftpPath);
        }
        ftpFiles = ftp.listFiles();
    } catch (IOException e) {
        throw new RuntimeException("FTP file listing failed: " + this, e);
    } finally {
        try {
            if (null != ftp) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException e) {
            logger.warn("Failed to close FTP connection: " + e.getMessage());
        }
    }
    // Index each of the files
    List<FileData> remoteFileDatas = new ArrayList<FileData>(ftpFiles.length);
    for (FTPFile ftpFile : ftpFiles) {
        String ftpFilename = ftpFile.getName();
        // Watch out for . and ..
        if (ftpFilename.equals(".") || ftpFilename.equals("..")) {
            continue;
        }
        String ftpExtension = FileData.getExtension(ftpFilename);
        long ftpSize = ftpFile.getSize();

        FileData remoteFileData = new FileData();
        remoteFileData.setRemoteName(ftpFilename);
        remoteFileData.setExtension(ftpExtension);
        remoteFileData.setSize(ftpSize);

        remoteFileDatas.add(remoteFileData);
    }
    // Done
    return remoteFileDatas;
}

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

/**
 * Test CWD for FTP server//from w ww.  ja  va  2 s  .  c o  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.amanzi.neo.geoptima.loader.core.parser.impl.FtpDataParser.java

/**
 * @param ftpClient//from   ww w  .j a  va 2 s.c  om
 * @param files
 * @param folder
 * @throws IOException
 */
private void uploadData(final FTPClient ftpClient, final FTPFile[] files, final File folder,
        final FTPFile source) throws IOException {
    try {
        for (FTPFile file : files) {
            if (file.isDirectory()) {
                File newFolder = createFolder(folder.getAbsolutePath() + File.separator + file.getName());
                uploadData(ftpClient, getFiles(ftpClient, file), newFolder, file);
            } else {
                FileOutputStream fos = new FileOutputStream(
                        folder.getAbsolutePath() + File.separator + file.getName());
                LOGGER.info("<Downloading file " + file.getName() + " to directory " + folder.getAbsolutePath()
                        + ">");
                ftpClient.retrieveFile(file.getLink(), fos);
                fos.close();
            }
        }
    } catch (IOException e) {
        LOGGER.error("can't upload file ", e);
        throw e;
    }
}

From source file:org.amanzi.neo.geoptima.loader.core.parser.impl.FtpDataParser.java

/**
 * @param ftpClient/*from   w  ww  .jav  a2  s  .co  m*/
 * @param file
 * @return
 * @throws IOException
 */
private FTPFile[] getFiles(final FTPClient ftpClient, final FTPFile file) throws IOException {
    FTPFile[] files = ftpClient.listFiles(file.getLink(), FTP_FILE_FILTER);
    for (FTPFile innerFile : files) {
        innerFile.setLink(file.getLink() + "/" + innerFile.getName());
    }
    return files;
}

From source file:org.amanzi.neo.geoptima.loader.ui.widgets.impl.FtpContentProvider.java

@Override
public boolean hasChildren(final Object element) {
    FTPFile file = (FTPFile) element;
    file.setLink((parentFile == null ? StringUtils.EMPTY : parentFile.getLink()) + "/" + file.getName());
    if (file.isDirectory()) {
        return true;

    }//  w ww.  j a  v a 2s . c o  m
    return false;
}

From source file:org.amanzi.neo.geoptima.loader.ui.widgets.impl.FtpLabelProvider.java

@Override
public String getText(final Object element) {
    FTPFile file = (FTPFile) element;
    return file.getName();
}

From source file:org.apache.camel.component.file.remote.FtpConsumer.java

protected boolean doPollDirectory(String absolutePath, String dirName, List<GenericFile<FTPFile>> fileList,
        int depth) {
    log.trace("doPollDirectory from absolutePath: {}, dirName: {}", absolutePath, dirName);

    depth++;//  w  w  w.ja va  2  s  .c  om

    // remove trailing /
    dirName = FileUtil.stripTrailingSeparator(dirName);

    // compute dir depending on stepwise is enabled or not
    String dir;
    if (isStepwise()) {
        dir = ObjectHelper.isNotEmpty(dirName) ? dirName : absolutePath;
        operations.changeCurrentDirectory(dir);
    } else {
        dir = absolutePath;
    }

    log.trace("Polling directory: {}", dir);
    List<FTPFile> files = null;
    if (isUseList()) {
        if (isStepwise()) {
            files = operations.listFiles();
        } else {
            files = operations.listFiles(dir);
        }
    } else {
        // we cannot use the LIST command(s) so we can only poll a named file
        // so created a pseudo file with that name
        FTPFile file = new FTPFile();
        file.setType(FTPFile.FILE_TYPE);
        fileExpressionResult = evaluateFileExpression();
        if (fileExpressionResult != null) {
            file.setName(fileExpressionResult);
            files = new ArrayList<FTPFile>(1);
            files.add(file);
        }
    }

    if (files == null || files.isEmpty()) {
        // no files in this directory to poll
        log.trace("No files found in directory: {}", dir);
        return true;
    } else {
        // we found some files
        log.trace("Found {} in directory: {}", files.size(), dir);
    }

    for (FTPFile file : files) {

        if (log.isTraceEnabled()) {
            log.trace("FtpFile[name={}, dir={}, file={}]",
                    new Object[] { file.getName(), file.isDirectory(), file.isFile() });
        }

        // check if we can continue polling in files
        if (!canPollMoreFiles(fileList)) {
            return false;
        }

        if (file.isDirectory()) {
            RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file);
            if (endpoint.isRecursive() && depth < endpoint.getMaxDepth() && isValidFile(remote, true, files)) {
                // recursive scan and add the sub files and folders
                String subDirectory = file.getName();
                String path = absolutePath + "/" + subDirectory;
                boolean canPollMore = pollSubDirectory(path, subDirectory, fileList, depth);
                if (!canPollMore) {
                    return false;
                }
            }
        } else if (file.isFile()) {
            RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file);
            if (depth >= endpoint.getMinDepth() && isValidFile(remote, false, files)) {
                // matched file so add
                fileList.add(remote);
            }
        } else {
            log.debug("Ignoring unsupported remote file type: " + file);
        }
    }

    return true;
}

From source file:org.apache.camel.component.file.remote.FtpConsumer.java

@Override
protected boolean isMatched(GenericFile<FTPFile> file, String doneFileName, List<FTPFile> files) {
    String onlyName = FileUtil.stripPath(doneFileName);

    for (FTPFile f : files) {
        if (f.getName().equals(onlyName)) {
            return true;
        }//from  w  w  w .  ja v  a 2  s.c o  m
    }

    log.trace("Done file: {} does not exist", doneFileName);
    return false;
}

From source file:org.apache.camel.component.file.remote.FtpConsumer.java

private RemoteFile<FTPFile> asRemoteFile(String absolutePath, FTPFile file) {
    RemoteFile<FTPFile> answer = new RemoteFile<FTPFile>();

    answer.setEndpointPath(endpointPath);
    answer.setFile(file);//w w w. ja v a2 s . c o  m
    answer.setFileNameOnly(file.getName());
    answer.setFileLength(file.getSize());
    answer.setDirectory(file.isDirectory());
    if (file.getTimestamp() != null) {
        answer.setLastModified(file.getTimestamp().getTimeInMillis());
    }
    answer.setHostname(((RemoteFileConfiguration) endpoint.getConfiguration()).getHost());

    // absolute or relative path
    boolean absolute = FileUtil.hasLeadingSeparator(absolutePath);
    answer.setAbsolute(absolute);

    // create a pseudo absolute name
    String dir = FileUtil.stripTrailingSeparator(absolutePath);
    String absoluteFileName = FileUtil.stripLeadingSeparator(dir + "/" + file.getName());
    // if absolute start with a leading separator otherwise let it be relative
    if (absolute) {
        absoluteFileName = "/" + absoluteFileName;
    }
    answer.setAbsoluteFilePath(absoluteFileName);

    // the relative filename, skip the leading endpoint configured path
    String relativePath = ObjectHelper.after(absoluteFileName, endpointPath);
    // skip leading /
    relativePath = FileUtil.stripLeadingSeparator(relativePath);
    answer.setRelativeFilePath(relativePath);

    // the file name should be the relative path
    answer.setFileName(answer.getRelativeFilePath());

    answer.setCharset(endpoint.getCharset());
    return answer;
}