Example usage for java.nio.file Path toRealPath

List of usage examples for java.nio.file Path toRealPath

Introduction

In this page you can find the example usage for java.nio.file Path toRealPath.

Prototype

Path toRealPath(LinkOption... options) throws IOException;

Source Link

Document

Returns the real path of an existing file.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("users.txt");

    System.out.println("Real path: " + path.toRealPath(LinkOption.NOFOLLOW_LINKS));
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("users.txt");

    if (path.toFile().exists()) {
        System.out.println("Real path: " + path.toRealPath(LinkOption.NOFOLLOW_LINKS));
    } else {//from   w ww.  ja v  a2 s  .  c  o m
        System.out.println("The file does not exist");
    }
}

From source file:Main.java

public static void main(String[] args) {

    Path path = Paths.get("/tutorial/Java/JavaFX", "Topic.txt");

    // convert path to "real" path
    try {/*from ww w .jav a  2s  .  c o  m*/
        Path real_path = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
        System.out.println("Path to real path: " + real_path);
    } catch (IOException e) {
        System.err.println(e);
    }

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path1 = Paths.get("/home/docs/users.txt");
    Path path2 = Paths.get("/home/music/users.txt");

    System.out.println(Files.isSymbolicLink(path1));
    System.out.println(Files.isSymbolicLink(path2));

    Path path = Paths.get(new URI("C:/home/./music/users.txt"));
    System.out.println("Normalized: " + path.normalize());
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("toRealPath (Do not follow links): " + path.toRealPath(LinkOption.NOFOLLOW_LINKS));
    System.out.println("toRealPath: " + path.toRealPath());

}

From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java

protected synchronized void processSyncWatchEvent(SyncWatchEvent syncWatchEvent) throws Exception {

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(_syncAccountId);

    if (syncAccount.getState() != SyncAccount.STATE_CONNECTED) {
        return;//from  www .j  ava 2s.  c  o  m
    }

    if (_processedSyncWatchEventIds.contains(syncWatchEvent.getSyncWatchEventId())) {

        SyncWatchEventService.deleteSyncWatchEvent(syncWatchEvent.getSyncWatchEventId());

        return;
    }

    String eventType = syncWatchEvent.getEventType();

    if (eventType.equals(SyncWatchEvent.EVENT_TYPE_RENAME_FROM)) {
        eventType = SyncWatchEvent.EVENT_TYPE_DELETE;

        syncWatchEvent.setEventType(eventType);

        SyncWatchEventService.update(syncWatchEvent);
    }

    if (_logger.isDebugEnabled()) {
        _logger.debug("Processing Sync watch event {}", syncWatchEvent.toString());
    }

    String fileType = syncWatchEvent.getFileType();

    if (eventType.equals(SyncWatchEvent.EVENT_TYPE_CREATE)) {
        if (fileType.equals(SyncFile.TYPE_FILE)) {
            SyncWatchEvent duplicateSyncWatchEvent = null;

            if (OSDetector.isApple()) {
                duplicateSyncWatchEvent = SyncWatchEventService.fetchDuplicateSyncWatchEvent(syncWatchEvent);
            }

            if (duplicateSyncWatchEvent != null) {
                if (_logger.isDebugEnabled()) {
                    _logger.debug("Skipping outdated Sync watch event");
                }
            } else {
                addFile(syncWatchEvent);
            }
        } else {
            addFolder(syncWatchEvent);
        }
    } else if (eventType.equals(SyncWatchEvent.EVENT_TYPE_DELETE)) {
        deleteFile(syncWatchEvent);
    } else if (eventType.equals(SyncWatchEvent.EVENT_TYPE_MODIFY)) {
        SyncWatchEvent duplicateSyncWatchEvent = SyncWatchEventService
                .fetchDuplicateSyncWatchEvent(syncWatchEvent);

        if (duplicateSyncWatchEvent != null) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("Skipping outdated Sync watch event");
            }
        } else {
            if (OSDetector.isWindows()) {

                // SYNC-1713

                String filePathName = syncWatchEvent.getFilePathName();

                Path filePath = Paths.get(filePathName);

                if (FileUtil.exists(filePath)) {
                    Path realFilePath = filePath.toRealPath(LinkOption.NOFOLLOW_LINKS);

                    if (!filePathName.equals(realFilePath.toString())) {
                        syncWatchEvent.setEventType(SyncWatchEvent.EVENT_TYPE_RENAME);
                        syncWatchEvent.setFilePathName(realFilePath.toString());
                        syncWatchEvent.setPreviousFilePathName(filePathName);

                        renameFile(syncWatchEvent);
                    }

                    if (fileType.equals(SyncFile.TYPE_FILE)) {
                        modifyFile(syncWatchEvent);
                    }
                } else {
                    modifyFile(syncWatchEvent);
                }
            } else {
                modifyFile(syncWatchEvent);
            }
        }
    } else if (eventType.equals(SyncWatchEvent.EVENT_TYPE_MOVE)) {
        moveFile(syncWatchEvent);
    } else if (eventType.equals(SyncWatchEvent.EVENT_TYPE_RENAME)) {
        renameFile(syncWatchEvent);
    }

    syncAccount = SyncAccountService.fetchSyncAccount(_syncAccountId);

    if (syncAccount.getState() == SyncAccount.STATE_CONNECTED) {
        SyncWatchEventService.deleteSyncWatchEvent(syncWatchEvent.getSyncWatchEventId());
    }
}

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

/**
 * Creates a test softlink with the given name in the specified directory resolved under
 * ${ddf.home}.//  www.  ja  va2s.c om
 *
 * @param dir the directory where to create the test softlink
 * @param name the name of the test softlink to create in the specified directory
 * @param dest the destination path for the softlink
 * @return a path corresponding to the test softlink created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test softlink
 * @throws UnsupportedOperationException if the implementation does not support symbolic links
 */
public Path createSoftLink(Path dir, String name, Path dest) throws IOException {
    final Path path = ddfHome.resolve(dir).resolve(name);

    dir.toFile().mkdirs();
    try {
        Files.createSymbolicLink(path, dest);
    } catch (FileSystemException exception) {
        // symlinks cannot be reliably created on Windows
        throw new AssumptionViolatedException("The system cannot create symlinks.", exception);
    }

    final Path apath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);

    return apath.startsWith(ddfHome) ? ddfHome.relativize(apath) : apath;
}

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

@Test
public void testStoreWhenRequiredAndFileRealPathCannotBeDetermined() throws Exception {
    final PathUtils pathUtils = Mockito.mock(PathUtils.class);
    final Path path = Mockito.mock(Path.class);
    final IOException ioe = new IOException("test");

    Mockito.when(context.getPathUtils()).thenReturn(pathUtils);
    Mockito.when(pathUtils.resolveAgainstDDFHome((Path) Mockito.any())).thenReturn(path);
    Mockito.when(pathUtils.relativizeFromDDFHome(Mockito.any())).thenReturn(path);
    Mockito.when(path.toRealPath(LinkOption.NOFOLLOW_LINKS)).thenThrow(ioe);

    final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(context, FILE_PATH);

    final StringWriter writer = new StringWriter();

    Mockito.when(context.getOutputStreamFor(Mockito.any()))
            .thenReturn(new WriterOutputStream(writer, Charsets.UTF_8));

    Assert.assertThat(entry.store(true), Matchers.equalTo(false));
    Assert.assertThat(writer.toString(), Matchers.emptyString());
    Assert.assertThat(report.hasErrors(), Matchers.equalTo(true));
    Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false));
    Assert.assertThat(report.wasSuccessful(), Matchers.equalTo(false));

    thrown.expect(MigrationException.class);
    thrown.expectMessage(Matchers.containsString("cannot be read"));
    thrown.expectCause(Matchers.sameInstance(ioe));

    report.verifyCompletion(); // to trigger an exception from the report
}

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

@Test
public void testStoreWithFilterWhenRequiredAndFileRealPathCannotBeDeterminedAndMatching() throws Exception {
    final PathUtils pathUtils = Mockito.mock(PathUtils.class);
    final Path path = Mockito.mock(Path.class);
    final IOException ioe = new IOException("test");

    Mockito.when(context.getPathUtils()).thenReturn(pathUtils);
    Mockito.when(pathUtils.resolveAgainstDDFHome((Path) Mockito.any())).thenReturn(path);
    Mockito.when(pathUtils.relativizeFromDDFHome(Mockito.any())).thenReturn(path);
    Mockito.when(path.toRealPath(LinkOption.NOFOLLOW_LINKS)).thenThrow(ioe);

    final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(context, FILE_PATH);

    final StringWriter writer = new StringWriter();

    Mockito.when(context.getOutputStreamFor(Mockito.any()))
            .thenReturn(new WriterOutputStream(writer, Charsets.UTF_8));

    Assert.assertThat(entry.store(true, p -> true), Matchers.equalTo(false));
    Assert.assertThat(writer.toString(), Matchers.emptyString());
    Assert.assertThat(report.hasErrors(), Matchers.equalTo(true));
    Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false));
    Assert.assertThat(report.wasSuccessful(), Matchers.equalTo(false));

    thrown.expect(MigrationException.class);
    thrown.expectMessage(Matchers.containsString("cannot be read"));
    thrown.expectCause(Matchers.sameInstance(ioe));

    report.verifyCompletion(); // to trigger an exception from the report
}

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

@Test
public void testStoreWithFilterWhenRequiredAndFileRealPathCannotBeDeterminedAndNotMatching() throws Exception {
    final PathUtils pathUtils = Mockito.mock(PathUtils.class);
    final Path path = Mockito.mock(Path.class);
    final IOException ioe = new IOException("test");

    Mockito.when(context.getPathUtils()).thenReturn(pathUtils);
    Mockito.when(pathUtils.resolveAgainstDDFHome((Path) Mockito.any())).thenReturn(path);
    Mockito.when(pathUtils.relativizeFromDDFHome(Mockito.any())).thenReturn(path);
    Mockito.when(path.toRealPath(LinkOption.NOFOLLOW_LINKS)).thenThrow(ioe);

    final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(context, FILE_PATH);

    final StringWriter writer = new StringWriter();

    Mockito.when(context.getOutputStreamFor(Mockito.any()))
            .thenReturn(new WriterOutputStream(writer, Charsets.UTF_8));

    Assert.assertThat(entry.store(true, p -> false), Matchers.equalTo(false));
    Assert.assertThat(writer.toString(), Matchers.emptyString());
    Assert.assertThat(report.hasErrors(), Matchers.equalTo(true));
    Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false));
    Assert.assertThat(report.wasSuccessful(), Matchers.equalTo(false));

    Mockito.verify(context, Mockito.never()).getOutputStreamFor(Mockito.any());

    thrown.expect(MigrationException.class);
    thrown.expectMessage(Matchers.containsString("does not match filter"));

    report.verifyCompletion(); // to trigger an exception from the report
}

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

@Test
public void testGetLastModifiedTime() throws Exception {
    final PathUtils pathUtils = Mockito.mock(PathUtils.class);
    final Path filePath = Mockito.mock(Path.class);
    final File file = Mockito.mock(File.class);
    final long modified = 12345L;

    Mockito.when(context.getPathUtils()).thenReturn(pathUtils);
    Mockito.when(pathUtils.resolveAgainstDDFHome(filePath)).thenReturn(filePath);
    Mockito.when(filePath.toRealPath(Mockito.any())).thenReturn(filePath);
    Mockito.when(pathUtils.relativizeFromDDFHome(filePath)).thenReturn(filePath);
    Mockito.when(filePath.toString()).thenReturn(UNIX_NAME);
    Mockito.when(filePath.toFile()).thenReturn(file);
    Mockito.when(file.lastModified()).thenReturn(modified);

    final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(context, filePath);

    Assert.assertThat(entry.getLastModifiedTime(), Matchers.equalTo(modified));

    Mockito.verify(file).lastModified();
}