List of usage examples for java.nio.file Path startsWith
default boolean startsWith(String other)
From source file:services.PathService.java
public static boolean isPathInProject(Path path, Project project) { for (Directory dir : project.directories) { if (path.startsWith(dir.getPath())) { return true; }/*from ww w. ja va2s. c o m*/ } return false; }
From source file:com.fizzed.rocker.compiler.RockerUtil.java
static public boolean isRelativePath(Path baseDir, Path file) { return file.startsWith(baseDir); }
From source file:com.facebook.buck.util.unarchive.Unzip.java
/** * Get a listing of all files in a zip file that start with a prefix, ignore others * * @param zip The zip file to scan/*from ww w .j a va 2s.c om*/ * @param relativePath The relative path where the extraction will be rooted * @param prefix The prefix that will be stripped off. * @return The list of paths in {@code zip} sorted by path so dirs come before contents. Prefixes * are stripped from paths in the zip file, such that foo/bar/baz.txt with a prefix of foo/ * will be in the map at {@code relativePath}/bar/baz.txt */ private static SortedMap<Path, ZipArchiveEntry> getZipFilePathsStrippingPrefix(ZipFile zip, Path relativePath, Path prefix, PatternsMatcher entriesToExclude) { SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>(); for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { String entryName = entry.getName(); if (entriesToExclude.matchesAny(entryName)) { continue; } Path entryPath = Paths.get(entryName); if (entryPath.startsWith(prefix)) { Path target = relativePath.resolve(prefix.relativize(entryPath)).normalize(); pathMap.put(target, entry); } } return pathMap; }
From source file:org.elasticsearch.bootstrap.JarHell.java
/** * Checks the set of URLs for duplicate classes * @throws IllegalStateException if jar hell was found *//*from w w w . j a va2s.com*/ @SuppressForbidden(reason = "needs JarFile for speed, just reading entries") public static void checkJarHell(URL urls[]) throws Exception { ESLogger logger = Loggers.getLogger(JarHell.class); // we don't try to be sneaky and use deprecated/internal/not portable stuff // like sun.boot.class.path, and with jigsaw we don't yet have a way to get // a "list" at all. So just exclude any elements underneath the java home String javaHome = System.getProperty("java.home"); logger.debug("java.home: {}", javaHome); final Map<String, Path> clazzes = new HashMap<>(32768); Set<Path> seenJars = new HashSet<>(); for (final URL url : urls) { final Path path = PathUtils.get(url.toURI()); // exclude system resources if (path.startsWith(javaHome)) { logger.debug("excluding system resource: {}", path); continue; } if (path.toString().endsWith(".jar")) { if (!seenJars.add(path)) { logger.debug("excluding duplicate classpath element: {}", path); continue; // we can't fail because of sheistiness with joda-time } logger.debug("examining jar: {}", path); try (JarFile file = new JarFile(path.toString())) { Manifest manifest = file.getManifest(); if (manifest != null) { checkManifest(manifest, path); } // inspect entries Enumeration<JarEntry> elements = file.entries(); while (elements.hasMoreElements()) { String entry = elements.nextElement().getName(); if (entry.endsWith(".class")) { // for jar format, the separator is defined as / entry = entry.replace('/', '.').substring(0, entry.length() - 6); checkClass(clazzes, entry, path); } } } } else { logger.debug("examining directory: {}", path); // case for tests: where we have class files in the classpath final Path root = PathUtils.get(url.toURI()); final String sep = root.getFileSystem().getSeparator(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String entry = root.relativize(file).toString(); if (entry.endsWith(".class")) { // normalize with the os separator entry = entry.replace(sep, ".").substring(0, entry.length() - 6); checkClass(clazzes, entry, path); } return super.visitFile(file, attrs); } }); } } }
From source file:org.wso2.carbon.logging.service.provider.FileLogProvider.java
/** * Tests if the provided path is inside the base directory path. * * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path * is inside//from ww w. j av a 2 s. c o m * @param path relative {@link Path} to be tested * @return {@code true} if the given path is inside the base directory path, otherwise {@code false} */ private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) { Path resolvedPath = baseDirPath.resolve(path.normalize()).normalize(); return resolvedPath.startsWith(baseDirPath.normalize()); }
From source file:org.orderofthebee.addons.support.tools.share.LogFileHandler.java
/** * Validates a log file paths and resolves them to file handles. * * @param filePaths//from w w w . j ava 2 s . c o m * the file paths to validate * @return the resolved file handles if the file paths are valid and allowed to be accessed * * @throws WebScriptException * if access to any log file is prohibited */ protected static List<File> validateFilePaths(final List<String> filePaths) { ParameterCheck.mandatoryCollection("filePaths", filePaths); final List<Path> paths = new ArrayList<>(); for (final String filePath : filePaths) { paths.add(Paths.get(filePath)); } boolean allPathsAllowed = true; final List<Logger> allLoggers = LogFileHandler.getAllLoggers(); final List<File> files = new ArrayList<>(); for (final Logger logger : allLoggers) { @SuppressWarnings("unchecked") final Enumeration<Appender> allAppenders = logger.getAllAppenders(); while (allAppenders.hasMoreElements() && allPathsAllowed) { final Appender appender = allAppenders.nextElement(); if (appender instanceof FileAppender) { final String appenderFile = ((FileAppender) appender).getFile(); final File configuredFile = new File(appenderFile); final Path configuredFilePath = configuredFile.toPath().toAbsolutePath().getParent(); for (final Path path : paths) { allPathsAllowed = allPathsAllowed && path.startsWith(configuredFilePath) && path.getFileName().toString().startsWith(configuredFile.getName()); if (!allPathsAllowed) { throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + path + " could not be resolved to a valid log file - access to any other file system contents is forbidden via this web script"); } final File file = path.toFile(); if (!file.exists()) { throw new WebScriptException(Status.STATUS_NOT_FOUND, "The log file path " + path + " could not be resolved to an existing log file"); } files.add(file); } } } } return files; }
From source file:org.sonarsource.scanner.maven.bootstrap.MavenProjectConverter.java
private static void removeTarget(MavenProject pom, Collection<String> relativeOrAbsolutePaths) { final Path baseDir = pom.getBasedir().toPath().toAbsolutePath().normalize(); final Path target = Paths.get(pom.getBuild().getDirectory()).toAbsolutePath().normalize(); final Path targetRelativePath = baseDir.relativize(target); relativeOrAbsolutePaths.removeIf(pathStr -> { Path path = Paths.get(pathStr).toAbsolutePath().normalize(); Path relativePath = baseDir.relativize(path); return relativePath.startsWith(targetRelativePath); });// w w w . j a v a 2 s .c om }
From source file:org.wso2.carbon.logging.service.util.LoggingUtil.java
/** * Tests if the provided path is inside the base directory path. * * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path * is inside// w w w .ja v a2s .co m * @param path {@link Path} to be tested * @return {@code true} if the given path is inside the base directory path, otherwise {@code false} */ private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) { Path resolvedPath = baseDirPath.resolve(path).normalize(); return resolvedPath.startsWith(baseDirPath.normalize()); }
From source file:com.facebook.buck.util.Escaper.java
/** * Escapes forward slashes in a Path as a String that is safe to consume with other tools (such * as gcc). On Unix systems, this is equivalent to {@link java.nio.file.Path Path.toString()}. * @param path the Path to escape// w w w. j a v a2 s .c o m * @return the escaped Path */ public static String escapePathForCIncludeString(Path path) { if (File.separatorChar != '\\') { return path.toString(); } StringBuilder result = new StringBuilder(); if (path.startsWith(File.separator)) { result.append("\\\\"); } for (Iterator<Path> iterator = path.iterator(); iterator.hasNext();) { result.append(iterator.next()); if (iterator.hasNext()) { result.append("\\\\"); } } if (path.getNameCount() > 0 && path.endsWith(File.separator)) { result.append("\\\\"); } return result.toString(); }
From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java
/** * Create a JavaScript engine packed with given scripts. If two scripts have methods with same name, * later method will override the previous method. * * @param domain// ww w .j a v a 2 s . co m * @return JavaScript engine * @throws TemplateDeploymentException if there are any errors in JavaScript evaluation */ public static ScriptEngine createJavaScriptEngine(Domain domain) throws TemplateDeploymentException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager .getEngineByName(TemplateManagerConstants.JAVASCRIPT_ENGINE_NAME); if (scriptEngine == null) { // Exception will be thrown later, only if function calls are used in the template log.warn("JavaScript engine is not available. Function calls in the templates cannot be evaluated"); } else { if (domain != null && domain.getScripts() != null && domain.getScripts().getScript() != null) { Path scriptDirectory = Paths.get(TemplateManagerConstants.TEMPLATE_SCRIPT_PATH); if (Files.exists(scriptDirectory, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(scriptDirectory)) { for (Script script : domain.getScripts().getScript()) { String src = script.getSrc(); String content = script.getContent(); if (src != null) { // Evaluate JavaScript file Path scriptFile = scriptDirectory.resolve(src).normalize(); if (Files.exists(scriptFile, LinkOption.NOFOLLOW_LINKS) && Files.isReadable(scriptFile)) { if (!scriptFile.startsWith(scriptDirectory)) { // The script file is not in the permitted directory throw new TemplateDeploymentException("Script file " + scriptFile.toAbsolutePath() + " is not in the permitted directory " + scriptDirectory.toAbsolutePath()); } try { scriptEngine .eval(Files.newBufferedReader(scriptFile, Charset.defaultCharset())); } catch (ScriptException e) { throw new TemplateDeploymentException("Error in JavaScript " + scriptFile.toAbsolutePath() + ": " + e.getMessage(), e); } catch (IOException e) { throw new TemplateDeploymentException( "Error in reading JavaScript file: " + scriptFile.toAbsolutePath()); } } else { throw new TemplateDeploymentException("JavaScript file not exist at: " + scriptFile.toAbsolutePath() + " or not readable."); } } if (content != null) { // Evaluate JavaScript content try { scriptEngine.eval(content); } catch (ScriptException e) { throw new TemplateDeploymentException( "JavaScript declared in " + domain.getName() + " has error", e); } } } } else { log.warn("Script directory not found at: " + scriptDirectory.toAbsolutePath()); } } } return scriptEngine; }