java.nio.file.FileVisitOption Java Examples

The following examples show how to use java.nio.file.FileVisitOption. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StreamTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #2
Source File: AbstractHelmMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
List<String> getChartDirectories(String path) throws MojoExecutionException {
	List<String> exclusions = new ArrayList<>();

	if (getExcludes() != null) {
		exclusions.addAll(Arrays.asList(getExcludes()));
	}

	exclusions.addAll(FileUtils.getDefaultExcludesAsList());

	MatchPatterns exclusionPatterns = MatchPatterns.from(exclusions);

	try (Stream<Path> files = Files.walk(Paths.get(path), FileVisitOption.FOLLOW_LINKS)) {
		List<String> chartDirs = files.filter(p -> p.getFileName().toString().equalsIgnoreCase("chart.yaml"))
				.map(p -> p.getParent().toString())
				.filter(shouldIncludeDirectory(exclusionPatterns))
				.collect(Collectors.toList());

		if (chartDirs.isEmpty()) {
			getLog().warn("No Charts detected - no Chart.yaml files found below " + path);
		}

		return chartDirs;
	} catch (IOException e) {
		throw new MojoExecutionException("Unable to scan chart directory at " + path, e);
	}
}
 
Example #3
Source File: AbstractFileSearch.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Starts searching for files in the given path, up to the specified depth.
 *
 * @param _p the FS path to search in
 * @param _depth the depth of nested directories to search in
 * @return a set of paths for all files found
 */
public Set<Path> search(@NotNull Path _p, int _depth) {
	try {
		if(Files.isDirectory(_p))
			Files.walkFileTree(_p, new HashSet<FileVisitOption>(), _depth, this);
		else if(Files.isRegularFile(_p))
			this.visitFile(_p, Files.readAttributes(_p, BasicFileAttributes.class));
	} catch (Exception e) {
		AbstractFileSearch.getLog().error("Error while analyzing path [" + _p + "]: " + e.getMessage());
       }
	if(_p.isAbsolute())
		AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in absolute path [" + _p.toAbsolutePath() + "]");
	else
		AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in relative path [" + _p + "], i.e., absolute path [" + _p.toAbsolutePath() + "]");
	return this.files;
}
 
Example #4
Source File: StreamTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #5
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
/**
 * Recursive search for all {@link #YAML_FILES_PATTERN} in provided base path
 *
 * @param path base path to start (can be file or directory)
 * @return list of all paths matching pattern. Only base file itself if it is a file matching pattern
 */
@Restricted(NoExternalUse.class)
public List<Path> configs(String path) throws ConfiguratorException {
    final Path root = Paths.get(path);

    if (!Files.exists(root)) {
        throw new ConfiguratorException("Invalid configuration: '"+path+"' isn't a valid path.");
    }

    if (Files.isRegularFile(root) && Files.isReadable(root)) {
        return Collections.singletonList(root);
    }

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
    try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE,
            (next, attrs) -> !attrs.isDirectory() && !isHidden(next) && matcher.matches(next), FileVisitOption.FOLLOW_LINKS)) {
        return stream.sorted().collect(toList());
    } catch (IOException e) {
        throw new IllegalStateException("failed config scan for " + path, e);
    }
}
 
Example #6
Source File: Utils.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a file or directory
 *
 * @param file {@link File} representing file or directory
 * @throws IOException
 */
public static void deleteFileOrDirectory(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            Path rootPath = Paths.get(file.getAbsolutePath());

            Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
        } else {
            file.delete();
        }
    } else {
        throw new RuntimeException("File or directory does not exist");
    }
}
 
Example #7
Source File: StreamTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #8
Source File: PathArchive.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
@NonNull
public Iterable<JavaFileObject> getFiles(
        @NonNull String folderName,
        @NullAllowed final ClassPath.Entry entry,
        @NullAllowed final Set<JavaFileObject.Kind> kinds,
        @NullAllowed final JavaFileFilterImplementation filter,
        final boolean recursive) throws IOException {
    if (separator != FileObjects.NBFS_SEPARATOR_CHAR) {
        folderName = folderName.replace(FileObjects.NBFS_SEPARATOR_CHAR, separator);
    }
    final Path target = root.resolve(folderName);
    final List<JavaFileObject> res = new ArrayList<>();
    try (final Stream<Path> s = recursive ? Files.walk(target, FileVisitOption.FOLLOW_LINKS) : Files.list(target)) {
        s.filter((p)->{
            return (kinds == null || kinds.contains(FileObjects.getKind(FileObjects.getExtension(p.getFileName().toString()))))
                && Files.isRegularFile(p);
        })
        .forEach((p)->{res.add(FileObjects.pathFileObject(p, root, rootURI, null));});
    }
    return Collections.unmodifiableCollection(res);
}
 
Example #9
Source File: StreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #10
Source File: Main.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    System.out.println("native-obfuscator v" + VERSION);
    if (args.length < 2) {
        System.err.println("java -jar native-obfuscator.jar <jar file> <output directory> [libraries dir] [exclusions file]");
        return;
    }

    List<Path> libs = new ArrayList<>();
    if (args.length > 2) {
        Files.walk(Paths.get(args[2]), FileVisitOption.FOLLOW_LINKS)
                .filter(f -> f.toString().endsWith(".jar") || f.toString().endsWith(".zip"))
                .forEach(libs::add);
    }

    new NativeObfuscator().process(Paths.get(args[0]), Paths.get(args[1]), libs,
    		args.length > 3 ? Files.readAllLines(Paths.get(args[3]), StandardCharsets.UTF_8) : Collections.emptyList());
}
 
Example #11
Source File: MapSource.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public Set<Path> getMapFolders(final Logger logger) throws IOException {
    final Set<Path> mapFolders = new HashSet<>();
    for(Path root : getRootPaths()) {
        int depth = "".equals(root.toString()) ? 0 : Iterables.size(root);
        Files.walkFileTree(getPath().resolve(root), ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth - depth, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if(!isExcluded(dir)) {
                    if(MapFolder.isMapFolder(dir)) {
                        mapFolders.add(dir);
                    }
                    return FileVisitResult.CONTINUE;
                } else {
                    logger.fine("Skipping excluded path " + dir);
                    return FileVisitResult.SKIP_SUBTREE;
                }
            }
        });
    }
    return mapFolders;
}
 
Example #12
Source File: EurostagDDB.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
EurostagDDB(List<Path> ddbDirs) throws IOException {
    for (Path ddbDir : ddbDirs) {
        ddbDir = readSymbolicLink(ddbDir);
        if (!Files.exists(ddbDir) && !Files.isDirectory(ddbDir)) {
            throw new IllegalArgumentException(ddbDir + " must exist and be a dir");
        }
        Files.walkFileTree(ddbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = file.getFileName().toString();
                Path tmpfile = readSymbolicLink(file);
                if (Files.isDirectory(tmpfile)) {
                    Files.walkFileTree(tmpfile, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, this);
                } else if (Files.isRegularFile(tmpfile) && fileName.endsWith(".tg")) {
                    String key = fileName.substring(0, fileName.length() - 3);
                    if (generators.containsKey(key)) {
                        LOGGER.warn("the processing has detected that the file {} is present in {} and {}", fileName, tmpfile, generators.get(key));
                    }
                    generators.put(key, tmpfile);
                }
                return super.visitFile(file, attrs);
            }
        });
    }
}
 
Example #13
Source File: MCRRestAPIObjectsHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static String listDerivateContentAsJson(MCRDerivate derObj, String path, int depth, UriInfo info,
    Application app)
    throws IOException {
    StringWriter sw = new StringWriter();
    MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
    root = MCRPath.toMCRPath(root.resolve(path));
    if (depth == -1) {
        depth = Integer.MAX_VALUE;
    }
    if (root != null) {
        JsonWriter writer = new JsonWriter(sw);
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), depth,
            new MCRJSONFileVisitor(writer, derObj.getOwnerID(), derObj.getId(), info, app));
        writer.close();
    }
    return sw.toString();
}
 
Example #14
Source File: StreamTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #15
Source File: StreamTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #16
Source File: Updater.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the latest version subfolder of the specified module folder.
 * 
 * @param modFolder module folder to look latest version subfolder in
 * @return the latest version subfolder of the specified module folder or <code>null</code> if the specified module folder contains no folders that are
 *         valid version strings
 * @throws IOException if scanning the specified module folder throws an {@link IOException}
 */
public static Path getLatestVersionSubfolder( final Path modFolder ) throws IOException {
	// Holders because "final" is needed to be accessible from visitFile()
	// (I store the path too because version folder name is ambiguous (e.g. "1.0" and "1.0.0")
	final Holder< Path > latestVersionPath = new Holder<>();
	final Holder< VersionBean > latestVersion = new Holder<>();
	
	Files.walkFileTree( modFolder, Collections.< FileVisitOption > emptySet(), 1, new SimpleFileVisitor< Path >() {
		@Override
		public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs ) throws IOException {
			if ( !attrs.isDirectory() )
				return FileVisitResult.CONTINUE;
			
			final VersionBean version = VersionBean.fromString( file.getFileName().toString() );
			if ( version != null )
				if ( latestVersion.value == null || version.compareTo( latestVersion.value ) > 0 ) {
					latestVersion.value = version;
					latestVersionPath.value = file;
				}
			
			return FileVisitResult.CONTINUE;
		}
	} );
	
	return latestVersionPath.value;
}
 
Example #17
Source File: CreateModulesBean.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the release file for the specified name prefix
 * 
 * @param folder folder in which to search
 * @param prefix file name prefix whose release file to return (the beginning of the file name)
 * @return the release file for the specified name prefix
 * @throws IOException if any error occurs during searching for the release file
 */
private static Path getReleaseFile( final Path folder, final String prefix ) throws IOException {
	final AtomicReference< Path > result = new AtomicReference<>();
	
	Files.walkFileTree( folder, Collections.< FileVisitOption > emptySet(), 1, new SimpleFileVisitor< Path >() {
		@Override
		public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs ) throws IOException {
			if ( attrs.isDirectory() )
				return FileVisitResult.CONTINUE;
			
			if ( file.getFileName().toString().startsWith( prefix ) ) {
				result.set( file );
				return FileVisitResult.TERMINATE;
			}
			
			return FileVisitResult.CONTINUE;
		}
	} );
	
	return result.get();
}
 
Example #18
Source File: GermlineVcfReader.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
private void findVcfFiles()
{
    // current prod examples
    // structuralVariants/gridss/CPCT02030278R_CPCT02030278T/CPCT02030278R_CPCT02030278T.gridss.vcf.gz
    // structural_caller/WIDE01010356T.gridss.unfiltered.vcf.gz
    final List<String> vcfFiles = Lists.newArrayList();

    try
    {
        final Stream<Path> stream = Files.walk(Paths.get(mConfig.BatchRunRootDir), 5, FileVisitOption.FOLLOW_LINKS);

        mVcfFiles.addAll(stream.filter(x -> !x.toFile().isDirectory())
                .map(x -> x.toFile().toString())
                .filter(x -> matchesGridssVcf(x))
                .collect(Collectors.toList()));
    }
    catch (Exception e)
    {
        LOGGER.error("failed find directories for batchDir({}) run: {}", mConfig.BatchRunRootDir, e.toString());
    }

    LOGGER.info("found {} VCF files", mVcfFiles.size());
}
 
Example #19
Source File: StreamTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #20
Source File: CreateBalanceDataPacks.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a balance data pack.
 * 
 * @param webExportFolder base web export folder
 * @param outFile output file
 * @throws Exception if any error occurs
 */
public static void createBDPack( final Path webExportFolder, final Path outFile ) throws Exception {
	try ( final GZIPOutputStream out = new GZIPOutputStream( Files.newOutputStream( outFile ) ) ) {
		
		// First add the SC2 strings
		addFile( out, webExportFolder.resolve( "enUS/S2Strings.xml" ) );
		
		Files.walkFileTree( webExportFolder, Collections.< FileVisitOption > emptySet(), 1, new SimpleFileVisitor< Path >() {
			@Override
			public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs ) throws IOException {
				if ( attrs.isDirectory() )
					return FileVisitResult.CONTINUE;
				
				addFile( out, file );
				
				return FileVisitResult.CONTINUE;
			};
		} );
	}
}
 
Example #21
Source File: RepUtils.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * Counts the SC2 replay files in the specified folder (non-recursive).
 * 
 * @param folder folder in which to count
 * @return the number of SC2 replay files in the specified folder; -1 if the specified path exists but is not a folder or if some error occurs
 */
public static int countReplays( final Path folder ) {
	if ( !Files.exists( folder ) )
		return 0;
	if ( !Files.isDirectory( folder ) )
		return -1;
	
	final Int count = new Int();
	
	try {
		Files.walkFileTree( folder, Collections.< FileVisitOption > emptySet(), 1, new SimpleFileVisitor< Path >() {
			@Override
			public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs ) throws IOException {
				if ( !attrs.isDirectory() && hasRepExt( file ) )
					count.value++;
				
				return FileVisitResult.CONTINUE;
			}
		} );
	} catch ( final IOException ie ) {
		Env.LOGGER.error( "Failed to count replays in folder: " + folder, ie );
		return -1;
	}
	
	return count.value;
}
 
Example #22
Source File: JavacFileManager.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
    this.archivePath = archivePath;
    if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
        Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
        FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
        Assert.checkNonNull(jarFSProvider, "should have been caught before!");
        this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
    } else {
        this.fileSystem = FileSystems.newFileSystem(archivePath, null);
    }
    packages = new HashMap<>();
    for (Path root : fileSystem.getRootDirectories()) {
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                        if (isValid(dir.getFileName())) {
                            packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
                            return FileVisitResult.CONTINUE;
                        } else {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                });
    }
}
 
Example #23
Source File: TestFinder.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static <T> void findTests(final String framework, final Path dir, final List<T> tests, final Set<String> orphanFiles, final Path[] excludePaths, final Set<String> excludedTests, final TestFactory<T> factory) throws Exception {
    final String pattern = System.getProperty(TEST_JS_INCLUDES);
    final String extension = pattern == null ? "js" : pattern;
    final Exception[] exceptions = new Exception[1];
    final List<String> excludedActualTests = new ArrayList<>();

    if (! dir.toFile().isDirectory()) {
        factory.log("WARNING: " + dir + " not found or not a directory");
    }

    Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String fileName = file.getName(file.getNameCount() - 1).toString();
            if (fileName.endsWith(extension)) {
                final String namex = file.toString().replace('\\', '/');
                if (!inExcludePath(file, excludePaths) && !excludedTests.contains(file.getFileName().toString())) {
                    try {
                        handleOneTest(framework, file, tests, orphanFiles, factory);
                    } catch (final Exception ex) {
                        exceptions[0] = ex;
                        return FileVisitResult.TERMINATE;
                    }
                } else {
                    excludedActualTests.add(namex);
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });
    Collections.sort(excludedActualTests);

    for (final String excluded : excludedActualTests) {
        factory.log("Excluding " + excluded);
    }

    if (exceptions[0] != null) {
        throw exceptions[0];
    }
}
 
Example #24
Source File: StreamTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example #25
Source File: StreamTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example #26
Source File: AbstractTest.java    From git-code-format-maven-plugin with MIT License 5 votes vote down vote up
@Before
public final void before() throws Exception {
  projectRoot = resources.getBasedir(projectRootDirectoryName).toPath();

  gitCLI = new GitCLI(projectRoot);

  jGit = Git.init().setDirectory(projectRoot.toFile()).call();
  jGit.add().addFilepattern(".").call();
  jGit.commit().setAll(true).setMessage("First commit").call();

  projectDestination =
      Files.createDirectories(Paths.get("target/test-projects"))
          .resolve(projectRoot.getParent().relativize(projectRoot));

  if (Files.notExists(projectDestination)) {
    return;
  }

  Files.walk(projectDestination, FileVisitOption.FOLLOW_LINKS)
      .sorted(Comparator.reverseOrder())
      .forEach(
          path -> {
            try {
              Files.deleteIfExists(path);
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          });
  Files.deleteIfExists(projectDestination);
}
 
Example #27
Source File: TestFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static <T> void findTests(final String framework, final Path dir, final List<T> tests, final Set<String> orphanFiles, final Path[] excludePaths, final Set<String> excludedTests, final TestFactory<T> factory) throws Exception {
    final String pattern = System.getProperty(TEST_JS_INCLUDES);
    final String extension = pattern == null ? "js" : pattern;
    final Exception[] exceptions = new Exception[1];
    final List<String> excludedActualTests = new ArrayList<>();

    if (!dir.toFile().isDirectory()) {
        factory.log("WARNING: " + dir + " not found or not a directory");
    }

    Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String fileName = file.getName(file.getNameCount() - 1).toString();
            if (fileName.endsWith(extension)) {
                final String namex = file.toString().replace('\\', '/');
                if (!inExcludePath(file, excludePaths) && !excludedTests.contains(file.getFileName().toString())) {
                    try {
                        handleOneTest(framework, file, tests, orphanFiles, factory);
                    } catch (final Exception ex) {
                        exceptions[0] = ex;
                        return FileVisitResult.TERMINATE;
                    }
                } else {
                    excludedActualTests.add(namex);
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });
    Collections.sort(excludedActualTests);

    for (final String excluded : excludedActualTests) {
        factory.log("Excluding " + excluded);
    }

    if (exceptions[0] != null) {
        throw exceptions[0];
    }
}
 
Example #28
Source File: StreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example #29
Source File: JmodTask.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void processSection(JmodOutputStream out, Section section, Path path)
    throws IOException
{
    Files.walkFileTree(path, Set.of(FileVisitOption.FOLLOW_LINKS),
        Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
            {
                Path relPath = path.relativize(file);
                if (relPath.toString().equals(MODULE_INFO)
                        && !Section.CLASSES.equals(section))
                    warning("warn.ignore.entry", MODULE_INFO, section);

                if (!relPath.toString().equals(MODULE_INFO)
                        && !matches(relPath, excludes)) {
                    try (InputStream in = Files.newInputStream(file)) {
                        out.writeEntry(in, section, relPath.toString());
                    } catch (IOException x) {
                        if (x.getMessage().contains("duplicate entry")) {
                            warning("warn.ignore.duplicate.entry",
                                    relPath.toString(), section);
                            return FileVisitResult.CONTINUE;
                        }
                        throw x;
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
}
 
Example #30
Source File: StreamTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}