Java Code Examples for java.nio.file.PathMatcher#matches()

The following examples show how to use java.nio.file.PathMatcher#matches() . 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: 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 2
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 3
Source File: BasicFileDetector.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean isExcluded(Path dir) {
	if (dir.getFileName() == null) {
		return true;
	}
	boolean excluded = false;
	for (String pattern : exclusions) {
		boolean includePattern = false;
		if (pattern.startsWith("!")) {
			includePattern = true;
			pattern = pattern.substring(1);
		}
		PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
		if (matcher.matches(dir)) {
			excluded = includePattern ? false : true;
		}
	}
	return excluded;
}
 
Example 4
Source File: FaultyFileSystem.java    From hottub 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 5
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 6
Source File: ResourceFilter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean test(String name) {
    Objects.requireNonNull(name);
    Path path = Utils.getJRTFSPath(name);

    for (PathMatcher matcher : matchers) {
        if (matcher.matches(path)) {
            return include;
        }
    }

    return otherwise;
}
 
Example 7
Source File: FileUtil.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@link PathMatcher} that negates {@code athMatcher}
 */
public static PathMatcher notPathMatcher(PathMatcher pathMatcher) {
  return new PathMatcher() {
    @Override
    public boolean matches(Path path) {
      return !pathMatcher.matches(path);
    }

    @Override
    public String toString() {
      return "not(" + pathMatcher + ")";
    }
  };
}
 
Example 8
Source File: JImageTask.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void processInclude(String include) {
    if (include.isEmpty()) {
        return;
    }

    for (String filter : include.split(",")) {
        final PathMatcher matcher = Utils.getPathMatcher(JRT_FILE_SYSTEM, filter);
        Predicate<String> predicate = (path) -> matcher.matches(JRT_FILE_SYSTEM.getPath(path));
        includePredicates.add(predicate);
    }
}
 
Example 9
Source File: FaultyFileSystem.java    From jdk8u_jdk 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 10
Source File: GitUtil.java    From RepoSense with MIT License 5 votes vote down vote up
/**
 * Returns true if the {@code ignoreGlob} is inside the current repository.
 * Produces log messages when the invalid {@code ignoreGlob} is skipped.
 */
private static boolean isValidIgnoreGlob(File repoRoot, String ignoreGlob) {
    String validPath = ignoreGlob;
    FileSystem fileSystem = FileSystems.getDefault();
    if (ignoreGlob.isEmpty()) {
        return false;
    } else if (ignoreGlob.startsWith("/") || ignoreGlob.startsWith("\\")) {
        // Ignore globs cannot start with a slash
        logger.log(Level.WARNING, ignoreGlob + " cannot start with / or \\.");
        return false;
    } else if (ignoreGlob.contains("/*") || ignoreGlob.contains("\\*")) {
        // contains directories
        validPath = ignoreGlob.substring(0, ignoreGlob.indexOf("/*"));
    } else if (ignoreGlob.contains("*")) {
        // no directories
        return true;
    }

    try {
        String fileGlobPath = "glob:" + repoRoot.getCanonicalPath().replaceAll("\\\\+", "\\/") + "/**";
        PathMatcher pathMatcher = fileSystem.getPathMatcher(fileGlobPath);
        validPath = new File(repoRoot, validPath).getCanonicalPath();
        if (pathMatcher.matches(Paths.get(validPath))) {
            return true;
        }
    } catch (IOException ioe) {
        logger.log(Level.WARNING, ioe.getMessage(), ioe);
        return false;
    }

    logger.log(Level.WARNING, ignoreGlob + " will be skipped as this glob points to the outside of "
            + "the repository.");
    return false;
}
 
Example 11
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 12
Source File: FaultyFileSystem.java    From jdk8u-jdk 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 13
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 14
Source File: FaultyFileSystem.java    From openjdk-jdk8u 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 15
Source File: WafFolder.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Matches URL
 * @param u url
 * @param pattern match patter (glob)
 * @return <code>true</code> if URL matches the pattern
 */
private boolean matchUrl(URL u, String pattern) {
  String[] split = u.getPath().split("(/|\\\\)+");
  List<String> items = Arrays.asList(split).stream().filter(s->s!=null && !s.isEmpty()).collect(Collectors.toList());
  if (!items.isEmpty()) {
    String first = items.get(0);
    List<String> subList = items.subList(1, items.size());
    Path path = fileSystem.getPath(first, subList.toArray(new String[]{}));
    PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:"+pattern);
    return pathMatcher.matches(path);
  } else {
    return false;
  }
}
 
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: GlobFilePathFilter.java    From flink with Apache License 2.0 5 votes vote down vote up
private boolean shouldExclude(java.nio.file.Path nioPath) {
	for (PathMatcher matcher : getExcludeMatchers()) {
		if (matcher.matches(nioPath)) {
			return true;
		}
	}
	return false;
}
 
Example 18
Source File: GlobFilePathFilter.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private boolean shouldExclude(java.nio.file.Path nioPath) {
	for (PathMatcher matcher : getExcludeMatchers()) {
		if (matcher.matches(nioPath)) {
			return true;
		}
	}
	return false;
}
 
Example 19
Source File: GlobPatternMatcher.java    From smart-testing with Apache License 2.0 4 votes vote down vote up
private static boolean matchPattern(String path, String pattern) {
    final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    return pathMatcher.matches(Paths.get(path));
}
 
Example 20
Source File: TransformDebug.java    From copybara with Apache License 2.0 4 votes vote down vote up
@Override
public void transform(TransformWork work)
    throws IOException, ValidationException, RepoException {
  Console console = work.getConsole();
  boolean fileDebug = false;
  if (debugOptions.getDebugFileBreak() != null) {
    fileDebug = true;
  }
  boolean metadataDebug = false;
  if (debugOptions.debugMetadataBreak) {
    metadataDebug = true;
  }

  Pattern debugTransformBreak = debugOptions.getDebugTransformBreak();
  boolean transformMatch = false;
  if (debugTransformBreak != null
      && debugTransformBreak.matcher(this.delegate.describe())
      .find()) {
    transformMatch = true;
  }

  if (!fileDebug && !metadataDebug && !transformMatch) {
    // Nothing to debug!
    delegate.transform(work);
    return;
  }

  TreeMap<String, byte[]> before = readState(work, fileDebug || transformMatch,
      work.getTreeState());
  delegate.transform(work);
  TreeMap<String, byte[]> after = readState(work, fileDebug || transformMatch,
      work.getTreeState().newTreeState());

  MapDifference<String, byte[]> difference = Maps.difference(before, after,
      new Equivalence<byte[]>() {
        @Override
        protected boolean doEquivalent(byte[] one, byte[] other) {
          return Arrays.equals(one, other);
        }

        @Override
        protected int doHash(byte[] bytes) {
          return Arrays.hashCode(bytes);
        }
      });

  boolean stop = transformMatch;
  if (fileDebug) {
    PathMatcher debugFileBreak = debugOptions.getDebugFileBreak()
        .relativeTo(Paths.get("/"));
    for (String path : Iterables.concat(difference.entriesOnlyOnLeft().keySet(),
        difference.entriesOnlyOnRight().keySet(), difference.entriesDiffering().keySet())) {
      if (path.equals(COPYBARA_METADATA_FAKE_FILE)) {
        continue;
      }
      if (debugFileBreak.matches(Paths.get("/" + path))) {
        stop = true;
        console.infoFmt("File '%s' change matched. Stopping", path);
        break;
      }
    }
  } else if (metadataDebug && !Arrays.equals(
        before.get(COPYBARA_METADATA_FAKE_FILE),
        after.get(COPYBARA_METADATA_FAKE_FILE))) {
    stop = true;
    console.infoFmt("Message, author and/or labels changed");
  }
  if (!stop) {
    return;
  }
  if (!transformMatch) {
    // Stopped because of file/metadata change. Show the diff directly
    showDiff(console, difference);
  }
  while (true) {
    String answer = console.ask(
        "Debugger stopped after '" + delegate.describe()
            + "' "
            + console.colorize(AnsiColor.PURPLE, delegate.location().toString())
            + ".\n"
            + "      Current file state can be checked at " + work.getCheckoutDir() +"\n"
            + "Diff (d), Continue (c), Stop (s): ",
        "d",
        input -> ImmutableSet.of("d", "c", "s").contains(input));

    switch (answer) {
      case "d": {
        showDiff(console, difference);
        break;
      }
      case "c":
        return;
      case "s":
        throw new ValidationException("Stopped by user");
    }
  }
}