下面列出了怎么用java.nio.file.PathMatcher的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
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);
}
}
}
}
/**
* 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();
}
@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();
}
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;
}
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;
}
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);
}
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);
}
/**
* 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);
}
@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.");
}
}
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("/"));
}
private ArrayList<PathMatcher> buildPatterns(List<String> patterns) {
FileSystem fileSystem = FileSystems.getDefault();
ArrayList<PathMatcher> matchers = new ArrayList<>(patterns.size());
for (String patternStr : patterns) {
matchers.add(fileSystem.getPathMatcher("glob:" + patternStr));
}
return matchers;
}
/**
* @param dir directory for search
* @param match search pattern (* - eny string, ? - eny one symbol, [X,Y] - X or Y, [0-5] - range, {ABC, XYX} - ABC or XYZ)
* @return collection of files
* @throws IOException
*/
public List<Path> findFiles(Path dir, String match) throws IOException {
ArrayList<Path> pathArrayList = new ArrayList<>();
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + match);
try (Stream<Path> pathStream = Files.find(dir, Integer.MAX_VALUE,
(path, basicFileAttributes) -> matcher.matches(path.getFileName()))) {
pathArrayList.addAll(pathStream.collect(Collectors.toList()));
}
return pathArrayList;
}
/**
* Adds the given permissions to the matching files under the given path.
*/
public static void addPermissionsRecursively(
Path path, Set<PosixFilePermission> permissionsToAdd, PathMatcher pathMatcher)
throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(file)) {
addPermissions(file, permissionsToAdd);
}
return FileVisitResult.CONTINUE;
}
});
}
private boolean shouldExclude(java.nio.file.Path nioPath) {
for (PathMatcher matcher : getExcludeMatchers()) {
if (matcher.matches(nioPath)) {
return true;
}
}
return false;
}
CopyMoveVisitor(Path before, Path after, @Nullable PathMatcher pathMatcher, boolean overwrite, boolean isCopy) {
this.before = before;
this.after = after;
this.pathMatcher = pathMatcher;
this.isCopy = isCopy;
if (overwrite) {
moveMode = new CopyOption[]{LinkOption.NOFOLLOW_LINKS, StandardCopyOption.REPLACE_EXISTING};
} else {
moveMode = new CopyOption[]{LinkOption.NOFOLLOW_LINKS};
}
}
@StarlarkMethod(
name = "run",
doc =
"Run a glob or a transform. For example:<br>"
+ "<code>files = ctx.run(glob(['**.java']))</code><br>or<br>"
+ "<code>ctx.run(core.move(\"foo\", \"bar\"))</code><br>or<br>",
parameters = {
@Param(
name = "runnable",
type = Object.class,
doc = "A glob or a transform (Transforms still not implemented)"),
})
public Object run(Object runnable) throws
EvalException, IOException, ValidationException, RepoException {
if (runnable instanceof Glob) {
PathMatcher pathMatcher = ((Glob) runnable).relativeTo(checkoutDir);
try (Stream<Path> stream = Files.walk(checkoutDir)) {
return StarlarkList.immutableCopyOf(
stream
.filter(Files::isRegularFile)
.filter(pathMatcher::matches)
.map(p -> new CheckoutPath(checkoutDir.relativize(p), checkoutDir))
.collect(Collectors.toList()));
}
} else if (runnable instanceof Transformation) {
// Works like Sequence. We keep always the latest transform work to allow
// catching for two sequential replaces.
skylarkTransformWork = skylarkTransformWork.withUpdatedTreeState();
((Transformation) runnable).transform(skylarkTransformWork);
this.updateFrom(skylarkTransformWork);
return Starlark.NONE;
}
throw Starlark.errorf(
"Only globs or transforms can be run, but '%s' is of type %s",
runnable, runnable.getClass());
}
private boolean shouldExclude(java.nio.file.Path nioPath) {
for (PathMatcher matcher : getExcludeMatchers()) {
if (matcher.matches(nioPath)) {
return true;
}
}
return false;
}
private static PathMatcher getPathMatcher(List<String> suffixes, String relativePath) {
String fileExpression = "*{" + String.join(",", suffixes) + "}";
if(!relativePath.isEmpty() && !relativePath.endsWith("/") && !relativePath.endsWith("**")){
relativePath = relativePath + "/";
}
return FileSystems.getDefault()
.getPathMatcher("glob:" + relativePath + fileExpression);
}
@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));
}
};
}
/**
* Creates a stream of PathMatchers, one for each glob.
* @param inputDirectory Path within which the globs are applied
* @param globs the glob patterns
* @return PathMatchers for the globs
*/
private static Stream<PathMatcher> pathMatchers(Path inputDirectory, String[] globs) {
return Arrays.stream(globs)
.map(glob -> {
if (WINDOWS) {
String pattern = "glob:" + inputDirectory + File.separator + glob.replace("/", "\\");
return FileSystems.getDefault().getPathMatcher(pattern.replace("\\", "\\\\"));
}
return FileSystems.getDefault().getPathMatcher("glob:" + inputDirectory + "/" + glob);
});
}
public static List<PathMatcher> getExcludes() {
if (excludes == null) {
excludes = new ArrayList<>();
List<String> excludePatterns = PropertyManager.getListProperty("mdw." + PropertyNames.FILEPANEL_EXCLUDE_PATTERNS);
if (excludePatterns != null) {
for (String excludePattern : excludePatterns) {
PathMatcher exclusion = FileSystems.getDefault().getPathMatcher("glob:" + excludePattern);
excludes.add(exclusion);
}
}
}
return excludes;
}
private ImmutableList<String> getBuildFileGenerationBlacklistRecursively(
List<String> buildFileGenerationBlacklist) {
Set<String> result = new HashSet<>();
for (String folderToIgnore : buildFileGenerationBlacklist) {
PathMatcher matcherRootFolders =
FileSystems.getDefault()
.getPathMatcher(String.format(GLOB_PATTERN_TO_FIND_FOLDERS, folderToIgnore));
PathMatcher matcherSubfolders =
FileSystems.getDefault()
.getPathMatcher(
String.format(GLOB_PATTERN_TO_FIND_SUBFOLDERS_RECURSIVELY, folderToIgnore));
try {
Files.walkFileTree(
Paths.get(fileUtils.getCurrentWorkingDirectory()),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(
Path dir, BasicFileAttributes basicFileAttributes) {
if (matcherRootFolders.matches(dir) || matcherSubfolders.matches(dir)) {
result.add(dir.toString());
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
return ImmutableList.copyOf(result);
}
/** Tries to locate adb utility under "platform-tools". */
private Optional<Path> locateAdbInSdkDir(SystemEnvironmentProvider systemEnvironmentProvider) {
Optional<String> sdkDir = systemEnvironmentProvider.getVariable(ANDROID_HOME_VARIABLE);
if (!sdkDir.isPresent()) {
return Optional.empty();
}
Path platformToolsDir = fileSystem.getPath(sdkDir.get(), "platform-tools");
if (!Files.isDirectory(platformToolsDir)) {
return Optional.empty();
}
// Expecting to find one entry.
PathMatcher adbPathMatcher = fileSystem.getPathMatcher(ADB_SDK_GLOB);
try (Stream<Path> pathStream =
Files.find(
platformToolsDir,
/* maxDepth= */ 1,
(path, attributes) -> adbPathMatcher.matches(path) && Files.isExecutable(path))) {
return pathStream.findFirst();
} catch (IOException e) {
throw CommandExecutionException.builder()
.withCause(e)
.withInternalMessage("Error while trying to locate adb in SDK dir '%s'.", sdkDir)
.build();
}
}
@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));
}
};
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return path -> {
if (path instanceof FilterPath) {
return matcher.matches(((FilterPath)path).delegate);
}
return false;
};
}
/**
* 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 + ")";
}
};
}
/** @return true iff the given location is matched the given GLOB specifier */
private boolean locationMatchesGlobSpecifier(ModuleFilterSpecifier spec, String prjRelativeLocation) {
String pathsToFind = spec.getModuleSpecifierWithWildcard();
if (pathsToFind == null) {
return false;
}
boolean matches = prjRelativeLocation.startsWith(pathsToFind);
if (!matches) {
PathMatcher pathMatcher = createPathMatcher(pathsToFind);
java.nio.file.Path path = Paths.get(prjRelativeLocation);
matches = pathMatcher.matches(path);
}
return matches;
}
@Test
public void windowsGlobWorks() throws Exception {
FileSystem workFs = Jimfs.newFileSystem(Configuration.windows());
workdir = workFs.getPath("c:/tmp");
Path folder = workdir.resolve("foo");
Files.createDirectories(folder);
Files.write(folder.resolve("bar"), new byte[0]);
PathMatcher matcher = createPathMatcher("glob(['foo/**'])");
assertThat(matcher.matches(workdir.resolve("foo/bar"))).isTrue();
}
@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));
}
};
}