Example usage for java.nio.file LinkOption NOFOLLOW_LINKS

List of usage examples for java.nio.file LinkOption NOFOLLOW_LINKS

Introduction

In this page you can find the example usage for java.nio.file LinkOption NOFOLLOW_LINKS.

Prototype

LinkOption NOFOLLOW_LINKS

To view the source code for java.nio.file LinkOption NOFOLLOW_LINKS.

Click Source Link

Document

Do not follow symbolic links.

Usage

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

/**
 * @see org.alfresco.repo.bulkimport.DirectoryAnalyser#analyseDirectory(org.alfresco.repo.bulkimport.ImportableItem, java.nio.file.DirectoryStream.Filter)
 *///from  w ww.ja v a 2s  .c  om
public AnalysedDirectory analyseDirectory(ImportableItem directory, DirectoryStream.Filter<Path> filter) {
    Path directoryFile = directory.getHeadRevision().getContentFile();
    AnalysedDirectory result = new AnalysedDirectory(listFiles(directoryFile, filter));

    if (log.isDebugEnabled()) {
        log.debug("Analysing directory " + FileUtils.getFileName(directoryFile) + "...");
    }

    // Build up the list of ImportableItems from the directory listing
    for (Path file : result.getOriginalPaths()) {
        // MNT-9763 bulkimport fails when there is a very large LastModified timestamp.
        String isoDate = null;
        try {
            isoDate = ISO8601DateFormat
                    .format(new Date(Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis()));
            ISO8601DateFormat.parse(isoDate);
        } catch (PlatformRuntimeException | IOException e) {
            log.warn("Failed to convert date " + isoDate + " to string for " + file.getFileName(), e);
            importStatus.incrementNumberOfUnreadableEntries();
            continue;
        }

        if (log.isTraceEnabled()) {
            log.trace("Scanning file " + FileUtils.getFileName(file) + "...");
        }

        if (Files.isReadable(file)) {
            try {
                nameChecker.evaluate(file.getFileName().toString());
            } catch (ConstraintException e) {
                if (log.isWarnEnabled()) {
                    log.warn("Skipping file with invalid name: '" + FileUtils.getFileName(file) + "'.");
                }
                // mark file with invalid name as unreadable
                importStatus.incrementNumberOfUnreadableEntries();

                continue;
            }

            if (isVersionFile(file)) {
                addVersionFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else if (isMetadataFile(file)) {
                addMetadataFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else {
                boolean isDirectory = addParentFile(directory, result, file);

                if (isDirectory) {
                    importStatus.incrementNumberOfFoldersScanned();
                } else {
                    importStatus.incrementNumberOfFilesScanned();
                }
            }
        } else {
            if (log.isWarnEnabled()) {
                log.warn("Skipping unreadable file '" + FileUtils.getFileName(file) + "'.");
            }

            importStatus.incrementNumberOfUnreadableEntries();
        }
    }

    // Finally, remove any items from the list that aren't valid (don't have either a
    // contentFile or a metadataFile)
    Iterator<ImportableItem> iter = result.getImportableItems().iterator();

    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid() || !isMetadataValid(importableItem)) {
            iter.remove();
        }
    }

    iter = result.getImportableDirectories().iterator();
    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid()) {
            iter.remove();
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Finished analysing directory " + FileUtils.getFileName(directoryFile) + ".");
    }

    return result;
}

From source file:io.hops.hopsworks.common.security.CertificatesMgmService.java

@PostConstruct
public void init() {
    masterPasswordFile = new File(settings.getHopsworksMasterEncPasswordFile());
    if (!masterPasswordFile.exists()) {
        throw new IllegalStateException("Master encryption file does not exist");
    }//from w ww . j a va 2s .co  m

    try {
        PosixFileAttributeView fileView = Files.getFileAttributeView(masterPasswordFile.toPath(),
                PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        Set<PosixFilePermission> filePermissions = fileView.readAttributes().permissions();
        boolean ownerRead = filePermissions.contains(PosixFilePermission.OWNER_READ);
        boolean ownerWrite = filePermissions.contains(PosixFilePermission.OWNER_WRITE);
        boolean ownerExecute = filePermissions.contains(PosixFilePermission.OWNER_EXECUTE);

        boolean groupRead = filePermissions.contains(PosixFilePermission.GROUP_READ);
        boolean groupWrite = filePermissions.contains(PosixFilePermission.GROUP_WRITE);
        boolean groupExecute = filePermissions.contains(PosixFilePermission.GROUP_EXECUTE);

        boolean othersRead = filePermissions.contains(PosixFilePermission.OTHERS_READ);
        boolean othersWrite = filePermissions.contains(PosixFilePermission.OTHERS_WRITE);
        boolean othersExecute = filePermissions.contains(PosixFilePermission.OTHERS_EXECUTE);

        // Permissions should be 700
        if ((ownerRead && ownerWrite && ownerExecute) && (!groupRead && !groupWrite && !groupExecute)
                && (!othersRead && !othersWrite && !othersExecute)) {
            String owner = fileView.readAttributes().owner().getName();
            String group = fileView.readAttributes().group().getName();
            String permStr = PosixFilePermissions.toString(filePermissions);
            LOG.log(Level.INFO, "Passed permissions check for file " + masterPasswordFile.getAbsolutePath()
                    + ". Owner: " + owner + " Group: " + group + " Permissions: " + permStr);
        } else {
            throw new IllegalStateException("Wrong permissions for file " + masterPasswordFile.getAbsolutePath()
                    + ", it should be 700");
        }

    } catch (UnsupportedOperationException ex) {
        LOG.log(Level.WARNING,
                "Associated filesystem is not POSIX compliant. "
                        + "Continue without checking the permissions of " + masterPasswordFile.getAbsolutePath()
                        + " This might be a security problem.");
    } catch (IOException ex) {
        throw new IllegalStateException(
                "Error while getting POSIX permissions of " + masterPasswordFile.getAbsolutePath());
    }

    // Register handlers when master encryption password changes
    MasterPasswordChangeHandler<CertsFacade> psUserCertsHandler = new PSUserCertsMasterPasswordHandler(
            userFacade);
    psUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(UserCerts.class, psUserCertsHandler);

    MasterPasswordChangeHandler<CertsFacade> pgUserCertsHandler = new PGUserCertsMasterPasswordHandler(
            projectFacade);
    pgUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(ProjectGenericUserCerts.class, pgUserCertsHandler);

    MasterPasswordChangeHandler<ClusterCertificateFacade> delaClusterCertsHandler = new DelaCertsMasterPasswordHandler(
            settings);
    delaClusterCertsHandler.setFacade(clusterCertificateFacade);
    registerMasterPasswordChangeHandler(ClusterCertificate.class, delaClusterCertsHandler);
}

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 w w  w . j  a v  a  2  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:com.vns.pdf.impl.PdfDocument.java

private void setWorkingDir() throws IOException {
    ApplicationProperties.KEY.PdfDir.asString();
    workingDir = Paths.get(ApplicationProperties.KEY.PdfDir.asString());
    Files.createDirectories(workingDir, new FileAttribute[0]);
    pdfTempDir = Paths.get(ApplicationProperties.KEY.Workspace.asString(), "temp");
    if (!Files.exists(pdfTempDir, LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(pdfTempDir);
    }/* w  w  w .  j a v  a  2s.  com*/
    ImageIO.setCacheDirectory(pdfTempDir.toFile());
    ImageIO.setUseCache(true);
}

From source file:com.drunkendev.io.recurse.tests.RecursionTest.java

/**
 * Answer provided by Brett Ryan./*w w w  .  j  a  v  a2  s.  co m*/
 *
 * This test uses Java-8's java {@link java.util.stream.Stream Stream API}
 * by {@link Files#walk}.
 *
 * This is the parallel version.
 *
 * @see     <a href="http://stackoverflow.com/a/24006711/140037">Stack-Overflow answer by Brett Ryan</a>
 */
//    @Test
public void testJava8StreamParallel() {
    System.out.println("\nTEST: Java 8 Stream Parallel");
    time(() -> {
        try {
            Map<Integer, Long> stats = Files.walk(startPath).parallel().collect(
                    groupingBy(n -> Files.isDirectory(n, LinkOption.NOFOLLOW_LINKS) ? 1 : 2, counting()));
            System.out.format("Files: %d, dirs: %d. ", stats.get(2), stats.get(1));
        } catch (IOException ex) {
            fail(ex.getMessage());
        }
    });
}

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 {//ww  w . j  a  v  a2s .  c  o  m
            Assert.assertTrue("Path " + actualChild + " has the wrong content.",
                    FileUtils.contentEquals(expectedChild.toFile(), actualChild.toFile()));
        }
    }
}

From source file:ws.michalski.velogen.VeloGenManager.java

/**
 * Liefert Output-Path fr generierte Dateien
 * /*from w  ww . j ava  2 s.co  m*/
 * 1. Es wird geprft, ob Parameter -op gesetzt ist, sonst
 * 2. wird geprft, ob config diese Information enthlt, sonst
 * 3. wird Unterverzeichnis ./output genutzt.
 * 
 * 
 * @return
 */
public String getOutputPath() {

    String outputPath = null;

    if (veloCmd.getCommonParam().getOutputPath() != null) {
        outputPath = veloCmd.getCommonParam().getOutputPath();
    } else if (config.getOutputPath() != null) {
        outputPath = config.getOutputPath();
    } else {
        outputPath = SystemUtils.USER_DIR + SystemUtils.FILE_SEPARATOR + "output";
    }

    Path path = Paths.get(outputPath);

    if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
        logger.error("Output path error");
        // TODO: Exception
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Path " + path.toAbsolutePath().normalize().toString());
    }

    return path.toAbsolutePath().normalize().toString();
}

From source file:org.discosync.ApplySyncPack.java

/**
 * Apply a syncpack to a target directory.
 *//*from  w  w  w  .  ja v a 2 s .c om*/
protected void applySyncPack(String syncPackDir, String targetDir) throws SQLException, IOException {

    // read file operations from database
    File fileOpDbFile = new File(syncPackDir, "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();

    Iterator<FileListEntry> it = db.getFileListOperationIterator();

    Path syncFileBaseDir = Paths.get(syncPackDir, "files");
    String syncFileBaseDirStr = syncFileBaseDir.toAbsolutePath().toString();

    int filesCopied = 0;
    int filesReplaced = 0;
    int filesDeleted = 0;
    long copySize = 0L;
    long deleteSize = 0L;

    // Collect directories during processing.
    List<FileListEntry> directoryOperations = new ArrayList<>();

    // First process all files, then the directories
    while (it.hasNext()) {

        FileListEntry e = it.next();

        // Remember directories
        if (e.isDirectory()) {
            directoryOperations.add(e);
            continue;
        }

        String path = e.getPath();
        Path sourcePath = Paths.get(syncFileBaseDirStr, path); // may not exist
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // copy new file, target files should not exist
            if (Files.exists(targetPath)) {
                System.out
                        .println("Error: the file should not exist: " + targetPath.toAbsolutePath().toString());
            } else {
                if (!Files.exists(targetPath.getParent())) {
                    Files.createDirectories(targetPath.getParent());
                }

                Files.copy(sourcePath, targetPath);
                filesCopied++;
                copySize += e.getSize();
            }

        } else if (e.getOperation() == FileOperations.REPLACE) {
            // replace existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            filesReplaced++;
            copySize += e.getSize();

        } else if (e.getOperation() == FileOperations.DELETE) {
            // delete existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            } else {
                long fileSize = Files.size(targetPath);
                if (fileSize != e.getSize()) {
                    // show info, delete anyway
                    System.out.println(
                            "Info: the file size is different: " + targetPath.toAbsolutePath().toString());
                }
                deleteSize += fileSize;
                Files.delete(targetPath);
                filesDeleted++;
            }
        }
    }

    db.close();

    // Sort directory list to ensure directories are deleted bottom-up (first /dir1/dir2, then /dir1)
    Collections.sort(directoryOperations, new Comparator<FileListEntry>() {
        @Override
        public int compare(FileListEntry e1, FileListEntry e2) {
            return e2.getPath().compareTo(e1.getPath().toString());
        }
    });

    // Now process directories - create and delete empty directories
    for (FileListEntry e : directoryOperations) {

        String path = e.getPath();
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // create directory if needed
            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }
        } else if (e.getOperation() == FileOperations.DELETE) {

            if (!Files.exists(targetPath)) {
                System.out.println(
                        "Info: Directory to DELETE does not exist: " + targetPath.toAbsolutePath().toString());

            } else if (!Files.isDirectory(targetPath, LinkOption.NOFOLLOW_LINKS)) {
                System.out.println("Info: Directory to DELETE is not a directory, but a file: "
                        + targetPath.toAbsolutePath().toString());

            } else if (!Utils.isDirectoryEmpty(targetPath)) {
                System.out.println("Info: Directory to DELETE is not empty, but should be empty: "
                        + targetPath.toAbsolutePath().toString());

            } else {
                // delete directory
                Files.delete(targetPath);
            }
        }
    }

    System.out.println("Apply of syncpack '" + syncPackDir + "' to directory '" + targetDir + "' finished.");
    System.out.println("Files copied  : " + String.format("%,d", filesCopied));
    System.out.println("Files replaced: " + String.format("%,d", filesReplaced));
    System.out.println("Files deleted : " + String.format("%,d", filesDeleted));
    System.out.println("Bytes copied  : " + String.format("%,d", copySize));
    System.out.println("Bytes deleted : " + String.format("%,d", deleteSize));
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {//from   ww  w  .  j  av  a 2 s  . c  om
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public long getCreationTime() {
    try {/*from www. ja  v a  2s  . c o  m*/
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.creationTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getCreationTime()", e);
        return 0;
    }
}