Example usage for java.nio.file Path equals

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

Introduction

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

Prototype

boolean equals(Object other);

Source Link

Document

Tests this path for equality with the given object.

Usage

From source file:com.kappaware.logtrawler.DirWatcher.java

private void register(Path path) throws IOException {
    WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    if (log.isDebugEnabled()) {
        Path prev = pathByKey.get(key);
        if (prev == null) {
            log.debug(String.format("register: %s", path));
        } else {/*w w  w. ja  v  a  2  s.  c  om*/
            if (!path.equals(prev)) {
                log.debug(String.format("update: %s -> %s", prev, path));
            }
        }
    }
    this.pathByKey.put(key, path);
}

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 ww .  j a v  a2 s.  com*/
        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:de.ks.flatadocdb.session.Session.java

private SessionEntry loadSessionEntry(IndexElement indexElement) {
    Objects.requireNonNull(indexElement);
    EntityDescriptor descriptor = metaModel.getEntityDescriptor(indexElement.getEntityClass());
    HashMap<Relation, Collection<String>> relationIds = new HashMap<>();
    descriptor.getAllRelations().forEach(rel -> relationIds.put(rel, new ArrayList<>()));
    EntityPersister persister = descriptor.getPersister();
    Object object = persister.load(repository, descriptor, indexElement.getPathInRepository(), relationIds);
    SessionEntry sessionEntry = new SessionEntry(object, indexElement.getId(), descriptor.getVersion(object),
            indexElement.getNaturalId(), indexElement.getPathInRepository(), descriptor);
    descriptor.writePathInRepo(object, indexElement.getPathInRepository());

    byte[] md5Sum = indexElement.getMd5Sum();
    sessionEntry.setMd5(md5Sum);//from w  w  w.  j  av  a  2 s  . c o m
    if (md5Sum == null) {
        try (FileInputStream stream = new FileInputStream(indexElement.getPathInRepository().toFile())) {
            sessionEntry.setMd5(DigestUtils.md5(stream));
        } catch (IOException e) {
            log.error("Could not get md5sum from {}", indexElement.getPathInRepository(), e);
        }
    }

    Path rootFolder = descriptor.getFolderGenerator().getFolder(repository, repository.getPath(), object);
    boolean isChild = !rootFolder.equals(sessionEntry.getCompletePath().getParent());
    sessionEntry.setChild(isChild);

    log.trace("Loaded {}", object);
    addToSession(sessionEntry);

    for (Map.Entry<Relation, Collection<String>> entry : relationIds.entrySet()) {
        Relation relation = entry.getKey();
        Collection<String> ids = entry.getValue();
        if (relation.isLazy()) {
            relation.setupLazy(object, ids, this);
        } else {
            List<Object> relatedEntities = ids.stream().sequential().map(this::findById).filter(o -> o != null)
                    .collect(Collectors.toList());
            relation.setRelatedEntities(object, relatedEntities);
        }
    }
    return sessionEntry;
}

From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

/**
 * get immediate children for path/*w  w w  .j a v  a2  s . c  om*/
 * @param path path to content
 */
public RepositoryItem[] getContentChildren(String path) {
    final List<RepositoryItem> retItems = new ArrayList<RepositoryItem>();

    try {
        EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        final String finalPath = path;
        Files.walkFileTree(constructRepoPath(finalPath), opts, 1, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException {

                if (!visitPath.equals(constructRepoPath(finalPath))) {
                    RepositoryItem item = new RepositoryItem();
                    item.name = visitPath.toFile().getName();

                    String visitFolderPath = visitPath.toString();//.replace("/index.xml", "");
                    //Path visitFolder = constructRepoPath(visitFolderPath);
                    item.isFolder = visitPath.toFile().isDirectory();
                    int lastIdx = visitFolderPath.lastIndexOf(File.separator + item.name);
                    if (lastIdx > 0) {
                        item.path = visitFolderPath.substring(0, lastIdx);
                    }
                    //item.path = visitFolderPath.replace("/" + item.name, "");
                    item.path = item.path.replace(getRootPath().replace("/", File.separator), "");
                    item.path = item.path.replace(File.separator + ".xml", "");
                    item.path = item.path.replace(File.separator, "/");

                    if (!".DS_Store".equals(item.name)) {
                        logger.debug("ITEM NAME: {0}", item.name);
                        logger.debug("ITEM PATH: {0}", item.path);
                        logger.debug("ITEM FOLDER: ({0}): {1}", visitFolderPath, item.isFolder);
                        retItems.add(item);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception err) {
        // log this error
    }

    RepositoryItem[] items = new RepositoryItem[retItems.size()];
    items = retItems.toArray(items);
    return items;
}

From source file:com.facebook.buck.util.unarchive.UntarTest.java

@Test
public void extractsFilesWithStrippedPrefix() throws IOException {
    ArchiveFormat format = ArchiveFormat.TAR;

    ImmutableList<Path> expectedPaths = ImmutableList.of(getDestPath("echo.sh"),
            getDestPath("alternative", "Main.java"), getDestPath("alternative", "Link.java"),
            getDestPath("src", "com", "facebook", "buck", "Main.java"));

    ImmutableList.Builder<Path> expectedDirsBuilder = ImmutableList.builder();
    expectedDirsBuilder.add(OUTPUT_SUBDIR);
    expectedDirsBuilder.add(getDestPath("alternative"));
    expectedDirsBuilder.add(getDestPath("src"));
    expectedDirsBuilder.add(getDestPath("src", "com"));
    expectedDirsBuilder.add(getDestPath("src", "com", "facebook"));
    expectedDirsBuilder.add(getDestPath("src", "com", "facebook", "buck"));
    expectedDirsBuilder.add(getDestPath("empty_dir"));
    ImmutableList<Path> expectedDirs = expectedDirsBuilder.build();

    Path archivePath = getTestFilePath(format.getExtension());
    ImmutableSet<Path> unarchivedFiles = format.getUnarchiver().extractArchive(archivePath, filesystem,
            Paths.get("output_dir"), Optional.of(Paths.get("root")),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);

    Assert.assertThat(unarchivedFiles, Matchers.containsInAnyOrder(expectedPaths.toArray()));
    Assert.assertEquals(expectedPaths.size(), unarchivedFiles.size());

    // Make sure we wrote the files
    assertOutputFileExists(expectedPaths.get(0), echoDotSh);
    assertOutputSymlinkExists(expectedPaths.get(1), Paths.get("Link.java"), mainDotJava);
    assertOutputSymlinkExists(expectedPaths.get(2),
            Paths.get("..", "src", "com", "facebook", "buck", "Main.java"), mainDotJava);
    assertOutputFileExists(expectedPaths.get(3), mainDotJava);

    // Make sure we make the dirs
    for (Path dir : expectedDirs) {
        assertOutputDirExists(dir);/*  w  ww.  j a  v  a2  s . c o m*/
        // Dest dir is created by buck, doesn't come from the archive
        if (!dir.equals(OUTPUT_SUBDIR)) {
            assertModifiedTime(dir);
        }
    }

    // Make sure that we set modified time and execute bit properly
    assertModifiedTime(expectedPaths);
    assertExecutable(expectedPaths.get(0), true);
    assertExecutable(expectedPaths.subList(1, expectedPaths.size()), false);

    Path siblingDirPath = getDestPath("root_sibling");
    Path siblingFilePath = getDestPath("root_sibling", "Other.java");
    Path siblingFile2Path = getDestPath("Other.java");
    Assert.assertFalse(String.format("Expected %s to not exist", siblingDirPath), Files.exists(siblingDirPath));
    Assert.assertFalse(String.format("Expected %s to not exist", siblingFilePath),
            Files.exists(siblingFilePath));
    Assert.assertFalse(String.format("Expected %s to not exist", siblingFile2Path),
            Files.exists(siblingFile2Path));
}

From source file:com.facebook.buck.util.unarchive.UntarTest.java

private void extractsFiles(ArchiveFormat format, Optional<Boolean> writeSymlinksLast) throws IOException {
    ImmutableList<Path> expectedPaths = ImmutableList.of(getDestPath("root", "echo.sh"),
            getDestPath("root", "alternative", "Main.java"), getDestPath("root", "alternative", "Link.java"),
            getDestPath("root", "src", "com", "facebook", "buck", "Main.java"),
            getDestPath("root_sibling", "Other.java"));

    ImmutableList.Builder<Path> expectedDirsBuilder = ImmutableList.builder();
    expectedDirsBuilder.add(OUTPUT_SUBDIR);
    expectedDirsBuilder.add(getDestPath("root"));
    expectedDirsBuilder.add(getDestPath("root", "alternative"));
    expectedDirsBuilder.add(getDestPath("root", "src"));
    expectedDirsBuilder.add(getDestPath("root", "src", "com"));
    expectedDirsBuilder.add(getDestPath("root", "src", "com", "facebook"));
    expectedDirsBuilder.add(getDestPath("root", "src", "com", "facebook", "buck"));
    expectedDirsBuilder.add(getDestPath("root_sibling"));
    expectedDirsBuilder.add(getDestPath("root", "empty_dir"));
    ImmutableList<Path> expectedDirs = expectedDirsBuilder.build();

    Path archivePath = getTestFilePath(format.getExtension());
    Untar unarchiver = (Untar) format.getUnarchiver();
    ImmutableSet<Path> unarchivedFiles;
    if (writeSymlinksLast.isPresent()) {
        unarchivedFiles = unarchiver.extractArchive(archivePath, filesystem, Paths.get("output_dir"),
                Optional.empty(), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES, PatternsMatcher.EMPTY,
                writeSymlinksLast.get());
    } else {/*from   w  ww  .j  a v  a  2  s .  co m*/
        unarchivedFiles = unarchiver.extractArchive(archivePath, filesystem, Paths.get("output_dir"),
                Optional.empty(), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    }

    Assert.assertThat(unarchivedFiles, Matchers.containsInAnyOrder(expectedPaths.toArray()));
    Assert.assertEquals(expectedPaths.size(), unarchivedFiles.size());

    // Make sure we wrote the files
    assertOutputFileExists(expectedPaths.get(0), echoDotSh);
    assertOutputSymlinkExists(expectedPaths.get(1), Paths.get("Link.java"), mainDotJava);
    assertOutputSymlinkExists(expectedPaths.get(2),
            Paths.get("..", "src", "com", "facebook", "buck", "Main.java"), mainDotJava);
    assertOutputFileExists(expectedPaths.get(3), mainDotJava);
    assertOutputFileExists(expectedPaths.get(4), otherDotJava);

    // Make sure we make the dirs
    for (Path dir : expectedDirs) {
        assertOutputDirExists(dir);
        // Dest dir is created by buck, doesn't come from the archive
        if (!dir.equals(OUTPUT_SUBDIR)) {
            assertModifiedTime(dir);
        }
    }

    // Make sure that we set modified time and execute bit properly
    assertModifiedTime(expectedPaths);
    assertExecutable(expectedPaths.get(0), true);
    if (tmpFolder.getRoot().getFileSystem().supportedFileAttributeViews().contains("posix")) {
        Path executablePath = tmpFolder.getRoot().resolve(expectedPaths.get(0));
        Assert.assertThat(Files.getPosixFilePermissions(executablePath),
                Matchers.hasItems(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OTHERS_EXECUTE,
                        PosixFilePermission.GROUP_EXECUTE));
    }
    assertExecutable(expectedPaths.subList(1, expectedPaths.size()), false);
}

From source file:org.apache.archiva.admin.mock.ArchivaIndexManagerMock.java

@Override
public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo)
        throws IndexCreationFailedException {
    if (context == null) {
        return null;
    }//ww  w  .j  a  v a2  s.c om
    if (context.supports(IndexingContext.class)) {
        try {
            Path newPath = getIndexPath(repo);
            IndexingContext ctx = context.getBaseContext(IndexingContext.class);
            Path oldPath = ctx.getIndexDirectoryFile().toPath();
            if (oldPath.equals(newPath)) {
                // Nothing to do, if path does not change
                return context;
            }
            if (!Files.exists(oldPath)) {
                return createContext(repo);
            } else if (context.isEmpty()) {
                context.close();
                return createContext(repo);
            } else {
                context.close(false);
                Files.move(oldPath, newPath);
                return createContext(repo);
            }
        } catch (IOException e) {
            log.error("IOException while moving index directory {}", e.getMessage(), e);
            throw new IndexCreationFailedException("Could not recreated the index.", e);
        } catch (UnsupportedBaseContextException e) {
            throw new IndexCreationFailedException("The given context, is not a maven context.");
        }
    } else {
        throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
    }
}

From source file:org.codice.ddf.configuration.admin.ImportMigrationConfigurationAdminContext.java

@Nullable
private Configuration getAndRemoveMemoryFactoryService(String factoryPid, Path exportedConfigPath) {
    final List<Configuration> memoryConfigs = managedServiceFactoriesToDelete.get(factoryPid);

    if (memoryConfigs == null) {
        return null;
    }/*from   w  w w .j av a  2s.c o m*/
    // @formatter:off - to shut up checkstyle!!!!!!!
    for (final Iterator<Configuration> i = memoryConfigs.iterator(); i.hasNext();) {
        // @formatter:on
        final Configuration memoryConfig = i.next();
        final Path memoryConfigPath = getPathFromConfiguration(memoryConfig.getProperties(),
                () -> String.format("configuration '%s'", memoryConfig.getPid()));

        if (exportedConfigPath.equals(memoryConfigPath)) {
            // remove it from memory list and clean the map if it was the last one
            i.remove();
            if (memoryConfigs.isEmpty()) {
                managedServiceFactoriesToDelete.remove(factoryPid);
            }
            return memoryConfig;
        }
    }
    return null;
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

private synchronized boolean isFormatterInSchemaPlugin(Path formatterDir, Path schemaDir) throws IOException {
    final Path canonicalPath = formatterDir.toRealPath();
    Boolean isInSchemaPlugin = this.isFormatterInSchemaPluginMap.get(canonicalPath);
    if (isInSchemaPlugin == null) {
        isInSchemaPlugin = false;/*www  .j  av a 2 s  .co m*/
        Path current = formatterDir;
        while (current.getParent() != null && Files.exists(current.getParent())) {
            if (current.equals(schemaDir)) {
                isInSchemaPlugin = true;
                break;
            }
            current = current.getParent();
        }

        this.isFormatterInSchemaPluginMap.put(canonicalPath, isInSchemaPlugin);
    }
    return isInSchemaPlugin;
}