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

The following are Jave code examples for showing how to use isSymbolicLink() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: bazel-tools   File: Main.java   Source Code and License Vote up 6 votes
private static void describeFile(
    final Path workspaceDirectory, final Path path, final PrintWriter out) {
  final Path relativeFileName = workspaceDirectory.relativize(path);
  if (Files.isDirectory(path)) {
    // Do nothing
  } else if (Files.isSymbolicLink(path)) {
    out.printf("link\t%s\t%s\t%s\n", Strings.repeat("-", 32), relativeFileName, readLink(path));
  } else if (Files.isRegularFile(path)) {
    final HashCode sha256;

    try {
      sha256 = PathUtils.sha256(path);
    } catch (IOException e) {
      throw new UncheckedIOException("Could not compute sha256 of " + path, e);
    }

    out.printf("file\t%s\t%s\n", sha256, relativeFileName);
  } else {
    throw new IllegalStateException("Path " + path + " is an unsupported type");
  }
}
 
Example 2
Project: hadoop   File: DockerLinuxContainerRuntime.java   Source Code and License Vote up 6 votes
@VisibleForTesting
protected String validateMount(String mount,
    Map<Path, List<String>> localizedResources)
    throws ContainerExecutionException {
  for (Entry<Path, List<String>> resource : localizedResources.entrySet()) {
    if (resource.getValue().contains(mount)) {
      java.nio.file.Path path = Paths.get(resource.getKey().toString());
      if (!path.isAbsolute()) {
        throw new ContainerExecutionException("Mount must be absolute: " +
                mount);
      }
      if (Files.isSymbolicLink(path)) {
        throw new ContainerExecutionException("Mount cannot be a symlink: " +
                mount);
      }
      if (isArbitraryMount(mount)) {
        throw new ContainerExecutionException("Mount is not allowed in the white list");
      }
      return path.toString();
    }
  }
  throw new ContainerExecutionException("Mount must be a localized " +
      "resource: " + mount);
}
 
Example 3
Project: openjdk-jdk10   File: DflCache.java   Source Code and License Vote up 5 votes
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.sameTimeDiffHash((AuthTimeWithHash)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 4
Project: goobi-viewer-indexer   File: DataRepository.java   Source Code and License Vote up 5 votes
/**
 * 
 * @param dir
 * @return
 * @throws IOException
 */
public static int countFiles(Path dir) throws IOException {
    int c = 0;
    if (Files.isDirectory(dir)) {
        try (DirectoryStream<Path> files = Files.newDirectoryStream(dir)) {
            for (Path file : files) {
                if (Files.isRegularFile(file) || Files.isSymbolicLink(file)) {
                    c++;
                }
            }
        }
    }

    return c;
}
 
Example 5
Project: jdk8u-jdk   File: ExecutionEnvironment.java   Source Code and License Vote up 5 votes
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
Project: incubator-netbeans   File: FileObjSymlinkTest.java   Source Code and License Vote up 5 votes
/**
 * Recursively delete all symlinks in a directory.
 */
private void deleteSymlinks(File root) {
    for (File f : root.listFiles()) {
        if (Files.isSymbolicLink(f.toPath())) {
            f.delete();
        } else if (f.isDirectory()) {
            deleteSymlinks(f);
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: FileObjectCyclicSymlinksTest.java   Source Code and License Vote up 5 votes
/**
 * Recursively delete directory, do not throw an exception if a file cannot
 * be deleted, do not traverse symbolic links.
 */
private static void deleteFile(File file) throws IOException {
    if (file.isDirectory() && file.equals(file.getCanonicalFile())
            && !Files.isSymbolicLink(file.toPath())) {
        // file is a directory - delete sub files first
        File files[] = file.listFiles();
        for (File file1 : files) {
            deleteFile(file1);
        }
    }
    // file is a File :-)
    file.delete();
}
 
Example 8
Project: uberscriptquery   File: FileUtils.java   Source Code and License Vote up 5 votes
public static Path getSymbolicLinkTargetFile(Path path) {
    if (!Files.isSymbolicLink(path)) {
        return path;
    }

    try {
        Path targetPath = Files.readSymbolicLink(path);
        return getSymbolicLinkTargetFile(targetPath);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read symbolic link: " + path, e);
    }
}
 
Example 9
Project: cornerstone   File: ProcOpenFile.java   Source Code and License Vote up 5 votes
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 10
Project: airsonic   File: MediaFileService.java   Source Code and License Vote up 5 votes
/**
 * 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") || name.equals("Thumbs.db");
}
 
Example 11
Project: metron-field-demos   File: DemoLoader.java   Source Code and License Vote up 5 votes
public static String toFileName(String path) throws IOException {
  File f = new File(path);
  String fileName = f.getName();
  if(Files.isSymbolicLink(f.toPath())) {
    Path p = Files.readSymbolicLink(f.toPath());
    fileName = p.getFileName().toFile().getName();
  }
  return fileName;
}
 
Example 12
Project: openjdk-jdk10   File: OptimisticTypesPersistence.java   Source Code and License Vote up 5 votes
/**
 * Returns true if the specified file is a symbolic link, and also logs a warning if it is.
 * @param file the file
 * @return true if file is a symbolic link, false otherwise.
 */
private static boolean isSymbolicLink(final File file) {
    if (Files.isSymbolicLink(file.toPath())) {
        getLogger().warning("Directory " + file + " is a symlink");
        return true;
    }
    return false;
}
 
Example 13
Project: OpenJSharp   File: OptimisticTypesPersistence.java   Source Code and License Vote up 5 votes
/**
 * Returns true if the specified file is a symbolic link, and also logs a warning if it is.
 * @param file the file
 * @return true if file is a symbolic link, false otherwise.
 */
private static boolean isSymbolicLink(final File file) {
    if (Files.isSymbolicLink(file.toPath())) {
        getLogger().warning("Directory " + file + " is a symlink");
        return true;
    }
    return false;
}
 
Example 14
Project: openjdk-jdk10   File: ClassPath.java   Source Code and License Vote up 5 votes
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 15
Project: AppCoins-ethereumj   File: LevelDbDataSource.java   Source Code and License Vote up 4 votes
@Override
public void init() {
    resetDbLock.writeLock().lock();
    try {
        logger.debug("~> LevelDbDataSource.init(): " + name);

        if (isAlive()) return;

        if (name == null) throw new NullPointerException("no name set to the db");

        Options options = new Options();
        options.createIfMissing(true);
        options.compressionType(CompressionType.NONE);
        options.blockSize(10 * 1024 * 1024);
        options.writeBufferSize(10 * 1024 * 1024);
        options.cacheSize(0);
        options.paranoidChecks(true);
        options.verifyChecksums(true);
        options.maxOpenFiles(32);

        try {
            logger.debug("Opening database");
            final Path dbPath = getPath();
            if (!Files.isSymbolicLink(dbPath.getParent())) Files.createDirectories(dbPath.getParent());

            logger.debug("Initializing new or existing database: '{}'", name);
            try {
                db = factory.open(dbPath.toFile(), options);
            } catch (IOException e) {
                // database could be corrupted
                // exception in std out may look:
                // org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: 16 missing files; e.g.: /Users/stan/ethereumj/database-test/block/000026.ldb
                // org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: checksum mismatch
                if (e.getMessage().contains("Corruption:")) {
                    logger.warn("Problem initializing database.", e);
                    logger.info("LevelDB database must be corrupted. Trying to repair. Could take some time.");
                    factory.repair(dbPath.toFile(), options);
                    logger.info("Repair finished. Opening database again.");
                    db = factory.open(dbPath.toFile(), options);
                } else {
                    // must be db lock
                    // org.fusesource.leveldbjni.internal.NativeDB$DBException: IO error: lock /Users/stan/ethereumj/database-test/state/LOCK: Resource temporarily unavailable
                    throw e;
                }
            }

            alive = true;
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
            throw new RuntimeException("Can't initialize database", ioe);
        }
        logger.debug("<~ LevelDbDataSource.init(): " + name);
    } finally {
        resetDbLock.writeLock().unlock();
    }
}
 
Example 16
Project: incubator-netbeans   File: BaseFileObj.java   Source Code and License Vote up 4 votes
@Override
public boolean isSymbolicLink() throws IOException {
    Path p = getNativePath();
    return Files.isSymbolicLink(p);
}
 
Example 17
Project: incubator-netbeans   File: LocalFileSystem.java   Source Code and License Vote up 4 votes
@Override
public boolean isSymbolicLink(String name) throws IOException {
    return Files.isSymbolicLink(fs.getPath(name));
}
 
Example 18
Project: talchain   File: LevelDbDataSource.java   Source Code and License Vote up 4 votes
@Override
public void init() {
    resetDbLock.writeLock().lock();
    try {
        logger.debug("~> LevelDbDataSource.init(): " + name);

        if (isAlive()) return;

        if (name == null) throw new NullPointerException("no name set to the db");

        Options options = new Options();
        options.createIfMissing(true);
        options.compressionType(CompressionType.NONE);
        options.blockSize(10 * 1024 * 1024);
        options.writeBufferSize(10 * 1024 * 1024);
        options.cacheSize(0);
        options.paranoidChecks(true);
        options.verifyChecksums(true);
        options.maxOpenFiles(32);

        try {
            logger.debug("Opening database");
            final Path dbPath = getPath();
            if (!Files.isSymbolicLink(dbPath.getParent())) Files.createDirectories(dbPath.getParent());

            logger.debug("Initializing new or existing database: '{}'", name);
            try {
                db = factory.open(dbPath.toFile(), options);
            } catch (IOException e) {
                // database could be corrupted
                // exception in std out may look:
                // org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: 16 missing files; e.g.: /Users/stan/ethereumj/database-test/block/000026.ldb
                // org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: checksum mismatch
                if (e.getMessage().contains("Corruption:")) {
                    logger.warn("Problem initializing database.", e);
                    logger.info("LevelDB database must be corrupted. Trying to repair. Could take some time.");
                    factory.repair(dbPath.toFile(), options);
                    logger.info("Repair finished. Opening database again.");
                    db = factory.open(dbPath.toFile(), options);
                } else {
                    // must be db lock
                    // org.fusesource.leveldbjni.internal.NativeDB$DBException: IO error: lock /Users/stan/ethereumj/database-test/state/LOCK: Resource temporarily unavailable
                    throw e;
                }
            }

            alive = true;
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
            throw new RuntimeException("Can't initialize database", ioe);
        }
        logger.debug("<~ LevelDbDataSource.init(): " + name);
    } finally {
        resetDbLock.writeLock().unlock();
    }
}
 
Example 19
Project: OpenJSharp   File: DflCache.java   Source Code and License Vote up 4 votes
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 20
Project: jdk8u-jdk   File: DflCache.java   Source Code and License Vote up 4 votes
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;
}