Example usage for java.nio.file Files readSymbolicLink

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

Introduction

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

Prototype

public static Path readSymbolicLink(Path link) throws IOException 

Source Link

Document

Reads the target of a symbolic link (optional operation).

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {

    Path file = Paths.get("/opt/platform/java");
    if (Files.isSymbolicLink(file)) {
        file = Files.readSymbolicLink(file);
    }/*from ww  w. j  a va 2  s . c  o m*/
    Files.readAttributes(file, BasicFileAttributes.class);

}

From source file:org.moe.cli.utils.NatJFileUtils.java

/**
 * Copies directory keeping symbolic links working
 * @param srcDir/*  w ww . j av a  2  s .c  o  m*/
 * @param destDir
 * @throws IOException 
 */
public static void copyDirectoryWithSymbolicLinks(@NonNull File srcDir, @NonNull File destDir)
        throws IOException {
    if (!srcDir.isDirectory())
        throw new IOException("Invalid framework file: " + srcDir + " is not a directory!");

    File[] frameworkFiles = srcDir.listFiles();
    for (File file : frameworkFiles) {
        try {
            boolean isSymlink = FileUtils.isSymlink(file);
            if (isSymlink) {
                Path target = Files.readSymbolicLink(file.toPath());
                File newLink = new File(destDir, file.getName());
                Files.createSymbolicLink(newLink.toPath(), target);
            } else {
                if (file.isDirectory()) {
                    File nextDestDir = new File(destDir, file.getName());
                    copyDirectoryWithSymbolicLinks(file, nextDestDir);
                } else {
                    FileUtils.copyFileToDirectory(file, destDir);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.google.jenkins.plugins.persistentmaster.volume.zip.ZipCreator.java

private void copySymlink(Path file, String filenameInZip) throws IOException {
    logger.finer("Adding symlink: " + file + " with filename: " + filenameInZip);
    Path symlinkTarget = Files.readSymbolicLink(file);
    // Unfortunately, there is no API method to create a symlink in a ZIP file,
    // however, a symlink entry can easily be created by hand.
    // The requirements for a symlink entry are:
    //  - the unix mode must have the LINK_FLAG set
    //  - the content must contain the target of the symlink as UTF8 string
    ZipArchiveEntry entry = new ZipArchiveEntry(filenameInZip);
    entry.setUnixMode(entry.getUnixMode() | UnixStat.LINK_FLAG);
    zipStream.putArchiveEntry(entry);//from ww w .  j  a v  a2 s . c o  m
    zipStream.write(symlinkTarget.toString().getBytes(StandardCharsets.UTF_8));
    zipStream.closeArchiveEntry();
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

/**
 * @see WorkspaceFileHandler#moveFile(java.io.File, java.io.File)
 *///from   w ww  .  j a  v  a2s .c o m
@Override
public void moveFile(File originNodeFile, File targetNodeFile) throws IOException {
    //file was probably not uploaded via lamus. Move target file if symbolic link
    if (Files.isSymbolicLink(originNodeFile.toPath())) {
        File originLinkToNodeFile = originNodeFile;
        originNodeFile = Files.readSymbolicLink(originNodeFile.toPath()).toFile();
        moveOrCopyFile(originNodeFile, targetNodeFile);
        Files.delete(originLinkToNodeFile.toPath());
    } else {
        moveOrCopyFile(originNodeFile, targetNodeFile);
    }
}

From source file:VOBackupFile.java

/**
 * Wrapper for metadata of backuped file.
 *
 * @param file backuped file//from   ww  w. j a  v a2  s .  c  o m
 */
public VOBackupFile(File file) {
    this.path = file.getAbsolutePath();
    this.directory = file.isDirectory();
    this.symLink = Files.isSymbolicLink(file.toPath());

    this.size = ((file.isDirectory() || symLink) ? 0 : file.length());
    this.modify = new Date(file.lastModified());

    if (symLink) {
        try {
            symlinkTarget = Files.readSymbolicLink(file.toPath()).toString();
        } catch (IOException e) {
            e.printStackTrace(); //TODO Lebeda - oetit do logu
        }
    } else {
        // advanced attributes

        try {

            owner = Files.getOwner(file.toPath(), LinkOption.NOFOLLOW_LINKS).getName();

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class)) {
                dosAttr = Boolean.TRUE;
                final DosFileAttributes dosFileAttributes = Files.readAttributes(file.toPath(),
                        DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);

                dosArchive = dosFileAttributes.isArchive();
                dosHidden = dosFileAttributes.isHidden();
                dosSystem = dosFileAttributes.isSystem();
                dosReadOnly = dosFileAttributes.isReadOnly();
            } else {
                dosAttr = Boolean.FALSE;
            }

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)) {
                posixAttr = Boolean.TRUE;
                final PosixFileAttributes posixFileAttributes = Files.readAttributes(file.toPath(),
                        PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
                posixGroup = posixFileAttributes.group().getName();
                posixPermitions = PosixFilePermissions.toString(posixFileAttributes.permissions());
            } else {
                posixAttr = Boolean.FALSE;
            }

        } catch (IOException e) {
            e.printStackTrace(); //Todo implementovat
        }
    }

}

From source file:org.nuxeo.ecm.core.blob.FilesystemBlobProvider.java

/**
 * Creates a filesystem blob with the given information.
 * <p>/*from w w  w .  j a  v  a 2 s.c om*/
 * The passed {@link BlobInfo} contains information about the blob, and the key is a file path.
 *
 * @param blobInfo the blob info where the key is a file path
 * @return the blob
 */
public ManagedBlob createBlob(BlobInfo blobInfo) throws IOException {
    String filePath = blobInfo.key;
    if (filePath.contains("..")) {
        throw new FileNotFoundException("Illegal path: " + filePath);
    }
    if (!filePath.startsWith(root)) {
        throw new FileNotFoundException("Path is not under configured root: " + filePath);
    }
    Path path = Paths.get(filePath);
    if (!Files.exists(path)) {
        throw new FileNotFoundException(filePath);
    }
    // dereference links
    while (Files.isSymbolicLink(path)) {
        // dereference if link
        path = Files.readSymbolicLink(path);
        if (!Files.exists(path)) {
            throw new FileNotFoundException(filePath);
        }
    }
    String relativePath = filePath.substring(root.length());
    long length = Files.size(path);
    blobInfo = new BlobInfo(blobInfo); // copy
    blobInfo.key = blobProviderId + ":" + relativePath;
    blobInfo.length = Long.valueOf(length);
    if (blobInfo.filename == null) {
        blobInfo.filename = Paths.get(filePath).getFileName().toString();
    }
    if (blobInfo.digest == null) {
        try (InputStream in = Files.newInputStream(path)) {
            blobInfo.digest = DigestUtils.md5Hex(in);
        }
    }
    return new SimpleManagedBlob(blobInfo);
}

From source file:com.facebook.buck.zip.UnzipTest.java

@Test
public void testExtractSymlink() throws 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) MoreFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);// w  ww  .  jav a2s . co m
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.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:ch.cyberduck.core.Local.java

public Local getSymlinkTarget() throws NotfoundException, LocalAccessDeniedException {
    try {//w  ww .  jav  a  2  s . c  o m
        // For a link that actually points to something (either a file or a directory),
        // the absolute path is the path through the link, whereas the canonical path
        // is the path the link references.
        return LocalFactory.get(Files.readSymbolicLink(Paths.get(path)).toAbsolutePath().toString());
    } catch (InvalidPathException | IOException e) {
        throw new LocalNotfoundException(String.format("Resolving symlink target for %s failed", path), e);
    }
}

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

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user.//ww  w.  ja v  a 2s .c  o  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:org.eclipse.tycho.plugins.tar.TarGzArchiver.java

private Path getRelativeSymLinkTarget(File source, File baseDir) throws IOException {
    Path sourcePath = source.toPath();
    Path linkTarget = Files.readSymbolicLink(sourcePath);
    // link target may be relative, so we resolve it first
    Path resolvedLinkTarget = sourcePath.getParent().resolve(linkTarget);
    Path relative = baseDir.toPath().relativize(resolvedLinkTarget);
    Path normalizedSymLinkPath = relative.normalize();
    log.debug("Computed symlink target path " + slashify(normalizedSymLinkPath) + " for symlink " + source
            + " relative to " + baseDir);
    return normalizedSymLinkPath;
}