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

The following examples show how to use java.nio.file.Files#isSymbolicLink() . 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: FileStatusCache.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isSymlink (Path path, Path checkoutRoot) {
    boolean symlink = false;
    if (path == null) {
        return false;
    }
    if (EXCLUDE_SYMLINKS) {
        Boolean cached = symlinks.get(path);
        if (cached == null) {
            symlink = Files.isSymbolicLink(path);
            if (symlink) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.log(Level.INFO, "isSymlink(): File {0} will be treated as a symlink", path); //NOI18N
                }
            } else if (checkoutRoot != null && !path.equals(checkoutRoot)) {
                // check if under symlinked parent
                symlink = isSymlink(path.getParent(), checkoutRoot);
            }
            symlinks.put(path, symlink);
        } else {
            symlink = cached;
        }
    }
    return symlink;
}
 
Example 2
Source File: CatStream.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void findReadableFiles(CrawlFile seed, List<CrawlFile> foundFiles) {

    final Path entry = seed.absolutePath;

    // Skip over paths that don't exist or that are symbolic links
    if ((!Files.exists(entry)) || (!Files.isReadable(entry)) || Files.isSymbolicLink(entry)) {
      return;
    }

    // We already know that the path in question exists, is readable, and is in our sandbox
    if (Files.isRegularFile(entry)) {
      foundFiles.add(seed);
    } else if (Files.isDirectory(entry)) {
      try (Stream<Path> directoryContents = Files.list(entry)) {
        directoryContents.sorted().forEach(iPath -> {
          // debatable: should the separator be OS/file-system specific, or perhaps always "/" ?
          final String displayPathSeparator = iPath.getFileSystem().getSeparator();
          final String itemDisplayPath = seed.displayPath + displayPathSeparator + iPath.getFileName();
          findReadableFiles(new CrawlFile(itemDisplayPath, iPath), foundFiles);
        });
      } catch (IOException e) {
        throw new RuntimeIOException(e);
      }
    }
  }
 
Example 3
Source File: SymLinkExample.java    From tutorials with MIT License 5 votes vote down vote up
public void printLinkFiles(Path path) throws IOException {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        for (Path file : stream) {
            if (Files.isDirectory(file)) {
                printLinkFiles(file);
            } else if (Files.isSymbolicLink(file)) {
                System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file));
            }
        }
    }
}
 
Example 4
Source File: MediaFileService.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether the given file is excluded.
 *
 * @param file The child file in question.
 * @return Whether the child file is excluded.
 */
private boolean isExcluded(File file) {
    if (settingsService.getIgnoreSymLinks() && Files.isSymbolicLink(file.toPath())) {
        LOG.info("excluding symbolic link " + file.toPath());
        return true;
    }
    String name = file.getName();
    if (settingsService.getExcludePattern() != null && settingsService.getExcludePattern().matcher(name).find()) {
        LOG.info("excluding file which matches exclude pattern " + settingsService.getExcludePatternString() + ": " + file.toPath());
        return true;
    }

    // Exclude all hidden files starting with a single "." or "@eaDir" (thumbnail dir created on Synology devices).
    return (name.startsWith(".") && !name.startsWith("..")) || name.startsWith("@eaDir") || "Thumbs.db".equals(name);
}
 
Example 5
Source File: ProcOpenFile.java    From vi with Apache License 2.0 5 votes vote down vote up
public static List<ProcOpenFile> list() throws FileNotFoundException {
    final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    final int index = jvmName.indexOf('@');
    String pid = (jvmName.substring(0, index));

    List<ProcOpenFile> rtn = new ArrayList<>();

    File folder = new File("/proc/" + pid + "/fd");
    if(folder.isDirectory()){
        File[] files = folder.listFiles();
        if(files == null){
            return rtn;
        }
        for(File fd:files){
            Path path = fd.toPath();
            if(Files.isSymbolicLink(path)){
                try {
                    File real = Files.readSymbolicLink(path).toFile();
                    if(real.isFile()) {
                        ProcOpenFile of = new ProcOpenFile();
                        of.name = real.getName();
                        of.size = real.length();
                        of.path = real.getAbsolutePath();
                        rtn.add(of);
                    }
                } catch (Throwable e) {
                    logger.warn("Read link:"+path.toString()+" failed!");
                }
            }
        }
    }
    return rtn;
}
 
Example 6
Source File: PathResourceManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true is some element of path inside base path is a symlink.
 */
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException {
    int nameCount = file.getNameCount();
    Path root = Paths.get(base);
    int rootCount = root.getNameCount();
    Path f = file;
    for (int i = nameCount - 1; i>=0; i--) {
        if (Files.isSymbolicLink(f)) {
            return new SymlinkResult(i+1 > rootCount, f);
        }
        f = f.getParent();
    }

    return null;
}
 
Example 7
Source File: SADLReplacements.java    From chipster with MIT License 5 votes vote down vote up
private String getSymlinkTarget(String path, String fileExtension) throws IOException {
	Path symlink = new File(toolsBin, path).toPath();
	if (Files.isSymbolicLink(symlink)) {
		String target = Files.readSymbolicLink(symlink).getFileName().toString();
		target = StringUtils.removeEnd(target, fileExtension);
		return target;
	} else {
		throw new IOException("failed to get symlink target, not a symlink: " + path);
	}
}
 
Example 8
Source File: InternalSubCreator.java    From SubServers-2 with Apache License 2.0 5 votes vote down vote up
private void updateDirectory(File from, File to) {
    if (from.isDirectory() && !Files.isSymbolicLink(from.toPath())) {
        if (!to.exists()) {
            to.mkdirs();
        }

        String files[] = from.list();

        for (String file : files) {
            File srcFile = new File(from, file);
            File destFile = new File(to, file);

            updateDirectory(srcFile, destFile);
        }
    } else {
        try {
            if (!to.exists() || from.length() != to.length() || !Arrays.equals(generateSHA256(to), generateSHA256(from))) {
                if (to.exists()) {
                    if (to.isDirectory()) Util.deleteDirectory(to);
                    else to.delete();
                }
                Files.copy(from.toPath(), to.toPath(), LinkOption.NOFOLLOW_LINKS, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 9
Source File: DetectorFinder.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
private Optional<DetectorEvaluationTree> findDetectors(final File directory, final DetectorRuleSet detectorRuleSet, final int depth, final DetectorFinderOptions options)
    throws DetectorFinderDirectoryListException {

    if (depth > options.getMaximumDepth()) {
        logger.trace("Skipping directory as it exceeds max depth: " + directory.toString());
        return Optional.empty();
    }

    if (null == directory || Files.isSymbolicLink(directory.toPath()) || !directory.isDirectory()) {
        final String directoryString = Optional.ofNullable(directory).map(File::toString).orElse("null");
        logger.trace("Skipping file as it is not a directory: " + directoryString);
        return Optional.empty();
    }

    logger.debug("Traversing directory: " + directory.getPath()); //TODO: Finding the perfect log level here is important. At INFO, we log a lot during a deep traversal but if we don't we might look stuck.
    final List<DetectorEvaluation> evaluations = detectorRuleSet.getOrderedDetectorRules().stream()
                                                     .map(DetectorEvaluation::new)
                                                     .collect(Collectors.toList());

    final Set<DetectorEvaluationTree> children = new HashSet<>();

    final List<File> subDirectories = findFilteredSubDirectories(directory, options.getFileFilter());
    for (final File subDirectory : subDirectories) {
        final Optional<DetectorEvaluationTree> childEvaluationSet = findDetectors(subDirectory, detectorRuleSet, depth + 1, options);
        childEvaluationSet.ifPresent(children::add);
    }

    return Optional.of(new DetectorEvaluationTree(directory, depth, detectorRuleSet, evaluations, children));
}
 
Example 10
Source File: SwiftOperationsImpl.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
private boolean isPathValid (Path path)
{
	if (Files.notExists(path))
		return false ;
	if (Files.isSymbolicLink(path))
		return false ;
	return true ;
}
 
Example 11
Source File: ExecutionEnvironment.java    From jdk8u_jdk 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 12
Source File: ExecutionEnvironment.java    From hottub 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 13
Source File: UploadManifest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private void mismatchedOutput(Path what) throws IllegalStateException, IOException {
  String kind =
      Files.isSymbolicLink(what)
          ? "symbolic link"
          : Files.isDirectory(what) ? "directory" : "file";
  String expected = kind.equals("directory") ? "file" : "directory";
  throw new IllegalStateException(
      String.format(
          "Output %s is a %s. It was expected to be a %s.",
          execRoot.relativize(what), kind, expected));
}
 
Example 14
Source File: FileUtils.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Path createDirectories(Path path) throws IOException {
  if (Files.exists(path) && Files.isSymbolicLink(path)) {
    Path real = path.toRealPath();
    if (Files.isDirectory(real)) return real;
    throw new FileExistsException("Tried to create a directory at to an existing non-directory symlink: " + path.toString());
  }
  return Files.createDirectories(path);
}
 
Example 15
Source File: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean isFileSystemSymbolicLink(IResource resource) {
    URI uri = resource.getLocationURI();
    return (uri == null ? false : Files.isSymbolicLink(Paths.get(uri)));
}
 
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: DflCache.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 18
Source File: FilePath.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
private boolean isLinkImpl()
{
  return Files.isSymbolicLink(getFile().toPath());
}
 
Example 19
Source File: NativeFileAccess.java    From mirror with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSymlink(Path relativePath) {
  return Files.isSymbolicLink(resolve(relativePath));
}
 
Example 20
Source File: Local.java    From cyberduck with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Checks whether a given file is a symbolic link.
 *
 * @return true if the file is a symbolic link.
 */
public boolean isSymbolicLink() {
    return Files.isSymbolicLink(Paths.get(path));
}