Example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor

List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor

Introduction

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

Prototype

protected SimpleFileVisitor() 

Source Link

Document

Initializes a new instance of this class.

Usage

From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

/**
 * get the version history for an item//w w  w .ja v  a2  s .c om
 * @param path - the path of the item
 */
public VersionTO[] getContentVersionHistory(String path) {
    final List<VersionTO> versionList = new ArrayList<VersionTO>();

    try {
        final String pathToContent = path.substring(0, path.lastIndexOf(File.separator));
        final String filename = path.substring(path.lastIndexOf(File.separator) + 1);

        Path versionPath = constructVersionRepoPath(pathToContent);

        EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

        Files.walkFileTree(versionPath, opts, 1, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException {
                String versionFilename = visitPath.toString();

                if (versionFilename.contains(filename)) {
                    VersionTO version = new VersionTO();
                    String label = versionFilename.substring(versionFilename.lastIndexOf("--") + 2);

                    BasicFileAttributes attr = Files.readAttributes(visitPath, BasicFileAttributes.class);

                    version.setVersionNumber(label);
                    version.setLastModifier("ADMIN");
                    version.setLastModifiedDate(new Date(attr.lastModifiedTime().toMillis()));
                    version.setComment("");

                    versionList.add(version);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception err) {
        logger.error("error while getting history for content item " + path);
        logger.debug("error while getting history for content item " + path, err);
    }
    final List<VersionTO> finalVersionList = new ArrayList<VersionTO>();
    if (versionList.size() > 0) {
        Collections.sort(versionList);
        VersionTO latest = versionList.get(versionList.size() - 1);
        String latestVersionLabel = latest.getVersionNumber();
        int temp = latestVersionLabel.indexOf(".");
        String currentMajorVersion = latestVersionLabel.substring(0, temp);

        for (int i = versionList.size(); i > 0; i--) {
            VersionTO v = versionList.get(i - 1);
            String versionId = v.getVersionNumber();
            boolean condition = !versionId.startsWith(currentMajorVersion) && !versionId.endsWith(".0");
            if (condition)
                continue;
            finalVersionList.add(v);
        }
    }
    //Collections.reverse(versionList);
    VersionTO[] versions = new VersionTO[finalVersionList.size()];
    versions = finalVersionList.toArray(versions);
    return versions;
}

From source file:dk.dma.msiproxy.common.provider.AbstractProviderService.java

/**
 * May be called periodically to clean up the message repo folder associated
 * with the provider.//from w w  w.j  a  v  a 2s  .c  o  m
 * <p>
 * The procedure will determine which repository message ID's are still active.
 * and delete folders associated with messages ID's that are not active anymore.
 */
public void cleanUpMessageRepoFolder() {

    long t0 = System.currentTimeMillis();

    // Compute the ID's for message repository folders to keep
    Set<Integer> ids = computeReferencedMessageIds(messages);

    // Build a lookup map of all the paths that ara still active
    Set<Path> paths = new HashSet<>();
    ids.forEach(id -> {
        try {
            Path path = getMessageRepoFolder(id);
            // Add the path and the hashed sub-folders above it
            paths.add(path);
            paths.add(path.getParent());
            paths.add(path.getParent().getParent());
        } catch (IOException e) {
            log.error("Failed computing " + getProviderId() + "  message repo paths for id " + id + ": "
                    + e.getMessage());
        }
    });

    // Scan all sub-folders and delete those
    Path messageRepoRoot = getRepositoryService().getRepoRoot().resolve(MESSAGE_REPO_ROOT_FOLDER)
            .resolve(getProviderId());
    paths.add(messageRepoRoot);

    try {
        Files.walkFileTree(messageRepoRoot, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!paths.contains(dir)) {
                    log.info("Deleting message repo directory :" + dir);
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!paths.contains(file.getParent())) {
                    log.info("Deleting message repo file      :" + file);
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Failed cleaning up " + getProviderId() + " message repo: " + e.getMessage());
    }

    log.info(String.format("Cleaned up %s message repo in %d ms", getProviderId(),
            System.currentTimeMillis() - t0));
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {//w  w w.ja  v  a2  s.co m
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:org.geowebcache.sqlite.OperationsRestTest.java

private void zipDirectory(Path directoryToZip, File outputZipFile) throws IOException {
    try (FileOutputStream fileOutputStream = new FileOutputStream(outputZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        Files.walkFileTree(directoryToZip, new SimpleFileVisitor<Path>() {

            public FileVisitResult visitFile(Path file, BasicFileAttributes fileAttributes) throws IOException {
                zipOutputStream.putNextEntry(new ZipEntry(directoryToZip.relativize(file).toString()));
                Files.copy(file, zipOutputStream);
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }//  ww w.ja  va 2  s .  c  o  m

            public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
                    throws IOException {
                if (directory.equals(directoryToZip)) {
                    return FileVisitResult.CONTINUE;
                }
                // the zip structure is not tied the OS file separator
                zipOutputStream
                        .putNextEntry(new ZipEntry(directoryToZip.relativize(directory).toString() + "/"));
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:org.apdplat.superword.rule.TextAnalysis.java

public static Set<String> getFileNames(String path) {
    Set<String> fileNames = new HashSet<>();
    if (Files.isDirectory(Paths.get(path))) {
        LOGGER.info("?" + path);
    } else {//from   w  w  w .ja  v a2  s  .  c  o m
        LOGGER.info("?" + path);
        fileNames.add(path);
        return fileNames;
    }
    try {
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                String fileName = file.toFile().getAbsolutePath();
                if (!fileName.endsWith(".txt")) {
                    LOGGER.info("??txt" + fileName);
                    return FileVisitResult.CONTINUE;
                }
                fileNames.add(fileName);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

public void copyNewerFilesToDataDir(final Path fromDir, final Path toDir) throws IOException {
    if (Files.exists(fromDir)) {
        Files.walkFileTree(fromDir, new SimpleFileVisitor<Path>() {
            @Override// w  ww . j a v a 2 s.com
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                final Path path = IO.relativeFile(fromDir, file, toDir);
                if (!file.getFileName().toString().toLowerCase().endsWith(".iml") && (!Files.exists(path)
                        || Files.getLastModifiedTime(path).compareTo(Files.getLastModifiedTime(file)) < 0)) {
                    Files.deleteIfExists(path);
                    IO.copyDirectoryOrFile(file, path, false);
                }
                return super.visitFile(file, attrs);
            }
        });
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy every file of given {@code zipFile} beginning with given {@code zipSubPath} to {@code destDir}
 *
 * @param zipFile/*from w w w .j a  v  a  2 s. com*/
 * @param zipSubPath must start with a "/"
 * @param destDir
 * @throws RuntimeIOException
 */
public static void unzipSubDirectoryIfExists(@Nonnull Path zipFile, @Nonnull String zipSubPath,
        @Nonnull final Path destDir) throws RuntimeIOException {
    Preconditions.checkArgument(zipSubPath.startsWith("/"), "zipSubPath '%s' must start with a '/'",
            zipSubPath);
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath(zipSubPath);
            if (Files.notExists(root)) {
                logger.trace("Zip sub path {} does not exist in {}", zipSubPath, zipFile);
                return;
            }

            //walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), root.relativize(file).toString());
                        logger.trace("Extract file {} to {} as {}", file, destDir, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' with root '" + root
                                + "' to destDir '" + destDir + "', ignore file", e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    dir.relativize(root).toString();
                    final Path dirToCreate = Paths.get(destDir.toString(), root.relativize(dir).toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubPath + " to " + destDir, e);
    }
}

From source file:org.vpac.ndg.storage.util.TimeSliceUtil.java

public void restore(String timesliceId) {
    TimeSlice ts = timeSliceDao.retrieve(timesliceId);
    Path tsPath = getFileLocation(ts);
    try {//www  .  ja  va  2 s  . c om
        Files.walkFileTree(tsPath, new SimpleFileVisitor<Path>() {
            /**
             * Import netcdf dataset
             */
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                String fileName = file.getFileName().toString();

                if (!fileName.endsWith("_old" + GdalFormat.NC.getExtension())) {
                    // IGNORE NON-BACKUP TILE
                    return FileVisitResult.CONTINUE;
                }

                String restoredFilename = fileName.replace("_old", "");
                Path backupTilePath = file.toAbsolutePath();
                Path restoredTilePath = Paths.get(backupTilePath.getParent().toString(), restoredFilename);
                try {
                    FileUtils.move(backupTilePath, restoredTilePath);
                    log.debug("RESTORE {} as {}", backupTilePath, restoredTilePath);
                } catch (Exception e) {
                    log.error("{}", e);
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Error restoring {} caused by {}", tsPath, e);
    }
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);/* w w w . j a v  a2  s.  co m*/
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:org.apdplat.superword.rule.TextAnalysis.java

public static Map<String, List<String>> findEvidence(Path dir, List<String> words) {
    LOGGER.info("?" + dir);
    Map<String, List<String>> data = new HashMap<>();
    try {/*from   w w  w.j a v  a2  s  .  c o  m*/
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = file.toFile().getAbsolutePath();
                if (file.toFile().getName().startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                if (!fileName.endsWith(".txt")) {
                    LOGGER.info("??txt" + fileName);
                    return FileVisitResult.CONTINUE;
                }

                LOGGER.info("?" + fileName);
                List<String> lines = Files.readAllLines(file);
                for (int i = 0; i < lines.size(); i++) {
                    final String line = lines.get(i);
                    final int index = i;
                    words.forEach(word -> {
                        if (line.toLowerCase().contains(word)) {
                            data.putIfAbsent(word, new ArrayList<>());
                            data.get(word).add(line + " <u><i>" + file.toFile().getName().replace(".txt", "")
                                    + "</i></u>");
                        }
                    });
                }

                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;
}