Java Code Examples for java.nio.file.FileSystem#getPathMatcher()
The following examples show how to use
java.nio.file.FileSystem#getPathMatcher() .
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: FileUtil.java From audiveris with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 2
Source File: ReadablePathMatcher.java From copybara with Apache License 2.0 | 6 votes |
/** * Creates a {@link PathMatcher} based on a glob relative to {@code path}. The string * representation of the {@code PathMatcher} is the actual glob. * * For example a glob "dir/**.java" would match any java file inside {@code path}/dir directory. */ public static ReadablePathMatcher relativeGlob(Path path, String glob) { FileUtil.checkNormalizedRelative(glob); FileSystem fs = path.getFileSystem(); String root = path.normalize().toString(); String separator = fs.getSeparator(); if (!root.endsWith(separator)) { root += separator; } // If the current filesystem uses a backslash as the separator, the root must be escaped // first to be valid glob syntax since backslash is considered an escaping character. if ("\\".equals(separator)) { root = root.replace("\\", "\\\\"); glob = glob.replace("/", "\\\\"); } return new ReadablePathMatcher(fs.getPathMatcher("glob:" + root + glob), glob); }
Example 3
Source File: VersionUpdateVisitor.java From statecharts with Eclipse Public License 1.0 | 6 votes |
@Override public FileVisitResult visitFile(Path path, BasicFileAttributes arg1) throws IOException { FileSystem fileSystem = FileSystems.getDefault(); PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + filePattern); if (pathMatcher.matches(path.getFileName())) { searchList.add(path); String charset = Charset.defaultCharset().name(); //System.out.println(charset); String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(this.searchPattern, this.replacePattern); Files.write(path, content.getBytes(charset)); fileCount++; } return FileVisitResult.CONTINUE; }
Example 4
Source File: GitUtil.java From RepoSense with MIT License | 5 votes |
/** * 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 5
Source File: Utils.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static PathMatcher getPathMatcher(FileSystem fs, String pattern) { if (!pattern.startsWith("glob:") && !pattern.startsWith("regex:")) { pattern = "glob:" + pattern; } return fs.getPathMatcher(pattern); }
Example 6
Source File: Basic.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider = "pathGlobPatterns") public void testGlobPathMatcher(String pattern, String path, boolean expectMatch) throws Exception { FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); PathMatcher pm = fs.getPathMatcher("glob:" + pattern); Path p = fs.getPath(path); assertTrue(Files.exists(p), path); assertTrue(!(pm.matches(p) ^ expectMatch), p + (expectMatch? " should match " : " should not match ") + pattern); }
Example 7
Source File: Basic.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider = "pathRegexPatterns") public void testRegexPathMatcher(String pattern, String path, boolean expectMatch) throws Exception { FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); PathMatcher pm = fs.getPathMatcher("regex:" + pattern); Path p = fs.getPath(path); assertTrue(Files.exists(p), path); assertTrue(!(pm.matches(p) ^ expectMatch), p + (expectMatch? " should match " : " should not match ") + pattern); }
Example 8
Source File: FeatureXMLGetVersionVisitor.java From statecharts with Eclipse Public License 1.0 | 5 votes |
@Override public FileVisitResult visitFile(Path path, BasicFileAttributes arg1) throws IOException { FileSystem fileSystem = FileSystems.getDefault(); PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + filePattern); if (pathMatcher.matches(path.getFileName())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(path.toFile()); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); XPathExpression expr = xpath.compile("string(//feature[1]/@version)"); Object result = expr.evaluate(doc, XPathConstants.STRING); if (result instanceof String) { this.version = result.toString(); } } catch (Exception e) { e.printStackTrace(); } return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; }
Example 9
Source File: PomXMLGetVersionVisitor.java From statecharts with Eclipse Public License 1.0 | 5 votes |
@Override public FileVisitResult visitFile(Path path, BasicFileAttributes arg1) throws IOException { FileSystem fileSystem = FileSystems.getDefault(); PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + filePattern); if (pathMatcher.matches(path.getFileName())) { System.out.println("File: "+path.toAbsolutePath()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(path.toFile()); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); XPathExpression expr = xpath.compile("//project[1]/version/text()"); Object result = expr.evaluate(doc, XPathConstants.STRING); if (result instanceof String && !((String)result).isEmpty()) { this.version = result.toString(); } else { //try in parent tag expr = xpath.compile("//project[1]/parent/version/text()"); result = expr.evaluate(doc, XPathConstants.STRING); if (result instanceof String && !((String)result).isEmpty()) { this.version = result.toString(); } else { System.out.println("Error: Unable to find version within pom.xmls."); version = null; } } } catch (Exception e) { e.printStackTrace(); } return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; }
Example 10
Source File: SingularityUploader.java From Singularity with Apache License 2.0 | 5 votes |
SingularityUploader( S3UploadMetadata uploadMetadata, FileSystem fileSystem, SingularityS3UploaderMetrics metrics, Path metadataPath, SingularityS3UploaderConfiguration configuration, String hostname, SingularityRunnerExceptionNotifier exceptionNotifier, Lock checkFileOpenLock ) { this.metrics = metrics; this.uploadMetadata = uploadMetadata; this.fileDirectory = uploadMetadata.getDirectory(); this.pathMatcher = fileSystem.getPathMatcher("glob:" + uploadMetadata.getFileGlob()); if (uploadMetadata.getOnFinishGlob().isPresent()) { finishedPathMatcher = Optional.of( fileSystem.getPathMatcher("glob:" + uploadMetadata.getOnFinishGlob().get()) ); } else { finishedPathMatcher = Optional.<PathMatcher>empty(); } this.hostname = hostname; this.bucketName = uploadMetadata.getS3Bucket(); this.metadataPath = metadataPath; this.logIdentifier = String.format("[%s]", metadataPath.getFileName()); this.configuration = configuration; this.exceptionNotifier = exceptionNotifier; this.checkFileOpenLock = checkFileOpenLock; }
Example 11
Source File: RegexGlobMatcherTest.java From jimfs with Apache License 2.0 | 5 votes |
@Override protected PathMatcher realMatcher(String pattern) { FileSystem defaultFileSystem = FileSystems.getDefault(); if ("/".equals(defaultFileSystem.getSeparator())) { return defaultFileSystem.getPathMatcher("glob:" + pattern); } return null; }
Example 12
Source File: FileObject.java From jphp with Apache License 2.0 | 5 votes |
@Signature(@Arg("pattern")) public Memory matches(Environment env, Memory... args) { FileSystem aDefault = FileSystems.getDefault(); PathMatcher pathMatcher = aDefault.getPathMatcher(args[0].toString()); return pathMatcher.matches(aDefault.getPath(file.getPath())) ? Memory.TRUE : Memory.FALSE; }
Example 13
Source File: CompressedDirectory.java From docker-client with Apache License 2.0 | 4 votes |
@VisibleForTesting static PathMatcher goPathMatcher(FileSystem fs, String pattern) { // Supposed to work the same way as Go's path.filepath.match.Match: // http://golang.org/src/path/filepath/match.go#L34 final String notSeparatorPattern = getNotSeparatorPattern(fs.getSeparator()); final String starPattern = String.format("%s*", notSeparatorPattern); final StringBuilder patternBuilder = new StringBuilder(); boolean inCharRange = false; boolean inEscape = false; // This is of course hugely inefficient, but it passes most of the test suite, TDD ftw... for (int i = 0; i < pattern.length(); i++) { final char c = pattern.charAt(i); if (inCharRange) { if (inEscape) { patternBuilder.append(c); inEscape = false; } else { switch (c) { case '\\': patternBuilder.append('\\'); inEscape = true; break; case ']': patternBuilder.append(']'); inCharRange = false; break; default: patternBuilder.append(c); } } } else { if (inEscape) { patternBuilder.append(Pattern.quote(Character.toString(c))); inEscape = false; } else { switch (c) { case '*': patternBuilder.append(starPattern); break; case '?': patternBuilder.append(notSeparatorPattern); break; case '[': patternBuilder.append("["); inCharRange = true; break; case '\\': inEscape = true; break; default: patternBuilder.append(Pattern.quote(Character.toString(c))); } } } } return fs.getPathMatcher("regex:" + patternBuilder.toString()); }