List of usage examples for java.nio.file FileVisitResult CONTINUE
FileVisitResult CONTINUE
To view the source code for java.nio.file FileVisitResult CONTINUE.
Click Source Link
From source file:majordodo.task.BrokerTestUtils.java
@After public void brokerTestUtilsAfter() throws Exception { if (startBroker) { server.close();/*from w w w . ja va 2 s .c o m*/ broker.close(); server = null; broker = null; } if (startReplicatedBrokers) { brokerLocator.close(); server2.close(); broker2.close(); server1.close(); broker1.close(); zkServer.close(); brokerLocator = null; server2 = null; broker2 = null; server1 = null; broker1 = null; zkServer = null; } // Resetting brokers config if (startBroker) { brokerConfig = new BrokerConfiguration(); } if (startReplicatedBrokers) { broker1Config = new BrokerConfiguration(); broker2Config = new BrokerConfiguration(); } if (workDir != null) { Files.walkFileTree(workDir, new FileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } if (!ignoreUnhandledExceptions && !unhandledExceptions.isEmpty()) { System.out.println("Errors occurred during excecution:"); for (Throwable e : unhandledExceptions) { System.out.println("\n" + ExceptionUtils.getStackTrace(e) + "\n"); } fail("There are " + unhandledExceptions.size() + " unhandled exceptions!"); } }
From source file:org.structr.web.maintenance.DirectFileImportCommand.java
private FileVisitResult createFileOrFolder(final SecurityContext ctx, final App app, final Path path, final Path file, final BasicFileAttributes attrs, final String sourcePath, final String targetPath, final Mode mode, final Existing existing, final boolean doIndex) { ctx.setDoTransactionNotifications(false); final String name = file.getFileName().toString(); try (final Tx tx = app.tx()) { final String relativePath = PathHelper.getRelativeNodePath(path.toString(), file.toString()); String parentPath = targetPath + PathHelper.getFolderPath(relativePath); // fix broken path concatenation if (parentPath.startsWith("//")) { parentPath = parentPath.substring(1); }//from ww w . j a v a 2 s . co m if (attrs.isDirectory()) { final Folder newFolder = app.create(Folder.class, new NodeAttribute(Folder.name, name), new NodeAttribute(StructrApp.key(File.class, "parent"), FileHelper.createFolderPath(securityContext, parentPath))); folderCount++; logger.info("Created folder " + newFolder.getPath()); } else if (attrs.isRegularFile()) { final File existingFile = app.nodeQuery(File.class) .and(StructrApp.key(AbstractFile.class, "path"), parentPath + name).getFirst(); if (existingFile != null) { switch (existing) { case SKIP: logger.info("Skipping import of {}, file exists and mode is SKIP.", parentPath + name); return FileVisitResult.CONTINUE; case OVERWRITE: logger.info("Overwriting {}, file exists and mode is OVERWRITE.", parentPath + name); app.delete(existingFile); break; case RENAME: logger.info("Renaming existing file {}, file exists and mode is RENAME.", parentPath + name); existingFile.setProperty(AbstractFile.name, existingFile.getProperty(AbstractFile.name) .concat("_").concat(FileHelper.getDateString())); break; } } final String contentType = FileHelper.getContentMimeType(file.toFile(), file.getFileName().toString()); boolean isImage = (contentType != null && contentType.startsWith("image")); boolean isVideo = (contentType != null && contentType.startsWith("video")); Class cls = null; if (isImage) { cls = Image.class; } else if (isVideo) { cls = SchemaHelper.getEntityClassForRawType("VideoFile"); if (cls == null) { logger.warn("Unable to create entity of type VideoFile, class is not defined."); } } else { cls = File.class; } final File newFile = (File) app.create(cls, new NodeAttribute(File.name, name), new NodeAttribute(StructrApp.key(File.class, "parent"), FileHelper.createFolderPath(securityContext, parentPath)), new NodeAttribute(AbstractNode.type, cls.getSimpleName())); final java.io.File fileOnDisk = newFile.getFileOnDisk(false); final Path fullFolderPath = fileOnDisk.toPath(); Files.createDirectories(fullFolderPath.getParent()); switch (mode) { case MOVE: Files.move(file, fullFolderPath); break; case COPY: Files.copy(file, fullFolderPath); break; } FileHelper.updateMetadata(newFile); if (doIndex) { indexer.addToFulltextIndex(newFile); } fileCount++; } tx.success(); } catch (IOException | FrameworkException ex) { logger.debug("File: " + name + ", path: " + sourcePath, ex); } return FileVisitResult.CONTINUE; }
From source file:gov.noaa.pfel.coastwatch.util.FileVisitorDNLS.java
/** Invoked for a file that could not be visited. */ public FileVisitResult visitFileFailed(Path file, IOException exc) { //2015-03-10 I added this method to override the superclass //which apparently throws the exception and stops the parent //SimpleFileVisitor. This class just ignores the error. //Partial test that this change solves the problem: call // new FileVisitorSubdir("/") // on my Windows computer with message analogous to below enabled. // It shows several files where visitFileFailed. //Always show message here. It is useful information. (message is just filename) String2.log("WARNING: FileVisitorDNLS.visitFileFailed: " + exc.getMessage()); return FileVisitResult.CONTINUE; }
From source file:org.vpac.ndg.storage.util.TimeSliceUtil.java
public void restore(String timesliceId) { TimeSlice ts = timeSliceDao.retrieve(timesliceId); Path tsPath = getFileLocation(ts); try {//from w w w.ja va2 s . c o m Files.walkFileTree(tsPath, new SimpleFileVisitor<Path>() { /** * Import netcdf dataset */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); if (!fileName.endsWith("_old" + GdalFormat.NC.getExtension())) { // IGNORE NON-BACKUP TILE return FileVisitResult.CONTINUE; } String restoredFilename = fileName.replace("_old", ""); Path backupTilePath = file.toAbsolutePath(); Path restoredTilePath = Paths.get(backupTilePath.getParent().toString(), restoredFilename); try { FileUtils.move(backupTilePath, restoredTilePath); log.debug("RESTORE {} as {}", backupTilePath, restoredTilePath); } catch (Exception e) { log.error("{}", e); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { log.error("Error restoring {} caused by {}", tsPath, e); } }
From source file:com.cloudbees.clickstack.util.Files2.java
/** * Copy every file of given {@code zipFile} beginning with given {@code zipSubPath} to {@code destDir} * * @param zipFile//from www . ja v a 2 s . c o m * @param zipSubPath must start with a "/" * @param destDir * @throws RuntimeIOException */ public static void unzipSubDirectoryIfExists(@Nonnull Path zipFile, @Nonnull String zipSubPath, @Nonnull final Path destDir) throws RuntimeIOException { Preconditions.checkArgument(zipSubPath.startsWith("/"), "zipSubPath '%s' must start with a '/'", zipSubPath); try { //if the destination doesn't exist, create it if (Files.notExists(destDir)) { logger.trace("Create dir: {}", destDir); Files.createDirectories(destDir); } try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) { final Path root = zipFileSystem.getPath(zipSubPath); if (Files.notExists(root)) { logger.trace("Zip sub path {} does not exist in {}", zipSubPath, zipFile); return; } //walk the zip file tree and copy files to the destination Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { final Path destFile = Paths.get(destDir.toString(), root.relativize(file).toString()); logger.trace("Extract file {} to {} as {}", file, destDir, destFile); Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } catch (IOException | RuntimeException e) { logger.warn("Exception copying file '" + file + "' with root '" + root + "' to destDir '" + destDir + "', ignore file", e); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { dir.relativize(root).toString(); final Path dirToCreate = Paths.get(destDir.toString(), root.relativize(dir).toString()); if (Files.notExists(dirToCreate)) { logger.trace("Create dir {}", dirToCreate); Files.createDirectory(dirToCreate); } return FileVisitResult.CONTINUE; } }); } } catch (IOException e) { throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubPath + " to " + destDir, e); } }
From source file:org.roda.core.storage.fs.FSUtils.java
/** * Deletes a directory/file// ww w .j a va 2s.c o m * * @param path * path to the directory/file that will be deleted. in case of a * directory, if not empty, everything in it will be deleted as well. * in case of a file, if metadata associated to it exists, it will be * deleted as well. * @throws NotFoundException * @throws GenericException */ public static void deletePath(Path path) throws NotFoundException, GenericException { if (path == null) { return; } try { Files.delete(path); } catch (NoSuchFileException e) { throw new NotFoundException("Could not delete path", e); } catch (DirectoryNotEmptyException e) { try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException e1) { throw new GenericException("Could not delete entity", e1); } } catch (IOException e) { throw new GenericException("Could not delete entity", e); } }
From source file:org.apdplat.superword.rule.TextAnalysis.java
public static Map<String, List<String>> findEvidence(Path dir, List<String> words) { LOGGER.info("?" + dir); Map<String, List<String>> data = new HashMap<>(); try {/* ww w . j a v a 2 s. c o m*/ Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.toFile().getAbsolutePath(); if (file.toFile().getName().startsWith(".")) { return FileVisitResult.CONTINUE; } if (!fileName.endsWith(".txt")) { LOGGER.info("??txt" + fileName); return FileVisitResult.CONTINUE; } LOGGER.info("?" + fileName); List<String> lines = Files.readAllLines(file); for (int i = 0; i < lines.size(); i++) { final String line = lines.get(i); final int index = i; words.forEach(word -> { if (line.toLowerCase().contains(word)) { data.putIfAbsent(word, new ArrayList<>()); data.get(word).add(line + " <u><i>" + file.toFile().getName().replace(".txt", "") + "</i></u>"); } }); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } return data; }
From source file:com.eqbridges.vertx.VerticleModuleMojo.java
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetPath = toPath.resolve(fromPath.relativize(dir)); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); }//from w w w . j a v a 2 s.c om return FileVisitResult.CONTINUE; }
From source file:com.evolveum.midpoint.init.InitialDataImport.java
private File[] getInitialImportObjects() { URL path = InitialDataImport.class.getClassLoader().getResource("initial-objects"); String resourceType = path.getProtocol(); File[] files = null;//from w w w . j av a 2 s . c o m File folder = null; if ("zip".equals(resourceType) || "jar".equals(resourceType)) { try { File tmpDir = new File(configuration.getMidpointHome() + "/tmp"); if (!tmpDir.mkdir()) { LOGGER.warn( "Failed to create temporary directory for inital objects {}. Maybe it already exists", configuration.getMidpointHome() + "/tmp"); } tmpDir = new File(configuration.getMidpointHome() + "/tmp/initial-objects"); if (!tmpDir.mkdir()) { LOGGER.warn( "Failed to create temporary directory for inital objects {}. Maybe it already exists", configuration.getMidpointHome() + "/tmp/initial-objects"); } //prerequisite: we are expecting that the files are store in the same archive as the source code that is loading it URI src = InitialDataImport.class.getProtectionDomain().getCodeSource().getLocation().toURI(); LOGGER.trace("InitialDataImport code location: {}", src); Map<String, String> env = new HashMap<>(); env.put("create", "false"); URI normalizedSrc = new URI(src.toString().replaceFirst("file:", "jar:file:")); LOGGER.trace("InitialDataImport normalized code location: {}", normalizedSrc); try (FileSystem zipfs = FileSystems.newFileSystem(normalizedSrc, env)) { Path pathInZipfile = zipfs.getPath("/initial-objects"); //TODO: use some well defined directory, e.g. midPoint home final Path destDir = Paths.get(configuration.getMidpointHome() + "/tmp"); Files.walkFileTree(pathInZipfile, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { final Path destFile = Paths.get(destDir.toString(), file.toString()); LOGGER.trace("Extracting file {} to {}", file, destFile); Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final Path dirToCreate = Paths.get(destDir.toString(), dir.toString()); if (Files.notExists(dirToCreate)) { LOGGER.trace("Creating directory {}", dirToCreate); Files.createDirectory(dirToCreate); } return FileVisitResult.CONTINUE; } }); } folder = new File(configuration.getMidpointHome() + "/tmp/initial-objects"); } catch (IOException ex) { throw new RuntimeException( "Failed to copy initial objects file out of the archive to the temporary directory", ex); } catch (URISyntaxException ex) { throw new RuntimeException("Failed get URI for the source code bundled with initial objects", ex); } } if ("file".equals(resourceType)) { folder = getResource("initial-objects"); } files = folder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory()) { return false; } return true; } }); Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { int n1 = getNumberFromName(o1); int n2 = getNumberFromName(o2); return n1 - n2; } }); return files; }
From source file:com.eqbridges.vertx.VerticleModuleMojo.java
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path to = toPath.resolve(fromPath.relativize(file)); Files.copy(file, to, copyOption); log.info(format("Copied file [%s] -> [%s]", file.getFileName(), to.normalize())); return FileVisitResult.CONTINUE; }