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:au.edu.uq.cmm.paul.servlet.WebUIController.java

private ArrayList<BuildInfo> loadBuildInfo(ServletContext servletContext) {
    final ArrayList<BuildInfo> res = new ArrayList<>();
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "aclslib"));
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "eccles"));
    try {/*  w  w  w. j  a  v  a 2 s .  c  o  m*/
        Path start = FileSystems.getDefault().getPath(servletContext.getRealPath("/META-INF/maven"));
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().equals("pom.properties")) {
                    try (InputStream is = new FileInputStream(file.toFile())) {
                        res.add(BuildInfo.readBuildInfo(is));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException ex) {
        LOG.error("Problem loading build info");
    }
    return res;
}

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

private static void moveRecursively(final Path sourcePath, final Path targetPath, final boolean replaceExisting)
        throws GenericException {
    final CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    try {//from   w  ww  .j  a  v  a 2 s  . c om
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path sourceDir, BasicFileAttributes attrs)
                    throws IOException {
                Path targetDir = targetPath.resolve(sourcePath.relativize(sourceDir));
                LOGGER.trace("Creating target directory {}", targetDir);
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
                Path targetFile = targetPath.resolve(sourcePath.relativize(sourceFile));
                LOGGER.trace("Moving file from {} to {}", sourceFile, targetFile);
                Files.move(sourceFile, targetFile, copyOptions);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path sourceFile, IOException exc) throws IOException {
                LOGGER.trace("Deleting source directory {}", sourceFile);
                Files.delete(sourceFile);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new GenericException(
                "Error while moving (recursively) directory from " + sourcePath + " to " + targetPath, e);
    }

}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

protected static void deleteDirectory(final Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override//from   ww  w . j a  v a2s.c  o  m
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
            throw exc;
        }
    });
}

From source file:stroom.streamstore.server.fs.FileSystemUtil.java

public static boolean deleteContents(final Path path) {
    try {/*from   w ww .jav  a  2s .  c  o  m*/
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
                // try to delete the file anyway, even if its attributes
                // could not be read, since delete-only access is
                // theoretically possible
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                    throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed; propagate exception
                    throw exc;
                }
            }
        });
    } catch (final IOException e) {
        return false;
    }

    return true;
}

From source file:de.dentrassi.rpm.builder.YumMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    this.logger = new Logger(getLog());

    try {// w  w  w . ja va 2 s.  c om
        final Builder builder = new RepositoryCreator.Builder();
        builder.setTarget(new FileSystemSpoolOutTarget(this.outputDirectory.toPath()));

        if (!this.skipSigning) {
            final PGPPrivateKey privateKey = SigningHelper.loadKey(this.signature, this.logger);
            if (privateKey != null) {
                final int digestAlgorithm = HashAlgorithm.from(this.signature.getHashAlgorithm()).getValue();
                builder.setSigning(output -> new SigningStream(output, privateKey, digestAlgorithm, false,
                        "RPM builder Mojo - de.dentrassi.maven:rpm"));
            }
        }

        final RepositoryCreator creator = builder.build();

        this.packagesPath = new File(this.outputDirectory, "packages");
        Files.createDirectories(this.packagesPath.toPath());

        final Collection<Path> paths = Lists.newArrayList();

        if (!this.skipDependencies) {
            final Set<Artifact> deps = this.project.getArtifacts();
            if (deps != null) {
                paths.addAll(deps.stream()//
                        .filter(d -> d.getType().equalsIgnoreCase("rpm"))//
                        .map(d -> d.getFile().toPath())//
                        .collect(Collectors.toList()));
            }
        } else {
            this.logger.debug("Skipped RPM artifacts from maven dependencies");
        }

        if (this.files != null) {
            paths.addAll(this.files.stream().map(f -> f.toPath()).collect(Collectors.toList()));
        }
        if (this.directories != null) {
            for (final File dir : this.directories) {
                Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        if (file.getFileName().toString().toLowerCase().endsWith(".rpm")) {
                            paths.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        }

        addPackageList(creator, paths);
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to write repository", e);
    }
}

From source file:org.schedulesdirect.grabber.Auditor.java

private Map<String, JSONObject> getStationMap() throws IOException, JSONException {
    final Map<String, JSONObject> map = new HashMap<>();
    final Path maps = vfs.getPath("maps");
    if (Files.isDirectory(maps)) {
        Files.walkFileTree(maps, new FileVisitor<Path>() {

            @Override/*from  w ww .j a v  a  2  s  .c om*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return dir.equals(maps) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String input;
                try (InputStream ins = Files.newInputStream(file)) {
                    input = IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString());
                }
                ObjectMapper mapper = Config.get().getObjectMapper();
                JSONArray jarr = mapper.readValue(
                        mapper.readValue(input, JSONObject.class).getJSONArray("stations").toString(),
                        JSONArray.class);
                for (int i = 0; i < jarr.length(); ++i) {
                    JSONObject jobj = jarr.getJSONObject(i);
                    String id = jobj.getString("stationID");
                    if (!map.containsKey(id))
                        map.put(id, jobj);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOG.error(String.format("Unable to process map file '%s'", file), exc);
                Auditor.this.failed = true;
                return FileVisitResult.CONTINUE;
            }

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

        });
    }
    return map;
}

From source file:org.fao.geonet.api.mapservers.GeoFile.java

/**
 * Returns the names of the vector layers (Shapefiles) in the geographic file.
 *
 * @param onlyOneFileAllowed Return exception if more than one shapefile found
 * @return a collection of layer names//from  www .  ja  v  a2s.  c om
 * @throws IllegalArgumentException If more than on shapefile is found and onlyOneFileAllowed is
 *                                  true or if Shapefile name is not equal to zip file base
 *                                  name
 */
public Collection<String> getVectorLayers(final boolean onlyOneFileAllowed) throws IOException {
    final LinkedList<String> layers = new LinkedList<String>();
    if (zipFile != null) {
        for (Path path : zipFile.getRootDirectories()) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileName = file.getFileName().toString();
                    if (fileIsShp(fileName)) {
                        String base = getBase(fileName);

                        if (onlyOneFileAllowed) {
                            if (layers.size() > 1)
                                throw new IllegalArgumentException("Only one shapefile per zip is allowed. "
                                        + layers.size() + " shapefiles found.");

                            if (base.equals(getBase(fileName))) {
                                layers.add(base);
                            } else
                                throw new IllegalArgumentException("Shapefile name (" + base
                                        + ") is not equal to ZIP file name (" + file.getFileName() + ").");
                        } else {
                            layers.add(base);
                        }
                    }
                    if (fileIsSld(fileName)) {
                        _containsSld = true;
                        _sldBody = fileName;
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
        if (_containsSld) {
            ZipFile zf = new ZipFile(new File(this.file.toString()));
            InputStream is = zf.getInputStream(zf.getEntry(_sldBody));
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String line;
            _sldBody = "";
            while ((line = br.readLine()) != null) {
                _sldBody += line;
            }
            br.close();
            is.close();
            zf.close();
        }
    }

    return layers;
}

From source file:org.neo4j.browser.CannedCypherExecutionTest.java

@Test
public void shouldBeAbleToExecuteAllTheCannedCypherQueriesContainedInStaticHtmlFiles() throws Exception {
    URL resourceLoc = getClass().getClassLoader().getResource("browser");
    assertNotNull(resourceLoc);//from ww  w.j a  v a  2 s  .  c  o  m

    final AtomicInteger explainCount = new AtomicInteger(0);
    final AtomicInteger executionCount = new AtomicInteger(0);

    Files.walkFileTree(Paths.get(resourceLoc.toURI()), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
            final GraphDatabaseService database = new TestGraphDatabaseFactory().newImpermanentDatabase();

            String fileName = file.getFileName().toString();
            if (fileName.endsWith(".html")) {
                String content = FileUtils.readTextFile(file.toFile(), Charsets.UTF_8);
                Elements cypherElements = Jsoup.parse(content).select("pre.runnable")
                        .not(".standalone-example");
                for (Element cypherElement : cypherElements) {
                    String statement = replaceAngularExpressions(cypherElement.text());

                    if (!statement.startsWith(":")) {
                        if (shouldExplain(statement)) {
                            try (Transaction transaction = database.beginTx()) {
                                Iterable<Notification> actual = database.execute(prependExplain(statement))
                                        .getNotifications();
                                boolean skipKnownInefficientCypher = !cypherElement.parent().select(".warn")
                                        .isEmpty();
                                if (skipKnownInefficientCypher) {

                                    List<Notification> targetCollection = new ArrayList<Notification>();
                                    CollectionUtils.addAll(targetCollection, actual);
                                    CollectionUtils.filter(targetCollection,
                                            new org.apache.commons.collections4.Predicate<Notification>()

                                            {
                                                @Override
                                                public boolean evaluate(Notification notification) {
                                                    return notification.getDescription()
                                                            .contains(NotificationCode.CARTESIAN_PRODUCT
                                                                    .values().toString());
                                                }
                                            });

                                    assertThat(
                                            format("Query [%s] should only produce cartesian product "
                                                    + "notifications. [%s]", statement, fileName),
                                            targetCollection, empty());

                                    explainCount.incrementAndGet();
                                    transaction.success();

                                } else {
                                    assertThat(format("Query [%s] should produce no notifications. [%s]",
                                            statement, fileName), actual, is(emptyIterable()));
                                    explainCount.incrementAndGet();
                                    transaction.success();
                                }
                            } catch (QueryExecutionException e) {
                                throw new AssertionError(
                                        format("Failed to explain query [%s] in file [%s]", statement, file),
                                        e);
                            }
                        }
                        try (Transaction transaction = database.beginTx()) {
                            database.execute(statement);
                            executionCount.incrementAndGet();
                            transaction.success();
                        } catch (QueryExecutionException e) {
                            throw new AssertionError(
                                    format("Failed to execute query [%s] in file [%s]", statement, file), e);
                        }
                    }
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });

    assertTrue("Static files should contain at least one valid cypher statement",
            executionCount.intValue() >= 1);
    System.out.printf("Explained %s cypher statements extracted from HTML files, with no notifications.%n",
            explainCount);
    System.out.printf("Executed %s cypher statements extracted from HTML files, with no errors.%n",
            executionCount);
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/** creates a plugin .zip and returns the url for testing */
private String createPlugin(final Path structure, String... properties) throws IOException {
    writeProperties(structure, properties);
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override/*from w  w w .  ja v  a2 s.  c  o m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                stream.putNextEntry(new ZipEntry(structure.relativize(file).toString()));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    if (randomBoolean()) {
        writeSha1(zip, false);
    } else if (randomBoolean()) {
        writeMd5(zip, false);
    }
    return zip.toUri().toURL().toString();
}

From source file:edu.cwru.jpdg.Javac.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
    if (attr.isRegularFile()) {
        String ext = FilenameUtils.getExtension(file.toString());
        if (ext.equals("class")) {
            files.add(file.toFile());/*from  w  ww . j  a va2  s .  c  o  m*/
        }
    }
    return FileVisitResult.CONTINUE;
}