Example usage for java.nio.file FileVisitOption FOLLOW_LINKS

List of usage examples for java.nio.file FileVisitOption FOLLOW_LINKS

Introduction

In this page you can find the example usage for java.nio.file FileVisitOption FOLLOW_LINKS.

Prototype

FileVisitOption FOLLOW_LINKS

To view the source code for java.nio.file FileVisitOption FOLLOW_LINKS.

Click Source Link

Document

Follow symbolic links.

Usage

From source file:org.omegat.util.FileUtil.java

public static List<String> buildRelativeFilesList(File rootDir, List<String> includes, List<String> excludes)
        throws IOException {
    Path root = rootDir.toPath();
    Pattern[] includeMasks = FileUtil.compileFileMasks(includes);
    Pattern[] excludeMasks = FileUtil.compileFileMasks(excludes);
    BiPredicate<Path, BasicFileAttributes> pred = (p, attr) -> {
        return p.toFile().isFile()
                && FileUtil.checkFileInclude(root.relativize(p).toString(), includeMasks, excludeMasks);
    };//from   w  w  w. ja  va  2s .co  m
    try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, pred, FileVisitOption.FOLLOW_LINKS)) {
        return stream.map(p -> root.relativize(p).toString().replace('\\', '/'))
                .sorted(StreamUtil.localeComparator(Function.identity())).collect(Collectors.toList());
    }
}

From source file:org.roda.core.common.monitor.TransferredResourcesScanner.java

public CloseableIterable<OptionalWithCause<LiteRODAObject>> listTransferredResources() {
    CloseableIterable<OptionalWithCause<LiteRODAObject>> resources = null;

    try {// ww  w . ja  va2 s .  co m
        final Stream<Path> files = Files.walk(basePath, FileVisitOption.FOLLOW_LINKS)
                .filter(path -> !path.equals(basePath));
        final Iterator<Path> fileIterator = files.iterator();

        resources = new CloseableIterable<OptionalWithCause<LiteRODAObject>>() {
            @Override
            public void close() throws IOException {
                files.close();
            }

            @Override
            public Iterator<OptionalWithCause<LiteRODAObject>> iterator() {

                return new Iterator<OptionalWithCause<LiteRODAObject>>() {
                    @Override
                    public boolean hasNext() {
                        return fileIterator.hasNext();
                    }

                    @Override
                    public OptionalWithCause<LiteRODAObject> next() {
                        Path file = fileIterator.next();
                        Optional<LiteRODAObject> liteResource = LiteRODAObjectFactory
                                .get(TransferredResource.class, Arrays.asList(file.toString()), false);
                        return OptionalWithCause.of(liteResource);
                    }
                };
            }
        };
    } catch (IOException e) {
        LOGGER.error("Errored when file walking to list transferred resources");
    }

    return resources;
}

From source file:org.roda.core.storage.fs.FSUtils.java

public static CloseableIterable<Resource> recursivelyListPath(final Path basePath, final Path path)
        throws NotFoundException, GenericException {
    CloseableIterable<Resource> resourceIterable;
    try {/*www  .j  a  v a  2s . c  om*/
        final Stream<Path> walk = Files.walk(path, FileVisitOption.FOLLOW_LINKS);
        final Iterator<Path> pathIterator = walk.iterator();

        // skip root
        if (pathIterator.hasNext()) {
            pathIterator.next();
        }

        resourceIterable = new CloseableIterable<Resource>() {

            @Override
            public Iterator<Resource> iterator() {
                return new Iterator<Resource>() {

                    @Override
                    public boolean hasNext() {
                        return pathIterator.hasNext();
                    }

                    @Override
                    public Resource next() {
                        Path next = pathIterator.next();
                        Resource ret;
                        try {
                            ret = convertPathToResource(basePath, next);
                        } catch (GenericException | NotFoundException | RequestNotValidException e) {
                            LOGGER.error(
                                    "Error while list path " + basePath + " while parsing resource " + next, e);
                            ret = null;
                        }

                        return ret;
                    }

                };
            }

            @Override
            public void close() throws IOException {
                walk.close();
            }
        };

    } catch (NoSuchFileException e) {
        throw new NotFoundException("Could not list contents of entity because it doesn't exist: " + path, e);
    } catch (IOException e) {
        throw new GenericException("Could not list contents of entity at: " + path, e);
    }

    return resourceIterable;
}

From source file:org.structr.web.maintenance.BulkMoveUnusedFilesCommand.java

@Override
public void execute(final Map<String, Object> properties) throws FrameworkException {

    String mode = (String) properties.get("mode");
    String targetDir = (String) properties.get("target");

    if (StringUtils.isBlank(mode)) {
        // default
        mode = "log";
    }/*  ww w. j av  a 2s.c o  m*/

    if (StringUtils.isBlank(targetDir)) {
        // default
        targetDir = "unused";
    }

    logger.log(Level.INFO, "Starting moving of unused files...");

    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final App app = StructrApp.getInstance();

    final String filesLocation = StructrApp.getConfigurationValue(Services.FILES_PATH);

    final Set<String> filePaths = new TreeSet<>();

    if (graphDb != null) {

        List<FileBase> fileNodes = null;

        try (final Tx tx = StructrApp.getInstance().tx()) {

            fileNodes = app.nodeQuery(FileBase.class, false).getAsList();

            for (final FileBase fileNode : fileNodes) {

                final String relativeFilePath = fileNode.getProperty(FileBase.relativeFilePath);

                if (relativeFilePath != null) {
                    filePaths.add(relativeFilePath);
                }
            }

            tx.success();
        }

        final List<Path> files = new LinkedList<>();

        try {

            Files.walk(Paths.get(filesLocation), FileVisitOption.FOLLOW_LINKS).filter(Files::isRegularFile)
                    .forEach((Path file) -> {
                        files.add(file);
                    });

        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }

        Path targetDirPath = null;

        if (targetDir.startsWith("/")) {
            targetDirPath = Paths.get(targetDir);
        } else {
            targetDirPath = Paths.get(filesLocation, targetDir);

        }

        if (mode.equals("move") && !Files.exists(targetDirPath)) {

            try {
                targetDirPath = Files.createDirectory(targetDirPath);

            } catch (IOException ex) {
                logger.log(Level.INFO, "Could not create target directory {0}: {1}",
                        new Object[] { targetDir, ex });
                return;
            }
        }

        for (final Path file : files) {

            final String filePath = file.toString();
            final String relPath = StringUtils.stripStart(filePath.substring(filesLocation.length()), "/");

            //System.out.println("files location: " + filesLocation + ", file path: " + filePath + ", rel path: " + relPath);
            if (!filePaths.contains(relPath)) {

                if (mode.equals("log")) {

                    System.out
                            .println("File " + file + " doesn't exist in database (rel path: " + relPath + ")");

                } else if (mode.equals("move")) {

                    try {
                        final Path targetPath = Paths.get(targetDirPath.toString(),
                                file.getFileName().toString());

                        Files.move(file, targetPath);

                        System.out.println("File " + file.getFileName() + " moved to " + targetPath);

                    } catch (IOException ex) {
                        logger.log(Level.INFO, "Could not move file {0} to target directory {1}: {2}",
                                new Object[] { file, targetDir, ex });
                    }

                }
            }

        }

    }

    logger.log(Level.INFO, "Done");
}

From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java

public static HashSet<Path> getAllFilesRecursive(Path folder, int deep) {
    folder = folder.toAbsolutePath();/*from www  . j  a  v a  2  s .c om*/
    AllFilesRecursive visitor = new AllFilesRecursive();
    try {
        Files.walkFileTree(folder, EnumSet.of(FileVisitOption.FOLLOW_LINKS), deep, visitor);
    } catch (IOException e) {
        // can not happen, since we overrided visitFileFailed, which throws no
        // exception ;)
    }
    return visitor.fFound;
}

From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java

public void searchAndParse(Path datasource, Path folder, int deep) {
    folder = folder.toAbsolutePath();/*from   www . j  a  v  a  2  s  .co  m*/
    SearchAndParseVisitor visitor = new SearchAndParseVisitor(datasource);
    try {
        Files.walkFileTree(folder, EnumSet.of(FileVisitOption.FOLLOW_LINKS), deep, visitor);
    } catch (IOException e) {
        // can not happen, since we override visitFileFailed, which throws no
        // exception ;)
    }
}

From source file:org.zanata.sync.jobs.cache.RepoCacheImpl.java

private long copyDir(Path source, Path target) throws IOException {
    Files.createDirectories(target);
    AtomicLong totalSize = new AtomicLong(0);
    Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override//from   www. j a v a  2 s  .  c  o  m
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    Path targetdir = target.resolve(source.relativize(dir));
                    try {
                        if (Files.isDirectory(targetdir) && Files.exists(targetdir)) {
                            return CONTINUE;
                        }
                        Files.copy(dir, targetdir, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (FileAlreadyExistsException e) {
                        if (!Files.isDirectory(targetdir)) {
                            throw e;
                        }
                    }
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file)) {
                        totalSize.accumulateAndGet(Files.size(file), (l, r) -> l + r);
                    }
                    Path targetFile = target.resolve(source.relativize(file));

                    // only copy to target if it doesn't exist or it exist but the content is different
                    if (!Files.exists(targetFile)
                            || !com.google.common.io.Files.equal(file.toFile(), targetFile.toFile())) {
                        Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    }
                    return CONTINUE;
                }
            });
    return totalSize.get();
}

From source file:se.trixon.filebydate.Operation.java

private boolean generateFileList() {
    mListener.onOperationLog("");
    mListener.onOperationLog(Dict.GENERATING_FILELIST.toString());
    PathMatcher pathMatcher = mProfile.getPathMatcher();

    EnumSet<FileVisitOption> fileVisitOptions = EnumSet.noneOf(FileVisitOption.class);
    if (mProfile.isFollowLinks()) {
        fileVisitOptions = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    }/* ww  w .  j  ava2s. co  m*/

    File file = mProfile.getSourceDir();
    if (file.isDirectory()) {
        FileVisitor fileVisitor = new FileVisitor(pathMatcher, mFiles, this);
        try {
            if (mProfile.isRecursive()) {
                Files.walkFileTree(file.toPath(), fileVisitOptions, Integer.MAX_VALUE, fileVisitor);
            } else {
                Files.walkFileTree(file.toPath(), fileVisitOptions, 1, fileVisitor);
            }

            if (fileVisitor.isInterrupted()) {
                return false;
            }
        } catch (IOException ex) {
            Xlog.e(getClass(), ex.getLocalizedMessage());
        }
    } else if (file.isFile() && pathMatcher.matches(file.toPath().getFileName())) {
        mFiles.add(file);
    }

    if (mFiles.isEmpty()) {
        mListener.onOperationLog(Dict.FILELIST_EMPTY.toString());
    } else {
        Collections.sort(mFiles);
    }

    return true;
}

From source file:se.trixon.mapollage.Operation.java

private boolean generateFileList() throws IOException {
    mListener.onOperationLog("");
    mListener.onOperationLog(Dict.GENERATING_FILELIST.toString());
    PathMatcher pathMatcher = mProfileSource.getPathMatcher();

    EnumSet<FileVisitOption> fileVisitOptions;
    if (mProfileSource.isFollowLinks()) {
        fileVisitOptions = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    } else {/*from   w  w  w .j ava 2 s  . c  o  m*/
        fileVisitOptions = EnumSet.noneOf(FileVisitOption.class);
    }

    File file = mProfileSource.getDir();
    if (file.isDirectory()) {
        FileVisitor fileVisitor = new FileVisitor(pathMatcher, mFiles, file, this);
        try {
            if (mProfileSource.isRecursive()) {
                Files.walkFileTree(file.toPath(), fileVisitOptions, Integer.MAX_VALUE, fileVisitor);
            } else {
                Files.walkFileTree(file.toPath(), fileVisitOptions, 1, fileVisitor);
            }

            if (fileVisitor.isInterrupted()) {
                return false;
            }
        } catch (IOException ex) {
            throw new IOException(String.format("E000 %s", file.getAbsolutePath()));
        }
    } else if (file.isFile() && pathMatcher.matches(file.toPath().getFileName())) {
        mFiles.add(file);
    }

    if (mFiles.isEmpty()) {
        mListener.onOperationFinished(Dict.FILELIST_EMPTY.toString(), 0);
    } else {
        Collections.sort(mFiles);
    }

    return true;
}

From source file:services.ImportExportService.java

public static List<DatabaseImage> findImportables(Path path) {
    final List<DatabaseImage> importable = new LinkedList<DatabaseImage>();
    try {//from   www  .j a  v a 2s. c  o  m
        Files.walkFileTree(path, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                        if (PathService.isImage(path)) {
                            DatabaseImage image = DatabaseImage.forPath(path);
                            if (hasFileToImport(image) && !image.imported) {
                                importable.add(image);
                            }
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException io) {
        io.printStackTrace();
        return importable;
    }
    return importable;
}