List of usage examples for java.nio.file PathMatcher matches
boolean matches(Path path);
From source file:org.apache.beam.sdk.io.LocalFileSystem.java
private MatchResult matchOne(String spec) throws IOException { if (spec.toLowerCase().startsWith("file:")) { spec = spec.substring("file:".length()); }/*www. j a va 2s . c om*/ if (SystemUtils.IS_OS_WINDOWS) { List<String> prefixes = Arrays.asList("///", "/"); for (String prefix : prefixes) { if (spec.toLowerCase().startsWith(prefix)) { spec = spec.substring(prefix.length()); } } } File file = Paths.get(spec).toFile(); if (file.exists()) { return MatchResult.create(Status.OK, ImmutableList.of(toMetadata(file))); } File parent = file.getAbsoluteFile().getParentFile(); if (!parent.exists()) { return MatchResult.create(Status.NOT_FOUND, Collections.<Metadata>emptyList()); } // Method getAbsolutePath() on Windows platform may return something like // "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat // '\' (backslash) as an escape character, instead of a directory // separator. Replacing backslash with double-backslash solves the problem. // We perform the replacement on all platforms, even those that allow // backslash as a part of the filename, because Globs.toRegexPattern will // eat one backslash. String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\")); final PathMatcher matcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch); // TODO: Avoid iterating all files: https://issues.apache.org/jira/browse/BEAM-1309 Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent); Iterable<File> matchedFiles = Iterables.filter(files, Predicates.and(com.google.common.io.Files.isFile(), new Predicate<File>() { @Override public boolean apply(File input) { return matcher.matches(input.toPath()); } })); List<Metadata> result = Lists.newLinkedList(); for (File match : matchedFiles) { result.add(toMetadata(match)); } if (result.isEmpty()) { // TODO: consider to return Status.OK for globs. return MatchResult.create(Status.NOT_FOUND, new FileNotFoundException(String.format("No files found for spec: %s.", spec))); } else { return MatchResult.create(Status.OK, result); } }
From source file:org.codice.ddf.configuration.migration.ExportMigrationContextImpl.java
@Override public Stream<ExportMigrationEntry> entries(Path path, boolean recurse, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(this, path); if (!isDirectory(entry)) { return Stream.empty(); }/*from www. j a v a2 s. co m*/ return FileUtils .listFiles(entry.getFile(), TrueFileFilter.INSTANCE, recurse ? TrueFileFilter.INSTANCE : null) .stream().map(File::toPath).map(p -> new ExportMigrationEntryImpl(this, p)) .filter(e -> filter.matches(e.getPath())).map(e -> entries.computeIfAbsent(e.getPath(), p -> e)); }
From source file:org.codice.ddf.configuration.migration.ExportMigrationEntryImpl.java
@Override public boolean store(boolean required, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); if (stored == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Exporting {}{} with path filter...", (required ? "required " : ""), toDebugString()); }/* ww w.j a v a2 s . c o m*/ this.stored = false; // until proven otherwise if (isFile && !filter.matches(path)) { this.stored = handleStoreWhenFilterMismatch(required); } else if (absolutePathError instanceof NoSuchFileException) { this.stored = handleStoreWhenNoSuchFile(required); } else if (absolutePathError != null) { SecurityLogger.audit(ExportMigrationEntryImpl.ERROR_EXPORTING_FILE, absolutePath); getReport().record(newError("cannot be read", absolutePathError)); } else { this.stored = handleStoreWhenFileExist(filter); } } return stored; }
From source file:org.codice.ddf.configuration.migration.ExportMigrationEntryImplTest.java
@Test public void testStoreWithFilterForAFileVerifyingFilterReceivingEntryPath() throws Exception { final PathMatcher filter = Mockito.mock(PathMatcher.class); Mockito.when(filter.matches(FILE_PATH)).thenReturn(false); entry.store(false, filter);//from www . j av a 2 s.co m Mockito.verify(filter).matches(FILE_PATH); }
From source file:org.codice.ddf.configuration.migration.ImportMigrationContextImpl.java
@Override public Stream<ImportMigrationEntry> entries(Path path, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); return entries(path).filter(e -> filter.matches(e.getPath())); }
From source file:org.codice.ddf.configuration.migration.ImportMigrationContextImplTest.java
@Test public void testEntriesWithPathAndFilter() throws Exception { final ImportMigrationEntryImpl entry3 = Mockito.mock(ImportMigrationEntryImpl.class); final PathMatcher filter = Mockito.mock(PathMatcher.class); Mockito.when(entry3.getPath()).thenReturn(ddfHome); Mockito.when(filter.matches(Mockito.any())).thenReturn(false); Mockito.when(filter.matches(MIGRATABLE_PATH)).thenReturn(true); context.getEntries().put(MIGRATABLE_PATH, ENTRY); context.getEntries().put(MIGRATABLE_PATH2, ENTRY2); context.getEntries().put(ddfHome, entry3); Assert.assertThat(/*from w ww . ja v a 2s .co m*/ context.entries(MIGRATABLE_PATH2.getParent(), filter).toArray(ImportMigrationEntry[]::new), Matchers.arrayContainingInAnyOrder(Matchers.sameInstance(ENTRY))); Mockito.verify(filter).matches(MIGRATABLE_PATH); Mockito.verify(filter).matches(MIGRATABLE_PATH2); Mockito.verify(filter, Mockito.never()).matches(ddfHome); }
From source file:org.codice.ddf.configuration.migration.ImportMigrationDirectoryEntryImpl.java
@Override public boolean restore(boolean required, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); if (restored == null) { super.restored = false; // until proven otherwise if (LOGGER.isDebugEnabled()) { LOGGER.debug("Importing {} with path filter...", toDebugString()); }/*from w w w . j a va 2 s. c om*/ // a directory is always exported by the framework, as such we can safely extend our // privileges AccessUtils.doPrivileged(() -> { // it is safe to ignore the 'required' parameter since if we get here, we have a // directory // exported to start with and all files underneath are always optional so pass false to // restore() super.restored = fileEntries.stream().filter(me -> filter.matches(me.getPath())) .map(me -> me.restore(false)).reduce(true, Boolean::logicalAnd); final Path apath = getAbsolutePath(); if (restored) { SecurityLogger.audit("Imported directory {}", apath); } else { SecurityLogger.audit("Error importing directory {}", apath); getReport().record(new MigrationException(Messages.IMPORT_PATH_COPY_ERROR, getPath(), getContext().getPathUtils().getDDFHome(), "some directory entries failed")); } }); } return restored; }
From source file:org.codice.ddf.configuration.migration.ImportMigrationEntryImpl.java
@Override public boolean restore(boolean required, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); if (restored == null) { this.restored = false; // until proven otherwise if (filter.matches(path)) { this.restored = handleRestore(required, filter); } else {/*from w w w . j a v a2 s. c om*/ this.restored = handleRestoreWhenFilterNotMatching(required); } } return restored; }
From source file:org.codice.ddf.configuration.migration.ImportMigrationEntryImplTest.java
@Test public void testRestoreWithFilterVerifyingFilterReceivingEntryPath() throws Exception { final PathMatcher filter = mock(PathMatcher.class); final ImportMigrationEntryImpl entry = new ImportMigrationEntryImpl(mockContext, ENTRY_NAME, true); when(filter.matches(entry.getPath())).thenReturn(false); entry.restore(false, filter);/*from w ww.ja va2s.c om*/ verify(filter).matches(entry.getPath()); }
From source file:org.codice.ddf.configuration.migration.ImportMigrationExternalEntryImpl.java
@Override public boolean restore(boolean required, PathMatcher filter) { Validate.notNull(filter, "invalid null path filter"); if (restored == null) { this.restored = false; // until proven otherwise if (LOGGER.isDebugEnabled()) { LOGGER.debug("Verifying {}{} with path filter...", (required ? "required " : ""), toDebugString()); }/*from w ww . j a va 2 s. c o m*/ if (filter.matches(getPath())) { super.restored = verifyRealFileOrDirectory(required); } else { super.restored = verifyRealFileOrDirectoryWhenFilterNotMatching(required); } } return restored; }