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:org.apache.gobblin.config.store.zip.ZipFileConfigStore.java

/**
 * Retrieves all the children of the given {@link ConfigKeyPath} using {@link Files#walk} to list files
 *///from ww  w.j ava2s  .  c  o  m
@Override
public Collection<ConfigKeyPath> getChildren(ConfigKeyPath configKey, String version)
        throws VersionDoesNotExistException {
    Preconditions.checkNotNull(configKey, "configKey cannot be null!");
    Preconditions.checkArgument(version.equals(getCurrentVersion()));

    List<ConfigKeyPath> children = new ArrayList<>();
    Path datasetDir = getDatasetDirForKey(configKey);

    try {

        if (!Files.exists(this.fs.getPath(datasetDir.toString()))) {
            return children;
        }

        Stream<Path> files = Files.walk(datasetDir, 1);

        for (Iterator<Path> it = files.iterator(); it.hasNext();) {
            Path path = it.next();

            if (Files.isDirectory(path) && !path.equals(datasetDir)) {
                children.add(configKey
                        .createChild(StringUtils.removeEnd(path.getName(path.getNameCount() - 1).toString(),
                                SingleLinkedListConfigKeyPath.PATH_DELIMETER)));
            }

        }
        return children;
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("Error while getting children for configKey: \"%s\"", configKey), e);
    }
}

From source file:com.ttech.cordovabuild.domain.application.source.ApplicationSourceFactoryImpl.java

private AssetRef getIconAssetRef(Path sourcePath, DomEditor.IconConfig iconConfig) {
    if (iconConfig == null)
        return null;
    Path path = sourcePath.resolve(iconConfig.getSrc()).normalize();
    if (isSubPath(path, sourcePath) && !path.equals(sourcePath)
            && path.getFileName().toString().toLowerCase().endsWith(".png")) {
        try (InputStream fs = new FileInputStream(path.toFile())) {
            if (iconConfig.getHeight() != null || iconConfig.getWidth() != null) {
                BufferedImage bufferedImage = ImageIO.read(fs);
                bufferedImage = scaleTo(bufferedImage, iconConfig.getHeight(), iconConfig.getWidth());
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "png", outputStream);
                return assetService.save(new ByteArrayInputStream(outputStream.toByteArray()), "image/png");
            } else
                return assetService.save(fs, "image/png");
        } catch (IOException e) {
            LOGGER.warn("image file cannot be read");
        }/*from   w w w.j a  va2 s  .c o  m*/
    }
    return null;
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemPath.java

Deque<Path> getPathSegments() {
    Deque<Path> paths = new ArrayDeque<>();
    Path root = getRoot();//from w w w. j a v a  2  s.  c o m
    Path p = this;
    while (p != null && !p.equals(root)) {
        paths.push(p.getFileName());
        p = p.getParent();
    }
    return paths;
}

From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java

/**
 * Starts up monitoring of the configuration for changes.
 *//*w  w w  .  j  ava  2 s.  c  om*/
private void monitorForChanges() {
    if (monitorRunning) {
        return;
    }

    final Path path = Paths.get(configPath);
    if (!path.toFile().exists()) {
        LOGGER.debug("Configuration {} does not exist, disabling monitoring", configPath);
        return;
    }
    final Path directoryPath = path.getParent();

    try {
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        directoryPath.register(watchService, ENTRY_MODIFY);

        monitorThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (;;) {
                        WatchKey key;
                        try {
                            key = watchService.take();
                        } catch (final InterruptedException e) {
                            LOGGER.debug("Interrupted the configuration monitor thread.");
                            break;
                        }

                        for (final WatchEvent<?> event : key.pollEvents()) {
                            final WatchEvent.Kind<?> kind = event.kind();
                            if (kind == OVERFLOW) {
                                continue;
                            }

                            // If the configuration file triggered this event, reload it
                            final Path changed = (Path) event.context();
                            if (changed.equals(path.getFileName())) {
                                LOGGER.info("Configuration {} has been updated, reloading.", path);
                                try {
                                    loadConfiguration();
                                } catch (final IOException e) {
                                    LOGGER.error("Failed to reload configuration {}", configPath, e);
                                }
                            }

                            // reset the key
                            final boolean valid = key.reset();
                            if (!valid) {
                                LOGGER.debug("Monitor of {} is no longer valid", path);
                                break;
                            }
                        }
                    }
                } finally {
                    try {
                        watchService.close();
                    } catch (final IOException e) {
                        LOGGER.error("Failed to stop configuration monitor", e);
                    }
                }
                monitorRunning = false;
            }
        });
    } catch (final IOException e) {
        LOGGER.error("Failed to start configuration monitor", e);
    }

    monitorThread.start();
    monitorRunning = true;
}

From source file:org.schedulesdirect.grabber.Auditor.java

private Map<String, JSONObject> getStationMap() throws IOException, JSONException {
    final Map<String, JSONObject> map = new HashMap<>();
    final Path maps = vfs.getPath("maps");
    if (Files.isDirectory(maps)) {
        Files.walkFileTree(maps, new FileVisitor<Path>() {

            @Override/*from w w  w .  j a  va  2  s .  c om*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return dir.equals(maps) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String input;
                try (InputStream ins = Files.newInputStream(file)) {
                    input = IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString());
                }
                ObjectMapper mapper = Config.get().getObjectMapper();
                JSONArray jarr = mapper.readValue(
                        mapper.readValue(input, JSONObject.class).getJSONArray("stations").toString(),
                        JSONArray.class);
                for (int i = 0; i < jarr.length(); ++i) {
                    JSONObject jobj = jarr.getJSONObject(i);
                    String id = jobj.getString("stationID");
                    if (!map.containsKey(id))
                        map.put(id, jobj);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOG.error(String.format("Unable to process map file '%s'", file), exc);
                Auditor.this.failed = true;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    }
    return map;
}

From source file:org.geowebcache.sqlite.OperationsRestTest.java

private void zipDirectory(Path directoryToZip, File outputZipFile) throws IOException {
    try (FileOutputStream fileOutputStream = new FileOutputStream(outputZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        Files.walkFileTree(directoryToZip, new SimpleFileVisitor<Path>() {

            public FileVisitResult visitFile(Path file, BasicFileAttributes fileAttributes) throws IOException {
                zipOutputStream.putNextEntry(new ZipEntry(directoryToZip.relativize(file).toString()));
                Files.copy(file, zipOutputStream);
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }//  ww w .j  a v a  2s.  co  m

            public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
                    throws IOException {
                if (directory.equals(directoryToZip)) {
                    return FileVisitResult.CONTINUE;
                }
                // the zip structure is not tied the OS file separator
                zipOutputStream
                        .putNextEntry(new ZipEntry(directoryToZip.relativize(directory).toString() + "/"));
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:org.schedulesdirect.grabber.Auditor.java

private void auditScheds() throws IOException, JSONException, ParseException {
    final Map<String, JSONObject> stations = getStationMap();
    final SimpleDateFormat FMT = Config.get().getDateTimeFormat();
    final Path scheds = vfs.getPath("schedules");
    if (Files.isDirectory(scheds)) {
        Files.walkFileTree(scheds, new FileVisitor<Path>() {

            @Override/*from  w  w w . j a  va 2 s . c o m*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return dir.equals(scheds) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                boolean failed = false;
                String id = getStationIdFromFileName(file.getFileName().toString());
                JSONObject station = stations.get(id);
                StringBuilder msg = new StringBuilder(String.format("Inspecting %s (%s)... ",
                        station != null ? station.getString("callsign") : String.format("[UNKNOWN: %s]", id),
                        id));
                String input;
                try (InputStream ins = Files.newInputStream(file)) {
                    input = IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString());
                }
                ObjectMapper mapper = Config.get().getObjectMapper();
                JSONArray jarr = mapper.readValue(
                        mapper.readValue(input, JSONObject.class).getJSONArray("programs").toString(),
                        JSONArray.class);
                for (int i = 1; i < jarr.length(); ++i) {
                    long start, prevStart;
                    JSONObject prev;
                    try {
                        start = FMT.parse(jarr.getJSONObject(i).getString("airDateTime")).getTime();
                        prev = jarr.getJSONObject(i - 1);
                        prevStart = FMT.parse(prev.getString("airDateTime")).getTime()
                                + 1000L * prev.getLong("duration");
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    if (prevStart != start) {
                        msg.append(String.format("FAILED! [%s]", prev.getString("airDateTime")));
                        LOG.error(msg);
                        failed = true;
                        Auditor.this.failed = true;
                        break;
                    }
                }
                if (!failed) {
                    msg.append("PASSED!");
                    LOG.info(msg);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOG.error(String.format("Unable to process schedule file '%s'", file), exc);
                Auditor.this.failed = true;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    }
}

From source file:de.thomasbolz.renamer.Renamer.java

/**
 * Step 2 of the renaming process:/* w w  w  .j a  v  a 2  s  .  c  o m*/
 * Executes the list of CopyTasks.
 */
public void executeCopyTasks() {
    log.info("Start executing CopyTasks");
    for (Path dir : copyTasks.keySet()) {
        Path targetDir = target.resolve(source.relativize(dir));
        try {
            if (!dir.equals(source)) {
                Files.copy(dir, targetDir);
            }
        } catch (FileAlreadyExistsException e) {
            log.error("Directory already exists " + targetDir, e);
        } catch (IOException e) {
            log.error("IO Exception while trying to create directory " + targetDir, e);
        }
        for (CopyTask task : copyTasks.get(dir)) {
            try {
                //                    updateCurrentCopyTask(task);
                Files.copy(task.getSourceFile(), task.getTargetFile());
            } catch (FileAlreadyExistsException e) {
                log.info("File already exists " + task.getTargetFile());
            } catch (IOException e) {
                log.error("IO Exception while trying to execute CopyTask " + task, e);
            }
        }
    }
    log.info("Finished executing CopyTasks");
}

From source file:org.fcrepo.http.api.ExternalContentPathValidator.java

/**
 * Starts up monitoring of the allowed list configuration for changes.
 *///from  w w w  .j  a v  a2  s .c o  m
private void monitorForChanges() {
    if (monitorRunning) {
        return;
    }

    final Path path = Paths.get(configPath);
    if (!path.toFile().exists()) {
        LOGGER.debug("Allow list configuration {} does not exist, disabling monitoring", configPath);
        return;
    }
    final Path directoryPath = path.getParent();

    try {
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        directoryPath.register(watchService, ENTRY_MODIFY);

        monitorThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (;;) {
                        WatchKey key;
                        try {
                            key = watchService.take();
                        } catch (final InterruptedException e) {
                            LOGGER.debug("Interrupted the configuration monitor thread.");
                            break;
                        }

                        for (final WatchEvent<?> event : key.pollEvents()) {
                            final WatchEvent.Kind<?> kind = event.kind();
                            if (kind == OVERFLOW) {
                                continue;
                            }

                            // If the configuration file triggered this event, reload it
                            final Path changed = (Path) event.context();
                            if (changed.equals(path.getFileName())) {
                                LOGGER.info("External binary configuration {} has been updated, reloading.",
                                        path);
                                try {
                                    loadAllowedPaths();
                                } catch (final IOException e) {
                                    LOGGER.error("Failed to reload external locations configuration", e);
                                }
                            }

                            // reset the key
                            final boolean valid = key.reset();
                            if (!valid) {
                                LOGGER.debug("Monitor of {} is no longer valid", path);
                                break;
                            }
                        }
                    }
                } finally {
                    try {
                        watchService.close();
                    } catch (final IOException e) {
                        LOGGER.error("Failed to stop configuration monitor", e);
                    }
                }
                monitorRunning = false;
            }
        });
    } catch (final IOException e) {
        LOGGER.error("Failed to start configuration monitor", e);
    }

    monitorThread.start();
    monitorRunning = true;
}

From source file:org.tinymediamanager.core.MediaEntityImageFetcherTask.java

@Override
public void run() {
    long timestamp = System.currentTimeMillis(); // multi episode same file
    try {/* w ww. jav  a 2  s . c om*/
        if (StringUtils.isBlank(filename)) {
            return;
        }

        // don't write jpeg -> write jpg
        if (FilenameUtils.getExtension(filename).equalsIgnoreCase("JPEG")) {
            filename = FilenameUtils.getBaseName(filename) + ".jpg";
        }

        String oldFilename = null;
        try {
            // store old filename at the first image
            if (firstImage) {
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    oldFilename = entity.getArtworkFilename(MediaFileType.getMediaFileType(type));
                    entity.removeAllMediaFiles(MediaFileType.getMediaFileType(type));
                    break;

                default:
                    return;
                }
            }

            // debug message
            LOGGER.debug("writing " + type + " " + filename);
            Path destFile = entity.getPathNIO().resolve(filename);
            Path tempFile = entity.getPathNIO().resolve(filename + "." + timestamp + ".part"); // multi episode same file

            // check if old and new file are the same (possible if you select it in the imagechooser)
            boolean sameFile = false;
            if (url.startsWith("file:")) {
                String newUrl = url.replace("file:/", "");
                Path file = Paths.get(newUrl);
                if (file.equals(destFile)) {
                    sameFile = true;
                }
            }

            // fetch and store images
            if (!sameFile) {
                Url url1 = new Url(url);
                FileOutputStream outputStream = new FileOutputStream(tempFile.toFile());
                InputStream is = url1.getInputStream();
                IOUtils.copy(is, outputStream);
                outputStream.flush();
                try {
                    outputStream.getFD().sync(); // wait until file has been completely written
                    // give it a few milliseconds
                    Thread.sleep(150);
                } catch (Exception e) {
                    // empty here -> just not let the thread crash
                }
                outputStream.close();
                is.close();

                // check if the file has been downloaded
                if (!Files.exists(tempFile) || Files.size(tempFile) == 0) {
                    throw new Exception("0byte file downloaded: " + filename);
                }

                // delete the old one if exisiting
                if (StringUtils.isNotBlank(oldFilename)) {
                    Path oldFile = entity.getPathNIO().resolve(oldFilename);
                    Utils.deleteFileSafely(oldFile);
                }

                // delete new destination if existing
                Utils.deleteFileSafely(destFile);

                // move the temp file to the expected filename
                if (!Utils.moveFileSafe(tempFile, destFile)) {
                    throw new Exception("renaming temp file failed: " + filename);
                }
            }

            // has tmm been shut down?
            if (Thread.interrupted()) {
                return;
            }

            // set the new image if its the first image
            if (firstImage) {
                LOGGER.debug("set " + type + " " + FilenameUtils.getName(filename));
                ImageCache.invalidateCachedImage(entity.getPathNIO().resolve(filename));
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    entity.setArtwork(destFile, MediaFileType.getMediaFileType(type));
                    entity.callbackForWrittenArtwork(type);
                    entity.saveToDb();
                    break;

                default:
                    return;
                }
            }
        }

        catch (Exception e) {
            if (e instanceof InterruptedException) {
                // only warning
                LOGGER.warn("interrupted image download");
            } else {
                LOGGER.error("fetch image", e);
            }

            // remove temp file
            Path tempFile = entity.getPathNIO().resolve(filename + "." + timestamp + ".part"); // multi episode same file
            if (Files.exists(tempFile)) {
                Utils.deleteFileSafely(tempFile);
            }

            // fallback
            if (firstImage && StringUtils.isNotBlank(oldFilename)) {
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    entity.setArtwork(Paths.get(oldFilename), MediaFileType.getMediaFileType(type));
                    entity.callbackForWrittenArtwork(type);
                    entity.saveToDb();
                    break;

                default:
                    return;
                }
            }

            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, "ArtworkDownload",
                    "message.artwork.threadcrashed", new String[] { ":", e.getLocalizedMessage() }));
        }

    } catch (Exception e) {
        LOGGER.error("crashed thread: ", e);
    }
}