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:oracle.kv.sample.fileloader.FileLoader.java

/**
 * After successful validation this method is run to load the content of a
 * TXT file into the given table/*  ww w  .  java  2s.c  o  m*/
 * 
 * @throws IOException
 */
private void loadData() throws IOException {
    if (inputPathStr != null) {
        dir = new File(inputPathStr);
        File file = null;
        File[] files = null;
        int len = 0;

        // If input path is a directory then load data from all the files
        // that are under the directory. Make sure all the files are of same
        // type
        // i.e. TXT (mix and match is not allowed)
        if (dir.exists()) {
            System.out.println("There are " + dir.listFiles().length + " to be loaded.");
            if (dir.isDirectory()) {
                files = dir.listFiles();
                len = files.length;

                // loop through all the files and load the content one by
                // one
                for (int i = 0; i < len; i++) {
                    file = files[i];
                    try {
                        Path filePath = Paths.get(file.getPath());
                        BasicFileAttributes attr = Files.readAttributes(filePath, BasicFileAttributes.class,
                                LinkOption.NOFOLLOW_LINKS);
                        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
                        FileOwnerAttributeView fileOwnerAttributeView = Files.getFileAttributeView(filePath,
                                FileOwnerAttributeView.class);
                        UserPrincipal userPrincipal = fileOwnerAttributeView.getOwner();

                        id = Integer.toString(i);
                        fileDate = formatter.format(attr.lastAccessTime().toMillis());
                        fileOwner = userPrincipal.getName();
                        binaryFile = FileUtils.readFileToByteArray(file);

                        row = table.createRow();
                        row.put("id", id);
                        row.put("date", fileDate.toString());
                        row.put("owner", fileOwner);
                        row.put("file", binaryFile);

                        tableh.put(row, null, null);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {
                System.out.println("There are no Files to Load");
            }
        }
    }

    if (fileId != null) {
        getData();
    }
}

From source file:org.zxg.hotupdate.HotUpdateClassLoader.java

@Override
public void fileDeleted(Path path) {
    if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
        synchronized (this) {
            classNameToClass.remove(relativePathToClassName(classesRootDirPath.relativize(path).toString()));
        }/* w w  w  . j a v a  2 s.  co m*/
    }
}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override//from  w  w  w .jav  a2 s .  co  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:schemacrawler.test.utility.TestUtility.java

public static List<String> compareOutput(final String referenceFile, final Path testOutputTempFile,
        final String outputFormat, final boolean isCompressed) throws Exception {

    requireNonNull(referenceFile, "Reference file is not defined");
    requireNonNull(testOutputTempFile, "Output file is not defined");
    requireNonNull(outputFormat, "Output format is not defined");

    if (!exists(testOutputTempFile) || !isRegularFile(testOutputTempFile, LinkOption.NOFOLLOW_LINKS)
            || !isReadable(testOutputTempFile) || size(testOutputTempFile) == 0) {
        return Collections.singletonList("Output file not created - " + testOutputTempFile);
    }/*from w ww.j a  va  2s  .  c  o  m*/

    final List<String> failures = new ArrayList<>();

    final boolean contentEquals;
    final Reader referenceReader = readerForResource(referenceFile, StandardCharsets.UTF_8, isCompressed);
    if (referenceReader == null)

    {
        contentEquals = false;
    } else {
        final Reader fileReader = readerForFile(testOutputTempFile, isCompressed);
        contentEquals = contentEquals(referenceReader, fileReader, neuters);
    }

    if ("html".equals(outputFormat)) {
        validateXML(testOutputTempFile, failures);
    }
    if ("htmlx".equals(outputFormat)) {
        validateXML(testOutputTempFile, failures);
    } else if ("json".equals(outputFormat)) {
        validateJSON(testOutputTempFile, failures);
    }

    if (!contentEquals) {
        final Path testOutputTargetFilePath = buildDirectory().resolve("unit_tests_results_output")
                .resolve(referenceFile);
        createDirectories(testOutputTargetFilePath.getParent());
        deleteIfExists(testOutputTargetFilePath);
        move(testOutputTempFile, testOutputTargetFilePath, ATOMIC_MOVE, REPLACE_EXISTING);

        if (!contentEquals) {
            failures.add("Output does not match");
        }

        failures.add("Actual output in " + testOutputTargetFilePath);
        System.err.println(testOutputTargetFilePath);
    } else {
        delete(testOutputTempFile);
    }

    return failures;
}

From source file:RestoreService.java

public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException {
    // advanced attributes
    // owner/*from   www  .ja v  a 2s.  com*/
    if (StringUtils.isNotBlank(voBackupFile.getOwner())) {
        try {
            UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
            UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(voBackupFile.getOwner());
            Files.setOwner(file.toPath(), userPrincipal);
        } catch (UserPrincipalNotFoundException e) {
            logger.warn("Cannot set owner {}", voBackupFile.getOwner());
        }
    }
    if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class)
            && BooleanUtils.isTrue(voBackupFile.getDosAttr())) {
        Files.setAttribute(file.toPath(), "dos:hidden", BooleanUtils.isTrue(voBackupFile.getDosHidden()));
        Files.setAttribute(file.toPath(), "dos:archive", BooleanUtils.isTrue(voBackupFile.getDosArchive()));
        Files.setAttribute(file.toPath(), "dos:readonly", BooleanUtils.isTrue(voBackupFile.getDosReadOnly()));
        Files.setAttribute(file.toPath(), "dos:system", BooleanUtils.isTrue(voBackupFile.getDosSystem()));
    }

    if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)
            && BooleanUtils.isTrue(voBackupFile.getPosixAttr())) {
        try {
            UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
            GroupPrincipal groupPrincipal = lookupService
                    .lookupPrincipalByGroupName(voBackupFile.getPosixGroup());
            Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
                    .setGroup(groupPrincipal);
        } catch (UserPrincipalNotFoundException e) {
            logger.warn("Cannot set group {}", voBackupFile.getOwner());
        }

        if (StringUtils.isNotBlank(voBackupFile.getPosixPermitions())) {
            Set<PosixFilePermission> perms = PosixFilePermissions.fromString(voBackupFile.getPosixPermitions());
            Files.setPosixFilePermissions(file.toPath(), perms);
        }
    }
}

From source file:com.vns.pdf.impl.PdfDocument.java

private PdfDocument(String pdfFileName) throws IOException {
    this.pdfFileName = pdfFileName;
    setWorkingDir();/*  w  w w .  ja  v  a 2  s. co  m*/
    Path filePath = Paths.get(pdfFileName);
    PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class)
            .readAttributes();
    String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode()
            + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml";
    textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName);
    pdfTextStripper = new CustomPDFTextStripper();
    document = PDDocument.load(new File(pdfFileName));
    pdfRenderer = new PDFRenderer(document);

    if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) {
        pdfTextStripper.setSortByPosition(false);
        pdfTextStripper.setStartPage(0);
        pdfTextStripper.setEndPage(document.getNumberOfPages());

        this.doc = new Doc(new ArrayList<>(), new ArrayList<>());
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage pdPage = document.getPage(i);
            PDRectangle box = pdPage.getMediaBox();
            this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(),
                    (int) box.getHeight()));
        }

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        try {
            pdfTextStripper.writeText(document, dummy);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        parseBookmarksAnnotation();
        createTextAreaFile();
        //document.save(pdfFileName + ".pdf");
    } else {
        loadTextAreaFile();
    }
}

From source file:view.BackgroundImageController.java

public void checkForAndLoadBackgroundImage(VisualizationViewer vv, String loadPath) {
    String fileName = FilenameUtils.removeExtension(loadPath);
    fileName += ".background";
    Path sourcePath = Paths.get(fileName);

    if (Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
        setGraphBackgroundImage(vv, new ImageIcon(fileName), 2, 2);
        setBackgroundImagePath(fileName);
    } else {/* w  ww  . ja v  a2 s .co m*/
        removeBackgroundImage(vv);
    }
}

From source file:specminers.evaluation.TracesFilter.java

private static void copyTraceFilesToOutput(Map<String, Set<File>> filteredTests, String testsType,
        Map<String, String> programOptions) throws IOException {

    Map<String, Set<File>> testValidTraces = new HashMap<>();

    Set<File> validTraceFiles = new HashSet<>();

    for (String clazz : filteredTests.keySet()) {
        String fullyQualifiedClassName = String.format("%s.%s", programOptions.get(TARGET_PACKAGE), clazz);
        File parentFolder = Paths.get(programOptions.get(TRACES_PATH_OPTION), clazz).toFile();
        Path filteredOutputFolder = Paths.get(programOptions.get(OUTPUT_OPTION), clazz, testsType)
                .toAbsolutePath();/*from   w ww  . jav  a  2 s.c o  m*/

        filteredOutputFolder.toFile().delete();
        filteredOutputFolder.toFile().mkdirs();
        if (!Files.exists(filteredOutputFolder, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(filteredOutputFolder);
        }

        for (File testFile : filteredTests.get(clazz)) {
            String traceFileName = testFile.getName();
            File traceFile = Paths.get(parentFolder.getAbsolutePath(), traceFileName).toFile();
            if (!programOptions.containsKey(AUTOMATICALLY_GENERATED_TESTS)) {
                traceFileName = testFile.getName().replace(".java", "_client_calls_trace.txt");
                traceFile = Paths.get(parentFolder.getAbsolutePath(), traceFileName).toFile();
            }

            if (traceFile.exists()) {
                TestTraceFilter traceFilter = new TestTraceFilter(traceFile, fullyQualifiedClassName);
                if (traceFilter.isValidTrace()) {
                    if (testValidTraces.get(clazz) == null) {
                        testValidTraces.put(clazz, new HashSet<>());
                    }
                    testValidTraces.get(clazz).add(traceFile);
                } else {
                    if (traceFile.exists()) {
                        /*
                        if (!traceFile.delete()) {
                        throw new RuntimeException("Not possible to delete invalid trace file " + traceFileName);
                        }*/
                    }
                }
            }
        }
    }

    testValidTraces = TestTraceFilter.removeSubTraces(testValidTraces, programOptions.get(TARGET_PACKAGE));

    for (String clazz : testValidTraces.keySet()) {
        Path filteredOutputFolder = Paths.get(programOptions.get(OUTPUT_OPTION), clazz, testsType)
                .toAbsolutePath();
        FileUtils.deleteDirectory(filteredOutputFolder.toFile());

        for (File validTrace : testValidTraces.get(clazz)) {
            FileUtils.copyFileToDirectory(validTrace, filteredOutputFolder.toFile());
        }

        if (filteredOutputFolder.toFile().list().length == 0) {
            FileUtils.deleteDirectory(filteredOutputFolder.toFile());
        }
    }
}

From source file:org.codice.ddf.configuration.migration.ImportMigrationJavaPropertyReferencedEntryImpl.java

private void verifyReferencedFileAfterCompletion(MigrationReport r, String val) {
    try {/*from ww w. j ava  2s . com*/
        if (!getAbsolutePath().toRealPath(LinkOption.NOFOLLOW_LINKS).equals(getContext().getPathUtils()
                .resolveAgainstDDFHome(Paths.get(val)).toRealPath(LinkOption.NOFOLLOW_LINKS))) {
            r.record(new MigrationException(Messages.IMPORT_JAVA_PROPERTY_ERROR, getProperty(), propertiesPath,
                    getPath(), "is now set to [" + val + ']'));
        }
    } catch (IOException e) {
        // cannot determine the location of either so it must not exist or be
        // different anyway
        r.record(new MigrationException(Messages.IMPORT_JAVA_PROPERTY_ERROR, getProperty(), propertiesPath,
                getPath(), String.format("is now set to [%s]; %s", val, e.getMessage()), e));
    }
}

From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java

@Override
public void setProperty(DavProperty<?> property) throws DavException {
    getProperties().add(property);//from w ww .j  a  v  a2  s  .  c o  m

    LOG.info("Set property {}", property.getName());

    try {
        final Path path = ResourcePathUtils.getPhysicalPath(this);
        if (DavPropertyName.CREATIONDATE.equals(property.getName()) && property.getValue() instanceof String) {
            final String createDateStr = (String) property.getValue();
            final FileTime createTime = FileTimeUtils.fromRfc1123String(createDateStr);
            final BasicFileAttributeView attrView = Files.getFileAttributeView(path,
                    BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            attrView.setTimes(null, null, createTime);
            LOG.info("Updating Creation Date: {}", createTime.toString());
        } else if (DavPropertyName.GETLASTMODIFIED.equals(property.getName())
                && property.getValue() instanceof String) {
            final String lastModifiedTimeStr = (String) property.getValue();
            final FileTime lastModifiedTime = FileTimeUtils.fromRfc1123String(lastModifiedTimeStr);
            final BasicFileAttributeView attrView = Files.getFileAttributeView(path,
                    BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            attrView.setTimes(lastModifiedTime, null, null);
            LOG.info("Updating Last Modified Date: {}", lastModifiedTime.toString());
        }
    } catch (IOException e) {
        throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}