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:fr.duminy.jbackup.core.archive.FileCollector.java

private long collect(final List<SourceWithPath> collectedFiles, final Path source,
        final IOFileFilter directoryFilter, final IOFileFilter fileFilter, final Cancellable cancellable)
        throws IOException {
    final long[] totalSize = { 0L };

    SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override//from  w  w w.java 2 s. c o m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            super.preVisitDirectory(dir, attrs);
            if ((directoryFilter == null) || source.equals(dir) || directoryFilter.accept(dir.toFile())) {
                return CONTINUE;
            } else {
                return SKIP_SUBTREE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if ((cancellable != null) && cancellable.isCancelled()) {
                return TERMINATE;
            }

            super.visitFile(file, attrs);

            if (!Files.isSymbolicLink(file)) {
                if ((fileFilter == null) || fileFilter.accept(file.toFile())) {
                    LOG.trace("visitFile {}", file.toAbsolutePath());
                    collectedFiles.add(new SourceWithPath(source, file));
                    totalSize[0] += Files.size(file);
                }
            }

            return CONTINUE;
        }
    };
    Files.walkFileTree(source, visitor);

    return totalSize[0];
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testCreateSymlinks() throws IOException, URISyntaxException {
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

    Path newDir = rootPath.resolve("newDir");
    Assert.assertFalse(Files.isSymbolicLink(newDir));

    Path innerDir = newDir.resolve("innerDir");
    Assert.assertFalse(Files.isSymbolicLink(innerDir));

    Path newSymlink = rootPath.resolve("newSymlink");
    Assert.assertTrue(Files.isSymbolicLink(newSymlink));

    Path innerSymlink = newSymlink.resolve("innerSymlink");
    Assert.assertTrue(Files.isSymbolicLink(innerSymlink));

    Path f = innerSymlink.getRoot();
    for (int i = 0; i < innerSymlink.getNameCount(); i++) {
        f = f.resolve(innerSymlink.getName(i).toString());
        System.out.println(f + " " + Files.isSymbolicLink(f));
    }//from w  ww .  j ava  2 s .  c o  m
    f = f.resolve(".");
    System.out.println(f + " " + Files.isSymbolicLink(f));
}

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

/**
 * Creates a filesystem blob with the given information.
 * <p>//from  w  w  w  .  ja v a  2 s .  c  o m
 * 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:org.codice.ddf.configuration.migration.ImportMigrationExternalEntryImpl.java

/**
 * Verifies the corresponding existing file or directory to see if it matches the original one
 * based on the exported info./*from   ww  w .ja  v  a2 s  .co  m*/
 *
 * @param required <code>true</code> if the file or directory was required to be exported; <code>
 * false</code> if it was optional
 * @return <code>false</code> if an error was detected during verification; <code>true</code>
 *     otherwise
 */
@SuppressWarnings("squid:S3725" /* Files.isRegularFile() is used for consistency and to make sure that softlinks are not followed. not worried about performance here */)
private boolean verifyRealFileOrDirectory(boolean required) {
    return AccessUtils.doPrivileged(() -> {
        final MigrationReport report = getReport();
        final Path apath = getAbsolutePath();
        final File file = getFile();

        if (!file.exists()) {
            if (required) {
                report.record(new MigrationException(Messages.IMPORT_PATH_ERROR, apath, "does not exist"));
                return false;
            }
            return true;
        }
        if (softlink) {
            if (!Files.isSymbolicLink(apath)) {
                report.record(
                        new MigrationWarning(Messages.IMPORT_PATH_WARNING, apath, "is not a symbolic link"));
                return false;
            }
        } else if (isFile() && !Files.isRegularFile(apath, LinkOption.NOFOLLOW_LINKS)) {
            report.record(new MigrationWarning(Messages.IMPORT_PATH_WARNING, apath, "is not a regular file"));
        } else if (isDirectory() && !Files.isDirectory(apath, LinkOption.NOFOLLOW_LINKS)) {
            report.record(
                    new MigrationWarning(Messages.IMPORT_PATH_WARNING, apath, "is not a regular directory"));
        }
        return verifyChecksum();
    });
}

From source file:ch.cyberduck.core.Local.java

/**
 * Checks whether a given file is a symbolic link.
 *
 * @return true if the file is a symbolic link.
 *///from  w w w.j a  v a2  s .  c o  m
public boolean isSymbolicLink() {
    return Files.isSymbolicLink(Paths.get(path));
}

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);/*  www.  j a  va2s  . c  om*/
        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:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public final File archiveFile(File file) throws QueueFileException {
    switch (getFileStatus(file)) {
    case NON_EXISTENT:
        throw new QueueFileException("File or symlink " + file + " no longer exists");
    case CAPTURED_FILE:
    case CAPTURED_SYMLINK:
        break;//from  w  w  w  .ja v a 2 s  .  co  m
    case BROKEN_CAPTURED_SYMLINK:
        throw new QueueFileException("Symlink target for " + file + " no longer exists");
    default:
        throw new QueueFileException("File or symlink " + file + " is not in the queue");
    }

    File dest = new File(archiveDirectory, file.getName());
    if (dest.exists()) {
        throw new QueueFileException("Archived file " + dest + " already exists");
    }

    if (Files.isSymbolicLink(file.toPath())) {
        dest = copyFile(file, dest, "archive");
        try {
            Files.delete(file.toPath());
        } catch (IOException ex) {
            throw new QueueFileException("Could not remove symlink " + file);
        }
    } else {
        if (!file.renameTo(dest)) {
            throw new QueueFileException("File " + file + " could not be renamed to " + dest);
        }
    }
    log.info("File " + file + " archived as " + dest);
    return dest;
}

From source file:org.codice.ddf.migration.util.MigratableUtilTest.java

@Test
public void copyFileSourceHasSymbolicLink() throws IOException {
    when(Files.isSymbolicLink(VALID_SOURCE_FILE)).thenReturn(true);

    MigratableUtil migratableUtil = new MigratableUtil();
    migratableUtil.copyFile(VALID_SOURCE_FILE, VALID_DESTINATION_PATH, warnings);

    assertWarnings("contains a symbolic link");
}

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiver.java

private static boolean isSymbolicLink(File file) {
    return Files.isSymbolicLink(file.toPath());
}

From source file:desktopsearch.WatchDir.java

private void UpdateDB(String Event, Path FullLocation) throws SQLException, IOException {

    File file = new File(FullLocation.toString());
    String path = file.getParent();
    String Name = file.getName();

    if (Name.contains("'")) {
        Name = Name.replace("'", "''");
    }/*  ww w.  j a  v  a 2 s. c  om*/
    if (path.contains("'")) {
        path = path.replace("'", "''");
    }

    if (Event.equals("ENTRY_CREATE") && file.exists()) {
        FileTime LastModifiedTime = Files.getLastModifiedTime(FullLocation);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(LastModifiedTime.toMillis());
        String Query;
        if (file.isFile()) {
            String Type = FilenameUtils.getExtension(FullLocation.toString());
            if (Type.endsWith("~") || Type.equals("")) {
                Type = "Text";
            }
            Query = "INSERT INTO FileInfo VALUES('" + path + "','" + Name + "','" + Type + "','"
                    + calendar.getTime() + "'," + (file.length() / 1024) + ");";
        } else if (!Files.isSymbolicLink(FullLocation)) {
            long size = FileUtils.sizeOfDirectory(file);
            Query = "INSERT INTO FileInfo VALUES('" + path + "','" + Name + "','FOLDER','" + calendar.getTime()
                    + "'," + size + ");";
        } else {
            Query = "INSERT INTO FileInfo VALUES('" + path + "','" + Name + "','LINK','" + calendar.getTime()
                    + "',0);";
        }
        statement.executeUpdate(Query);

    } else if (Event.equals("ENTRY_MODIFY")) {
        System.out.println(path + "/" + Name);
        FileTime LastModifiedTime = Files.getLastModifiedTime(FullLocation);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(LastModifiedTime.toMillis());
        String Query = "UPDATE FileInfo SET LastModified='" + calendar.getTime() + "' WHERE FileLocation='"
                + path + "' and FileName='" + Name + "';";
        System.out.println(Query);
        statement.executeUpdate(Query);

    } else if (Event.equals("ENTRY_DELETE")) {

        String Query = "DELETE FROM FileInfo WHERE FileLocation = '" + path + "' AND FileName = '" + Name
                + "';";
        statement.executeUpdate(Query);

    }
    connection.commit();

}