java.nio.file.PathMatcher Java Examples

The following examples show how to use java.nio.file.PathMatcher. 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: GlobFilePathFilter.java    From flink with Apache License 2.0 7 votes vote down vote up
@Override
public boolean filterPath(Path filePath) {
	if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) {
		return false;
	}

	// compensate for the fact that Flink paths are slashed
	final String path = filePath.hasWindowsDrive() ?
			filePath.getPath().substring(1) :
			filePath.getPath();

	final java.nio.file.Path nioPath = Paths.get(path);

	for (PathMatcher matcher : getIncludeMatchers()) {
		if (matcher.matches(nioPath)) {
			return shouldExclude(nioPath);
		}
	}

	return true;
}
 
Example #2
Source File: FileResolver.java    From jpa2ddl with Apache License 2.0 6 votes vote down vote up
static List<String> listClassNamesInPackage(String packageName) throws Exception {
	List<String> classes = new ArrayList<>();
	Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', File.separatorChar));
	if (!resources.hasMoreElements()) {
		throw new IllegalStateException("No package found: " + packageName);
	}
	PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.class");
	while (resources.hasMoreElements()) {
		URL resource = resources.nextElement();
		Files.walkFileTree(Paths.get(resource.toURI()), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				if (pathMatcher.matches(path.getFileName())) {
					try {
						String className = Paths.get(resource.toURI()).relativize(path).toString().replace(File.separatorChar, '.');
						classes.add(packageName + '.' + className.substring(0, className.length() - 6));
					} catch (URISyntaxException e) {
						throw new IllegalStateException(e);
					}
				}
				return FileVisitResult.CONTINUE;
			}
		});
	}
	return classes;
}
 
Example #3
Source File: JrtFileSystem.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public PathMatcher getPathMatcher(String syntaxAndInput) {
    int pos = syntaxAndInput.indexOf(':');
    if (pos <= 0 || pos == syntaxAndInput.length()) {
        throw new IllegalArgumentException("pos is " + pos);
    }
    String syntax = syntaxAndInput.substring(0, pos);
    String input = syntaxAndInput.substring(pos + 1);
    String expr;
    if (syntax.equalsIgnoreCase("glob")) {
        expr = JrtUtils.toRegexPattern(input);
    } else if (syntax.equalsIgnoreCase("regex")) {
        expr = input;
    } else {
            throw new UnsupportedOperationException("Syntax '" + syntax
                    + "' not recognized");
    }
    // return matcher
    final Pattern pattern = Pattern.compile(expr);
    return (Path path) -> pattern.matcher(path.toString()).matches();
}
 
Example #4
Source File: MCRAbstractFileSystem.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PathMatcher getPathMatcher(final String syntaxAndPattern) {
    final int pos = syntaxAndPattern.indexOf(':');
    if (pos <= 0 || pos == syntaxAndPattern.length()) {
        throw new IllegalArgumentException();
    }
    final String syntax = syntaxAndPattern.substring(0, pos);
    final String pattern = syntaxAndPattern.substring(pos + 1);
    switch (syntax) {
        case "glob":
            return new MCRGlobPathMatcher(pattern);
        case "regex":
            return new MCRPathMatcher(pattern);
        default:
            throw new UnsupportedOperationException("If the pattern syntax '" + syntax + "' is not known.");
    }
}
 
Example #5
Source File: GitRepository.java    From copybara with Apache License 2.0 6 votes vote down vote up
public void checkout(Glob glob, Path destRoot, GitRevision rev) throws RepoException {
  ImmutableList<TreeElement> treeElements = lsTree(rev, null, true, true);
  PathMatcher pathMatcher = glob.relativeTo(destRoot);
  for (TreeElement file : treeElements) {
    Path path = destRoot.resolve(file.getPath());
    if (pathMatcher.matches(path)) {
      try {
        Files.write(
            path, readFile(rev.getSha1(), file.getPath()).getBytes(StandardCharsets.UTF_8));
      } catch (IOException e) {
        throw new RepoException(String
            .format("Cannot write '%s' from reference '%s' into '%s'", file.getPath(), rev,
                path), e);
      }
    }
  }
}
 
Example #6
Source File: FileUtil.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the files that match the PathMatcher.
 *
 * <p> Note that this method doesn't delete the directories, only the files inside those
 * directories. This is fine for our use case since the majority of SCMs don't care about empty
 * directories.
 *
 * @throws IOException If it fails traversing or deleting the tree.
 */
public static int deleteFilesRecursively(Path path, PathMatcher pathMatcher)
    throws IOException {
  AtomicInteger counter = new AtomicInteger();
  // Normalize so that the patchMatcher works
  Files.walkFileTree(path.normalize(), new SimpleFileVisitor<Path>() {

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      if (pathMatcher.matches(file)) {
        Files.delete(file);
        counter.incrementAndGet();
      }
      return FileVisitResult.CONTINUE;
    }
  });
  return counter.get();
}
 
Example #7
Source File: FileUtil.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Opens a directory stream on provided 'dir' folder, filtering file names according
 * to the provided glob syntax.
 * <p>
 * See http://blog.eyallupu.com/2011/11/java-7-working-with-directories.html
 *
 * @param dir  the directory to read from
 * @param glob the glob matching
 * @return the opened DirectoryStream (remaining to be closed)
 * @throws IOException if anything goes wrong
 */
public static DirectoryStream newDirectoryStream (Path dir,
                                                  String glob)
        throws IOException
{
    // create a matcher and return a filter that uses it.
    final FileSystem fs = dir.getFileSystem();
    final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
    final DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>()
    {
        @Override
        public boolean accept (Path entry)
        {
            return matcher.matches(entry.getFileName());
        }
    };

    return fs.provider().newDirectoryStream(dir, filter);
}
 
Example #8
Source File: MavenProjectImporter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean exclude(java.nio.file.Path path) {
	List<String> javaImportExclusions = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaImportExclusions();
	boolean excluded = false;
	if (javaImportExclusions != null) {
		for (String pattern : javaImportExclusions) {
			boolean includePattern = false;
			if (pattern.startsWith("!")) {
				includePattern = true;
				pattern = pattern.substring(1);
			}
			PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
			if (matcher.matches(path)) {
				excluded = includePattern ? false : true;
			}
		}
	}
	return excluded;
}
 
Example #9
Source File: IoCGeneratorHelper.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
public static IoCSwaggerGenerator getGenerator(File dir, Predicate<Module> toSelect) throws Exception {
      final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.yang");

      Predicate<Path> acc = p ->  matcher.matches(p.getFileName());

      final SchemaContext ctx = dir == null ? getFromClasspath(acc) : getFromDir(dir.toPath(), acc);
      if(ctx.getModules().isEmpty()) throw new IllegalArgumentException(String.format("No YANG modules found in %s", dir == null ? "classpath"  : dir.toString()));
      log.info("Context parsed {}", ctx);

      final Set<Module> toGenerate = ctx.getModules().stream().filter(toSelect).collect(Collectors.toSet());

return swaggerGeneratorFactory.createSwaggerGenerator(ctx, toGenerate)
              .defaultConfig()
              .format(IoCSwaggerGenerator.Format.YAML)
              .consumes("application/xml")
              .produces("application/xml")
              .host("localhost:1234")
              .elements(IoCSwaggerGenerator.Elements.DATA, IoCSwaggerGenerator.Elements.RCP);
  }
 
Example #10
Source File: GeneratorHelper.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
public static SwaggerGenerator getGenerator(File dir, Predicate<Module> toSelect) throws Exception {
    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.yang");

    Predicate<Path> acc = p ->  matcher.matches(p.getFileName());

    final SchemaContext ctx = dir == null ? getFromClasspath(acc) : getFromDir(dir.toPath(), acc);
    if(ctx.getModules().isEmpty()) throw new IllegalArgumentException(String.format("No YANG modules found in %s", dir == null ? "classpath"  : dir.toString()));
    log.info("Context parsed {}", ctx);

    final Set<Module> toGenerate = ctx.getModules().stream().filter(toSelect).collect(Collectors.toSet());

    return new SwaggerGenerator(ctx, toGenerate)
            .defaultConfig()
            .format(SwaggerGenerator.Format.YAML)
            .consumes("application/xml")
            .produces("application/xml")
            .host("localhost:1234")
            .elements(SwaggerGenerator.Elements.DATA, SwaggerGenerator.Elements.RCP);
}
 
Example #11
Source File: FaultyFileSystem.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
    final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
    return new PathMatcher() {
        @Override
        public boolean matches(Path path) {
            return matcher.matches(unwrap(path));
        }
    };
}
 
Example #12
Source File: JmodTask.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
boolean matches(Path path, List<PathMatcher> matchers) {
    if (matchers != null) {
        for (PathMatcher pm : matchers) {
            if (pm.matches(path))
                return true;
        }
    }
    return false;
}
 
Example #13
Source File: ApkUtils.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all files in an apk that match a given regular expression.
 *
 * @param apkFile The {@link FileSystem} representation of the apk zip archive.
 * @param matcher A {@link PathMatcher} to match the requested filenames.
 * @return A mapping of the matched filenames to their byte contents.
 * @throws IOException Thrown if a matching file cannot be read from the apk.
 */
public static Map<String, byte[]> getFiles(FileSystem apkFile, PathMatcher matcher)
    throws IOException {
  ImmutableMap.Builder<String, byte[]> result = ImmutableMap.builder();
  for (Path path : findFiles(apkFile, matcher)) {
    result.put(path.toString(), Files.readAllBytes(path));
  }
  return result.build();
}
 
Example #14
Source File: BazelClasspathContainer.java    From eclipse with Apache License 2.0 5 votes vote down vote up
private boolean matchPatterns(Path path, IPath[] patterns) {
  if (patterns != null) {
    for (IPath p : patterns) {
      PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + p.toOSString());
      if (matcher.matches(path)) {
        return true;
      }
    }
  }
  return false;
}
 
Example #15
Source File: FileUtil.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves {@code symlink} recursively until it finds a regular file or directory. It also
 * checks that all its intermediate paths jumps are under {@code matcher}.
 */
public static ResolvedSymlink resolveSymlink(PathMatcher matcher, Path symlink)
    throws IOException {
  // Normalize since matcher glob:foo/bar/file* doesn't match foo/bar/../bar/file*
  Path path = symlink.normalize();
  checkArgument(matcher.matches(path), "%s doesn't match %s", path, matcher);

  Set<Path> visited = new LinkedHashSet<>();
  while (Files.isSymbolicLink(path)) {
    visited.add(path);
    // Avoid 'dot' -> . like traps by capping to a sane limit
    if (visited.size() > 50) {
      throw new IOException("Symlink cycle detected:\n  "
          + Joiner.on("\n  ").join(Iterables.concat(visited, ImmutableList.of(symlink))));
    }
    Path newPath = Files.readSymbolicLink(path);
    if (!newPath.isAbsolute()) {
      newPath = path.resolveSibling(newPath).toAbsolutePath().normalize();
    } else {
      newPath = newPath.normalize();
    }
    if (!matcher.matches(newPath)) {
      if (!Files.isDirectory(newPath)
          // Special support for symlinks in the form of ROOT/symlink -> '.'. Technically we
          // shouldn't allow this because of our glob implementation, but this is a regression
          // from the old code and the correct behavior is difficult to understand by our users.
          || !matcher.matches(newPath.resolve("copybara_random_path.txt"))) {
        Path realPath = newPath.toRealPath();
        return new ResolvedSymlink(realPath, /*allUnderRoot=*/ false);
      }
    }
    path = newPath;
  }
  return new ResolvedSymlink(path, /*allUnderRoot=*/ true);
}
 
Example #16
Source File: WorkflowRunHelper.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true iff the given change should be skipped based on the origin globs and flags
 * provided.
 */
final boolean shouldSkipChange(Change<?> currentChange) {
  if (workflow.isMigrateNoopChanges()) {
    return false;
  }
  // We cannot know the files included. Try to migrate then.
  if (currentChange.getChangeFiles() == null) {
    return false;
  }
  PathMatcher pathMatcher = getOriginFiles().relativeTo(Paths.get("/"));
  for (String changedFile : currentChange.getChangeFiles()) {
    if (pathMatcher.matches(Paths.get("/" + changedFile))) {
      return false;
    }
  }
  // This is an heuristic for cases where the Copybara configuration is stored in the same
  // folder as the origin code but excluded.
  //
  // The config root can be a subfolder of the files as seen by the origin. For example:
  // admin/copy.bara.sky could be present in the origin as root/admin/copy.bara.sky.
  // This might give us some false positives but they would be noop migrations.
  for (String changesFile : currentChange.getChangeFiles()) {
    for (String configPath : getConfigFiles()) {
      if (changesFile.endsWith(configPath)) {
        workflow.getConsole()
            .infoFmt("Migrating %s because %s config file changed at that revision",
                currentChange.getRevision().asString(), changesFile);
        return false;
      }
    }
  }
  return true;
}
 
Example #17
Source File: GlobConverterTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlob() throws IOException {
  PathMatcher matcher = parseGlob("some/test1/**,some/test2/**,-some/test2/exclude/**");

  assertThat(matcher.matches(Paths.get("/some/test1/file"))).isTrue();
  assertThat(matcher.matches(Paths.get("/some/test2/file"))).isTrue();
  assertThat(matcher.matches(Paths.get("/some/test2/include/file"))).isTrue();
  assertThat(matcher.matches(Paths.get("/some/test2/exclude/file"))).isFalse();
}
 
Example #18
Source File: HuntBugs.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
static Stream<Path> glob(String mask) throws IOException {
    Matcher matcher = Pattern.compile("(.*)[\\\\/](.*)").matcher(mask);
    Path parentPath;
    String fName;
    if(matcher.matches()) {
        parentPath = Paths.get(matcher.group(1));
        fName = matcher.group(2);
    } else {
        parentPath = Paths.get(".");
        fName = mask;
    }
    PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + fName);
    return Files.list(parentPath).filter(p -> pathMatcher.matches(p.getFileName()));
}
 
Example #19
Source File: Main.java    From bazel-tools with Apache License 2.0 5 votes vote down vote up
@MustBeClosed
@Override
public Stream<Path> findFilesMatching(final Path directory, final String syntaxAndPattern)
    throws IOException {
  final PathMatcher matcher = directory.getFileSystem().getPathMatcher(syntaxAndPattern);
  return Files.find(
      directory, Integer.MAX_VALUE, (p, a) -> matcher.matches(p) && !a.isDirectory());
}
 
Example #20
Source File: FileUtil.java    From copybara with Apache License 2.0 5 votes vote down vote up
CopyVisitor(Path from,
    Path to,
    CopySymlinkStrategy symlinkStrategy,
    PathMatcher originPathMatcher,
    PathMatcher destPathMatcher,
    Optional<CopyVisitorValidator> additionalValidator) {
  this.to = to;
  this.from = from;
  this.symlinkStrategy = symlinkStrategy;
  this.originPathMatcher = originPathMatcher;
  this.destPathMatcher = destPathMatcher;
  this.additonalValidator = additionalValidator;
}
 
Example #21
Source File: FaultyFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
    final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
    return new PathMatcher() {
        @Override
        public boolean matches(Path path) {
            return matcher.matches(unwrap(path));
        }
    };
}
 
Example #22
Source File: SimpleGlob.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Override
public PathMatcher relativeTo(Path path) {
  Builder<PathMatcher> includeList = ImmutableList.builder();
  for (String path1 : include) {
    includeList.add(ReadablePathMatcher.relativeGlob(path, path1));
  }
  PathMatcher excludeMatcher = (exclude == null)
      ? FileUtil.anyPathMatcher(ImmutableList.of())
      : exclude.relativeTo(path);
  return new GlobPathMatcher(
      FileUtil.anyPathMatcher(includeList.build()),
      excludeMatcher);
}
 
Example #23
Source File: JmodTask.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PathMatcher convert(String pattern) {
    try {
        return Utils.getPathMatcher(FileSystems.getDefault(), pattern);
    } catch (PatternSyntaxException e) {
        throw new CommandException("err.bad.pattern", pattern);
    }
}
 
Example #24
Source File: FaultyFileSystem.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
    final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
    return new PathMatcher() {
        @Override
        public boolean matches(Path path) {
            return matcher.matches(unwrap(path));
        }
    };
}
 
Example #25
Source File: OrderResourcesPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void configure(Map<String, String> config) {
    List<String> patterns = Utils.parseList(config.get(NAME));
    int ordinal = 0;

    for (String pattern : patterns) {
        if (pattern.startsWith("@")) {
            File file = new File(pattern.substring(1));

            if (file.exists()) {
                List<String> lines;

                try {
                    lines = Files.readAllLines(file.toPath());
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }

                for (String line : lines) {
                    if (!line.startsWith("#")) {
                        orderedPaths.put(line + ".class", ordinal++);
                    }
                }
            }
        } else {
            final int result = ordinal++;
            final PathMatcher matcher = Utils.getPathMatcher(JRT_FILE_SYSTEM, pattern);
            ToIntFunction<String> function = (path)-> matcher.matches(JRT_FILE_SYSTEM.getPath(path)) ? result : Integer.MAX_VALUE;
            filters.add(function);
         }
    }
}
 
Example #26
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static PathMatcher getPathMatcher(FileSystem fs, String pattern) {
    if (!pattern.startsWith("glob:") && !pattern.startsWith("regex:")) {
        pattern = "glob:" + pattern;
    }

    return fs.getPathMatcher(pattern);
}
 
Example #27
Source File: Source.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static List<PathMatcher> createPathMatchers(FileSystem fs, List<String> patterns) {
    List<PathMatcher> matchers = new ArrayList<>();
    for (String pattern : patterns) {
        try {
            matchers.add(fs.getPathMatcher("glob:" + pattern));
        } catch (PatternSyntaxException e) {
            Log.error("Invalid pattern: " + pattern);
            throw e;
        }
    }
    return matchers;
}
 
Example #28
Source File: GlobConverterTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
private PathMatcher parseGlob(String value) throws IOException {
  ImmutableMap<String, String> envWithHome =
      ImmutableMap.of("HOME", Files.createTempDirectory("foo").toString());

  ModuleSupplier moduleSupplier = new ModuleSupplier(envWithHome, FileSystems.getDefault(),
      new TestingConsole());
  Options options = moduleSupplier.create().getOptions();
  JCommander jCommander = new JCommander(options.getAll());
  jCommander.parse("--read-config-from-head-paths", value);
  return options.get(WorkflowOptions.class).readConfigFromChangePaths
      .relativeTo(Paths.get("/"));
}
 
Example #29
Source File: SolrResourceLoader.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to get the URLs of all paths under a given directory that match a regex
 *
 * @param libDir the root directory
 * @param regex  the regex as a String
 * @return all matching URLs
 * @throws IOException on error
 */
public static List<URL> getFilteredURLs(Path libDir, String regex) throws IOException {
  final PathMatcher matcher = libDir.getFileSystem().getPathMatcher("regex:" + regex);
  return getURLs(libDir, new DirectoryStream.Filter<Path>() {
    @Override
    public boolean accept(Path entry) throws IOException {
      return matcher.matches(entry.getFileName());
    }
  });
}
 
Example #30
Source File: PathUtils.java    From oneops with Apache License 2.0 5 votes vote down vote up
/**
 * Copy the src file/dir to the dest path recursively.
 * This will replace the file if it's already exists.
 *
 * @param src source file /dir path
 * @param dest destination path to copy
 * @param globPattern glob patterns to filter out when copying.
 * Note: Glob pattern matching is case sensitive.
 * @throws IOException throws if any error copying the file/dir.
 */
public static void copy(Path src, Path dest, List<String> globPattern) throws IOException {
  // Make sure the target dir exists.
  dest.toFile().mkdirs();

  // Create path matcher from list of glob pattern strings.
  FileSystem fs = FileSystems.getDefault();
  List<PathMatcher> matchers = globPattern.stream()
      .map(pattern -> fs.getPathMatcher("glob:" + pattern))
      .collect(Collectors.toList());

  try (Stream<Path> stream = Files.walk(src)) {
    // Filter out Glob pattern
    stream.filter(path -> {
      Path name = src.relativize(path);
      return matchers.stream().noneMatch(m -> m.matches(name));
    }).forEach(srcPath -> {
      try {
        Path target = dest.resolve(src.relativize(srcPath));
        // Don't try to copy existing dir entry.
        if (!target.toFile().isDirectory()) {
          Files.copy(srcPath, target, REPLACE_EXISTING);
        }
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    });
  }
}