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:at.beris.virtualfile.client.ftp.FtpClient.java

public String getPhysicalRootPath() throws IOException {
    if (physicalRootPath == null) {
        physicalRootPath = executionHandler(new Callable<String>() {
            @Override// w ww.  j ava 2s  . c  o m
            public String call() throws Exception {
                ftpClient.changeWorkingDirectory("/");
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    if (ftpFile.isSymbolicLink() && ".".equals(ftpFile.getLink())) {
                        return "/" + ftpFile.getName() + "/";
                    }
                }
                return "";
            }
        });
    }
    return physicalRootPath;
}

From source file:de.aw.awlib.fragments.AWRemoteFileChooser.java

@Override
protected AWItemListAdapterTemplate<FTPFile> createListAdapter() {
    return new AWSortedItemListAdapter<FTPFile>(FTPFile.class, this) {
        @Override/*from w ww .ja v  a  2  s .  co  m*/
        protected boolean areContentsTheSame(FTPFile item, FTPFile other) {
            return false;
        }

        @Override
        protected boolean areItemsTheSame(FTPFile item, FTPFile other) {
            return item.getName().equals(other.getName());
        }

        @Override
        protected int compare(FTPFile item, FTPFile other) {
            if (item.isDirectory() && !other.isDirectory()) {
                // Directory before File
                return -1;
            } else if (!item.isDirectory() && other.isDirectory()) {
                // File after directory
                return 1;
            } else {
                // Otherwise in Alphabetic order...
                return item.getName().compareTo(other.getName());
            }
        }

        @Override
        protected long getID(@NonNull FTPFile item) {
            return 0;
        }
    };
}

From source file:GridFDock.DataDistribute.java

private void traverse(FTPFile[] fileList) throws IOException {
    String tempDir = null;//from  w w  w .  ja  va 2s.c  o m
    for (FTPFile file : fileList) {
        if (file.getName().equals(".") || file.getName().equals("..")) {
            continue;
        }
        if (file.isDirectory()) {
            System.out.println("***************** Directory: " + file.getName() + "  Start **************");
            tempDir = ftpClient.printWorkingDirectory();
            if (tempDir.matches("^((/\\w+))+$"))
                tempDir += "/" + file.getName();
            else
                tempDir += file.getName();
            ftpClient.changeWorkingDirectory(new String(tempDir.getBytes(CODING_1), CODING_2));
            traverse(ftpClient.listFiles(tempDir));

            // If is not a directory.
            System.out.println("***************** Directory:" + file.getName() + "   End **************\n");
        } else {
            System.out.println("FileName:" + file.getName() + " FileSize:" + file.getSize() / (1024) + "KB"
                    + " CreateTime:" + file.getTimestamp().getTime());
        }
    }

    ftpClient.changeToParentDirectory();
}

From source file:br.gov.frameworkdemoiselle.behave.regression.repository.FTPRepository.java

private int countAndRemove(FTPFile ftpFile, boolean remove) {
    int result = 0;
    try {/* w  w  w. j  a  v a  2s.  co m*/
        if (ftpFile.isFile()) {
            if (remove && !ftp.deleteFile(ftpFile.getName())) {
                throw new BehaveException(message.getString("exception-erro-remove-file", ftpFile.getName()));
            }
            if (FileUtils.getExtension(ftpFile.getName()).equals("txt")) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (ftp.changeWorkingDirectory(ftpFile.getName())) {
                FTPFile[] files = ftp.listFiles();
                for (FTPFile _ftpFile : files) {
                    result += countAndRemove(_ftpFile, remove);
                }
                if (!ftp.changeToParentDirectory()) {
                    throw new BehaveException(message.getString("exception-erro-change-folder", ".."));
                }
                if (remove && !ftp.removeDirectory(ftpFile.getName())) {
                    throw new BehaveException(
                            message.getString("exception-erro-remove-folder", ftpFile.getName()));
                }
            } else {
                throw new BehaveException(message.getString("exception-erro-change-folder", ftpFile.getName()));
            }
        }
    } catch (Exception e) {
        throw new BehaveException(e);
    }
    return result;
}

From source file:com.bdaum.zoom.ui.internal.wizards.FtpDirPage.java

private ContainerCheckedTreeViewer createViewerGroup(Composite comp) {
    urlLabel = new Label(comp, SWT.NONE);
    urlLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    ExpandCollapseGroup expandCollapseGroup = new ExpandCollapseGroup(comp, SWT.NONE);
    final ContainerCheckedTreeViewer cbViewer = new ContainerCheckedTreeViewer(comp,
            SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    expandCollapseGroup.setViewer(cbViewer);
    final Tree tree = cbViewer.getTree();
    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    cbViewer.setLabelProvider(new ZColumnLabelProvider() {
        @Override/* w  w w . j a  v  a  2 s.  co  m*/
        public String getText(Object element) {
            if (element instanceof FTPFile)
                return ((FTPFile) element).getName();
            return element.toString();
        }
    });
    cbViewer.setContentProvider(new ITreeContentProvider() {
        public void inputChanged(Viewer v, Object oldInput, Object newInput) {
            fileParents.clear();
            dirPaths.clear();
        }

        public void dispose() {
            fileParents.clear();
            dirPaths.clear();
        }

        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof FTPClient) {
                FTPClient ftpClient = (FTPClient) inputElement;
                List<FTPFile> files = new ArrayList<FTPFile>();
                try {
                    FTPFile[] listFiles = ftpClient.listFiles();
                    for (FTPFile ftpFile : listFiles) {
                        if (ftpFile.isDirectory()) {
                            if (!ftpFile.getName().endsWith(".")) { //$NON-NLS-1$
                                files.add(ftpFile);
                                dirPaths.put(ftpFile, dir + '/' + ftpFile.getName());
                            }
                        } else if (filter.accept(ftpFile.getName()))
                            files.add(ftpFile);
                    }
                } catch (IOException e) {
                    // ignore
                }
                return files.toArray();
            }
            return new Object[0];
        }

        public boolean hasChildren(Object element) {
            if (element instanceof FTPFile)
                return ((FTPFile) element).isDirectory();
            return false;
        }

        public Object getParent(Object element) {
            return fileParents.get(element);
        }

        public Object[] getChildren(Object parentElement) {
            if (parentElement instanceof FTPFile) {
                FTPFile parent = (FTPFile) parentElement;
                if (parent.isDirectory()) {
                    String path = dirPaths.get(parent);
                    if (path != null)
                        try {
                            if (ftp.changeWorkingDirectory(path)) {
                                List<FTPFile> files = new ArrayList<FTPFile>();
                                for (FTPFile ftpFile : ftp.listFiles()) {
                                    if (ftpFile.isDirectory()) {
                                        if (!ftpFile.getName().endsWith(".")) { //$NON-NLS-1$
                                            files.add(ftpFile);
                                            dirPaths.put(ftpFile, path + '/' + ftpFile.getName());
                                        }
                                    } else if (filter.accept(ftpFile.getName()))
                                        files.add(ftpFile);
                                    fileParents.put(ftpFile, parent);
                                }
                                return files.toArray();
                            }
                        } catch (IOException e) {
                            // ignore
                        }
                }
            }
            return new Object[0];
        }
    });
    cbViewer.setComparator(new ViewerComparator() {
        @Override
        public int compare(Viewer v, Object e1, Object e2) {
            if (e1 instanceof FTPFile && e2 instanceof FTPFile) {
                int i1 = ((FTPFile) e1).isDirectory() ? 1 : 2;
                int i2 = ((FTPFile) e2).isDirectory() ? 1 : 2;
                if (i1 != i2)
                    return i1 - i2;
                return ((FTPFile) e1).getName().compareToIgnoreCase(((FTPFile) e2).getName());
            }
            return super.compare(v, e1, e2);
        }
    });
    cbViewer.addCheckStateListener(new ICheckStateListener() {
        public void checkStateChanged(CheckStateChangedEvent event) {
            validatePage();
        }
    });
    UiUtilities.installDoubleClickExpansion(cbViewer);
    return cbViewer;
}

From source file:com.connection.factory.FtpConnectionApacheLib.java

@Override
public void readAllFilesInCurrentPathWithListener(FileListener listener, String remotePath) {

    try {/* w  w  w .j  a  v a 2s  .  c o m*/
        FTPFile[] fileListTemp = _ftpObj.listFiles(remotePath);
        for (FTPFile each : fileListTemp) {
            RemoteFileObject objectTemp = null;
            if (each.isFile()) {
                objectTemp = new FtpApacheFileObject(FileInfoEnum.FILE);
                objectTemp.setFileName(each.getName());
                objectTemp.setAbsolutePath(remotePath);
                objectTemp.setFileSize(each.getSize());
                objectTemp.setFileType();
                objectTemp.setDate(each.getTimestamp().getTime());
                listener.handleRemoteFile(objectTemp);
            }
        }
    } catch (IOException | ConnectionException ex) {

    }

}

From source file:domain.Proceso.java

public void borrarArchivosFTP() {

    log.log("Borrando Archivos del FTP", false);

    for (FTPFile arch : ftp.archivosFTP) {

        String ls_nombre_archivo = arch.getName();
        ftp.borrarArchivo(ls_nombre_archivo);
    }/*from  w ww  .  j a  v  a2s.  co m*/
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java

private List<FileInfo> getListing(final String path, final int depth, final int maxResults,
        final Integer maxDepth) throws IOException {

    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }// w ww  .j av  a  2 s.c o  m

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth
                + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransfer.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransfer.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransfer.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransfer.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransfer.REMOTE_PATH).evaluateAttributeExpressions()
            .getValue();

    logger.info(String.format("path : %s", path));
    logger.info(String.format("pathPattern : %s", pathPattern));

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    logger.info(String.format("pathFilterMatches : %s", pathFilterMatches));

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (file.isDirectory()) {
            logger.info("PATH: {} ", new Object[] { newFullForwardPath });
            // Repertoire
            if (maxDepth != null) {
                // Si la profondeur de recherche est dfinieoct@ve12
                int level = maxDepth.intValue() - 1;
                if (depth == level) {
                    logger.info("depth == level");
                    boolean matches = true;
                    if (pathPattern != null) {
                        Path reldir = path == null ? Paths.get(".") : Paths.get(newFullForwardPath);
                        if (remotePath != null) {
                            reldir = Paths.get(remotePath).relativize(reldir);
                        }
                        if (reldir != null && !reldir.toString().isEmpty()) {
                            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                                matches = false;
                            }
                        }
                    }
                    if (pathPattern == null || matches) {
                        try {
                            logger.info("going into depth depth:{} and maxDepth: {} ",
                                    new Object[] { depth, maxDepth });
                            listing.addAll(
                                    getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                        } catch (final IOException e) {
                            logger.error("Unable to get listing from " + newFullForwardPath
                                    + "; skipping this subdirectory");
                            throw e;
                        }
                    }
                } else if (depth < level) {
                    logger.info("depth < level");
                    try {
                        logger.info("going into depth depth:{} and maxDepth: {} ",
                                new Object[] { depth, maxDepth });
                        listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                    } catch (final IOException e) {
                        logger.error("Unable to get listing from " + newFullForwardPath
                                + "; skipping this subdirectory");
                        throw e;
                    }
                }
            } else if (recurse) {
                logger.info("MAxDepth  null and recurse = true");
                try {
                    logger.info("Recurse mode depth depth:{}", new Object[] { depth });
                    listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                } catch (final IOException e) {
                    logger.error("Unable to get listing from " + newFullForwardPath
                            + "; skipping this subdirectory");
                    throw e;
                }
            }

        }

        /*
         * if ((file.isDirectory() && pathFilterMatches && maxDepth!=null &&
         * depth<=maxDepth)) { try { logger.info(
         * "going into depth depth:{} and maxDepth: {} ",new
         * Object[]{depth,maxDepth});
         * listing.addAll(getListing(newFullForwardPath, depth + 1,
         * maxResults - count, maxDepth)); } catch (final IOException e) {
         * logger.error("Unable to get listing from " + newFullForwardPath +
         * "; skipping this subdirectory"); throw e; } }else{ if ((recurse
         * && file.isDirectory()) ) { try { logger.info(
         * "Recurse mode depth depth:{}",new Object[]{depth});
         * listing.addAll(getListing(newFullForwardPath, depth + 1,
         * maxResults - count, maxDepth)); } catch (final IOException e) {
         * logger.error("Unable to get listing from " + newFullForwardPath +
         * "; skipping this subdirectory"); throw e; } } }
         */

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                logger.info(String.format("Ajout du fichier %s/%s", path, file.getName()));
                listing.add(newFileInfo(file, path));
                count++;
                logger.info(String.format("Nb fichiers retenus %s", count));
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}

From source file:domain.Proceso.java

public void cargarArchivos() {

    Integer porcentaje = 0;//from www . j a va  2s.  c  o m
    Integer conteo = 1;
    Integer fin;
    /*
     10 - 60
     0 - 50
     */

    fin = ftp.archivosFTP.length;

    for (FTPFile arch : ftp.archivosFTP) {

        String ls_nombre_archivo = arch.getName();
        log.log("Cargando el Archivo: tempfiles\\" + ls_nombre_archivo, false);
        cargarArchivoSql("tempfiles\\" + ls_nombre_archivo);

        porcentaje = ((conteo * 50) / fin) + 10;
        conteo++;
        ventana.setBar(porcentaje);
    }
}

From source file:ch.cyberduck.core.ftp.parser.UnixFTPEntryParserTest.java

@Test
public void testUpperCaseMonths() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser.parseFTPEntry("drwxrwxrwx    41 spinkb  spinkb      1394 Feb 21 20:57 Desktop");
    assertNotNull(parsed);//from  w ww.j av  a2s  . c o m
    assertEquals("Desktop", parsed.getName());
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
    assertEquals("spinkb", parsed.getUser());
    assertEquals("spinkb", parsed.getGroup());
    assertEquals(Calendar.FEBRUARY, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(21, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
}