Example usage for java.nio.file Files isSymbolicLink

List of usage examples for java.nio.file Files isSymbolicLink

Introduction

In this page you can find the example usage for java.nio.file Files isSymbolicLink.

Prototype

public static boolean isSymbolicLink(Path path) 

Source Link

Document

Tests whether a file is a symbolic link.

Usage

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user./*from  www. j a v  a  2 s  .co m*/
 * @param file {@link Path} to test.
 * @param user {@link UserPrincipal} to test. If {@code null}, defaults to
 * current user.
 * @param symlinkDepth Number of symbolic links allowed.
 * @return {@code true} if file's directory is secure.
 */
public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) {
    if (!file.isAbsolute()) {
        file = file.toAbsolutePath();
    }
    if (symlinkDepth <= 0) {
        // Too many levels of symbolic links
        return false;
    }
    // Get UserPrincipal for specified user and superuser
    final Path fileRoot = file.getRoot();
    if (fileRoot == null) {
        return false;
    }
    final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem();
    final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService();
    UserPrincipal root = null;
    try {
        if (SystemUtils.IS_OS_UNIX) {
            root = upls.lookupPrincipalByName("root");
        } else {
            root = upls.lookupPrincipalByName("Administrators");
        }
        if (user == null) {
            user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        }
        if (root == null || user == null) {
            return false;
        }
    } catch (final IOException x) {
        return false;
    }
    // If any parent dirs (from root on down) are not secure, dir is not secure
    for (int i = 1; i <= file.getNameCount(); i++) {
        final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString());
        try {
            if (Files.isSymbolicLink(partialPath)) {
                if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) {
                    // Symbolic link, linked-to dir not secure
                    return false;
                }
            } else {
                final UserPrincipal owner = Files.getOwner(partialPath);
                if (!user.equals(owner) && !root.equals(owner)) {
                    // dir owned by someone else, not secure
                    return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath);
                }
            }
        } catch (final IOException x) {
            return false;
        }
    }
    return true;
}

From source file:com.spotify.scio.util.RemoteFileUtil.java

private Path downloadImpl(URI src) {
    try {/*from  w ww.  ja  va 2  s  . com*/
        Path dst = getDestination(src);

        if (src.getScheme() == null || src.getScheme().equals("file")) {
            // Local URI
            Path srcPath = src.getScheme() == null ? Paths.get(src.toString()) : Paths.get(src);
            if (Files.isSymbolicLink(dst) && Files.readSymbolicLink(dst).equals(srcPath)) {
                LOG.info("URI {} already symlink-ed", src);
            } else {
                Files.createSymbolicLink(dst, srcPath);
                LOG.info("Symlink-ed {} to {}", src, dst);
            }
        } else {
            // Remote URI
            long srcSize = getRemoteSize(src);
            boolean shouldDownload = true;
            if (Files.exists(dst)) {
                long dstSize = Files.size(dst);
                if (srcSize == dstSize) {
                    LOG.info("URI {} already downloaded", src);
                    shouldDownload = false;
                } else {
                    LOG.warn("Destination exists with wrong size. {} [{}B] -> {} [{}B]", src, srcSize, dst,
                            dstSize);
                    Files.delete(dst);
                }
            }
            if (shouldDownload) {
                copyToLocal(src, dst);
                LOG.info("Downloaded {} -> {} [{}B]", src, dst, srcSize);
            }
        }

        return dst;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.facebook.buck.util.unarchive.UntarTest.java

/**
 * Assert that a symlink exists inside of the temp directory with given contents and that links to
 * the right file/*from w ww. ja  va  2  s.  c om*/
 */
private void assertOutputSymlinkExists(Path symlinkPath, Path expectedLinkedToPath, String expectedContents)
        throws IOException {
    Path fullPath = tmpFolder.getRoot().resolve(symlinkPath);
    if (Platform.detect() != Platform.WINDOWS) {
        Assert.assertTrue(String.format("Expected %s to be a symlink", fullPath),
                Files.isSymbolicLink(fullPath));
        Path linkedToPath = Files.readSymbolicLink(fullPath);
        Assert.assertEquals(String.format("Expected symlink at %s to point to %s, not %s", symlinkPath,
                expectedLinkedToPath, linkedToPath), expectedLinkedToPath, linkedToPath);
    }

    Path realExpectedLinkedToPath = filesystem.getRootPath()
            .resolve(symlinkPath.getParent().resolve(expectedLinkedToPath).normalize());
    Assert.assertTrue(
            String.format("Expected link %s to be the same file as %s", fullPath, realExpectedLinkedToPath),
            Files.isSameFile(fullPath, realExpectedLinkedToPath));

    String contents = Joiner.on('\n').join(Files.readAllLines(fullPath));
    Assert.assertEquals(expectedContents, contents);
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractSymlink() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);/*w  w  w  .j a  v  a2 s.c o m*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:com.github.blindpirate.gogradle.common.GoSourceCodeFilter.java

@Override
protected boolean acceptDir(File dir) {
    if (Files.isSymbolicLink(dir.toPath())) {
        return false;
    }/*w w w  . j  a  v a 2  s  .  co  m*/
    if (fileNameStartsWithDotOrUnderline(dir)) {
        return false;
    }
    if (fileNameEqualsAny(dir, TESTDATA_DIRECTORY)) {
        return false;
    }
    return dirPredicate.test(dir);
}

From source file:uk.co.unclealex.executable.impl.MakeLinksCommandRunnerTest.java

protected void checkDirectoriesEqual(Path expectedDir, Path actualDir) throws IOException {
    Assert.assertTrue("Path " + expectedDir + "is not a directory.",
            Files.isDirectory(expectedDir, LinkOption.NOFOLLOW_LINKS));
    Assert.assertTrue("Path " + actualDir + "is not a directory.",
            Files.isDirectory(actualDir, LinkOption.NOFOLLOW_LINKS));
    Assert.assertArrayEquals("Directory " + actualDir + " has the wrong file entries.",
            filenamesIn(expectedDir), filenamesIn(actualDir));
    DirectoryStream<Path> directoryStream = Files.newDirectoryStream(actualDir);
    for (Path expectedChild : directoryStream) {
        Path actualChild = expectedDir.resolve(expectedChild.getFileName());
        if (Files.isDirectory(expectedChild, LinkOption.NOFOLLOW_LINKS)) {
            Assert.assertTrue("Path " + actualChild + " is not a directory.",
                    Files.isDirectory(actualChild, LinkOption.NOFOLLOW_LINKS));
            checkDirectoriesEqual(expectedChild, actualChild);
        } else if (Files.isSymbolicLink(expectedChild)) {
            Assert.assertTrue("Path " + actualChild + " is not a symbolic link",
                    Files.isSymbolicLink(actualChild));
            Assert.assertEquals("Symbolic link " + actualChild + " points to the wrong place.",
                    Files.readSymbolicLink(expectedChild), Files.readSymbolicLink(actualChild));
        } else {/*  www . java  2s  .c  o  m*/
            Assert.assertTrue("Path " + actualChild + " has the wrong content.",
                    FileUtils.contentEquals(expectedChild.toFile(), actualChild.toFile()));
        }
    }
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Recursively scan the specified file/directory, collecting the SHA1 sums
 * //from w w w.j a v a 2  s  .  c o m
 * @param file
 */
private void recursiveScan(File file) {
    // Do one of the scan plugins tell us to ignore this folder?
    // This will usually be done if we are going to identify the
    // dependencies from a dependency file.
    if (exportDependencies) {
        for (IScanPlugin plugin : plugins) {
            if (plugin.ignore(file))
                return;
        }
    }

    if (file.isFile()) {
        // Progress information
        System.out.println(file);
        System.out.flush();

        // Run through each scan plugin
        for (IScanPlugin plugin : plugins) {
            plugin.run(file);
        }
    } else {
        // Recursively do for all sub-folders and files.
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                if (!Files.isSymbolicLink(child.toPath())) {
                    recursiveScan(child);
                }
            }
        }
    }
}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public FileStatus getFileStatus(File file) {
    Path path = file.toPath();/*from w  w  w . j  a  v  a2 s .  c o m*/
    File parent = path.getParent().toFile();
    if (Files.exists(path)) {
        if (parent.equals(captureDirectory)) {
            if (Files.isSymbolicLink(path)) {
                return FileStatus.CAPTURED_SYMLINK;
            } else {
                return FileStatus.CAPTURED_FILE;
            }
        } else if (parent.equals(archiveDirectory)) {
            if (Files.isSymbolicLink(path)) {
                return FileStatus.ARCHIVED_SYMLINK;
            } else {
                return FileStatus.ARCHIVED_FILE;
            }
        } else {
            return FileStatus.NOT_OURS;
        }
    } else {
        if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            if (parent.equals(captureDirectory)) {
                return FileStatus.BROKEN_CAPTURED_SYMLINK;
            } else if (parent.equals(archiveDirectory)) {
                return FileStatus.BROKEN_ARCHIVED_SYMLINK;
            } else {
                return FileStatus.NOT_OURS;
            }
        } else {
            return FileStatus.NON_EXISTENT;
        }
    }
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToTarGz(TarArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tOut.putArchiveEntry(tarEntry);//w  ww .j  ava 2 s  .  com
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToTarGz(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
        tarEntry.setLinkName(Files.readSymbolicLink(f).toString());
        tOut.putArchiveEntry(tarEntry);
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tarEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin/"))) {
            if (entryName.endsWith(".bat")) {
                tarEntry.setMode(0644);
            } else {
                tarEntry.setMode(0755);
            }
        }
        tOut.putArchiveEntry(tarEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

public boolean copyFile(final File source, final File target, final CopyModeType copyMode)
        throws MojoExecutionException {
    boolean fileChange = false;
    if (CopyModeType.FILE.equals(copyMode)) {
        if (target.exists() && Files.isSymbolicLink(target.toPath())) {
            target.delete();/*from  ww w . jav  a  2s . co m*/
        }
        fileChange = overCopyFile(source, target);
    } else {
        try {
            if (target.exists()) {
                Path targetPath = target.toPath();

                if (Files.isSymbolicLink(targetPath)) {

                    Path symbolicLinkTarget = Files.readSymbolicLink(targetPath);
                    File symbolicLinkTargetFile = symbolicLinkTarget.toFile();
                    if (!symbolicLinkTargetFile.equals(source)) {
                        target.delete();
                        createSymbolicLink(target, source);
                        fileChange = true;
                    }
                } else {
                    target.delete();
                    createSymbolicLink(target, source);
                    fileChange = true;
                }
            } else {
                createSymbolicLink(target, source);
                fileChange = true;
            }
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Could not check the target of the symbolic link " + target.getAbsolutePath(), e);
        }
    }
    return fileChange;
}