Refine search
@Signature public static boolean match(String path, String pattern) { PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(pattern); return pathMatcher.matches(Paths.get(path)); }
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:data"); if (matcher.matches(dir.getFileName())) { System.out.println("dir found " + dir); if (matcher.matches(file.getFileName())) { System.out.println("file found " + file); Files.walkFileTree(Paths.get("full/path/to/your/search"), new MyVisitor());
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attributes) { Path relative = Paths.get(base.relativize(dir.toUri()).getPath()); if (excludeMatcher.stream().anyMatch(pathMatcher -> pathMatcher.matches(relative))) { return FileVisitResult.SKIP_SUBTREE; } if (isParentIncluded.getOrDefault(dir.getParent(), false) || includeMatcher.stream().anyMatch(pathMatcher -> pathMatcher.matches(relative))) { isParentIncluded.put(dir, true); return FileVisitResult.CONTINUE; } return FileVisitResult.CONTINUE; }
@Override public List<String> getSubdirectories(String glob) throws IOException { List<String> result = new ArrayList<String>(); PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher( "glob:" + glob); for (Path path : files.keySet()) { if (!this.directory.equals(path.getParent())) { continue; } if (pathMatcher.matches(path.getFileName())) { result.add(path.getFileName().toString()); } } return result; }
/** * Search for all {@link #YAML_FILES_PATTERN} in provided base path * * @param path base path to start (can be file or directory) * @return list of all paths matching pattern. Only base file itself if it is a file matching pattern */ public List<Path> configs(String path) throws ConfiguratorException { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN); final Path root = Paths.get(path); if (!Files.exists(root)) { throw new ConfiguratorException("Invalid configuration: '"+path+"' isn't a valid path."); } if (!Files.isDirectory(root)) { return matcher.matches(root) ? Collections.singletonList(root) : Collections.emptyList(); } try { return Files.list(root) .filter(Files::isRegularFile) // only consider regular files, following symlinks .filter(matcher::matches) // matching pattern .collect(toList()); } catch (IOException e) { throw new IllegalStateException("failed config scan for " + path, e); } }
static public List<File> get(File base, String pattern) { Path p = Paths.get(pattern); List<Path> ff; List<String> segments = new ArrayList<>(Arrays.asList(pattern.split(Pattern.quote(File.separator)))); if ( p.isAbsolute() ) { Path absStart = Paths.get(segments.remove(0) + File.separator); assert Files.isDirectory(absStart); ff = Collections.singletonList(absStart); } else { PathMatcher matcher = FileSystems.getDefault() .getPathMatcher("glob:" + segment); if (Files.isDirectory(d)) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(d)) { for (Path path : directoryStream) { if (matcher.matches(path.getFileName())) { fff.add(path); files.add(path.toFile());
/** * Read all the SQL files in the given folder. * * @return List of {{@link SQLQuery}. * @throws SQLReaderException Error while reading the files. */ public Map<String, SQLQuery> readAllQueries() throws SQLReaderException { Map<String, SQLQuery> sqlQueries = new HashMap<>(); try (Stream<Path> pathStream = Files.walk(path)) { pathStream.forEach(LambdaExceptionUtils.rethrowConsumer(paths -> { PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.sql"); if (matcher.matches(paths.getFileName())) { SQLQuery sqlQuery = new SQLQuery(new String(Files.readAllBytes(paths))); sqlQuery.setBaseDirectory(paths.getParent().toFile().getName()); sqlQuery.setSqlQueryType( getQueryTypeForSQLQuery(paths.getFileName().toString(), paths.getParent())); sqlQuery.setFollowedByQuery( getFollowedBySQLQuery(paths.getFileName().toString(), paths.getParent())); sqlQueries.put(paths.getFileName().toString(), sqlQuery); if (log.isDebugEnabled()) { log.debug("Following SQL query read from the file: {}", sqlQuery); } } })); } catch (IOException e) { throw new SQLReaderException("Error occurred while reading the SQL files.", e); } return sqlQueries; }
public void convertY2X(InputStream zip) throws MultiException { Path path = Utils.unzipFile(zip); LOGGER.debug("Unzip path: {}", path); PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{yml,yaml}"); MultiException exception = Arrays.stream(Optional.ofNullable(path.toFile().listFiles()).orElse(new File[] {})) .map(File::toPath) .filter(file -> matcher.matches(file.getFileName())) .map(file -> { Reader reader = Reader.getReader(); try { String id = file.getFileName().toString().substring(0, file.getFileName().toString().lastIndexOf(".")); Path fileName = file.subpath(path.getNameCount(), file.getNameCount()); Path fileOutPath = path.resolve("tmp"); String namespace = reader.getNamespace(path, fileName); TServiceTemplate serviceTemplate = reader.parse(path, fileName); LOGGER.debug("Convert filePath = {}, fileName = {}, id = {}, namespace = {}, fileOutPath = {}", path, fileName, id, namespace, fileOutPath); this.convertY2X(serviceTemplate, id, namespace, path, fileOutPath); } catch (MultiException e) { return e; } return null; }) .filter(Objects::nonNull) .reduce(MultiException::add) .orElse(new MultiException()); if (exception.hasException()) throw exception; }
PathMatcher matcher = FileSystems.getDefault().getPathMatcher( "glob:igfs-log-" + arg.getIgfsName() + "-*.csv"); try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(logsDir)) { for (Path p : dirStream) { if (matcher.matches(p.getFileName())) { try { Files.delete(p); // Try to delete file. if (Files.exists(p)) // Checks if it still exists. notDeleted++; else
Path rootPath = Paths.get("src/test/resources/ch/inftec/ju/util/libs/glob"); Path pFile1Txt = rootPath.resolve("File1.txt"); Path pFile1Sql = rootPath.resolve("File1.sql"); Path pSubFile1Txt = rootPath.resolve("sub/subFile1.txt"); DirectoryStream<Path> ds = Files.newDirectoryStream(rootPath, "*.txt"); List<Path> paths = JuCollectionUtils.asList(ds); Assert.assertEquals(1, paths.size()); // Note that search is not recursive PathMatcher pm1 = FileSystems.getDefault().getPathMatcher("glob:*"); // Note that we need the glob prefix here Assert.assertFalse(pm1.matches(pFile1Txt)); // Note that * doesn't cross directory boundaries Assert.assertTrue(pm1.matches(pFile1Txt.getFileName())); Assert.assertTrue(FileSystems.getDefault().getPathMatcher("glob:**").matches(pFile1Txt)); Assert.assertTrue(FileSystems.getDefault().getPathMatcher("glob:**.{txt,sql}").matches(pFile1Txt)); Assert.assertFalse(FileSystems.getDefault().getPathMatcher("glob:**.{html,xml}").matches(pFile1Txt)); PathMatcher pm2 = FileSystems.getDefault().getPathMatcher("glob:**/sub/sub[A-F]ile?.{txt,bak}"); Assert.assertFalse(pm2.matches(pFile1Txt)); Assert.assertTrue(pm2.matches(pSubFile1Txt));
if (Files.isDirectory(fileOnVisit.toRealPath())) { return FileVisitResult.CONTINUE; throw new RuntimeException("Can't resolve symbolic link", ex); if (lastPath != null && fileOnVisit.toString().compareTo(lastPath) <= 0) { } else if (!dirNameMatcher.matches(fileOnVisit)) { final Path parent = Optional.ofNullable(fileOnVisit.getParent()).orElse(WORKING_DIRECTORY); if (parent.equals(dirToStartWalking)) { if (baseFileNameMatcher.matches(fileOnVisit.getFileName())) { filesFound.add(fileOnVisit.toString()); return FileVisitResult.CONTINUE;
try pm = FileSystems.getDefault().getPathMatcher( "glob:" + ((justPattern.length() == 0) ? path : String.join("/", path, justPattern )) ); Files.walk( Paths.get( path ), numLevels ).filter( p -> pm.matches( p ) ).filter( new Predicate< Path >() .forEach( p -> paths.add( new File(p.toString() )) );
@Override public FileVisitResult preVisitDirectory(final Path dirOnVisit, final BasicFileAttributes attrs) { if (dirOnVisit.equals(dirToStartWalking)) { return FileVisitResult.CONTINUE; } else if (lastPath != null && dirOnVisit.toString().compareTo(lastPath) <= 0) { } else if (!dirNameMatcher.matches(dirOnVisit)) { final Path parent = Optional.ofNullable(dirOnVisit.getParent()).orElse(WORKING_DIRECTORY); if (parent.equals(dirToStartWalking)) { if (baseFileNameMatcher.matches(dirOnVisit.getFileName())) { return FileVisitResult.CONTINUE; } else {
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (exclusionMatcher.matches(dir) || exclusions.contains(dir) || (ignoreHiddenFolders && dir.toFile().isHidden())) { return FileVisitResult.SKIP_SUBTREE; } Path targetPath = targetFolder.toPath().resolve(fromFolder.toPath().relativize(dir)); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); } return FileVisitResult.CONTINUE; }
public boolean isAnExcludedPath(Path candidatePath, SensorContext context) { List<String> listExcludedPath = getExcludedPath(context); for (String s : listExcludedPath) { Path pathAbsolute = candidatePath.toAbsolutePath(); Path pathBase = context.fileSystem().baseDir().toPath(); Path pathRelative = pathBase.relativize(pathAbsolute); if (s.contains("*")) { PathMatcher pathMatcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + s); if (pathMatcher.matches(pathRelative)) { return true; } } if ((candidatePath.isAbsolute() && candidatePath.endsWith(s)) || (candidatePath.getFileName().toFile().getName().equals(s))) { return true; } } return false; }
static Stream<Path> glob(String mask) throws IOException { Matcher matcher = Pattern.compile("(.*)[\\\\/](.*)").matcher(mask); Path parentPath; String fName; if(matcher.matches()) { parentPath = Paths.get(matcher.group(1)); fName = matcher.group(2); } else { parentPath = Paths.get("."); fName = mask; } PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + fName); return Files.list(parentPath).filter(p -> pathMatcher.matches(p.getFileName())); }
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (exclusionMatcher.matches(file) || (ignoreHiddenFiles && file.toFile().isHidden())) { return FileVisitResult.SKIP_SUBTREE; } Files.copy(file, targetFolder.toPath().resolve(fromFolder.toPath().relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; }
private void find(final Path path) throws IOException { final Path name = path.getFileName(); if (name != null && matcher.matches(name)) { try (final InputStream inputStream = Files.newInputStream(path)) { final ClassParser parser = new ClassParser(inputStream, name.toAbsolutePath().toString()); final JavaClass jc = parser.parse(); Assert.assertNotNull(jc); } } }
/** * Parse all IGFS log files in specified log directory. * * @param logDir Folder were log files located. * @return List of line with aggregated information by files. */ private List<VisorIgfsProfilerEntry> parse(Path logDir, String igfsName) throws IOException { List<VisorIgfsProfilerEntry> parsedFiles = new ArrayList<>(512); try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(logDir)) { PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:igfs-log-" + igfsName + "-*.csv"); for (Path p : dirStream) { if (matcher.matches(p.getFileName())) { try { parsedFiles.addAll(parseFile(p)); } catch (NoSuchFileException ignored) { // Files was deleted, skip it. } catch (Exception e) { ignite.log().warning("Failed to parse IGFS profiler log file: " + p, e); } } } } return parsedFiles; }