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

The following examples show how to use java.nio.file.Path#normalize() . 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: DirectoryHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return {@code true} if paths {@code from} and {@code to} are located on same FileStore (volume or
 * partition). The {@code from} must exists, while {@code to} does not have to.
 */
private static boolean areOnSameFileStore(final Path from, final Path to) {
  try {
    final FileStore fromStore = Files.getFileStore(from); // from must exist
    Path toExistingParent = to.normalize(); // to usually does not exists, is about to be created as part of move
    while (toExistingParent != null && !Files.exists(toExistingParent)) {
      toExistingParent = toExistingParent.getParent();
    }
    if (toExistingParent != null) {
      final FileStore toStore = Files.getFileStore(toExistingParent);
      return fromStore.equals(toStore);
    }
    else {
      log.warn("No ultimate parent path found for '{}'", to, new RuntimeException("marker")); // record the stack trace?
      return false; // no ultimate parent? be on safe side
    }
  }
  catch (IOException e) {
    return false; // be on safe side
  }
}
 
Example 2
Source File: ClassPathUtils.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public static void addToolsJar() throws Exception {
  String home = System.getProperty("java.home");
  String parent = new File(home).getParent();
  Path path = Paths.get(parent, "lib", "tools.jar");
  path = path.normalize();
  File file = path.toFile();
  if (file.exists()) {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL());
    log.info("add tools.jar path:{}", path.toFile().getCanonicalPath());
  } else {
    if (isJava8()) {
      log.error("missing tools.jar path:{}", path.toFile().getCanonicalPath());
    }
  }
}
 
Example 3
Source File: CipherFileChannel.java    From encfs4j with Apache License 2.0 5 votes vote down vote up
public CipherFileChannel(Path path, String cipherTransformation,
		SecretKeySpec secretKeySpec, Path fileSystemRoot, boolean isReverse)
		throws IOException {

	try {
		this.path = path.normalize();

		// this.encrypt =
		// "encfs".equals(path.getFileSystem().provider().getScheme());

		this.persistentFile = new RandomAccessFile(path.toFile(), "rw");

		this.persistentChannel = this.persistentFile.getChannel();
		this.isOpen = true;

		this.cipherTransformation = cipherTransformation;
		this.secretKeySpec = secretKeySpec;

		this.relativeFilename = fileSystemRoot.relativize(this.path)
				.toString();

		this.isReverse = isReverse;

	} catch (FileNotFoundException e) {
		throw new IOException(e.getMessage(), e);
	}
}
 
Example 4
Source File: FileSystemMapFileHashCache.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
    throws IOException {
  Path relativeFilePath = archiveRelativePath.normalize();
  JarHashCodeAndFileType fileHashCodeAndFileType =
      (JarHashCodeAndFileType) loadingCache.get(relativeFilePath);
  HashCodeAndFileType memberHashCodeAndFileType =
      fileHashCodeAndFileType.getContents().get(memberPath);
  if (memberHashCodeAndFileType == null) {
    throw new NoSuchFileException(archiveRelativePath.toString());
  }
  return memberHashCodeAndFileType.getHashCode();
}
 
Example 5
Source File: SourceParser.java    From jeka with Apache License 2.0 5 votes vote down vote up
private static JkDependencySet dependenciesFromImports(Path baseDir, List<String> deps) {
    JkDependencySet result = JkDependencySet.of();
    for (final String dependency : deps) {
        if (isModuleDependencyDescription(dependency)) {
            result = result.and(JkModuleDependency.of(dependency));
        } else  if (dependency.contains("*")) {
            if (dependency.contains("*")) {
                for (Path path : JkPathTree.of(baseDir).andMatching(true, dependency).getFiles()) {
                    result = result.andFile(path);
                }
            }
        } else {
            Path depFile = Paths.get(dependency);
            if (!Files.exists(depFile)) {
                final Path relativeFile = baseDir.resolve(dependency);
                if (Files.exists(relativeFile)) {
                    depFile = relativeFile.normalize();
                } else {
                    JkLog.warn("File '" + dependency
                            + "' mentionned in @JkDefClasspath does not exist.");
                }
            }
            result = result.andFile(depFile);
        }
    }
    return result;
}
 
Example 6
Source File: PathUtils.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to resolve the given path against the list of available roots.
 *
 * If path starts with one of the listed roots, it returned back by this method, otherwise null is returned.
 */
public static Path get(Path[] roots, String path) {
    for (Path root : roots) {
        Path normalizedRoot = root.normalize();
        Path normalizedPath = normalizedRoot.resolve(path).normalize();
        if(normalizedPath.startsWith(normalizedRoot)) {
            return normalizedPath;
        }
    }
    return null;
}
 
Example 7
Source File: SolrResourceLoader.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private Path checkPathIsSafe(Path pathToCheck) throws IOException {
  if (Boolean.getBoolean("solr.allow.unsafe.resourceloading"))
    return pathToCheck;
  pathToCheck = pathToCheck.normalize();
  if (pathToCheck.startsWith(instanceDir))
    return pathToCheck;
  throw new IOException("File " + pathToCheck + " is outside resource loader dir " + instanceDir +
      "; set -Dsolr.allow.unsafe.resourceloading=true to allow unsafe loading");
}
 
Example 8
Source File: WorkspaceGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a reference to a project file to the generated workspace.
 *
 * @param path Path to the referenced project file in the repository.
 */
public void addFilePath(Path path) {
  path = path.normalize();

  Optional<Path> groupPath = Optional.empty();
  // We skip the last name before the file name as it's usually the same as the project name, and
  // adding a group would add an unnecessary level of nesting. We don't check whether it's the
  // same or not to avoid inconsistent behaviour: this will result in all projects to show up in a
  // group with the path of their grandparent directory in all cases.
  if (path.getNameCount() > 2) {
    groupPath = Optional.of(path.subpath(0, path.getNameCount() - 2));
  }
  addFilePath(path, groupPath);
}
 
Example 9
Source File: PathUtils.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to resolve the given path against the list of available roots.
 * <p>
 * If path starts with one of the listed roots, it returned back by this method, otherwise null is returned.
 */
public static Path get(Path[] roots, String path) {
    for (Path root : roots) {
        Path normalizedRoot = root.normalize();
        Path normalizedPath = normalizedRoot.resolve(path).normalize();
        if (normalizedPath.startsWith(normalizedRoot)) {
            return normalizedPath;
        }
    }
    return null;
}
 
Example 10
Source File: JarUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Map a file path to the equivalent name in a JAR file
 */
private static String toJarEntryName(Path file) {
    Path normalized = file.normalize();
    return normalized.subpath(0, normalized.getNameCount())  // drop root
            .toString()
            .replace(File.separatorChar, '/');
}
 
Example 11
Source File: LimitedFileHashCacheEngine.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
    throws IOException {
  Path relativeFilePath = archiveRelativePath.normalize();
  Preconditions.checkState(
      isArchive(relativeFilePath), "%s is not an archive.", relativeFilePath);
  Data data = fileSystemMap.get(relativeFilePath);
  HashCode hashCode = data.getJarContentsHashes().get(memberPath);
  if (hashCode == null) {
    throw new NoSuchFileException(archiveRelativePath.toString());
  }
  return hashCode;
}
 
Example 12
Source File: IntellijPath.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private IntellijPath(Path delegate) {
  /*
   * OpenJDK 7 on Linux has a bug which causes normalize() to throw an
   * ArrayIndexOutOfBoundsException if called on the empty path.
   */
  this.delegate = delegate.equals(Paths.get("")) ? delegate : delegate.normalize();
}
 
Example 13
Source File: MorePaths.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Get a path without unnecessary path parts.
 *
 * <p>This method is a workaround for JDK-8037945 (Paths.get("").normalize() throws
 * ArrayIndexOutOfBoundsException).
 */
public static Path normalize(Path path) {
  if (!isEmpty(path)) {
    path = path.normalize();
  }
  return path;
}
 
Example 14
Source File: FileRepositoryService.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Path rootNormalizedPath()
{
	Path rootPath = rootNormalizedPath;
	if (rootPath == null)
	{
		Path path = Paths.get(root);
		rootPath = rootNormalizedPath = path.normalize();
	}
	return rootPath;
}
 
Example 15
Source File: ZipUtils.java    From Strata with 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 16
Source File: PathManualTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
    Path p = Paths.get("/home/./baeldung/articles");
    p = p.normalize();
    assertEquals("\\home\\baeldung\\articles", p.toString());
}
 
Example 17
Source File: CheckoutPath.java    From copybara with Apache License 2.0 4 votes vote down vote up
static CheckoutPath createWithCheckoutDir(Path relative, Path checkoutDir) throws EvalException {
  if (relative.isAbsolute()) {
    throw Starlark.errorf("Absolute paths are not allowed: %s", relative);
  }
  return new CheckoutPath(relative.normalize(), checkoutDir);
}
 
Example 18
Source File: MavenConfig.java    From galleon with Apache License 2.0 4 votes vote down vote up
public void setLocalRepository(Path path) throws XMLStreamException, IOException {
    localRepository = path.normalize();
    advertise();
}
 
Example 19
Source File: PathResource.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Create a new PathResource from a Path handle.
 * <p>Note: Unlike {@link FileSystemResource}, when building relative resources
 * via {@link #createRelative}, the relative path will be built <i>underneath</i>
 * the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" -> "C:/dir1/dir2"!
 * @param path a Path handle
 */
public PathResource(Path path) {
	Assert.notNull(path, "Path must not be null");
	this.path = path.normalize();
}
 
Example 20
Source File: PathResource.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Create a new PathResource from a Path handle.
 * <p>Note: Unlike {@link FileSystemResource}, when building relative resources
 * via {@link #createRelative}, the relative path will be built <i>underneath</i>
 * the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" -> "C:/dir1/dir2"!
 * @param path a Path handle
 */
public PathResource(Path path) {
	Assert.notNull(path, "Path must not be null");
	this.path = path.normalize();
}