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 Project: flink   Author: flink-tpc-ds   File: GlobFilePathFilter.java    License: 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 Project: copybara   Author: google   File: GitRepository.java    License: 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 #3
Source Project: copybara   Author: google   File: FileUtil.java    License: 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 #4
Source Project: Bytecoder   Author: mirkosertic   File: JrtFileSystem.java    License: 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 #5
Source Project: eclipse.jdt.ls   Author: eclipse   File: MavenProjectImporter.java    License: 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 #6
Source Project: jpa2ddl   Author: Devskiller   File: FileResolver.java    License: 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 #7
Source Project: yang2swagger   Author: bartoszm   File: IoCGeneratorHelper.java    License: 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 #8
Source Project: yang2swagger   Author: bartoszm   File: GeneratorHelper.java    License: 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 #9
Source Project: audiveris   Author: Audiveris   File: FileUtil.java    License: 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 #10
Source Project: mycore   Author: MyCoRe-Org   File: MCRAbstractFileSystem.java    License: 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 #11
Source Project: copybara   Author: google   File: GlobConverterTest.java    License: 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 #12
Source Project: Flink-CEPplus   Author: ljygz   File: GlobFilePathFilter.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source Project: ariADDna   Author: StnetixDevTeam   File: LocalStoreIndexingService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #14
Source Project: copybara   Author: google   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
  });
}
 
Example #15
Source Project: Flink-CEPplus   Author: ljygz   File: GlobFilePathFilter.java    License: 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 #16
Source Project: copybara   Author: google   File: CopyMoveVisitor.java    License: Apache License 2.0 5 votes vote down vote up
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};
  }
}
 
Example #17
Source Project: copybara   Author: google   File: TransformWork.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #18
Source Project: flink   Author: flink-tpc-ds   File: GlobFilePathFilter.java    License: 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 Project: raml-module-builder   Author: folio-org   File: GenerateRunner.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source Project: TencentKona-8   Author: Tencent   File: FaultyFileSystem.java    License: 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 #21
Source Project: helidon-build-tools   Author: oracle   File: AbstractAsciiDocMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
            });
}
 
Example #22
Source Project: mdw   Author: CenturyLinkCloud   File: FilePanelService.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source Project: startup-os   Author: google   File: BuildFileGenerator.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #24
Source Project: bundletool   Author: google   File: SdkToolsLocator.java    License: Apache License 2.0 5 votes vote down vote up
/** 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();
  }
}
 
Example #25
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: FaultyFileSystem.java    License: 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 #26
Source Project: lucene-solr   Author: apache   File: FilterFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@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;
  };
}
 
Example #27
Source Project: copybara   Author: google   File: FileUtil.java    License: 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 #28
Source Project: n4js   Author: eclipse   File: WildcardPathFilterHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** @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;
}
 
Example #29
Source Project: copybara   Author: google   File: GlobTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source Project: openjdk-8   Author: bpupadhyaya   File: FaultyFileSystem.java    License: 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));
        }
    };
}