Example usage for java.nio.file Path resolveSibling

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

Introduction

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

Prototype

default Path resolveSibling(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this path's #getParent parent path in exactly the manner specified by the #resolveSibling(Path) resolveSibling method.

Usage

From source file:org.sonar.xoo.rule.AnalysisErrorSensor.java

private void processFileError(InputFile inputFile, SensorContext context) {
    Path ioFile = inputFile.file().toPath();
    Path errorFile = ioFile.resolveSibling(ioFile.getFileName() + ERROR_EXTENSION).toAbsolutePath();
    if (Files.exists(errorFile) && Files.isRegularFile(errorFile)) {
        LOG.debug("Processing " + errorFile.toString());
        try {/*from  www  . ja  va  2s  . com*/
            List<String> lines = Files.readAllLines(errorFile, context.fileSystem().encoding());
            for (String line : lines) {
                if (StringUtils.isBlank(line) || line.startsWith("#")) {
                    continue;
                }
                processLine(line, inputFile, context);
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:org.tinymediamanager.core.movie.MovieRenamer.java

private static void renameSubtitles(Movie m) {
    // build language lists
    Set<String> langArray = LanguageUtils.KEY_TO_LOCALE_MAP.keySet();

    for (MediaFile sub : m.getMediaFiles(MediaFileType.SUBTITLE)) {
        String originalLang = "";
        String lang = "";
        String forced = "";
        List<MediaFileSubtitle> mfsl = sub.getSubtitles();

        if (mfsl != null && mfsl.size() > 0) {
            // use internal values
            MediaFileSubtitle mfs = mfsl.get(0);
            originalLang = mfs.getLanguage();
            if (mfs.isForced()) {
                forced = ".forced";
            }// w  w w . ja  va2 s  .  com
        } else {
            // detect from filename, if we don't have a MediaFileSubtitle entry!
            // remove the filename of movie from subtitle, to ease parsing
            List<MediaFile> mfs = m.getMediaFiles(MediaFileType.VIDEO);
            String shortname = sub.getBasename().toLowerCase(Locale.ROOT);
            if (mfs != null && mfs.size() > 0) {
                shortname = sub.getBasename().toLowerCase(Locale.ROOT)
                        .replace(m.getVideoBasenameWithoutStacking(), "");
            }

            if (sub.getFilename().toLowerCase(Locale.ROOT).contains("forced")) {
                // add "forced" prior language
                forced = ".forced";
                shortname = shortname.replaceAll("\\p{Punct}*forced", "");
            }
            // shortname = shortname.replaceAll("\\p{Punct}", "").trim(); // NEVER EVER!!!

            for (String s : langArray) {
                if (shortname.equalsIgnoreCase(s) || shortname.matches("(?i).*[ _.-]+" + s + "$")) {
                    originalLang = s;
                    // lang = Utils.getIso3LanguageFromLocalizedString(s);
                    // LOGGER.debug("found language '" + s + "' in subtitle; displaying it as '" + lang + "'");
                    break;
                }
            }
        }

        lang = LanguageStyle.getLanguageCodeForStyle(originalLang,
                MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerLanguageStyle());
        if (StringUtils.isBlank(lang)) {
            lang = originalLang;
        }

        // rebuild new filename
        String newSubName = "";

        if (sub.getStacking() == 0) {
            // fine, so match to first movie file
            MediaFile mf = m.getMediaFiles(MediaFileType.VIDEO).get(0);
            newSubName = mf.getBasename();
            if (!lang.isEmpty()) {
                newSubName += "." + lang;
            }
            newSubName += forced;
        } else {
            // with stacking info; try to match
            for (MediaFile mf : m.getMediaFiles(MediaFileType.VIDEO)) {
                if (mf.getStacking() == sub.getStacking()) {
                    newSubName = mf.getBasename();
                    if (!lang.isEmpty()) {
                        newSubName += "." + lang;
                    }
                    newSubName += forced;
                }
            }
        }
        newSubName += "." + sub.getExtension();

        Path newFile = m.getPathNIO().resolve(newSubName);
        try {
            boolean ok = Utils.moveFileSafe(sub.getFileAsPath(), newFile);
            if (ok) {
                if (sub.getFilename().endsWith(".sub")) {
                    // when having a .sub, also rename .idx (don't care if error)
                    try {
                        Path oldidx = sub.getFileAsPath()
                                .resolveSibling(sub.getFilename().toString().replaceFirst("sub$", "idx"));
                        Path newidx = newFile
                                .resolveSibling(newFile.getFileName().toString().replaceFirst("sub$", "idx"));
                        Utils.moveFileSafe(oldidx, newidx);
                    } catch (Exception e) {
                        // no idx found or error - ignore
                    }
                }
                m.removeFromMediaFiles(sub);
                MediaFile mf = new MediaFile(newFile);
                MediaFileSubtitle mfs = new MediaFileSubtitle();
                if (!lang.isEmpty()) {
                    mfs.setLanguage(lang);
                }
                if (!forced.isEmpty()) {
                    mfs.setForced(true);
                }
                mfs.setCodec(sub.getExtension());
                mf.setContainerFormat(sub.getExtension()); // set containerformat, so mediainfo deos not overwrite our new array
                mf.addSubtitle(mfs);
                m.addToMediaFiles(mf);
            } else {
                MessageManager.instance.pushMessage(
                        new Message(MessageLevel.ERROR, sub.getFilename(), "message.renamer.failedrename"));
            }
        } catch (Exception e) {
            LOGGER.error("error moving subtitles", e);
            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, sub.getFilename(),
                    "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
        }
    } // end MF loop
    m.saveToDb();
}

From source file:org.tinymediamanager.core.tvshow.TvShowRenamer.java

/**
 * Renames a MediaFiles<br>//  w  w  w .j ava2 s .co m
 * gets all episodes of it, creates season folder, updates MFs & DB
 * 
 * @param mf
 *          the MediaFile
 * @param show
 *          the tvshow (only needed for path)
 */
public static void renameMediaFile(MediaFile mf, TvShow show) {
    // #######################################################
    // Assumption: all multi-episodes share the same season!!!
    // #######################################################

    List<TvShowEpisode> eps = TvShowList.getInstance().getTvEpisodesByFile(show, mf.getFile());
    if (eps == null || eps.size() == 0) {
        // FIXME: workaround for r1972
        // when moving video file, all NFOs get deleted and a new gets created.
        // so this OLD NFO is not found anylonger - just delete it
        if (mf.getType() == MediaFileType.NFO) {
            Utils.deleteFileSafely(mf.getFileAsPath());
            return;
        }

        LOGGER.warn("No episodes found for file '" + mf.getFilename() + "' - skipping");
        return;
    }

    // get first, for isDisc and season
    TvShowEpisode ep = eps.get(0);

    // test access rights or return
    LOGGER.debug("testing file S:" + ep.getSeason() + " E:" + ep.getEpisode() + " MF:"
            + mf.getFile().getAbsolutePath());
    File f = mf.getFile();
    boolean testRenameOk = false;
    for (int i = 0; i < 5; i++) {
        testRenameOk = f.renameTo(f); // haahaa, try to rename to itself :P
        if (testRenameOk) {
            break; // ok it worked, step out
        }
        try {
            if (!f.exists()) {
                LOGGER.debug("Hmmm... file " + f + " does not even exists; delete from DB");
                // delete from MF
                for (TvShowEpisode e : eps) {
                    e.removeFromMediaFiles(mf);
                    e.saveToDb();
                }
                return;
            }
            LOGGER.debug("rename did not work - sleep a while and try again...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOGGER.warn("I'm so excited - could not sleep");
        }
    }
    if (!testRenameOk) {
        LOGGER.warn("File " + mf.getFileAsPath() + " is not accessible!");
        MessageManager.instance
                .pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(), "message.renamer.failedrename"));
        return;
    }

    // create SeasonDir
    // String seasonName = "Season " + String.valueOf(ep.getSeason());
    String seasonName = generateSeasonDir(SETTINGS.getRenamerSeasonFoldername(), ep);
    Path seasonDir = show.getPathNIO();
    if (StringUtils.isNotBlank(seasonName)) {
        seasonDir = show.getPathNIO().resolve(seasonName);
        if (!Files.exists(seasonDir)) {
            try {
                Files.createDirectory(seasonDir);
            } catch (IOException e) {
            }
        }
    }

    // rename epFolder accordingly
    if (ep.isDisc() || mf.isDiscFile()) {
        // \Season 1\S01E02E03\VIDEO_TS\VIDEO_TS.VOB
        // ........ \epFolder \disc... \ file
        Path disc = mf.getFileAsPath().getParent();
        Path epFolder = disc.getParent();

        // sanity check
        if (!disc.getFileName().toString().equalsIgnoreCase("BDMV")
                && !disc.getFileName().toString().equalsIgnoreCase("VIDEO_TS")) {
            LOGGER.error(
                    "Episode is labeled as 'on BD/DVD', but structure seems not to match. Better exit and do nothing... o_O");
            return;
        }

        String newFoldername = FilenameUtils.getBaseName(generateFolderename(show, mf)); // w/o extension
        if (newFoldername != null && !newFoldername.isEmpty()) {
            Path newEpFolder = seasonDir.resolve(newFoldername);
            Path newDisc = newEpFolder.resolve(disc.getFileName()); // old disc name

            try {
                // if (!epFolder.equals(newEpFolder)) {
                if (!epFolder.toAbsolutePath().toString().equals(newEpFolder.toAbsolutePath().toString())) {
                    boolean ok = false;
                    try {
                        // create parent if needed
                        if (!Files.exists(newEpFolder.getParent())) {
                            Files.createDirectory(newEpFolder.getParent());
                        }
                        ok = Utils.moveDirectorySafe(epFolder, newEpFolder);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage());
                        MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, epFolder,
                                "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
                    }
                    if (ok) {
                        // iterate over all EPs & MFs and fix new path
                        LOGGER.debug("updating *all* MFs for new path -> " + newEpFolder);
                        for (TvShowEpisode e : eps) {
                            e.updateMediaFilePath(disc, newDisc);
                            e.setPath(newEpFolder.toAbsolutePath().toString());
                            e.saveToDb();
                        }
                    }
                    // and cleanup
                    cleanEmptyDir(epFolder);
                } else {
                    // old and new folder are equal, do nothing
                }
            } catch (Exception e) {
                LOGGER.error("error moving video file " + disc + " to " + newFoldername, e);
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(),
                        "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
            }
        }
    } // end isDisc
    else {
        MediaFile newMF = new MediaFile(mf); // clone MF
        if (mf.getType().equals(MediaFileType.TRAILER)) {
            // move trailer into separate dir - not supported by XBMC
            Path sample = seasonDir.resolve("sample");
            if (!Files.exists(sample)) {
                try {
                    Files.createDirectory(sample);
                } catch (IOException e) {
                }
            }
            seasonDir = sample; // change directory storage
        }
        String filename = generateFilename(show, mf);
        LOGGER.debug("new filename should be " + filename);
        if (StringUtils.isNotBlank(filename)) {
            Path newFile = seasonDir.resolve(filename);

            try {
                // if (!mf.getFile().equals(newFile)) {
                if (!mf.getFileAsPath().toString().equals(newFile.toString())) {
                    Path oldMfFile = mf.getFileAsPath();
                    boolean ok = false;
                    try {
                        // create parent if needed
                        if (!Files.exists(newFile.getParent())) {
                            Files.createDirectory(newFile.getParent());
                        }
                        ok = Utils.moveFileSafe(oldMfFile, newFile);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage());
                        MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, oldMfFile,
                                "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
                    }
                    if (ok) {
                        if (mf.getFilename().endsWith(".sub")) {
                            // when having a .sub, also rename .idx (don't care if error)
                            try {
                                Path oldidx = mf.getFileAsPath().resolveSibling(
                                        mf.getFilename().toString().replaceFirst("sub$", "idx"));
                                Path newidx = newFile.resolveSibling(
                                        newFile.getFileName().toString().replaceFirst("sub$", "idx"));
                                Utils.moveFileSafe(oldidx, newidx);
                            } catch (Exception e) {
                                // no idx found or error - ignore
                            }
                        }
                        newMF.setPath(seasonDir.toString());
                        newMF.setFilename(filename);
                        // iterate over all EPs and delete old / set new MF
                        for (TvShowEpisode e : eps) {
                            e.removeFromMediaFiles(mf);
                            e.addToMediaFiles(newMF);
                            e.setPath(seasonDir.toString());
                            e.saveToDb();
                        }
                    }
                    // and cleanup
                    cleanEmptyDir(oldMfFile.getParent());
                } else {
                    // old and new file are equal, keep MF
                }
            } catch (Exception e) {
                LOGGER.error("error moving video file " + mf.getFilename() + " to " + newFile, e);
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(),
                        "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
            }
        }
    }
}

From source file:org.wurtele.ifttt.watchers.TrainingScheduleWatcher.java

private Path processedPath(Path path) {
    return path.resolveSibling(FilenameUtils.getBaseName(path.getFileName().toString()).concat(".data"));
}

From source file:org.wurtele.ifttt.watchers.WorkTimesWatcher.java

public WorkTimesWatcher(Path path) throws IOException {
    super(path);/*from  w ww.ja  v  a 2s.c  o  m*/
    this.output = path.resolveSibling(OUTPUT_FILENAME);
}

From source file:pm.filemanager.operations.FileOperations.java

/**
 * boolean function RenameAFile/*from  w w w .ja  va 2s  .  c  o  m*/
 * @param path String
 * @param nameOfFile String
 */
public static void renameFile(String path, String nameOfFile) {

    Path source = Paths.get(path);
    try {
        Files.move(source, source.resolveSibling(nameOfFile));
    } catch (IOException ex) {
        Logger.getLogger(RenameCommand.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:uk.co.unclealex.executable.impl.MakeLinksCommandRunnerTest.java

protected Path copy(String testCase, String directoryName) throws IOException {
    Path sourceDir = rootDir.resolve(testCase).resolve(directoryName);
    Path target = tmpDir.resolve(directoryName);
    Files.createDirectories(target);
    if (Files.exists(sourceDir)) {
        FileUtils.copyDirectory(sourceDir.toFile(), target.toFile());
        FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
            @Override/*from ww w  .  ja  va  2s .com*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = file.getFileName().toString();
                for (Entry<String, Path> entry : symlinksByName.entrySet()) {
                    String suffix = entry.getKey();
                    Path symlink = entry.getValue();
                    if (name.endsWith(suffix)) {
                        Files.delete(file);
                        String newName = name.substring(0, name.length() - suffix.length());
                        Files.createSymbolicLink(file.resolveSibling(newName), symlink);
                        return FileVisitResult.CONTINUE;
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(target, visitor);
    }
    return target;
}