Java Code Examples for java.nio.file.Files#readSymbolicLink()

The following examples show how to use java.nio.file.Files#readSymbolicLink() . 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: SymbolicLinkHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the target path of a symbolic link.
 *
 * @param link the path to the symbolic link
 * @return path the target path of the symbolic link
 */
public static String readSymbolicLink(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        Path pathObject = Files.readSymbolicLink(linkPath);
        if (nonNull(pathObject)) {
          return pathObject.toString();
        }
      }
    } catch (Throwable thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }

  return null;
}
 
Example 2
Source File: PathUtils.java    From bazel-tools with Apache License 2.0 6 votes vote down vote up
private static void syncSymbolicLink(
    final Path source, final Path target, final Path sourceFile, final Path targetFile)
    throws IOException {
  final Path sourceLink = Files.readSymbolicLink(sourceFile);
  final Path expectedTargetLink = equivalentSubpath(source, target, sourceLink);

  if (Files.exists(targetFile)) {
    final Path actualTargetLink = Files.readSymbolicLink(targetFile);

    if (expectedTargetLink.toRealPath().equals(actualTargetLink.toRealPath())) {
      return;
    }
  }

  Files.deleteIfExists(targetFile);
  Files.createSymbolicLink(targetFile, expectedTargetLink);
}
 
Example 3
Source File: SymbolicLinkHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the target path of a symbolic link.
 *
 * @param link the path to the symbolic link
 * @return path the target path of the symbolic link
 */
public static String readSymbolicLink(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        Path pathObject = Files.readSymbolicLink(linkPath);
        if (nonNull(pathObject)) {
          return pathObject.toString();
        }
      }
    } catch (Throwable thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }

  return null;
}
 
Example 4
Source File: MorePathsTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRelativeSymlinkToFileInRoot() throws IOException {
  ProjectFilesystem projectFilesystem =
      TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
  tmp.newFile("biz.txt");

  tmp.newFolder("alpha", "beta");
  Path pathToDesiredLinkUnderProjectRoot = Paths.get("alpha/beta/gamma.txt");
  Path pathToExistingFileUnderProjectRoot = Paths.get("biz.txt");
  Path relativePath =
      MoreProjectFilesystems.createRelativeSymlink(
          pathToDesiredLinkUnderProjectRoot,
          pathToExistingFileUnderProjectRoot,
          projectFilesystem);

  Path absolutePathToDesiredLinkUnderProjectRoot =
      projectFilesystem.resolve(pathToDesiredLinkUnderProjectRoot);
  assertTrue(Files.isSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot));

  Path targetOfSymbolicLink = Files.readSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot);

  validateSymlinklTarget(
      pathToExistingFileUnderProjectRoot,
      pathToDesiredLinkUnderProjectRoot,
      absolutePathToDesiredLinkUnderProjectRoot,
      targetOfSymbolicLink,
      relativePath);

  Path absolutePathToExistingFileUnderProjectRoot =
      projectFilesystem.resolve(pathToExistingFileUnderProjectRoot);
  Files.write(absolutePathToExistingFileUnderProjectRoot, "Hello, World!".getBytes());
  String dataReadFromSymlink =
      new String(Files.readAllBytes(absolutePathToDesiredLinkUnderProjectRoot));
  assertEquals("Hello, World!", dataReadFromSymlink);
}
 
Example 5
Source File: ExecutionEnvironment.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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 6
Source File: Generator.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private void itemizeSymlink(int index, LocatableSymlinkInfo linkInfo)
        throws IOException, ChannelException
{
    try {
        RsyncFileAttributes curAttrsOrNull = deleteIfDifferentType(linkInfo);
        if (curAttrsOrNull != null) {
            Path curTarget = Files.readSymbolicLink(linkInfo.path());
            if (curTarget.toString().equals(linkInfo.targetPathName())) {
                if (_isAlwaysItemize) {
                    sendItemizeInfo(index, curAttrsOrNull, linkInfo.attrs(),
                                    Item.NO_CHANGE);
                }
                return;
            }
            if (_log.isLoggable(Level.FINE)) {
                _log.fine(String.format(
                        "deleting symlink %s -> %s",
                        linkInfo.path(), curTarget));
            }
            FileOps.unlink(linkInfo.path());
        }
        if (_log.isLoggable(Level.FINE)) {
            _log.fine(String.format("creating symlink %s -> %s",
                                    linkInfo.path(),
                                    linkInfo.targetPathName()));
        }
        Path targetPath = linkInfo.path().getFileSystem().getPath(linkInfo.targetPathName());
        Files.createSymbolicLink(linkInfo.path(), targetPath);

        sendItemizeInfo(index,
                        null /* curAttrsOrNull */,
                        linkInfo.attrs(),
                        (char) (Item.LOCAL_CHANGE | Item.REPORT_CHANGE));
    } catch (UnsupportedOperationException e) {
        throw new IOException(e);
    }
}
 
Example 7
Source File: ExecutionEnvironment.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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 8
Source File: ExecutionEnvironment.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 9
Source File: EdenMount.java    From buck with Apache License 2.0 5 votes vote down vote up
/** @return an Eden mount point if {@code projectRoot} is backed by Eden or {@code null}. */
public static Optional<EdenMount> createEdenMountForProjectRoot(
    Path projectRoot, EdenClientPool pool) {
  Path rootSymlink = projectRoot.resolve(".eden/root");
  Path rootOfEdenMount;
  try {
    rootOfEdenMount = Files.readSymbolicLink(rootSymlink);
  } catch (IOException e) {
    return Optional.empty();
  }

  return Optional.of(new EdenMount(pool, rootOfEdenMount, projectRoot));
}
 
Example 10
Source File: MorePathsTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRelativeSymlinkToFilesInRoot() throws IOException {
  ProjectFilesystem projectFilesystem =
      TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
  tmp.newFile("biz.txt");

  Path pathToDesiredLinkUnderProjectRoot = Paths.get("gamma.txt");
  Path pathToExistingFileUnderProjectRoot = Paths.get("biz.txt");
  Path relativePath =
      MoreProjectFilesystems.createRelativeSymlink(
          pathToDesiredLinkUnderProjectRoot,
          pathToExistingFileUnderProjectRoot,
          projectFilesystem);

  Path absolutePathToDesiredLinkUnderProjectRoot =
      projectFilesystem.resolve(pathToDesiredLinkUnderProjectRoot);
  assertTrue(Files.isSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot));

  Path targetOfSymbolicLink = Files.readSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot);

  validateSymlinklTarget(
      pathToExistingFileUnderProjectRoot,
      pathToDesiredLinkUnderProjectRoot,
      absolutePathToDesiredLinkUnderProjectRoot,
      targetOfSymbolicLink,
      relativePath);

  Path absolutePathToExistingFileUnderProjectRoot =
      projectFilesystem.resolve(pathToExistingFileUnderProjectRoot);
  Files.write(absolutePathToExistingFileUnderProjectRoot, "Hello, World!".getBytes());
  String dataReadFromSymlink =
      new String(Files.readAllBytes(absolutePathToDesiredLinkUnderProjectRoot));
  assertEquals("Hello, World!", dataReadFromSymlink);
}
 
Example 11
Source File: FileUtil.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves {@code symlink} recursively until it finds a regular file or directory. It also
 * checks that all its intermediate paths jumps are under {@code matcher}.
 */
public static ResolvedSymlink resolveSymlink(PathMatcher matcher, Path symlink)
    throws IOException {
  // Normalize since matcher glob:foo/bar/file* doesn't match foo/bar/../bar/file*
  Path path = symlink.normalize();
  checkArgument(matcher.matches(path), "%s doesn't match %s", path, matcher);

  Set<Path> visited = new LinkedHashSet<>();
  while (Files.isSymbolicLink(path)) {
    visited.add(path);
    // Avoid 'dot' -> . like traps by capping to a sane limit
    if (visited.size() > 50) {
      throw new IOException("Symlink cycle detected:\n  "
          + Joiner.on("\n  ").join(Iterables.concat(visited, ImmutableList.of(symlink))));
    }
    Path newPath = Files.readSymbolicLink(path);
    if (!newPath.isAbsolute()) {
      newPath = path.resolveSibling(newPath).toAbsolutePath().normalize();
    } else {
      newPath = newPath.normalize();
    }
    if (!matcher.matches(newPath)) {
      if (!Files.isDirectory(newPath)
          // Special support for symlinks in the form of ROOT/symlink -> '.'. Technically we
          // shouldn't allow this because of our glob implementation, but this is a regression
          // from the old code and the correct behavior is difficult to understand by our users.
          || !matcher.matches(newPath.resolve("copybara_random_path.txt"))) {
        Path realPath = newPath.toRealPath();
        return new ResolvedSymlink(realPath, /*allUnderRoot=*/ false);
      }
    }
    path = newPath;
  }
  return new ResolvedSymlink(path, /*allUnderRoot=*/ true);
}
 
Example 12
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "packagesLinks")
public void testPackagesLinks(String link) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath(link);
    assertTrue(Files.exists(path), link + " missing");
    assertTrue(Files.isSymbolicLink(path), path + " is not a link");
    path = Files.readSymbolicLink(path);
    assertEquals(path.toString(), "/modules" + link.substring(link.lastIndexOf("/")));
}
 
Example 13
Source File: ClassPath.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
synchronized Path getPackagePath(String pkgName) throws IOException {
    // check the cache first
    if (pkgDirs.containsKey(pkgName)) {
        return pkgDirs.get(pkgName);
    }

    Path pkgLink = fs.getPath("/packages/" + pkgName.replace('/', '.'));
    // check if /packages/$PACKAGE directory exists
    if (Files.isDirectory(pkgLink)) {
       try (DirectoryStream<Path> stream = Files.newDirectoryStream(pkgLink)) {
            for (Path p : stream) {
                // find first symbolic link to module directory
                if (Files.isSymbolicLink(p)) {
                    Path modDir = Files.readSymbolicLink(p);
                    if (Files.isDirectory(modDir)) {
                        // get package subdirectory under /modules/$MODULE/
                        Path pkgDir = fs.getPath(modDir.toString() + "/" + pkgName);
                        if (Files.isDirectory(pkgDir)) {
                            // it is a package directory only if contains
                            // at least one .class file
                            try (DirectoryStream<Path> pstream =
                                    Files.newDirectoryStream(pkgDir)) {
                                for (Path f : pstream) {
                                    if (Files.isRegularFile(f)
                                            && f.toString().endsWith(".class")) {
                                        pkgDirs.put(pkgName, pkgDir);
                                        return pkgDir;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example 14
Source File: WatchServiceFileWatcher.java    From mirror with Apache License 2.0 5 votes vote down vote up
private void onChangedSymbolicLink(BlockingQueue<Update> queue, Path path) throws IOException {
  Path symlink = Files.readSymbolicLink(path);
  String targetPath;
  if (symlink.isAbsolute()) {
    targetPath = path.getParent().toAbsolutePath().relativize(symlink).toString();
  } else {
    // the symlink is already relative, so we can leave it alone, e.g. foo.txt
    targetPath = symlink.toString();
  }
  String relativePath = toRelativePath(path);
  log.trace("Symlink {}, relative={}, target={}", path, relativePath, targetPath);
  put(queue, Update.newBuilder().setPath(relativePath).setSymlink(targetPath).setModTime(lastModified(path)).setLocal(true).build());
}
 
Example 15
Source File: FaultyFileSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Path readSymbolicLink(Path link) throws IOException {
    Path target = Files.readSymbolicLink(unwrap(link));
    triggerEx(target, "readSymbolicLink");
    return new PassThroughFileSystem.PassThroughPath(delegate, target);
}
 
Example 16
Source File: JRTIndex.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
synchronized Entry getEntry(RelativeDirectory rd) throws IOException {
    SoftReference<Entry> ref = entries.get(rd);
    Entry e = (ref == null) ? null : ref.get();
    if (e == null) {
        Map<String, Path> files = new LinkedHashMap<>();
        Set<RelativeDirectory> subdirs = new LinkedHashSet<>();
        Path dir;
        if (rd.path.isEmpty()) {
            dir = jrtfs.getPath("/modules");
        } else {
            Path pkgs = jrtfs.getPath("/packages");
            dir = pkgs.resolve(rd.getPath().replaceAll("/$", "").replace("/", "."));
        }
        if (Files.exists(dir)) {
            try (DirectoryStream<Path> modules = Files.newDirectoryStream(dir)) {
                for (Path module: modules) {
                    if (Files.isSymbolicLink(module))
                        module = Files.readSymbolicLink(module);
                    Path p = rd.resolveAgainst(module);
                    if (!Files.exists(p))
                        continue;
                    try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {
                        for (Path entry: stream) {
                            String name = entry.getFileName().toString();
                            if (Files.isRegularFile(entry)) {
                                // TODO: consider issue of files with same name in different modules
                                files.put(name, entry);
                            } else if (Files.isDirectory(entry)) {
                                subdirs.add(new RelativeDirectory(rd, name));
                            }
                        }
                    }
                }
            }
        }
        e = new Entry(Collections.unmodifiableMap(files),
                Collections.unmodifiableSet(subdirs),
                getCtInfo(rd));
        entries.put(rd, new SoftReference<>(e));
    }
    return e;
}
 
Example 17
Source File: FaultyFileSystem.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Path readSymbolicLink(Path link) throws IOException {
    Path target = Files.readSymbolicLink(unwrap(link));
    triggerEx(target, "readSymbolicLink");
    return new PassThroughFileSystem.PassThroughPath(delegate, target);
}
 
Example 18
Source File: FaultyFileSystem.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Path readSymbolicLink(Path link) throws IOException {
    Path target = Files.readSymbolicLink(unwrap(link));
    triggerEx(target, "readSymbolicLink");
    return new PassThroughFileSystem.PassThroughPath(delegate, target);
}
 
Example 19
Source File: DefaultProjectFilesystem.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Returns the target of the specified symbolic link. */
@Override
public Path readSymLink(Path path) throws IOException {
  return Files.readSymbolicLink(getPathForRelativePath(path));
}
 
Example 20
Source File: FaultyFileSystem.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Path readSymbolicLink(Path link) throws IOException {
    Path target = Files.readSymbolicLink(unwrap(link));
    triggerEx(target, "readSymbolicLink");
    return new PassThroughFileSystem.PassThroughPath(delegate, target);
}