Example usage for java.nio.file FileVisitResult CONTINUE

List of usage examples for java.nio.file FileVisitResult CONTINUE

Introduction

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

Prototype

FileVisitResult CONTINUE

To view the source code for java.nio.file FileVisitResult CONTINUE.

Click Source Link

Document

Continue.

Usage

From source file:lucene.IndexFiles.java

/**
135   * Indexes the given file using the given writer, or if a directory is given,
136   * recurses over files and directories found under the given directory.
137   * /*from  www .  ja  va2 s.c  om*/
138   * NOTE: This method indexes one document per input file.  This is slow.  For good
139   * throughput, put multiple documents into your input file(s).  An example of this is
140   * in the benchmark module, which can create "line doc" files, one document per line,
141   * using the
142   * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
143   * >WriteLineDocTask</a>.
144   *  
145   * @param writer Writer to the index where the given file/dir info will be stored
146   * @param path The file to index, or the directory to recurse into to find files to index
147   * @throws IOException If there is a low-level I/O error
148   */
static void indexDocs(final IndexWriter writer, Path path) throws IOException {
    System.out.println("Test 2.1");

    if (Files.isDirectory(path)) {
        System.out.println("Test 2.2");
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    System.out.println("Test 2.3");
                    System.out.println(file.toString());
                    indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
                    System.out.println("Test 2.4");
                } catch (IOException ignore) {
                    // don't index files that can't be read.
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
    }
}

From source file:com.ejisto.util.IOUtils.java

public static boolean emptyDir(File file) {
    Path directory = file.toPath();
    if (!Files.isDirectory(directory)) {
        return true;
    }/*from w  ww  .  jav a2  s .com*/
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.TERMINATE;
            }
        });
    } catch (IOException e) {
        IOUtils.log.error(format("error while trying to empty the directory %s", directory.toString()), e);
        return false;
    }
    return true;
}

From source file:ch.bender.evacuate.Runner.java

/**
 * visit// w  ww  .j ava  2  s. com
 * <p>
 * @param aPath
 * @return
 */
private FileVisitResult visit(Path aPath) {
    if (isExcluded(aPath)) {
        myLog.debug("Skip because on exclude list: " + aPath.toString());

        if (Files.isDirectory(aPath)) {
            myExclusionDirCount++;
        } else {
            myExclusionFileCount++;
        }

        return FileVisitResult.SKIP_SUBTREE;
    }

    Path subDirToBackupRoot = myBackupDir.relativize(aPath);
    Path origPendant = myOrigDir.resolve(subDirToBackupRoot);

    if (Files.notExists(origPendant)) {
        evacuate(aPath);

        if (Files.isDirectory(aPath)) {
            myEvacuationDirCount++;
            return FileVisitResult.SKIP_SUBTREE;
        }

        // else is file:
        myEvacuationFileCount++;
        return FileVisitResult.CONTINUE;
    }

    return FileVisitResult.CONTINUE;
}

From source file:org.pentaho.di.core.plugins.PluginFolderTest.java

private void cleanTempDir(Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override//from   ww w  .jav a  2 s. c o  m
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("SchemaDist plugin started");

    try {/*  www .j  a  va 2s . com*/
        processArtifactItems();
    } catch (InvalidVersionSpecificationException e) {
        handleFailure(e);
    }
    final File outDir = initializeOutDir(outputDirectory);

    CatalogManager catalogManager = new CatalogManager();
    catalogManager.setVerbosity(999);

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist unpacking artifact " + artifact);
        File workDir = new File(workDirectory, artifact.getArtifactId());
        initializeOutDir(workDir);
        artifactItem.setWorkDir(workDir);
        unpack(artifactItem, workDir);

        if (translateSchemaLocation) {
            String catalogPath = artifactItem.getCatalog();
            File catalogFile = new File(workDir, catalogPath);
            if (!catalogFile.exists()) {
                throw new MojoExecutionException("No catalog file " + catalogPath + " in artifact " + artifact);
            }
            Catalog catalog = new Catalog(catalogManager);
            catalog.setupReaders();
            try {
                // UGLY HACK. On Windows, file names like d:\abc\def\catalog.xml eventually get treated very strangely
                // (resulting in names like "file:<current-working-dir>d:\abc\def\catalog.xml" that are obviously wrong)
                // Prefixing such names with "file:/" helps.
                String prefix;
                if (catalogFile.isAbsolute() && !catalogFile.getPath().startsWith("/")) {
                    prefix = "/";
                } else {
                    prefix = "";
                }
                String fileName = "file:" + prefix + catalogFile.getPath();
                getLog().debug("Calling parseCatalog with: " + fileName);
                catalog.parseCatalog(fileName);
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            } catch (IOException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            }
            artifactItem.setResolveCatalog(catalog);
        }
    }

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist processing artifact " + artifact);
        final File workDir = artifactItem.getWorkDir();
        FileVisitor<Path> fileVisitor = new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
                String fileName = filePath.getFileName().toString();
                if (fileName.endsWith(".xsd")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processXsd(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else if (fileName.endsWith(".wsdl")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processWsdl(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    getLog().debug("Skipping file " + filePath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }
        };
        try {
            Files.walkFileTree(workDir.toPath(), fileVisitor);
        } catch (IOException e) {
            throw new MojoExecutionException("Error processing files of artifact " + artifact, e);
        }

    }
    getLog().info("SchemaDist plugin finished");
}

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

/**
 * get the version history for an item/*from  w ww  . ja v a2 s.co  m*/
 * @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 .  ja  v  a 2s. co 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 {/* ww  w. j  av a 2 s  . c o 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.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 .  j  a 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.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;
            }/*  w w  w  .j av  a2s.co  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;
            }
        });
    }
}