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.reactor.monitoring.util.FileHandler.java

public static void createAndUpdateFile(final boolean replaceFile, final String fileLocation,
        final String output) {
    try {/*  w  w  w  .  j  a v a2  s. c om*/
        Path path = Paths.get(fileLocation);
        Path parentDir = path.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }

        if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            Files.createFile(path);
        } else if (replaceFile) {
            Files.delete(path);
            Files.createFile(path);
        }

        Files.write(path, output.getBytes(), StandardOpenOption.APPEND);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.jejking.hh.nord.corpus.DrucksachenHtmlFetcher.java

/**
* Schedules tasks to fetch all the specified URLs leaving a random duration between the 
* execution of each task. /*from  w  ww  .  j a v  a 2s  . co m*/
* 
* @param urlsToFetch
* @param storageDirectory
*/
public void fetchUrls(final ImmutableList<URL> urlsToFetch, final Path storageDirectory) {

    Observable<Runnable> tasks = Observable.from(urlsToFetch).filter(new Func1<URL, Boolean>() {

        @Override
        public Boolean call(URL url) {
            String encodedUrl = fileNameFromUrl(url) + ".gz";
            Path filePath = storageDirectory.resolve(encodedUrl);
            // retain only URLs for which we have no record yet so as not to download them twice
            return Files.notExists(filePath, LinkOption.NOFOLLOW_LINKS);
        }

    }).map(new Func1<URL, Runnable>() {
        @Override
        public Runnable call(final URL url) {
            return new Runnable() {

                @Override
                public void run() {

                    try {
                        File target = storageDirectory.resolve(fileNameFromUrl(url) + ".gz").toFile();
                        try (GzipCompressorOutputStream outputStream = new GzipCompressorOutputStream(
                                new BufferedOutputStream(new FileOutputStream(target)))) {
                            Resources.copy(url, outputStream);
                            System.out.println("Copied " + url + " to " + target);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            };

        };
    });

    tasks.subscribe(new Action1<Runnable>() {

        Random random = new Random();
        long cumulativeDelayInSeconds = 0;
        int count = 0;

        @Override
        public void call(Runnable runnable) {
            count++;
            DrucksachenHtmlFetcher.this.scheduledExecutorService.schedule(runnable, cumulativeDelayInSeconds,
                    TimeUnit.SECONDS);
            // at least two seconds, at most 10
            cumulativeDelayInSeconds = cumulativeDelayInSeconds + 2 + random.nextInt(9);
            DrucksachenHtmlFetcher.this.totalDelayHolder[0] = cumulativeDelayInSeconds;
            DrucksachenHtmlFetcher.this.actualCount[0] = count;
        }

    });

    System.out.println("Scheduled " + actualCount[0] + " tasks");
    System.out.println("Estimated duration " + totalDelayHolder[0] + " seconds");

    try {
        this.scheduledExecutorService.shutdown();
        // + 60 to allow task to finish comfortably...
        boolean finishedOK = this.scheduledExecutorService.awaitTermination(this.totalDelayHolder[0] + 60,
                TimeUnit.SECONDS);
        if (finishedOK) {
            System.out.println("Finished all tasks. Scheduled executor service shutdown.");
        } else {
            System.out.println("Executor service shutdown, but not all tasks completed.");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:com.ignorelist.kassandra.steam.scraper.FileCache.java

private long getModified(String key) throws IOException {
    FileTime lastModifiedTime = Files.getLastModifiedTime(buildCacheFile(key), LinkOption.NOFOLLOW_LINKS);
    return lastModifiedTime.toMillis();
}

From source file:org.fcrepo.indexer.persistence.BasePersistenceIndexer.java

/**
 * Return the path where a given record should be persisted.
 * @param id The record's URI/*from  w  w  w  . j a  v a2 s. c o m*/
 * @return the path where a given record should be persisted
 * @throws IOException if IO exception occurred
**/
protected Path pathFor(final URI id) throws IOException {

    // strip the http protocol and replace column(:) in front of the port number
    String fullPath = id.toString().substring(id.toString().indexOf("//") + 2);
    fullPath = StringUtils.substringBefore(fullPath, "/").replace(":", "/") + "/"
            + StringUtils.substringAfter(fullPath, "/");
    // URL encode the id
    final String idPath = URLEncoder.encode(substringAfterLast(fullPath, "/"), "UTF-8");

    // URL encode and build the file path
    final String[] pathTokens = StringUtils.substringBeforeLast(fullPath, "/").split("/");
    final StringBuilder pathBuilder = new StringBuilder();
    for (final String token : pathTokens) {
        if (StringUtils.isNotBlank(token)) {
            pathBuilder.append(URLEncoder.encode(token, "UTF-8") + "/");
        }
    }

    fullPath = pathBuilder.substring(0, pathBuilder.length() - 1).toString();

    final Path dir = Paths.get(pathName, fullPath);
    if (Files.notExists(dir, LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(Paths.get(pathName, fullPath));
    }
    return Paths.get(dir.toString(), idPath + extension);
}

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

@Before
public void setup() throws Exception {
    final File file = new File(root.toFile(), "testname");

    FileUtils.writeStringToFile(file, file.getName(), Charsets.UTF_8);
    path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);

    when(mockContext.getPathUtils()).thenReturn(mockPathUtils);

    report = new MigrationReportImpl(MigrationOperation.IMPORT, Optional.empty());
    when(mockContext.getReport()).thenReturn(report);

    when(mockPathUtils.resolveAgainstDDFHome(any(Path.class))).thenReturn(path);
    when(mockPathUtils.getChecksumFor(any(Path.class))).thenReturn(CHECKSUM);

    entry = new ImportMigrationExternalEntryImpl(mockContext, METADATA_MAP);
}

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

private List<Path> listArchiveFiles(Path underHere) {
    List res = new ArrayList<>();

    try {/*w w w  . jav a 2 s  . c o  m*/
        Files.newDirectoryStream(underHere).forEach((p) -> {
            if (Files.isRegularFile(p, LinkOption.NOFOLLOW_LINKS)) {
                res.add(p);
            } else if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
                res.addAll(listArchiveFiles(p));
            }
        });
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }

    return res;
}

From source file:org.v2020.service.ie.test.VnaImportTest.java

@Test
public void testVna() throws Exception {
    byte[] vnaFileData = FileSystem.readByteArrayFromClasspath(RISK_CATALOG_FILE_NAME);
    assertNotNull("File data is null, file name: " + RISK_CATALOG_FILE_NAME, vnaFileData);
    Vna vna = new Vna(vnaFileData);
    byte[] xmlFiledata = vna.getXmlFileData();
    assertNotNull("Xml file data is null.", xmlFiledata);
    SyncRequest syncRequest = vna.getXml();
    assertNotNull("SyncRequest is null.", syncRequest);
    SyncData syncData = syncRequest.getSyncData();
    assertNotNull("SyncData is null.", syncData);
    List<SyncObject> syncObjects = syncData.getSyncObject();
    assertNotNull("SyncObject list is null.", syncObjects);
    assertFalse("SyncObject list is empty.", syncObjects.isEmpty());
    SyncObject syncObject = syncObjects.get(0);
    assertNotNull("SyncObject is null.", syncObject);
    vna.clear();//  w  w w.  j  av a2  s .c om
    assertFalse("Temp folder still exists: " + vna.getTempFileName(),
            Files.exists(Paths.get(vna.getTempFileName()), LinkOption.NOFOLLOW_LINKS));
}

From source file:com.kamike.misc.FsUtils.java

public static void createDirectory(String dstPath) {

    Properties props = System.getProperties(); //    
    String osName = props.getProperty("os.name"); //???   
    Path newdir = FileSystems.getDefault().getPath(dstPath);

    boolean pathExists = Files.exists(newdir, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
    if (!pathExists) {
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
        try {/*  ww  w.ja  v a 2  s . c om*/
            if (!osName.contains("Windows")) {
                Files.createDirectories(newdir, attr);
            } else {
                Files.createDirectories(newdir);
            }
        } catch (Exception e) {
            System.err.println(e);

        }
    }
}

From source file:org.reactor.monitoring.util.FileHandler.java

public static boolean isFileExist(final String fileLocation) {
    Path path = Paths.get(fileLocation);
    return Files.exists(path, LinkOption.NOFOLLOW_LINKS);
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelperTest.java

@Test
public void testModifyFiles() throws Exception {
    Path path = Paths.get("temp-testsuite.suite");
    try {//from ww w.  j a v  a  2  s .  com
        String source = "line1\r\n\r\nbla\r\n";
        FileUtils.writeStringToFile(path.toFile(), source);
        FileTime beforeTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        Thread.sleep(1100);

        String result = TestSuiteHelper.prepareTestSuiteFile(path);
        assertEquals(result, "line1\r\n//\r\nbla\r\n");
        FileTime afterTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        assertNotEquals(beforeTimeStamp, afterTimeStamp);
    } finally {
        Files.deleteIfExists(path);
    }
}