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

The following examples show how to use java.nio.file.Files#isSymbolicLink() . 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: netbeans   File: FileStatusCache.java    License: 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 Project: lucene-solr   File: CatStream.java    License: 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
/**
 * 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 4
Source Project: lucene-solr   File: FileUtils.java    License: 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 5
Source Project: bazel-buildfarm   File: UploadManifest.java    License: 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 6
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 7
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
private boolean isPathValid (Path path)
{
	if (Files.notExists(path))
		return false ;
	if (Files.isSymbolicLink(path))
		return false ;
	return true ;
}
 
Example 9
Source Project: synopsys-detect   File: DetectorFinder.java    License: 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 Project: SubServers-2   File: InternalSubCreator.java    License: 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 11
Source Project: chipster   File: SADLReplacements.java    License: 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 12
/**
 * 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 13
Source Project: vi   File: ProcOpenFile.java    License: 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 14
Source Project: tutorials   File: SymLinkExample.java    License: 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 15
private static boolean isFileSystemSymbolicLink(IResource resource) {
    URI uri = resource.getLocationURI();
    return (uri == null ? false : Files.isSymbolicLink(Paths.get(uri)));
}
 
Example 16
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
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 Project: baratine   File: FilePath.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean isLinkImpl()
{
  return Files.isSymbolicLink(getFile().toPath());
}
 
Example 19
Source Project: mirror   File: NativeFileAccess.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSymlink(Path relativePath) {
  return Files.isSymbolicLink(resolve(relativePath));
}
 
Example 20
Source Project: cyberduck   File: Local.java    License: 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));
}