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

The following examples show how to use java.nio.file.Path#subpath() . 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 File: RestrictedPath.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
/**
 * resolve other in a secure manner without any call to stat.
 * @throws RsyncSecurityException
 */
private Path resolve(Path path) throws RsyncSecurityException
{
    Path result;
    Path normalized = path.normalize();
    if (normalized.startsWith(_moduleName)) {
        if (normalized.getNameCount() == 1) {
            result = _rootPath;
        } else {
            Path strippedOfModulePrefix =
                    normalized.subpath(1, normalized.getNameCount());
            result = _rootPath.resolve(strippedOfModulePrefix).normalize();
        }
    } else {
        throw new RsyncSecurityException(String.format(
            "\"%s\" is outside virtual dir for module %s",
            path, _moduleName));
    }
    if (path.endsWith(_dotDir)) {
        return result.resolve(_dotDir);
    } else {
        return result;
    }
}
 
Example 2
Source File: TestFolderComposite.java    From PeerWasp with MIT License 6 votes vote down vote up
/**
 * Appends a new component to the FolderComposite. Inexistent folders are added on the
 * fly. Existing items are replaced. Triggers updates of content and name hashes.
 */
@Override
public synchronized void putComponent(Path remainingPath, FileComponent component) {
	remainingPath = stripOffPrefix(remainingPath, getPath());

	Path nextLevelPath = remainingPath.getName(0);

	// if we are at the last recursion, perform the add, else recursively continue
	if (remainingPath.getNameCount() == 1) {
		addComponentToChildren(nextLevelPath, component);
	} else {
		FileComponent nextLevel = getChildren().get(nextLevelPath);
		if (nextLevel == null) {
			// next level does not exist yet, create it
			Path childPath = constructFullPath(nextLevelPath);
			nextLevel = new TestFolderComposite(childPath, updateContentHash);
			addComponentToChildren(nextLevelPath, nextLevel);
		}
		Path newRemainingPath = remainingPath.subpath(1, remainingPath.getNameCount());
		((FolderComposite)nextLevel).putComponent(newRemainingPath, component);
	}
}
 
Example 3
Source File: N4JSProjectExplorerHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private String getRootLocationName(final IN4JSProject project) {
	String rootLocationName = null;
	List<IN4JSProject> shadowingProjects = shadowingInfoHelper.findShadowingProjects(project);
	if (!shadowingProjects.isEmpty()) {
		IN4JSProject shadowedProject = shadowingProjects.get(0);
		if (shadowedProject.isExternal()) {
			FileURI location = (FileURI) shadowedProject.getLocation();
			FileURI rootLocation = externalLibraryWorkspace.getRootLocationForResource(location);
			if (rootLocation != null) {
				Path rootPath = rootLocation.toFileSystemPath();
				Path subpath = rootPath.subpath(rootPath.getNameCount() - 2, rootPath.getNameCount());
				rootLocationName = subpath.toString();
			} else {
				rootLocationName = "unknown";
			}
		} else {
			rootLocationName = "workspace";
		}
		rootLocationName = " [shadowed by " + rootLocationName + "]";
	}
	return rootLocationName;
}
 
Example 4
Source File: AbstractFileEditor.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Notify about changed the edited file.
 *
 * @param prevFile the prev file.
 * @param newFile  the new file.
 */
@FxThread
private void notifyChangedEditedFile(final @NotNull Path prevFile, final @NotNull Path newFile) {

    final Path editFile = getEditFile();

    if (editFile.equals(prevFile)) {
        setEditFile(newFile);
        return;
    }

    if (!editFile.startsWith(prevFile)) return;

    final Path relativeFile = editFile.subpath(prevFile.getNameCount(), editFile.getNameCount());
    final Path resultFile = newFile.resolve(relativeFile);

    setEditFile(resultFile);
}
 
Example 5
Source File: DefaultDefectReporter.java    From buck with Apache License 2.0 6 votes vote down vote up
private void addFilesToArchive(CustomZipOutputStream out, ImmutableSet<Path> paths)
    throws IOException {
  for (Path logFile : paths) {
    Path destPath = logFile;
    if (destPath.isAbsolute()) {
      // If it's an absolute path, make it relative instead
      destPath = destPath.subpath(0, logFile.getNameCount());
      Preconditions.checkArgument(!destPath.isAbsolute(), "Should be a relative path", destPath);
    }
    if (destPath.getFileName().toString().startsWith(".")) {
      // If the file is hidden(UNIX terms) save it as normal file.
      destPath =
          Optional.ofNullable(destPath.getParent())
              .orElse(Paths.get(""))
              .resolve(destPath.getFileName().toString().replaceAll("^\\.*", ""));
    }

    out.putNextEntry(new CustomZipEntry(destPath));

    try (InputStream input = filesystem.newFileInputStream(logFile)) {
      ByteStreams.copy(input, out);
    }
    out.closeEntry();
  }
}
 
Example 6
Source File: MemoryBasedJavaFileManager.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
		throws IOException {
	if (file.getNameCount() > 3 && file.toString().endsWith(".class")) {
		int fnc = file.getNameCount();
		if (fnc > 3) { // There is a package name - e.g.
			// /modules/java.base/java/lang/Object.class
			Path packagePath = file.subpath(2, fnc - 1); // e.g. java/lang
			String packagePathString = packagePath.toString() + "/";
			CompilationInfoCache.this.packageCache.put(packagePathString,
					file.subpath(0, fnc - 1)); // java/lang
			// ->
			// /modules/java.base/java/lang
		}
	}
	return FileVisitResult.CONTINUE;
}
 
Example 7
Source File: ZipFileData.java    From size-analyzer with Apache License 2.0 6 votes vote down vote up
@Override
public Path getPathWithinModule() {
  if (cachedPathWithinModule != null) {
    return cachedPathWithinModule;
  }

  Path fullPath = getPathWithinRoot();
  if (fullPath.getNameCount() <= 1
      || fullPath.startsWith("BUNDLE-METADATA")
      || fullPath.startsWith("META-INF")) {
    cachedPathWithinModule = fullPath;
  } else {
    cachedPathWithinModule = fullPath.subpath(1, fullPath.getNameCount());
  }
  return cachedPathWithinModule;
}
 
Example 8
Source File: AndroidResourceOutputs.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Collects all the compiled resources into an archive, normalizing the paths to the root. */
public static Path archiveCompiledResources(
    final Path archiveOut,
    final Path databindingResourcesRoot,
    final Path compiledRoot,
    final List<Path> compiledArtifacts)
    throws IOException {
  final Path relativeDatabindingProcessedResources =
      databindingResourcesRoot.getRoot().relativize(databindingResourcesRoot);

  try (ZipBuilder builder = ZipBuilder.createFor(archiveOut)) {
    for (Path artifact : compiledArtifacts) {
      Path relativeName = artifact;

      // remove compiled resources prefix
      if (artifact.startsWith(compiledRoot)) {
        relativeName = compiledRoot.relativize(relativeName);
      }
      // remove databinding prefix
      if (relativeName.startsWith(relativeDatabindingProcessedResources)) {
        relativeName =
            relativeName.subpath(
                relativeDatabindingProcessedResources.getNameCount(),
                relativeName.getNameCount());
      }

      builder.addEntry(
          relativeName.toString(),
          Files.readAllBytes(artifact),
          ZipEntry.STORED,
          ResourceCompiler.getCompiledType(relativeName.toString()).asComment());
    }
  }
  return archiveOut;
}
 
Example 9
Source File: FolderComposite.java    From PeerWasp with MIT License 5 votes vote down vote up
/**
 * Deletes the FileComponent at location remainingPath. Triggers updates of
 * content and name hashes.
 *
 * @return The deleted component. If it does not exist, null is returned
 */
public synchronized FileComponent deleteComponent(Path remainingPath) {
	remainingPath = stripOffPrefix(remainingPath, getPath());

	Path nextLevelPath = remainingPath.getName(0);

	FileComponent removed = null;
	if (remainingPath.getNameCount() == 1) {

		children.get(nextLevelPath);
		FileComponent toRemove = children.get(nextLevelPath);
		if(toRemove != null){
			if(toRemove instanceof FolderComposite){
				removeBottomUp((FolderComposite)toRemove);
			}
			removed = children.remove(nextLevelPath);
		}
		if (updateContentHash) {
			updateContentHash();
		}
		updateStructureHash();
	} else {
		FileComponent nextLevel = children.get(nextLevelPath);
		if (nextLevel != null && nextLevel.isFolder()) {
			Path newRemainingPath = remainingPath.subpath(1, remainingPath.getNameCount());
			removed = ((FolderComposite)nextLevel).deleteComponent(newRemainingPath);
		}
	}
	return removed;
}
 
Example 10
Source File: DirectoryService.java    From AsciidocFX with Apache License 2.0 5 votes vote down vote up
public String interPath(Path path) {

        try {
            Path subpath = path.subpath(0, path.getNameCount());
            return subpath.toString().replace('\\', '/');
        } catch (Exception e) {
            return ".";
        }
    }
 
Example 11
Source File: MemoryBasedJavaFileManager.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
		throws IOException {
	if (file.getNameCount() > 2 && file.toString().endsWith(".class")) {
		// /modules/jdk.rmic/sun/tools/tree/CaseStatement.class
		String moduleName = file.getName(1).toString(); // jdk.rmic
		Path moduleRootPath = file.subpath(0, 2); // /modules/jdk.rmic
		if (!this.modules.containsKey(moduleName)) {
			this.modules.put(moduleName, moduleRootPath);
		}
	}
	return FileVisitResult.CONTINUE;
}
 
Example 12
Source File: PathArguments.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Filter files under the project root, and convert to canonical relative path style. For example,
 * the project root is /project, 1. file path /project/./src/com/facebook/./test/../Test.java will
 * be converted to src/com/facebook/Test.java 2. file path
 * /otherproject/src/com/facebook/Test.java will be ignored.
 */
static ReferencedFiles getCanonicalFilesUnderProjectRoot(
    AbsPath projectRoot, Iterable<String> nonCanonicalFilePaths) throws IOException {
  // toRealPath() is used throughout to resolve symlinks or else the Path.startsWith() check will
  // not be reliable.
  ImmutableSet.Builder<RelPath> projectFiles = ImmutableSet.builder();
  ImmutableSet.Builder<AbsPath> nonProjectFiles = ImmutableSet.builder();
  AbsPath normalizedRoot = projectRoot.toRealPath();
  for (String filePath : nonCanonicalFilePaths) {
    Path canonicalFullPath = Paths.get(filePath);
    if (!canonicalFullPath.isAbsolute()) {
      canonicalFullPath = projectRoot.resolve(canonicalFullPath).getPath();
    }
    if (!canonicalFullPath.toFile().exists()) {
      nonProjectFiles.add(AbsPath.of(canonicalFullPath));
      continue;
    }
    canonicalFullPath = canonicalFullPath.toRealPath();

    // Ignore files that aren't under project root.
    if (canonicalFullPath.startsWith(normalizedRoot.getPath())) {
      Path relativePath =
          canonicalFullPath.subpath(
              normalizedRoot.getPath().getNameCount(), canonicalFullPath.getNameCount());
      projectFiles.add(RelPath.of(relativePath));
    } else {
      nonProjectFiles.add(AbsPath.of(canonicalFullPath));
    }
  }
  return new ReferencedFiles(projectFiles.build(), nonProjectFiles.build());
}
 
Example 13
Source File: ModuleHelper.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
public static Optional<String> pathToModule(Path p) {

    if (p.startsWith(File.separator + "modules" + File.separator)) {
      // module path
      Path subpath = p.subpath(1, 2);
      return Optional.of(subpath.toString());
    }
    return Optional.empty();
  }
 
Example 14
Source File: MCRAutoDeploy.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void deployWebResources(final ServletContext servletContext, final MCRComponent comp) {
    final Path webRoot = Optional.ofNullable(servletContext.getRealPath("/")).map(Paths::get).orElse(null);
    if (webRoot != null) {
        int resourceDirPathComponents = RESOURCE_DIR.split("/").length;
        try (InputStream fin = Files.newInputStream(comp.getJarFile().toPath());
            ZipInputStream zin = new ZipInputStream(fin)) {
            LOGGER.info("Deploy web resources from {} to {}...", comp.getName(), webRoot);
            for (ZipEntry zipEntry = zin.getNextEntry(); zipEntry != null; zipEntry = zin.getNextEntry()) {
                if (zipEntry.getName().startsWith(RESOURCE_DIR)) {
                    Path relativePath = toNativePath(zipEntry);
                    if (relativePath.getNameCount() > resourceDirPathComponents) {
                        //strip RESOURCE_DIR:
                        relativePath = relativePath.subpath(resourceDirPathComponents, relativePath.getNameCount());
                        Path target = webRoot.resolve(relativePath);
                        if (zipEntry.isDirectory()) {
                            Files.createDirectories(target);
                        } else if (isUnzipRequired(zipEntry, target)) {
                            LOGGER.debug("...deploy {}", zipEntry.getName());
                            Files.copy(zin, target, StandardCopyOption.REPLACE_EXISTING);
                            Files.setLastModifiedTime(target, zipEntry.getLastModifiedTime());
                        }
                    }
                }
            }
            LOGGER.info("...done.");
        } catch (final IOException e) {
            LOGGER.error("Could not deploy web resources of " + comp.getJarFile() + "!", e);
        }
    }
}
 
Example 15
Source File: JImageExtractTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testExtractFromDir() {
    Path imagePath = Paths.get(getImagePath());
    Path imageDirPath = imagePath.subpath(0, imagePath.getNameCount() - 1);
    jimage("extract", imageDirPath.toString())
            .assertFailure()
            .assertShowsError();
}
 
Example 16
Source File: MemoryBasedJavaFileManager.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
	if (file.getNameCount() > 2 && file.toString().endsWith(".class")) {
		// /modules/jdk.rmic/sun/tools/tree/CaseStatement.class
		String moduleName = file.getName(1).toString(); // jdk.rmic
		Path moduleRootPath = file.subpath(0, 2); // /modules/jdk.rmic
		if (!modules.containsKey(moduleName)) {
			modules.put(moduleName, moduleRootPath);
		}
	}
	return FileVisitResult.CONTINUE;
}
 
Example 17
Source File: MergeContent.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String getPath(final FlowFile flowFile) {
    Path path = Paths.get(flowFile.getAttribute(CoreAttributes.PATH.key()));
    if (path.getNameCount() == 0) {
        return "";
    }

    if (".".equals(path.getName(0).toString())) {
        path = path.getNameCount() == 1 ? null : path.subpath(1, path.getNameCount());
    }

    return path == null ? "" : path.toString() + "/";
}
 
Example 18
Source File: SymlinkCache.java    From buck with Apache License 2.0 5 votes vote down vote up
private Map<Path, Path> inputFilesUnderSymlink(
    // We use Collection<Path> instead of Iterable<Path> to prevent
    // accidentally passing in Path, since Path itself is Iterable<Path>.
    Collection<ForwardRelativePath> inputs, ProjectFilesystem projectFilesystem)
    throws IOException {
  Map<Path, Path> newSymlinksEncountered = new HashMap<>();
  for (ForwardRelativePath input : inputs) {
    Path inputPath = input.toPath(projectFilesystem.getFileSystem());
    for (int i = 1; i < inputPath.getNameCount(); i++) {
      Path subpath = inputPath.subpath(0, i);
      Optional<Path> resolvedSymlink = symlinkExistenceCache.get(subpath);
      if (resolvedSymlink != null) {
        if (resolvedSymlink.isPresent()) {
          LOG.verbose("Detected cached symlink %s -> %s", subpath, resolvedSymlink.get());
          newSymlinksEncountered.put(subpath, resolvedSymlink.get());
        }
        // If absent, not a symlink.
      } else {
        // Not cached, look it up.
        if (projectFilesystem.isSymLink(subpath)) {
          Path symlinkTarget = projectFilesystem.resolve(subpath).toRealPath();
          Path relativeSymlinkTarget =
              projectFilesystem.getPathRelativeToProjectRoot(symlinkTarget).orElse(symlinkTarget);
          LOG.verbose("Detected symbolic link %s -> %s", subpath, relativeSymlinkTarget);
          newSymlinksEncountered.put(subpath, relativeSymlinkTarget);
          symlinkExistenceCache.put(subpath, Optional.of(relativeSymlinkTarget));
        } else {
          symlinkExistenceCache.put(subpath, Optional.empty());
        }
      }
    }
  }
  return newSymlinksEncountered;
}
 
Example 19
Source File: MerkleTreeNodeCache.java    From buck with Apache License 2.0 5 votes vote down vote up
private TreeNodeBuilder getMutableDirectory(Path dir) {
  Preconditions.checkArgument(dir.getNameCount() > getPathSegments());
  Path subPath = dir.subpath(0, getPathSegments() + 1);
  verifyPathNotYetProcessed(subPath);
  return childrenBuilder
      .compute(
          subPath,
          (ignored, value) ->
              Either.ofRight(
                  value == null
                      ? new TreeNodeBuilder(subPath)
                      : value.transform(TreeNodeBuilder::new, right -> right)))
      .getRight();
}
 
Example 20
Source File: BuckUnixPathTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@Parameters({",0,1", "a,-1,1", "/a,-1,1", "a,0,2", "/a,0,2", "a/b,1,0", "/a/b/c/d,0,5"})
public void subpathMethodException(String data, int beginIndex, int endIndex) {
  Path path = BuckUnixPathUtils.createPath(data);
  path.subpath(beginIndex, endIndex);
}