List of usage examples for java.nio.file Files newDirectoryStream
public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException
From source file:org.niord.core.batch.BatchService.java
/** Returns if the given directory is empty **/ private boolean isDirEmpty(final Path directory) throws IOException { try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) { return !dirStream.iterator().hasNext(); }//w w w . jav a 2 s . co m }
From source file:com.cloudbees.clickstack.util.Files2.java
/** * @param srcDir/*from ww w . ja v a 2 s . c om*/ * @return * @throws RuntimeIOException * @throws IllegalStateException More or less than 1 child dir found */ @Nonnull public static Path findUniqueChildDirectory(@Nonnull Path srcDir) throws RuntimeIOException, IllegalStateException { Preconditions.checkArgument(Files.isDirectory(srcDir), "Source %s is not a directory", srcDir.toAbsolutePath()); try (DirectoryStream<Path> paths = Files.newDirectoryStream(srcDir)) { try { return Iterables.getOnlyElement(paths); } catch (NoSuchElementException e) { throw new IllegalStateException( "No child directory found in : " + srcDir + ", absolutePath: " + srcDir.toAbsolutePath()); } catch (IllegalArgumentException e) { throw new IllegalStateException("More than 1 child directory found in path: " + srcDir + ", absolutePath: " + srcDir.toAbsolutePath() + " -> " + paths); } } catch (IOException e) { throw new RuntimeIOException("Exception finding unique child directory in " + srcDir); } }
From source file:org.tinymediamanager.core.movie.MovieRenamer.java
/** * Rename movie./*from www. j a v a2 s . c om*/ * * @param movie * the movie */ public static void renameMovie(Movie movie) { // FIXME: what? when? boolean posterRenamed = false; boolean fanartRenamed = false; boolean downloadMissingArtworks = false; // check if a datasource is set if (StringUtils.isEmpty(movie.getDataSource())) { LOGGER.error("no Datasource set"); return; } // if (!movie.isScraped()) { if (movie.getTitle().isEmpty()) { LOGGER.error("won't rename movie '" + movie.getPathNIO() + "' / '" + movie.getTitle() + "' not even title is set?"); return; } // all the good & needed mediafiles ArrayList<MediaFile> needed = new ArrayList<>(); ArrayList<MediaFile> cleanup = new ArrayList<>(); LOGGER.info("Renaming movie: " + movie.getTitle()); LOGGER.debug("movie year: " + movie.getYear()); LOGGER.debug("movie path: " + movie.getPathNIO()); LOGGER.debug("movie isDisc?: " + movie.isDisc()); LOGGER.debug("movie isMulti?: " + movie.isMultiMovieDir()); if (movie.getMovieSet() != null) { LOGGER.debug("movieset: " + movie.getMovieSet().getTitle()); } LOGGER.debug("path expression: " + MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname()); LOGGER.debug("file expression: " + MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerFilename()); String newPathname = createDestinationForFoldername( MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname(), movie); String oldPathname = movie.getPathNIO().toString(); if (!newPathname.isEmpty()) { newPathname = movie.getDataSource() + File.separator + newPathname; Path srcDir = movie.getPathNIO(); Path destDir = Paths.get(newPathname); if (!srcDir.toAbsolutePath().equals(destDir.toAbsolutePath())) { boolean newDestIsMultiMovieDir = false; // re-evaluate multiMovieDir based on renamer settings // folder MUST BE UNIQUE, we need at least a T/E-Y combo or IMDBid // so if renaming just to a fixed pattern (eg "$S"), movie will downgrade to a MMD if (!isFolderPatternUnique(MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname())) { // FIXME: if we already in a normal dir - keep it? newDestIsMultiMovieDir = true; } // FIXME: add warning to GUI if downgrade!!!!!! LOGGER.debug("movie willBeMulti?: " + newDestIsMultiMovieDir); // ###################################################################### // ## 1) old = separate movie dir, and new too -> move folder // ###################################################################### if (!movie.isMultiMovieDir() && !newDestIsMultiMovieDir) { boolean ok = false; try { ok = Utils.moveDirectorySafe(srcDir, destDir); if (ok) { movie.setMultiMovieDir(false); movie.updateMediaFilePath(srcDir, destDir); movie.setPath(newPathname); movie.saveToDb(); // since we moved already, save it } } catch (Exception e) { LOGGER.error("error moving folder: ", e); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, srcDir, "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() })); } if (!ok) { // FIXME: when we were not able to rename folder, display error msg and abort!!! LOGGER.error("Could not move to destination '" + destDir + "' - NOT renaming folder"); return; } } else if (movie.isMultiMovieDir() && !newDestIsMultiMovieDir) { // ###################################################################### // ## 2) MMD movie -> normal movie (upgrade) // ###################################################################### LOGGER.trace("Upgrading movie into it's own dir :) " + newPathname); try { Files.createDirectories(destDir); } catch (Exception e) { LOGGER.error("Could not create destination '" + destDir + "' - NOT renaming folder ('upgrade' movie)"); // well, better not to rename return; } movie.setMultiMovieDir(false); downloadMissingArtworks = true; // yay - we upgraded our movie, so we could try to get additional artworks :) } else { // ###################################################################### // ## Can be // ## 3) MMD movie -> MMD movie (but foldername possible changed) // ## 4) normal movie -> MMD movie (downgrade) // ## either way - check & create dest folder // ###################################################################### LOGGER.trace("New movie path is a MMD :( " + newPathname); if (!Files.exists(destDir)) { // if existent, all is good -> MMD (FIXME: kinda, we *might* have another full movie in there) try { Files.createDirectories(destDir); } catch (Exception e) { LOGGER.error("Could not create destination '" + destDir + "' - NOT renaming folder ('MMD' movie)"); // well, better not to rename return; } } movie.setMultiMovieDir(true); } } // src == dest } // folder pattern empty else { LOGGER.info("Folder rename settings were empty - NOT renaming folder"); // set it to current for file renaming newPathname = movie.getPathNIO().toString(); } // ###################################################################### // ## mark ALL existing and known files for cleanup (clone!!) // ###################################################################### for (MovieNfoNaming s : MovieNfoNaming.values()) { String nfoFilename = movie.getNfoFilename(s); if (StringUtils.isBlank(nfoFilename)) { continue; } // mark all known variants for cleanup MediaFile del = new MediaFile(movie.getPathNIO().resolve(nfoFilename), MediaFileType.NFO); cleanup.add(del); } for (MoviePosterNaming s : MoviePosterNaming.values()) { MediaFile del = new MediaFile( movie.getPathNIO() .resolve(replaceInvalidCharacters(MovieArtworkHelper.getPosterFilename(s, movie))), MediaFileType.POSTER); cleanup.add(del); } for (MovieFanartNaming s : MovieFanartNaming.values()) { MediaFile del = new MediaFile( movie.getPathNIO() .resolve(replaceInvalidCharacters(MovieArtworkHelper.getFanartFilename(s, movie))), MediaFileType.FANART); cleanup.add(del); } // cleanup ALL MFs for (MediaFile del : movie.getMediaFiles()) { cleanup.add(new MediaFile(del)); } cleanup.removeAll(Collections.singleton(null)); // remove all NULL ones! // update movie path at end of renaming - we need the old one here!! // movie.setPath(newPathname); // movie.saveToDb(); // BASENAME String newVideoBasename = ""; if (!isFilePatternValid()) { // Template empty or not even title set, so we are NOT renaming any files // we keep the same name on renaming ;) newVideoBasename = movie.getVideoBasenameWithoutStacking(); LOGGER.warn("Filepattern is not valid - NOT renaming files!"); } else { // since we rename, generate the new basename MediaFile ftr = generateFilename(movie, movie.getMediaFiles(MediaFileType.VIDEO).get(0), newVideoBasename).get(0); // there can be only one newVideoBasename = FilenameUtils.getBaseName(ftr.getFilenameWithoutStacking()); } LOGGER.debug("Our new basename for renaming: " + newVideoBasename); // unneeded / more reliable with with java 7? // // ###################################################################### // // ## test VIDEO rename // // ###################################################################### // for (MediaFile vid : movie.getMediaFiles(MediaFileType.VIDEO)) { // LOGGER.debug("testing file " + vid.getFileAsPath()); // Path f = vid.getFileAsPath(); // 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 // } // // we had the case, that the renaemoTo didn't work, // // and even the exists did not work! // // so we skip this additional check, which results in not removing the movie file // // if (!f.exists()) { // // LOGGER.debug("Hmmm... file " + f + " does not even exists; delete from DB"); // // // delete from MF or ignore for later cleanup (but better now!) // // movie.removeFromMediaFiles(vid); // // testRenameOk = true; // we "tested" this ok // // break; // // } // try { // 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 " + vid.getFileAsPath() + " is not accessible!"); // MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, vid.getFilename(), "message.renamer.failedrename")); // return; // } // } // ###################################################################### // ## rename VIDEO (move 1:1) // ###################################################################### for (MediaFile vid : movie.getMediaFiles(MediaFileType.VIDEO)) { LOGGER.trace("Rename 1:1 " + vid.getType() + " " + vid.getFileAsPath()); MediaFile newMF = generateFilename(movie, vid, newVideoBasename).get(0); // there can be only one boolean ok = moveFile(vid.getFileAsPath(), newMF.getFileAsPath()); if (ok) { vid.setFile(newMF.getFileAsPath()); // update } needed.add(vid); // add vid, since we're updating existing MF object } // ###################################################################### // ## rename POSTER, FANART (copy 1:N) // ###################################################################### // we can have multiple ones, just get the newest one and copy(overwrite) them to all needed ArrayList<MediaFile> mfs = new ArrayList<>(); mfs.add(movie.getNewestMediaFilesOfType(MediaFileType.FANART)); mfs.add(movie.getNewestMediaFilesOfType(MediaFileType.POSTER)); mfs.removeAll(Collections.singleton(null)); // remove all NULL ones! for (MediaFile mf : mfs) { LOGGER.trace("Rename 1:N " + mf.getType() + " " + mf.getFileAsPath()); ArrayList<MediaFile> newMFs = generateFilename(movie, mf, newVideoBasename); // 1:N for (MediaFile newMF : newMFs) { posterRenamed = true; fanartRenamed = true; boolean ok = copyFile(mf.getFileAsPath(), newMF.getFileAsPath()); if (ok) { needed.add(newMF); } } } // ###################################################################### // ## rename NFO (copy 1:N) - only TMM NFOs // ###################################################################### // we need to find the newest, valid TMM NFO MediaFile nfo = new MediaFile(); for (MediaFile mf : movie.getMediaFiles(MediaFileType.NFO)) { if (mf.getFiledate() >= nfo.getFiledate() && MovieConnectors.isValidNFO(mf.getFileAsPath())) { nfo = new MediaFile(mf); } } if (nfo.getFiledate() > 0) { // one valid found? copy our NFO to all variants ArrayList<MediaFile> newNFOs = generateFilename(movie, nfo, newVideoBasename); // 1:N if (newNFOs.size() > 0) { // ok, at least one has been set up for (MediaFile newNFO : newNFOs) { boolean ok = copyFile(nfo.getFileAsPath(), newNFO.getFileAsPath()); if (ok) { needed.add(newNFO); } } } else { // list was empty, so even remove this NFO cleanup.add(nfo); } } else { LOGGER.trace("No valid NFO found for this movie"); } // now iterate over all non-tmm NFOs, and add them for cleanup or not for (MediaFile mf : movie.getMediaFiles(MediaFileType.NFO)) { if (MovieConnectors.isValidNFO(mf.getFileAsPath())) { cleanup.add(mf); } else { if (MovieModuleManager.MOVIE_SETTINGS.isMovieRenamerNfoCleanup()) { cleanup.add(mf); } else { needed.add(mf); } } } // ###################################################################### // ## rename all other types (copy 1:1) // ###################################################################### mfs = new ArrayList<>(); mfs.addAll(movie.getMediaFilesExceptType(MediaFileType.VIDEO, MediaFileType.NFO, MediaFileType.POSTER, MediaFileType.FANART, MediaFileType.SUBTITLE)); mfs.removeAll(Collections.singleton(null)); // remove all NULL ones! for (MediaFile other : mfs) { LOGGER.trace("Rename 1:1 " + other.getType() + " " + other.getFileAsPath()); ArrayList<MediaFile> newMFs = generateFilename(movie, other, newVideoBasename); // 1:N newMFs.removeAll(Collections.singleton(null)); // remove all NULL ones! for (MediaFile newMF : newMFs) { boolean ok = copyFile(other.getFileAsPath(), newMF.getFileAsPath()); if (ok) { needed.add(newMF); } else { // FIXME: what to do? not copied/exception... keep it for now... needed.add(other); } } } // ###################################################################### // ## rename subtitles later, but ADD it to not clean up // ###################################################################### needed.addAll(movie.getMediaFiles(MediaFileType.SUBTITLE)); // ###################################################################### // ## invalidade image cache // ###################################################################### for (MediaFile gfx : movie.getMediaFiles()) { if (gfx.isGraphic()) { ImageCache.invalidateCachedImage(gfx.getFileAsPath()); } } // remove duplicate MediaFiles Set<MediaFile> newMFs = new LinkedHashSet<>(needed); needed.clear(); needed.addAll(newMFs); movie.removeAllMediaFiles(); movie.addToMediaFiles(needed); movie.setPath(newPathname); // update .actors for (MovieActor actor : movie.getActors()) { actor.setEntityRoot(newPathname); } movie.saveToDb(); // cleanup & rename subtitle files renameSubtitles(movie); movie.gatherMediaFileInformation(false); // rewrite NFO if it's a MP NFO and there was a change with poster/fanart if (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector() == MovieConnectors.MP && (posterRenamed || fanartRenamed)) { movie.writeNFO(); } movie.saveToDb(); // ###################################################################### // ## CLEANUP - delete all files marked for cleanup, which are not "needed" // ###################################################################### LOGGER.info("Cleanup..."); for (int i = cleanup.size() - 1; i >= 0; i--) { // cleanup files which are not needed if (!needed.contains(cleanup.get(i))) { MediaFile cl = cleanup.get(i); if (cl.getFileAsPath().equals(Paths.get(movie.getDataSource())) || cl.getFileAsPath().equals(movie.getPathNIO()) || cl.getFileAsPath().equals(Paths.get(oldPathname))) { LOGGER.warn("Wohoo! We tried to remove complete datasource / movie folder. Nooo way...! " + cl.getType() + ": " + cl.getFileAsPath()); // happens when iterating eg over the getNFONaming and we return a "" string. // then the path+filename = movie path and we want to delete :/ // do not show an error anylonger, just silently ignore... // MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, cl.getFile(), "message.renamer.failedrename")); // return; // rename failed continue; } if (Files.exists(cl.getFileAsPath())) { // unneeded, but for not displaying wrong deletes in logger... LOGGER.debug("Deleting " + cl.getFileAsPath()); Utils.deleteFileWithBackup(cl.getFileAsPath(), movie.getDataSource()); } try (DirectoryStream<Path> directoryStream = Files .newDirectoryStream(cl.getFileAsPath().getParent())) { if (!directoryStream.iterator().hasNext()) { // no iterator = empty LOGGER.debug("Deleting empty Directory " + cl.getFileAsPath().getParent()); Files.delete(cl.getFileAsPath().getParent()); // do not use recursive her } } catch (IOException ex) { } } } if (downloadMissingArtworks) { LOGGER.debug("Yay - movie upgrade :) download missing artworks"); MovieArtworkHelper.downloadMissingArtwork(movie); } }
From source file:org.fao.geonet.api.site.SiteApi.java
@ApiOperation(value = "Get XSL tranformations available", notes = "XSL transformations may be applied while importing or harvesting records.", nickname = "getXslTransformations") @RequestMapping(path = "/info/transforms", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK)/*w w w. j a va 2s. co m*/ @ApiResponses(value = { @ApiResponse(code = 200, message = "XSLT available.") }) @ResponseBody public List<String> getXslTransformations() throws Exception { ApplicationContext applicationContext = ApplicationContextHolder.get(); GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class); try (DirectoryStream<Path> sheets = Files .newDirectoryStream(dataDirectory.getWebappDir().resolve(Geonet.Path.IMPORT_STYLESHEETS))) { List<String> list = new ArrayList<>(); for (Path sheet : sheets) { String id = sheet.toString(); if (id != null && id.endsWith(".xsl")) { String name = com.google.common.io.Files .getNameWithoutExtension(sheet.getFileName().toString()); list.add(name); } } return list; } }
From source file:com.spectralogic.ds3client.integration.Smoke_Test.java
@Test public void testRecoverReadJob() throws IOException, XmlProcessingException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_read_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1)); final Ds3Object obj2 = new Ds3Object(book2, Files.size(objPath2)); final Path dirPath = FileSystems.getDefault().getPath("output"); if (!Files.exists(dirPath)) { Files.createDirectory(dirPath); }//from w w w .ja va 2 s. c o m try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); putJob.transfer(new ResourceObjectPutter(RESOURCE_BASE_NAME)); final FileChannel channel1 = FileChannel.open(dirPath.resolve(book1), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); final Ds3ClientHelpers.Job readJob = HELPERS.startReadJob(bucketName, Lists.newArrayList(obj1, obj2)); final GetObjectResponse readResponse1 = client .getObject(new GetObjectRequest(bucketName, book1, channel1, readJob.getJobId().toString(), 0)); assertThat(readResponse1, is(notNullValue())); assertThat(readResponse1.getStatusCode(), is(equalTo(200))); // Interruption... final Ds3ClientHelpers.Job recoverJob = HELPERS.recoverReadJob(readJob.getJobId()); final FileChannel channel2 = FileChannel.open(dirPath.resolve(book2), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); final GetObjectResponse readResponse2 = client.getObject( new GetObjectRequest(bucketName, book2, channel2, recoverJob.getJobId().toString(), 0)); assertThat(readResponse2, is(notNullValue())); assertThat(readResponse2.getStatusCode(), is(equalTo(200))); } finally { deleteAllContents(client, bucketName); for (final Path tempFile : Files.newDirectoryStream(dirPath)) { Files.delete(tempFile); } Files.delete(dirPath); } }
From source file:org.tinymediamanager.core.tvshow.tasks.TvShowUpdateDatasourceTask2.java
/** * simple NIO File.listFiles() replacement<br> * returns ONLY regular files (NO folders, NO hidden) in specified dir (NOT recursive) * /*from w w w . j ava 2 s . com*/ * @param directory * the folder to list the files for * @return list of files&folders */ public static List<Path> listFilesOnly(Path directory) { List<Path> fileNames = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) { for (Path path : directoryStream) { if (Utils.isRegularFile(path)) { String fn = path.getFileName().toString().toUpperCase(Locale.ROOT); if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !TvShowModuleManager.SETTINGS .getTvShowSkipFolders().contains(path.toFile().getAbsolutePath())) { fileNames.add(path.toAbsolutePath()); } else { LOGGER.debug("Skipping: " + path); } } } } catch (IOException ex) { } return fileNames; }
From source file:org.fao.geonet.kernel.harvest.harvester.geonet.Aligner.java
private void removeOldFile(String id, Element infoFiles, String dir) { Path resourcesDir = Lib.resource.getDir(context, dir, id); try (DirectoryStream<Path> paths = Files.newDirectoryStream(resourcesDir)) { for (Path file : paths) { if (file != null && file.getFileName() != null && infoFiles != null && !existsFile(file.getFileName().toString(), infoFiles)) { if (log.isDebugEnabled()) { log.debug(" - Removing old " + dir + " file with name=" + file.getFileName()); }/*from w ww . ja v a2s . co m*/ try { Files.delete(file); } catch (IOException e) { log.warning("Unable to delete file: " + file); } } } } catch (IOException e) { log.error(" - Cannot scan directory for " + dir + " files : " + resourcesDir.toAbsolutePath().normalize()); } }
From source file:org.tinymediamanager.core.Utils.java
/** * returns a list of all available GUI languages * //from w w w .j a v a 2 s . co m * @return List of Locales */ public static List<Locale> getLanguages() { ArrayList<Locale> loc = new ArrayList<>(); loc.add(getLocaleFromLanguage(Locale.ENGLISH.getLanguage())); try { try (DirectoryStream<Path> directoryStream = Files .newDirectoryStream(Paths.get(Constants.LOCALE_FOLDER))) { for (Path path : directoryStream) { // String l = file.getName().substring(9, 11); // messages_XX.properties Matcher matcher = localePattern.matcher(path.getFileName().toString()); if (matcher.matches()) { Locale myloc = null; String language = matcher.group(1); String country = matcher.group(2); if (country != null) { // found language & country myloc = new Locale(language, country); } else { // found only language myloc = getLocaleFromLanguage(language); } if (myloc != null && !loc.contains(myloc)) { loc.add(myloc); } } } } } catch (Exception e) { LOGGER.warn("could not read locales: " + e.getMessage()); } return loc; }
From source file:org.tinymediamanager.core.tvshow.tasks.TvShowUpdateDatasourceTask2.java
/** * simple NIO File.listFiles() replacement<br> * returns all files & folders in specified dir (NOT recursive) * //from w w w .j av a 2 s . c om * @param directory * the folder to list the items for * @return list of files&folders */ public static List<Path> listFilesAndDirs(Path directory) { List<Path> fileNames = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) { for (Path path : directoryStream) { String fn = path.getFileName().toString().toUpperCase(Locale.ROOT); if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !TvShowModuleManager.SETTINGS .getTvShowSkipFolders().contains(path.toFile().getAbsolutePath())) { fileNames.add(path.toAbsolutePath()); } else { LOGGER.debug("Skipping: " + path); } } } catch (IOException ex) { } return fileNames; }