List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:com.kappaware.logtrawler.MFile.java
public void setPath(Path path) { this.path = path.toAbsolutePath().normalize(); }
From source file:misc.FileHandler.java
/** * Copies the source file with the given options to the target file. The * source is first copied to the system's default temporary directory and * the temporary copy is then moved to the target file. In order to avoid * performance problems, the file is directly copied from the source to a * temporary file in the target directory first, if the temporary directory * and the target file lie on a different <code>FileStore</code>. The * temporary file is also moved to the target file. * //from ww w.j a va 2s . c o m * @param source * the file to copy. * @param target * the target location where the file should be stored. Must not * be identical with source. The file might or might not exist. * The parent directory must exist. * @param replaceExisting * <code>true</code>, if the target file may be overwritten. * Otherwise, <code>false</code>. * @return <code>true</code>, if the file was successfully copied. * Otherwise, <code>false</code>. */ public static boolean copyFile(Path source, Path target, boolean replaceExisting) { if ((source == null) || !Files.isReadable(source)) { throw new IllegalArgumentException("source must exist and be readable!"); } if (target == null) { throw new IllegalArgumentException("target may not be null!"); } if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) { throw new IllegalArgumentException("source and target must not match!"); } boolean success = false; Path tempFile = null; target = target.normalize(); try { tempFile = FileHandler.getTempFile(target); if (tempFile != null) { Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); if (replaceExisting) { Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); } else { Files.move(tempFile, target); } success = true; } } catch (IOException e) { Logger.logError(e); } finally { if (tempFile != null) { try { Files.deleteIfExists(tempFile); } catch (IOException eDelete) { Logger.logError(eDelete); } } } return success; }
From source file:com.github.blindpirate.gogradle.crossplatform.DefaultGoBinaryManager.java
private Optional<Pair<Path, String>> tryInvokeGoVersion(Path executablePath) { try {// w w w. ja va2 s . c o m Process process = processUtils.run(executablePath.toAbsolutePath().toString(), "version"); ProcessResult result = processUtils.getResult(process); Matcher m = GO_VERSION_OUTPUT_REGEX.matcher(result.getStdout()); if (m.find()) { Pair binaryPathAndVersion = Pair.of(executablePath, m.group(1)); return Optional.of(binaryPathAndVersion); } else { return Optional.empty(); } } catch (Exception e) { LOGGER.debug("Encountered exception when running go version via: " + executablePath.toAbsolutePath(), e); return Optional.empty(); } }
From source file:org.tinymediamanager.UpgradeTasks.java
/** * performs some upgrade tasks from one version to another<br> * <b>make sure, this upgrade can run multiple times (= needed for nightlies!!!) * /*from ww w .ja v a 2 s . c om*/ * @param oldVersion * our current version */ public static void performUpgradeTasksAfterDatabaseLoading(String oldVersion) { MovieList movieList = MovieList.getInstance(); TvShowList tvShowList = TvShowList.getInstance(); String v = "" + oldVersion; if (StringUtils.isBlank(v)) { v = "2.6.9"; // set version for other updates } // **************************************************** // PLEASE MAKE THIS TO RUN MULTIPLE TIMES WITHOUT ERROR // NEEDED FOR NIGHTLY SNAPSHOTS ET ALL // SVN BUILD IS ALSO CONSIDERED AS LOWER !!! // **************************************************** // upgrade to v2.7 if (StrgUtils.compareVersion(v, "2.7") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.7"); // delete tmm.odb; objectdb.conf; log dir FileUtils.deleteQuietly(new File("tmm.odb")); FileUtils.deleteQuietly(new File("tmm.odb$")); FileUtils.deleteQuietly(new File("objectdb.conf")); FileUtils.deleteQuietly(new File("log")); Globals.settings.removeSubtitleFileType(".idx"); // aww, we never removed... // We do not migrate settings! // We cannot determine, if a user has unset a value, or the default changed! // So reSet some default values, but ONLY for release ONCE; // else every start of prerel/nightly would reset this over and over again if (ReleaseInfo.isReleaseBuild()) { MovieModuleManager.MOVIE_SETTINGS.setImageBanner(true); MovieModuleManager.MOVIE_SETTINGS.setImageLogo(true); MovieModuleManager.MOVIE_SETTINGS.setImageClearart(true); MovieModuleManager.MOVIE_SETTINGS.setImageDiscart(true); MovieModuleManager.MOVIE_SETTINGS.setImageThumb(true); MovieModuleManager.MOVIE_SETTINGS.setUseTrailerPreference(true); Globals.settings.writeDefaultSettings(); // activate default plugins } } // upgrade to v2.7.2 if (StrgUtils.compareVersion(v, "2.7.2") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.7.2"); // we forgot to update the actor thumbs in DB for (Movie movie : movieList.getMovies()) { boolean dirty = false; for (MovieActor actor : movie.getActors()) { if (StringUtils.isNotBlank(actor.getThumbPath())) { if (actor.updateThumbRoot(movie.getPath())) { // true when changed dirty = true; } } } if (dirty) { movie.saveToDb(); } } } // upgrade to v2.7.3 if (StrgUtils.compareVersion(v, "2.7.3") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.7.3"); // get movie set artwork for (MovieSet movieSet : movieList.getMovieSetList()) { MovieSetArtworkHelper.updateArtwork(movieSet); movieSet.saveToDb(); } // reset new indicator for (Movie movie : movieList.getMovies()) { movie.setNewlyAdded(false); movie.saveToDb(); } for (TvShow tvShow : tvShowList.getTvShows()) { for (TvShowEpisode episode : tvShow.getEpisodes()) { episode.setNewlyAdded(false); episode.saveToDb(); } tvShow.saveToDb(); } } // upgrade to v2.8 if (StrgUtils.compareVersion(v, "2.8") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.8"); // upgrade certification settings // if MP NFO style is chosen, set the certification style to TECHNICAL if (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector() == MovieConnectors.MP) { MovieModuleManager.MOVIE_SETTINGS.setMovieCertificationStyle(CertificationStyle.TECHNICAL); } // reevaluate movie stacking and offline stubs (without the need for UDS) and save for (Movie movie : movieList.getMovies()) { movie.reEvaluateStacking(); boolean isOffline = false; for (MediaFile mf : movie.getMediaFiles(MediaFileType.VIDEO)) { if ("disc".equalsIgnoreCase(mf.getExtension())) { isOffline = true; } } movie.setOffline(isOffline); movie.saveToDb(); } } // upgrade to v2.8.2 if (StrgUtils.compareVersion(v, "2.8.2") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.8.2"); Date initialDate = new Date(0); for (Movie movie : movieList.getMovies()) { if (movie.getReleaseDate() != null && DateUtils.isSameDay(initialDate, movie.getReleaseDate())) { movie.setReleaseDate((Date) null); movie.saveToDb(); } } for (TvShow tvShow : tvShowList.getTvShows()) { if (tvShow.getFirstAired() != null && DateUtils.isSameDay(initialDate, tvShow.getFirstAired())) { tvShow.setFirstAired((Date) null); tvShow.saveToDb(); } for (TvShowEpisode episode : tvShow.getEpisodes()) { if (episode.getFirstAired() != null && DateUtils.isSameDay(initialDate, episode.getFirstAired())) { episode.setFirstAired((Date) null); episode.saveToDb(); } } } } // upgrade to v2.8.3 if (StrgUtils.compareVersion(v, "2.8.3") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.8.3"); // reset "container format" for MFs, so that MI tries them again on next UDS (ISOs and others) // (but only if we do not have some video information yet, like "width") for (Movie movie : movieList.getMovies()) { boolean changed = false; for (MediaFile mf : movie.getMediaFiles(MediaFileType.VIDEO)) { if (mf.getVideoResolution().isEmpty()) { mf.setContainerFormat(""); changed = true; } } if (changed) { movie.saveToDb(); } } for (TvShow tvShow : tvShowList.getTvShows()) { for (TvShowEpisode episode : tvShow.getEpisodes()) { boolean changed = false; for (MediaFile mf : episode.getMediaFiles(MediaFileType.VIDEO)) { if (mf.getVideoResolution().isEmpty()) { mf.setContainerFormat(""); changed = true; } } if (episode.isDisc()) { // correct episode path when extracted disc folder Path discRoot = episode.getPathNIO().toAbsolutePath(); // folder String folder = tvShow.getPathNIO().relativize(discRoot).toString() .toUpperCase(Locale.ROOT); // relative while (folder.contains("BDMV") || folder.contains("VIDEO_TS")) { discRoot = discRoot.getParent(); folder = tvShow.getPathNIO().relativize(discRoot).toString().toUpperCase(Locale.ROOT); // reevaluate episode.setPath(discRoot.toAbsolutePath().toString()); changed = true; } } if (changed) { episode.saveToDb(); } } } } // upgrade to v2.9 if (StrgUtils.compareVersion(v, "2.9") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.9"); // Update actors to current structure; add entitiy root and cleanout actor path for (Movie movie : movieList.getMovies()) { boolean changed = false; for (MovieActor a : movie.getActors()) { if (a.getEntityRoot().isEmpty()) { a.setEntityRoot(movie.getPathNIO().toString()); a.setThumbPath(""); changed = true; } } for (MovieProducer a : movie.getProducers()) { if (a.getEntityRoot().isEmpty()) { a.setEntityRoot(movie.getPathNIO().toString()); a.setThumbPath(""); changed = true; } } // also clean out the sorttitle if a movie set is assigned (not needed any more) if (movie.getMovieSet() != null) { movie.setSortTitle(""); changed = true; } // re-evaluate MediaSource; changed *.strm files to MediaSource.STREAM if (movie.getMediaSource() == MediaSource.UNKNOWN) { MediaFile source = movie.getMediaFiles(MediaFileType.VIDEO).get(0); MediaSource ms = MediaSource.parseMediaSource(source.getPath()); if (movie.getMediaSource() != ms) { movie.setMediaSource(ms); changed = true; } } if (changed) { movie.saveToDb(); } } for (TvShow tvShow : tvShowList.getTvShows()) { boolean changed = false; for (TvShowActor a : tvShow.getActors()) { if (a.getEntityRoot().isEmpty()) { a.setEntityRoot(tvShow.getPathNIO().toString()); a.setThumbUrl(a.getThumb()); a.setThumbPath(""); a.setThumb(""); changed = true; } } for (TvShowEpisode episode : tvShow.getEpisodes()) { for (TvShowActor a : episode.getActors()) { if (a.getEntityRoot().isEmpty()) { a.setEntityRoot(episode.getPathNIO().toString()); a.setThumbUrl(a.getThumb()); a.setThumbPath(""); a.setThumb(""); changed = true; } } } if (changed) { tvShow.saveToDb(); } } } // upgrade to v2.9.1 if (StrgUtils.compareVersion(v, "2.9.1") < 0) { LOGGER.info("Performing database upgrade tasks to version 2.9.1"); if (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector() == MovieConnectors.XBMC) { MovieModuleManager.MOVIE_SETTINGS.setMovieConnector(MovieConnectors.KODI); Settings.getInstance().saveSettings(); } // fix swedish subs detected as sme for (Movie movie : movieList.getMovies()) { boolean changed = false; for (MediaFile mf : movie.getMediaFiles()) { for (MediaFileSubtitle sub : mf.getSubtitles()) { if ("sme".equals(sub.getLanguage())) { sub.setLanguage("swe"); changed = true; } } } if (changed) { movie.saveToDb(); } } for (TvShow show : tvShowList.getTvShows()) { boolean changed = false; for (TvShowEpisode episode : show.getEpisodes()) { for (MediaFile mf : episode.getMediaFiles()) { for (MediaFileSubtitle sub : mf.getSubtitles()) { if ("sme".equals(sub.getLanguage())) { sub.setLanguage("swe"); changed = true; } } } if (changed) { episode.saveToDb(); } } } } }
From source file:com.netflix.spinnaker.clouddriver.artifacts.github.GithubArtifactCredentialsTest.java
@Test void downloadWithTokenFromFile(@TempDirectory.TempDir Path tempDir, @WiremockResolver.Wiremock WireMockServer server) throws IOException { Path authFile = tempDir.resolve("auth-file"); Files.write(authFile, "zzz".getBytes()); GitHubArtifactAccount account = new GitHubArtifactAccount(); account.setName("my-github-account"); account.setTokenFile(authFile.toAbsolutePath().toString()); runTestCase(server, account, m -> m.withHeader("Authorization", equalTo("token zzz"))); }
From source file:illarion.compile.Compiler.java
private static void processPath(@Nonnull final Path path) throws IOException { if (Files.isDirectory(path)) { return;//from w w w . j av a2s. c o m } int compileResult = 1; for (CompilerType type : CompilerType.values()) { if (type.isValidFile(path)) { Compile compile = type.getImplementation(); if (path.isAbsolute()) { if (storagePaths.containsKey(type)) { compile.setTargetDir(storagePaths.get(type)); } else { compile.setTargetDir(path.getParent()); } } else { if (storagePaths.containsKey(type)) { Path parent = path.getParent(); if (parent == null) { compile.setTargetDir(storagePaths.get(type)); } else { compile.setTargetDir(storagePaths.get(type).resolve(parent)); } } else { Path parent = path.getParent(); if (parent == null) { compile.setTargetDir(path.toAbsolutePath().getParent()); } else { compile.setTargetDir(parent); } } } compileResult = compile.compileFile(path.toAbsolutePath()); if (compileResult == 0) { break; } } } switch (compileResult) { case 1: LOGGER.info("Skipped file: {}", path.getFileName()); break; case 0: return; default: System.exit(compileResult); } }
From source file:org.apache.storm.daemon.logviewer.utils.DirectoryCleaner.java
/** * If totalSize of files exceeds the either the per-worker quota or global quota, * Logviewer deletes oldest inactive log files in a worker directory or in all worker dirs. * We use the parameter forPerDir to switch between the two deletion modes. * * @param dirs the list of directories to be scanned for deletion * @param quota the per-dir quota or the total quota for the all directories * @param forPerDir if true, deletion happens for a single dir; otherwise, for all directories globally * @param activeDirs only for global deletion, we want to skip the active logs in activeDirs * @return number of files deleted/*from w w w . ja va 2 s . co m*/ */ public DeletionMeta deleteOldestWhileTooLarge(List<Path> dirs, long quota, boolean forPerDir, Set<Path> activeDirs) throws IOException { long totalSize = 0; for (Path dir : dirs) { try (DirectoryStream<Path> stream = getStreamForDirectory(dir)) { for (Path path : stream) { totalSize += Files.size(path); } } } LOG.debug("totalSize: {} quota: {}", totalSize, quota); long toDeleteSize = totalSize - quota; if (toDeleteSize <= 0) { return DeletionMeta.EMPTY; } int deletedFiles = 0; long deletedSize = 0; // the oldest pq_size files in this directory will be placed in PQ, with the newest at the root PriorityQueue<Pair<Path, FileTime>> pq = new PriorityQueue<>(PQ_SIZE, Comparator.comparing((Pair<Path, FileTime> p) -> p.getRight()).reversed()); int round = 0; final Set<Path> excluded = new HashSet<>(); while (toDeleteSize > 0) { LOG.debug("To delete size is {}, start a new round of deletion, round: {}", toDeleteSize, round); for (Path dir : dirs) { try (DirectoryStream<Path> stream = getStreamForDirectory(dir)) { for (Path path : stream) { if (!excluded.contains(path)) { if (isFileEligibleToSkipDelete(forPerDir, activeDirs, dir, path)) { excluded.add(path); } else { Pair<Path, FileTime> p = Pair.of(path, Files.getLastModifiedTime(path)); if (pq.size() < PQ_SIZE) { pq.offer(p); } else if (p.getRight().toMillis() < pq.peek().getRight().toMillis()) { pq.poll(); pq.offer(p); } } } } } } if (!pq.isEmpty()) { // need to reverse the order of elements in PQ to delete files from oldest to newest Stack<Pair<Path, FileTime>> stack = new Stack<>(); while (!pq.isEmpty()) { stack.push(pq.poll()); } while (!stack.isEmpty() && toDeleteSize > 0) { Pair<Path, FileTime> pair = stack.pop(); Path file = pair.getLeft(); final String canonicalPath = file.toAbsolutePath().normalize().toString(); final long fileSize = Files.size(file); final long lastModified = pair.getRight().toMillis(); //Original implementation doesn't actually check if delete succeeded or not. try { Utils.forceDelete(file.toString()); LOG.info("Delete file: {}, size: {}, lastModified: {}", canonicalPath, fileSize, lastModified); toDeleteSize -= fileSize; deletedSize += fileSize; deletedFiles++; } catch (IOException e) { excluded.add(file); } } pq.clear(); round++; if (round >= MAX_ROUNDS) { if (forPerDir) { LOG.warn( "Reach the MAX_ROUNDS: {} during per-dir deletion, you may have too many files in " + "a single directory : {}, will delete the rest files in next interval.", MAX_ROUNDS, dirs.get(0).toAbsolutePath().normalize()); } else { LOG.warn("Reach the MAX_ROUNDS: {} during global deletion, you may have too many files, " + "will delete the rest files in next interval.", MAX_ROUNDS); } break; } } else { LOG.warn("No more files able to delete this round, but {} is over quota by {} MB", forPerDir ? "this directory" : "root directory", toDeleteSize * 1e-6); } } return new DeletionMeta(deletedSize, deletedFiles); }
From source file:com.collaborne.jsonschema.generator.driver.GeneratorDriver.java
/** * Calculate type URIs for all the given {@code schemaFiles}. * * @param rootUri//ww w.j ava2 s .com * @param baseDirectory * @param schemaFiles * @return */ public Set<URI> getInitialTypes(URI rootUri, Path baseDirectory, List<Path> schemaFiles) { Set<URI> types = new HashSet<>(); URI baseDirectoryUri = baseDirectory.toAbsolutePath().normalize().toUri(); for (Path schemaFile : schemaFiles) { URI schemaFileUri = schemaFile.toAbsolutePath().normalize().toUri(); URI relativeSchemaUri = baseDirectoryUri.relativize(schemaFileUri); URI schemaUri = rootUri.resolve(relativeSchemaUri); types.add(schemaUri.resolve("#")); } return types; }
From source file:org.apache.geode.management.internal.cli.commands.StartMemberUtilsTest.java
@Test public void testWorkingDirWithRelativePath() throws Exception { Path relativePath = Paths.get("some").resolve("relative").resolve("path"); assertThat(relativePath.isAbsolute()).isFalse(); String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1"); assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString()); }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);/*from w w w. jav a 2s . c om*/ } CommandLine cmdLine; if (execPath != null) { // Run the configured calibre ebook-convert executable logger.info("Calibre ebook-convert will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Calibre ebook-convert will be run within the PATH variable."); cmdLine = new CommandLine(command); } // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString()); cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString()); // Output will be in format "KF8" only, old format does not allow external CSS files cmdLine.addArgument("--mobi-file-type=new"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(calibreStreamHandler); logger.debug("Launching calibres ebook-convert:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("calibres ebook-convert failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("calibre ebook-converts execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) { logger.error("calibres ebook-convert could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("calibre ebook-converts execution got interrupted: "); logger.error(e.getMessage(), e); } String output = ""; try { output += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading calibre ebook-converts output from buffer:"); logger.error(e.getMessage(), e); } logger.debug("Calibre ebook-convert output: \n" + output); return tempMobiFilepath.toFile(); }