Java Code Examples for java.nio.file.Path#startsWith()

The following examples show how to use java.nio.file.Path#startsWith() . These examples are extracted from open source projects. 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 Project: mycore   File: MCRStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes the data stored in the given file object from the store
 *
 * @see <a href="https://stackoverflow.com/questions/39628328/trying-to-create-a-directory-immediately-after-a-successful-deleteifexists-throw">stackoverflow</a>
 * @param path
 *            the file object to be deleted
 */
void delete(final Path path) throws IOException {
    if (!path.startsWith(baseDirectory)) {
        throw new IllegalArgumentException(path + " is not in the base directory " + baseDirectory);
    }
    Path current = path;
    Path parent = path.getParent();
    Files.walkFileTree(path, MCRRecursiveDeleter.instance());

    while (!Files.isSameFile(baseDirectory, parent)) {

        // Prevent access denied error in windows with closing the stream correctly
        try (Stream<Path> streamParent = Files.list(parent)) {
            if (streamParent.findAny().isPresent()) {
                break;
            }
            current = parent;
            parent = current.getParent();
            Files.delete(current);
        }
    }
}
 
Example 2
Source Project: vscode-as3mxml   File: SourcePathUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isInProjectSourcePath(Path path, IASProject project, RoyaleProjectConfigurator configurator)
  {
if (project == null)
{
	return false;
}
      for (File sourcePath : project.getSourcePath())
      {
	if (path.startsWith(sourcePath.toPath()))
	{
		return true;
	}
      }
      if (configurator != null)
      {
          Configuration configuration = configurator.getConfiguration();
          for (String includedSource : configuration.getIncludeSources())
          {
              if (path.startsWith(Paths.get(includedSource)))
              {
                  return true;
              }
          }
      }
      return false;
  }
 
Example 3
@Override
public ResourceInfo getResourceInfo(RepositoryContext context, String location)
{
	File file = getFile(context, location);
	if (file != null)
	{
		try
		{
			Path filePath = file.toPath().toRealPath();
			if (rootRealPath != null && filePath.startsWith(rootRealPath))
			{
				Path relativePath = rootRealPath.relativize(filePath);
				return StandardResourceInfo.from(relativePath);
			}
			else if(resolveAbsolutePath)
			{
				return StandardResourceInfo.from(filePath);
			}
		}
		catch (IOException e)
		{
			log.warn("Failed to resolve real path for file " + file, e);
		}
	}
	return null;
}
 
Example 4
Source Project: archiva   File: MavenIndexContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public StorageAsset getPath() {
    if (dir==null) {
        StorageAsset repositoryDirAsset = repository.getRoot();
        Path repositoryDir = repositoryDirAsset.getFilePath().toAbsolutePath();
        Path indexDir = delegate.getIndexDirectoryFile().toPath();
        if (indexDir.startsWith(repositoryDir)) {
            dir = repository.getAsset(repositoryDir.relativize(indexDir).toString());
        } else {
            try {
                FilesystemStorage storage = new FilesystemStorage(indexDir, new DefaultFileLockManager());
                dir = storage.getRoot();
            } catch (IOException e) {
                log.error("Error occured while creating storage for index dir");
            }
        }
    }
    return dir;
}
 
Example 5
/**
 * Register the given directory with the WatchService.
 *
 * @param dir the directory to register watch on
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void register(Path dir) throws IOException {

    for(Path p: keys.values()) {
        // This may NOT be correct for all cases (ensure resolve will work!)
        if(dir.startsWith(p)) {
            LOGGER.debug("Path {} watched via {}", dir, p);
            return;
        }
    }

    if (FILE_TREE == null) {
        LOGGER.debug("WATCHING:ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - high} {}", dir);
    } else {
        LOGGER.debug("WATCHING: ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - fileTree,high {}", dir);
    }

    final WatchKey key = dir.register(watcher, KINDS,  MODIFIERS);

    keys.put(key, dir);
}
 
Example 6
Source Project: Bytecoder   File: BootLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds the module at the given location defined to the boot loader.
 * The module is either in runtime image or exploded image.
 * Otherwise this method returns null.
 */
private static Module findModule(String location) {
    String mn = null;
    if (location.startsWith("jrt:/")) {
        // named module in runtime image ("jrt:/".length() == 5)
        mn = location.substring(5, location.length());
    } else if (location.startsWith("file:/")) {
        // named module in exploded image
        Path path = Path.of(URI.create(location));
        Path modulesDir = Path.of(JAVA_HOME, "modules");
        if (path.startsWith(modulesDir)) {
            mn = path.getFileName().toString();
        }
    }

    // return the Module object for the module name. The Module may
    // in the boot layer or a child layer for the case that the module
    // is loaded into a running VM
    if (mn != null) {
        String name = mn;
        return Modules.findLoadedModule(mn)
            .orElseThrow(() -> new InternalError(name + " not loaded"));
    } else {
        return null;
    }
}
 
Example 7
Source Project: reasonml-idea-plugin   File: BsConfig.java    License: MIT License 6 votes vote down vote up
boolean accept(@Nullable String canonicalPath) {
    if (canonicalPath == null || m_basePath == null) {
        return false;
    }

    Path relativePath = m_basePath.relativize(new File(canonicalPath).toPath());
    if (relativePath.startsWith("node_modules")) {
        if (relativePath.startsWith(m_rootBsPlatform)) {
            return true;
        }
        for (Path path : m_paths) {
            if (relativePath.startsWith(path)) {
                return true;
            }
        }
        return false;
    }

    return !relativePath.startsWith("..");
}
 
Example 8
Source Project: tmc-cli   File: WorkDir.java    License: MIT License 6 votes vote down vote up
/**
 * Add a path to this object's directories.
 * Return true if and only if the path is in the same course directory
 * as all other directories.
 * @param path: given path
 * @return whether the path given is in the course directory
 */
public boolean addPath(Path path) {
    path = makeAbsolute(path);
    if (this.directories.isEmpty()) {
        this.directories.add(path);
        this.courseDirectory = findCourseDir(path);
        if (this.courseDirectory != null) {
            this.configFile = this.courseDirectory.resolve(CourseInfoIo.COURSE_CONFIG);
            return true;
        }
        return false;
    }
    if (!this.directories.contains(path)) {
        this.directories.add(path);
    }
    return path.startsWith(this.courseDirectory);
}
 
Example 9
private void verifySymLinks(String bindir) throws IOException {
    File binDir = new File(bindir);
    System.err.println("verifying links in: " + bindir);
    File isaDir = new File(binDir, getArch()).getAbsoluteFile();
    if (!isaDir.exists()) {
        throw new RuntimeException("dir: " + isaDir + " does not exist");
    }
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
        for (Path p : ds) {
            if (symlinkExcludes.matcher(p.toString()).matches() ||
                    Files.isDirectory(p, NOFOLLOW_LINKS)) {
                continue;
            }
            Path link = new File(isaDir, p.getFileName().toString()).toPath();
            if (Files.isSymbolicLink(link)) {
                Path target = Files.readSymbolicLink(link);
                if (target.startsWith("..") && p.endsWith(target.getFileName())) {
                    // System.out.println(target + " OK");
                    continue;
                }
                System.err.println("target:" + target);
                System.err.println("file:" + p);
            }
            throw new RuntimeException("could not find link to " + p);
        }
    }

}
 
Example 10
Source Project: vscode-as3mxml   File: SourcePathUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getPackageForDirectoryPath(Path directory, IASProject project)
{
    //find the source path that the parent directory is inside
    //that way we can strip it down to just the package
    String basePath = null;
    for (File sourcePath : project.getSourcePath())
    {
        if (directory.startsWith(sourcePath.toPath()))
        {
            basePath = sourcePath.toPath().toString();
            break;
        }
    }
    if (basePath == null)
    {
        //we couldn't find the source path!
        return "";
    }

    String expectedPackage = directory.toString().substring(basePath.length());
    //replace / in path on Unix
    expectedPackage = expectedPackage.replaceAll("/", ".");
    //replaces \ in path on Windows
    expectedPackage = expectedPackage.replaceAll("\\\\", ".");
    if (expectedPackage.startsWith("."))
    {
        expectedPackage = expectedPackage.substring(1);
    }
    return expectedPackage;
}
 
Example 11
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

    dir = dir.toAbsolutePath();

    // skip anything not in /home
    if (!dir.startsWith(getHomeDirectoryBasePath())) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Not visiting non-home dir {}", dir.toAbsolutePath());
        }
        return FileVisitResult.SKIP_SUBTREE;
    }
    // skip paths that are excluded, as we may not want to scan some directories for various reasons.
    for (Path excluded : getExcludedPaths()) {
        if (dir.startsWith(excluded)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Not visiting excluded dir {}", dir.toAbsolutePath());
            }
            return FileVisitResult.SKIP_SUBTREE;
        }
    }

    // skip anything that is more than homedir length+2 and not named .ssh
    final int dirCount = dir.getNameCount();
    if (dirCount > getHomeDirNameCount() + 1 && !dir.endsWith(".ssh")) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Not visiting deep dir {}", dir.toAbsolutePath());
        }
        return FileVisitResult.SKIP_SUBTREE;
    }

    register(dir);
    return FileVisitResult.CONTINUE;
}
 
Example 12
Source Project: startup-os   File: WorkspaceCommand.java    License: Apache License 2.0 5 votes vote down vote up
private boolean removeWorkspace() {
  Path currentPath = Paths.get("").toAbsolutePath();
  if (!fileUtils.folderExists(workspacePath)) {
    System.err.println(RED_ERROR + "Workspace does not exist");
    return false;
  }

  if (currentPath.startsWith(workspacePath)) {
    System.err.println(RED_ERROR + "Trying to remove active workspace");
    return false;
  }
  fileUtils.deleteDirectoryUnchecked(workspacePath);
  return true;
}
 
Example 13
Source Project: js-dossier   File: Config.java    License: Apache License 2.0 5 votes vote down vote up
private void checkSourcePrefix() {
  if (getSourcePrefix().isPresent()) {
    Path prefix = getSourcePrefix().get();
    for (Path source : concat(getSources(), getModules())) {
      if (!source.startsWith(prefix)) {
        throw new InvalidConfigurationException(
            "Input file does not start with <%s>: %s", prefix, source);
      }
    }
  } else {
    setSourcePrefix(getSourcePrefixPath(getFileSystem(), getSources(), getModules()));
  }
}
 
Example 14
Source Project: Strata   File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Path validateZipPathName(Path rootPath, ZipEntry entry) throws ZipException {
  Path normalizedRootPath = rootPath.normalize();
  Path resolved = normalizedRootPath.resolve(entry.getName()).normalize();
  if (!resolved.startsWith(normalizedRootPath)) {
    throw new ZipException("ZIP file contains illegal file name: " + entry.getName());
  }
  return resolved;
}
 
Example 15
/**
 * Validates a {@code spec} and throws an exception for invalid ones.
 *
 * <p>Ideally validation should happen as part of spec creation and some of them actually happen,
 * but others, especially those that require filesystem interactions, are too expensive to carry
 * for every single build target.
 */
private void validateTargetSpec(TargetNodeSpec spec, String arg, Cell owningCell) {
  CanonicalCellName cellName = spec.getBuildFileSpec().getCellRelativeBaseName().getCellName();
  ForwardRelativePath basePath = spec.getBuildFileSpec().getCellRelativeBaseName().getPath();
  Path basePathPath = basePath.toPath(owningCell.getFilesystem().getFileSystem());
  Cell realCell = owningCell.getCellProvider().getCellByCanonicalCellName(cellName);
  if (!realCell.getFilesystem().exists(basePathPath)) {
    // If someone passes in bar:baz while in subdir foo, and foo/bar does not exist, BUT <root
    // cell>/bar does, tell the user to fix their usage. We do not want to support too many
    // extraneous build target patterns, so hard error, but at least try to help users along.
    if (!rootRelativePackage.isEmpty() && owningCell.equals(realCell) && !arg.contains("//")) {
      Path rootRelativePackagePath = Paths.get(rootRelativePackage);
      if (basePathPath.startsWith(rootRelativePackagePath)
          && owningCell
              .getFilesystem()
              .exists(rootRelativePackagePath.relativize(basePathPath))) {
        Path rootBasePath = rootRelativePackagePath.relativize(basePathPath);
        String str =
            "%s references a non-existent directory %s when run from %s\n"
                + "However, %s exists in your repository root (%s).\n"
                + "Non-absolute build targets are relative to your working directory.\n"
                + "Try either re-running your command the repository root, or re-running your "
                + " command with //%s instead of %s";
        throw new HumanReadableException(
            str,
            arg,
            basePath,
            rootRelativePackage,
            rootBasePath,
            owningCell.getRoot(),
            arg,
            arg);
      }
    }
    throw new HumanReadableException("%s references non-existent directory %s", arg, basePath);
  }
}
 
Example 16
private static boolean isUnchecked(final Path testFile) {
    for (final String uncheckedDir : uncheckedDirs) {
        if (testFile.startsWith(uncheckedDir)) {
            return true;
        }
    }
    return false;
}
 
Example 17
public static Optional<String> pathToClassName(Path p) {

    if (p.startsWith(File.separator + "modules" + File.separator)) {
      // module path
      Path subpath = p.subpath(2, p.getNameCount());

      String s = ClassNameUtils.replaceSlash(subpath.toString());
      if (s.endsWith(".class")) {
        s = s.substring(0, s.length() - 6);
        return Optional.of(s);
      }
    }
    return Optional.empty();
  }
 
Example 18
Source Project: vespa   File: NodeAgentContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Path pathInNodeFromPathOnHost(Path pathOnHost) {
    requireValidPath(pathOnHost);

    if (! pathOnHost.isAbsolute())
        throw new IllegalArgumentException("Expected an absolute path on the host, got: " + pathOnHost);

    if (!pathOnHost.startsWith(pathToNodeRootOnHost))
        throw new IllegalArgumentException("Path " + pathOnHost + " does not exist in the container");

    return pathOnHost.getRoot().resolve(pathToNodeRootOnHost.relativize(pathOnHost));
}
 
Example 19
Source Project: PeerWasp   File: FolderComposite.java    License: MIT License 4 votes vote down vote up
protected Path stripOffPrefix(Path path, final Path prefix) {
	if (path.startsWith(prefix)) {
		path = prefix.relativize(path);
	}
	return path;
}
 
Example 20
/**
 * Resolves a relative path against the target directory, making sure the resulting path does not escape the target.
 *
 * @param relativePath
 *         Relative path to resolve
 * @return Resolved path
 * @throws FirebirdEmbeddedLoadingException
 *         When resolving {@code relativePath} against the target directory escaped the target.
 */
private Path safeResolve(String relativePath) throws FirebirdEmbeddedLoadingException {
    Path targetFile = targetDirectory.resolve(relativePath).toAbsolutePath();
    if (targetFile.startsWith(targetDirectory)) {
        return targetFile;
    }
    throw new FirebirdEmbeddedLoadingException(
            getProviderName() + ": File " + relativePath + " escapes the target directory");
}