Search in sources :

Example 41 with PathMatcher

use of java.nio.file.PathMatcher in project copybara by google.

the class GlobTest method unionOfDifferences.

@Test
public void unionOfDifferences() throws Exception {
    Glob glob = parseGlob("(glob(['foo/**']) - glob(['**/bar'])) + (glob(['foo2/**']) - glob(['**/bar2']))");
    assertThat(glob.roots()).containsExactly("foo", "foo2");
    PathMatcher matcher = glob.relativeTo(workdir);
    assertThat(matcher.matches(workdir.resolve("foo/bar"))).isFalse();
    assertThat(matcher.matches(workdir.resolve("foo/bar2"))).isTrue();
    assertThat(matcher.matches(workdir.resolve("foo2/bar"))).isTrue();
    assertThat(matcher.matches(workdir.resolve("foo2/bar2"))).isFalse();
}
Also used : PathMatcher(java.nio.file.PathMatcher) Glob.createGlob(com.google.copybara.util.Glob.createGlob) Test(org.junit.Test)

Example 42 with PathMatcher

use of java.nio.file.PathMatcher in project karaf by apache.

the class FilesStream method files.

private static Stream<Path> files(Path cur, String glob) {
    String prefix;
    String rem;
    int idx = glob.lastIndexOf(File.separatorChar);
    if (idx >= 0) {
        prefix = glob.substring(0, idx + 1);
        rem = glob.substring(idx + 1);
    } else {
        prefix = "";
        rem = glob;
    }
    Path dir = cur.resolve(prefix);
    final PathMatcher matcher = dir.getFileSystem().getPathMatcher("glob:" + rem);
    Stream.Builder<Path> stream = Stream.builder();
    try {
        Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.equals(dir)) {
                    return FileVisitResult.CONTINUE;
                }
                if (Files.isHidden(file)) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                Path r = dir.relativize(file);
                if (matcher.matches(r)) {
                    stream.add(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!Files.isHidden(file)) {
                    Path r = dir.relativize(file);
                    if (matcher.matches(r)) {
                        stream.add(file);
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        LOGGER.warn("Error generating filenames", e);
    }
    return stream.build();
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) Stream(java.util.stream.Stream) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 43 with PathMatcher

use of java.nio.file.PathMatcher in project fabric8 by jboss-fuse.

the class FabricProfileFileSystem method getPathMatcher.

@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
    int colonIndex = syntaxAndPattern.indexOf(':');
    if (colonIndex <= 0 || colonIndex == syntaxAndPattern.length() - 1) {
        throw new IllegalArgumentException("syntaxAndPattern must have form \"syntax:pattern\" but was \"" + syntaxAndPattern + "\"");
    }
    String syntax = syntaxAndPattern.substring(0, colonIndex);
    String pattern = syntaxAndPattern.substring(colonIndex + 1);
    String expr;
    switch(syntax) {
        case "glob":
            expr = globToRegex(pattern);
            break;
        case "regex":
            expr = pattern;
            break;
        default:
            throw new UnsupportedOperationException("Unsupported syntax \'" + syntax + "\'");
    }
    final Pattern regex = Pattern.compile(expr);
    return new PathMatcher() {

        @Override
        public boolean matches(Path path) {
            return regex.matcher(path.toString()).matches();
        }
    };
}
Also used : Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) PathMatcher(java.nio.file.PathMatcher)

Example 44 with PathMatcher

use of java.nio.file.PathMatcher in project jetty.project by eclipse.

the class BaseHome method getPaths.

/**
     * Get a List of {@link Path}s from a provided pattern.
     * <p>
     * Resolution Steps:
     * <ol>
     * <li>If the pattern starts with "regex:" or "glob:" then a standard {@link PathMatcher} is built using
     * {@link java.nio.file.FileSystem#getPathMatcher(String)} as a file search.</li>
     * <li>If pattern starts with a known filesystem root (using information from {@link java.nio.file.FileSystem#getRootDirectories()}) then this is assumed to
     * be a absolute file system pattern.</li>
     * <li>All other patterns are treated as relative to BaseHome information:
     * <ol>
     * <li>Search ${jetty.home} first</li>
     * <li>Search ${jetty.base} for overrides</li>
     * </ol>
     * </li>
     * </ol>
     * <p>
     * Pattern examples:
     * <dl>
     * <dt><code>lib/logging/*.jar</code></dt>
     * <dd>Relative pattern, not recursive, search <code>${jetty.home}</code> then <code>${jetty.base}</code> for lib/logging/*.jar content</dd>
     * 
     * <dt><code>lib/**&#47;*-dev.jar</code></dt>
     * <dd>Relative pattern, recursive search <code>${jetty.home}</code> then <code>${jetty.base}</code> for files under <code>lib</code> ending in
     * <code>-dev.jar</code></dd>
     * 
     * <dt><code>etc/jetty.xml</code></dt>
     * <dd>Relative pattern, no glob, search for <code>${jetty.home}/etc/jetty.xml</code> then <code>${jetty.base}/etc/jetty.xml</code></dd>
     * 
     * <dt><code>glob:/opt/app/common/*-corp.jar</code></dt>
     * <dd>PathMapper pattern, glob, search <code>/opt/app/common/</code> for <code>*-corp.jar</code></dd>
     * 
     * </dl>
     * 
     * <p>
     * Notes:
     * <ul>
     * <li>FileSystem case sensitivity is implementation specific (eg: linux is case-sensitive, windows is case-insensitive).<br>
     * See {@link java.nio.file.FileSystem#getPathMatcher(String)} for more details</li>
     * <li>Pattern slashes are implementation neutral (use '/' always and you'll be fine)</li>
     * <li>Recursive searching is limited to 30 levels deep (not configurable)</li>
     * <li>File System loops are detected and skipped</li>
     * </ul>
     * 
     * @param pattern
     *            the pattern to search.
     * @return the collection of paths found
     * @throws IOException
     *             if error during search operation
     */
public List<Path> getPaths(String pattern) throws IOException {
    StartLog.debug("getPaths('%s')", pattern);
    List<Path> hits = new ArrayList<>();
    if (PathMatchers.isAbsolute(pattern)) {
        // Perform absolute path pattern search
        // The root to start search from
        Path root = PathMatchers.getSearchRoot(pattern);
        // The matcher for file hits
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        if (FS.isValidDirectory(root)) {
            PathFinder finder = new PathFinder();
            finder.setIncludeDirsInResults(true);
            finder.setFileMatcher(matcher);
            finder.setBase(root);
            Files.walkFileTree(root, SEARCH_VISIT_OPTIONS, MAX_SEARCH_DEPTH, finder);
            hits.addAll(finder.getHits());
        }
    } else {
        // Perform relative path pattern search
        Path relativePath = PathMatchers.getSearchRoot(pattern);
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        PathFinder finder = new PathFinder();
        finder.setIncludeDirsInResults(true);
        finder.setFileMatcher(matcher);
        // walk config sources backwards ...
        ListIterator<ConfigSource> iter = sources.reverseListIterator();
        while (iter.hasPrevious()) {
            ConfigSource source = iter.previous();
            if (source instanceof DirConfigSource) {
                DirConfigSource dirsource = (DirConfigSource) source;
                Path dir = dirsource.getDir();
                Path deepDir = dir.resolve(relativePath);
                if (FS.isValidDirectory(deepDir)) {
                    finder.setBase(dir);
                    Files.walkFileTree(deepDir, SEARCH_VISIT_OPTIONS, MAX_SEARCH_DEPTH, finder);
                }
            }
        }
        hits.addAll(finder.getHits());
    }
    Collections.sort(hits, new NaturalSort.Paths());
    return hits;
}
Also used : Path(java.nio.file.Path) DirConfigSource(org.eclipse.jetty.start.config.DirConfigSource) JettyHomeConfigSource(org.eclipse.jetty.start.config.JettyHomeConfigSource) ConfigSource(org.eclipse.jetty.start.config.ConfigSource) JettyBaseConfigSource(org.eclipse.jetty.start.config.JettyBaseConfigSource) CommandLineConfigSource(org.eclipse.jetty.start.config.CommandLineConfigSource) PathMatcher(java.nio.file.PathMatcher) ArrayList(java.util.ArrayList) DirConfigSource(org.eclipse.jetty.start.config.DirConfigSource)

Example 45 with PathMatcher

use of java.nio.file.PathMatcher in project jetty.project by eclipse.

the class BaseHome method getPaths.

/**
     * Search specified Path with pattern and return hits
     * 
     * @param dir
     *            the path to a directory to start search from
     * @param searchDepth
     *            the number of directories deep to perform the search
     * @param pattern
     *            the raw pattern to use for the search (must be relative)
     * @return the list of Paths found
     * @throws IOException
     *             if unable to search the path
     */
public List<Path> getPaths(Path dir, int searchDepth, String pattern) throws IOException {
    if (PathMatchers.isAbsolute(pattern)) {
        throw new RuntimeException("Pattern cannot be absolute: " + pattern);
    }
    List<Path> hits = new ArrayList<>();
    if (FS.isValidDirectory(dir)) {
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        PathFinder finder = new PathFinder();
        finder.setFileMatcher(matcher);
        finder.setBase(dir);
        finder.setIncludeDirsInResults(true);
        Files.walkFileTree(dir, SEARCH_VISIT_OPTIONS, searchDepth, finder);
        hits.addAll(finder.getHits());
        Collections.sort(hits, new NaturalSort.Paths());
    }
    return hits;
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) ArrayList(java.util.ArrayList)

Aggregations

PathMatcher (java.nio.file.PathMatcher)107 Path (java.nio.file.Path)47 Test (org.junit.Test)30 IOException (java.io.IOException)28 File (java.io.File)18 ArrayList (java.util.ArrayList)13 FileSystem (java.nio.file.FileSystem)11 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)11 FileVisitResult (java.nio.file.FileVisitResult)10 Glob.createGlob (com.google.copybara.util.Glob.createGlob)8 Files (java.nio.file.Files)6 Paths (java.nio.file.Paths)6 List (java.util.List)6 FileSystems (java.nio.file.FileSystems)5 HashSet (java.util.HashSet)5 ProjectHandlerRegistry (org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry)5 ProjectImporterRegistry (org.eclipse.che.api.project.server.importer.ProjectImporterRegistry)5 ProjectTypeRegistry (org.eclipse.che.api.project.server.type.ProjectTypeRegistry)5 DefaultFileWatcherNotificationHandler (org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler)5 FileTreeWatcher (org.eclipse.che.api.vfs.impl.file.FileTreeWatcher)5