Java Code Examples for java.nio.file.FileVisitResult

The following are top voted examples for showing how to use java.nio.file.FileVisitResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Squid   File: FileUtilities.java   Source Code and License 7 votes vote down vote up
/**
 *
 * @param directory
 * @throws IOException
 */
public static void recursiveDelete(Path directory) throws IOException {
    Files.walkFileTree(directory, 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;
        }
    });
}
 
Example 2
Project: Hollow-Knight-SaveManager   File: Listeners.java   Source Code and License 6 votes vote down vote up
public static void deleteFiles (String path){    
	 try {
		 Path directory = Paths.get(path);
		 Files.walkFileTree(directory, 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 e) {
		e.printStackTrace();
	}      
}
 
Example 3
Project: launcher-backend   File: FileUploadHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Deletes a directory recursively
 *
 * @param directory
 * @return true if deletion succeeds, false otherwise
 */
public static boolean deleteDirectory(Path directory) {
    if (directory != null) {
        try {
            Files.walkFileTree(directory, 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 ignored) {
            return false;
        }
    }
    return true;
}
 
Example 4
Project: openjdk-jdk10   File: ClasspathDependencies.java   Source Code and License 6 votes vote down vote up
static void delete(Path root) throws IOException {
    if (!Files.exists(root))
        return;
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
             @Override
             public FileVisitResult visitFile(Path f, BasicFileAttributes a)
                     throws IOException {
                 Files.delete(f);
                 return FileVisitResult.CONTINUE;
             }

             @Override
             public FileVisitResult postVisitDirectory(Path dir, IOException e)
                     throws IOException {
                 if (e != null)
                     throw e;
                 if (!dir.equals(root))
                     Files.delete(dir);
                 return FileVisitResult.CONTINUE;
             }
        });
}
 
Example 5
Project: Lagerta   File: FileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Deletes directory along with all inner files.
 *
 * @param path to directory.
 * @throws IOException if there are errors during deleting.
 */
public static void deleteDir(Path path) throws IOException {
    if (!Files.exists(path)) {
        return;
    }
    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 super.postVisitDirectory(dir, exc);
        }
    });
}
 
Example 6
Project: sumo   File: ClearCacheAction.java   Source Code and License 6 votes vote down vote up
@Override
public boolean execute() {
	File folder=CacheManager.getRootCacheInstance().getPath();
	//System.gc();
	try {
		Files.walkFileTree(folder.toPath(), 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 e) {
		logger.error(e.getMessage());
		return false;
	}
   	super.notifyEvent(new SumoActionEvent(SumoActionEvent.ENDACTION,"cache cleaned...", -1));
	return true;
}
 
Example 7
Project: jpa2ddl   File: FileResolver.java   Source Code and License 6 votes vote down vote up
static List<String> listClassNamesInPackage(String packageName) throws Exception {
	List<String> classes = new ArrayList<>();
	Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', File.separatorChar));
	if (!resources.hasMoreElements()) {
		throw new IllegalStateException("No package found: " + packageName);
	}
	PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.class");
	while (resources.hasMoreElements()) {
		URL resource = resources.nextElement();
		Files.walkFileTree(Paths.get(resource.toURI()), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				if (pathMatcher.matches(path.getFileName())) {
					try {
						String className = Paths.get(resource.toURI()).relativize(path).toString().replace(File.separatorChar, '.');
						classes.add(packageName + '.' + className.substring(0, className.length() - 6));
					} catch (URISyntaxException e) {
						throw new IllegalStateException(e);
					}
				}
				return FileVisitResult.CONTINUE;
			}
		});
	}
	return classes;
}
 
Example 8
Project: bazel-tools   File: PathUtils.java   Source Code and License 6 votes vote down vote up
public static void removeRecursive(final Path path) throws IOException {
  Files.walkFileTree(
      path,
      new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
            throws IOException {
          Files.deleteIfExists(file);
          return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
            throws IOException {
          Files.deleteIfExists(dir);
          return FileVisitResult.CONTINUE;
        }
      });
}
 
Example 9
Project: chipKIT-importer   File: ChipKitProjectImporter.java   Source Code and License 6 votes vote down vote up
private void importSketchFiles( Path sketchDirPath ) throws IOException {
    if ( !copyingFiles ) return;
    Files.walkFileTree(sketchDirPath, new CopyingFileVisitor(sketchDirPath, getSourceFilesDirectoryPath(), PROJECT_SOURCE_FILE_MATCHER) {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            if ( file.toString().endsWith(".ino.cpp") ) {
                String filename = file.getFileName().toString();
                String newFilename = filename.replace(".ino.cpp", ".cpp");
                Path targetFilePath = target.resolve( source.relativize( Paths.get(file.getParent().toString(), newFilename) ) );
                copyFile( file, targetFilePath );
                try {
                    removeLineDirectives( targetFilePath);
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            } else { 
                copyFile( file, target.resolve( source.relativize(file) ) );
            }
            return CONTINUE;
        }            
    });
}
 
Example 10
Project: VKMusicUploader   File: WatchDirs.java   Source Code and License 6 votes vote down vote up
/**
 * Starts watching the subdirectories of the provided directory for changes.
 * @param root Root directory of the subdirectories to register.
 * @throws IOException If a subdirectory cannot be registered.
 * @checkstyle RequireThisCheck (20 lines)
 * @checkstyle NonStaticMethodCheck (20 lines)
 */
private void processSubevents(final Path root) throws IOException {
    try {
        Files.walkFileTree(
            root,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(
                    final Path subdir,
                    final BasicFileAttributes attrs
                ) throws IOException {
                    registerDirectory(subdir);
                    return FileVisitResult.CONTINUE;
                }
            });
    } catch (final IOException ex) {
        throw new IOException("Failed to register subdirectories", ex);
    }
}
 
Example 11
Project: java-course   File: LsShellCommand.java   Source Code and License 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir,
		BasicFileAttributes attrs) throws IOException {
	String dirName = dir.toFile().getName();
	long directorySize = getDirectorySize(dir.toFile());

	printAttributes(getPermissions(dir), directorySize,
			getFormattedDate(dir), dirName);
	return FileVisitResult.CONTINUE;
}
 
Example 12
Project: Equella   File: FileUtils.java   Source Code and License 6 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
	if( exc != null )
	{
		success = false;
		LOGGER.warn("Folder traversal failed.  Could not traverse " + dir.toString());
	}
	try
	{
		Files.delete(dir);
	}
	catch( Exception e )
	{
		success = false;
		LOGGER.warn("Folder deletion failed.  Could not delete " + dir.toString());
	}
	return FileVisitResult.CONTINUE;
}
 
Example 13
Project: jtsgen   File: TsGenProcessorTmpDirTest.java   Source Code and License 6 votes vote down vote up
@After
public void deleteTmpDir() throws IOException {
    Files.walkFileTree(this.tmpDir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult postVisitDirectory(final Path theDir, final IOException e) throws IOException {
            if (e != null) return TERMINATE;
            Files.delete(theDir);
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path theFile, final BasicFileAttributes attrs) throws IOException {
            Files.delete(theFile);
            return CONTINUE;
        }
    });
}
 
Example 14
Project: cljbuck   File: PathTraversal.java   Source Code and License 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
    final String d = dir.getFileName().toString();
    final String abs = dir.toAbsolutePath().toString();

    if (d.startsWith(".")) {
        return SKIP_SUBTREE;
    } else if (abs.equals(workspacePath+"/clj-out")) {
        return SKIP_SUBTREE;
    } else if (abs.equals(workspacePath+"/target")) {
        return SKIP_SUBTREE;
    } else if (abs.equals(workspacePath+"/buck-out")) {
        return SKIP_SUBTREE;
    }
    find(dir);
    return CONTINUE;
}
 
Example 15
Project: guava-mock   File: MoreFilesTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  if (tempDir != null) {
    // delete tempDir and its contents
    Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.deleteIfExists(file);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        if (exc != null) {
          return FileVisitResult.TERMINATE;
        }
        Files.deleteIfExists(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }
}
 
Example 16
Project: ProjectAres   File: MapSource.java   Source Code and License 6 votes vote down vote up
public Set<Path> getMapFolders(final Logger logger) throws IOException {
    final Set<Path> mapFolders = new HashSet<>();
    for(Path root : getRootPaths()) {
        int depth = "".equals(root.toString()) ? 0 : Iterables.size(root);
        Files.walkFileTree(getPath().resolve(root), ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth - depth, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if(!isExcluded(dir)) {
                    if(MapFolder.isMapFolder(dir)) {
                        mapFolders.add(dir);
                    }
                    return FileVisitResult.CONTINUE;
                } else {
                    logger.fine("Skipping excluded path " + dir);
                    return FileVisitResult.SKIP_SUBTREE;
                }
            }
        });
    }
    return mapFolders;
}
 
Example 17
Project: omero-ms-queue   File: ClassPathFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Builds a class path with all the files selected by the given predicate 
 * in the specified base directory and, recursively, in all of its 
 * sub-directories.
 * @param dir the directory in which to find the (jar) files.
 * @param select tests whether or not to include a regular file.
 * @return the class path.
 * @throws NullPointerException if the argument is {@code null}.
 * @throws IOException if an I/O error occurs while trawling the directory.
 */
public static ClassPath fromDir(Path dir, Predicate<Path> select) 
        throws IOException {
    requireNonNull(dir, "dir");
    requireNonNull(select, "select");
    
    ClassPath cp = new ClassPath();
    
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attrs) throws IOException {
            if (attrs.isRegularFile() && select.test(file)) {
                cp.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    
    return cp;
}
 
Example 18
Project: Lagerta   File: FileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Deletes directory along with all inner files.
 *
 * @param path to directory.
 * @throws IOException if there are errors during deleting.
 */
public static void deleteDir(Path path) throws IOException {
    if (!Files.exists(path)) {
        return;
    }
    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 super.postVisitDirectory(dir, exc);
        }
    });
}
 
Example 19
Project: sstable-adaptor   File: DirectorySizeCalculator.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
    if (isAcceptable(file))
        size += attrs.size();
    return FileVisitResult.CONTINUE;
}
 
Example 20
Project: openjdk-jdk10   File: Basic.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file,
                                 BasicFileAttributes attrs)
{
    indent();
    System.out.print(file.getFileName());
    if (attrs.isRegularFile())
        System.out.format("%n%s%n", attrs);

    System.out.println();
    return FileVisitResult.CONTINUE;
}
 
Example 21
Project: Java_Swing_Programming   File: FWI.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
   Path p= (Path)file; //To change body of generated methods, choose Tools | Templates.
   
   PathMatcher pm= FileSystems.getDefault().getPathMatcher("glob:**.{log}");
   if(pm.matches(p)){
        System.out.println(p.toString());
   }
   return FileVisitResult.CONTINUE;
}
 
Example 22
Project: n4js   File: FileCopier.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
	if (exc instanceof FileSystemLoopException) {
		LOGGER.error("File system loop/cycle detected: " + file, exc);
	} else {
		LOGGER.error("Error while copying resource: " + file, exc);
	}
	return CONTINUE;
}
 
Example 23
Project: jfrog-idea-plugin   File: NpmPackageFileFinder.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    String fileName = file.getFileName().toString();
    if (isYarn(fileName)) {
        throw new IOException("Yarn is not supported");
    }
    if (isPackageFile(fileName)) {
        applicationPaths.add(file.getParent().toString());
    }
    return FileVisitResult.CONTINUE;
}
 
Example 24
Project: bazel-buildfarm   File: Worker.java   Source Code and License 5 votes vote down vote up
public static void removeDirectory(Path directory) throws IOException {
  Files.walkFileTree(directory, 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;
    }
  });
}
 
Example 25
Project: n4js   File: FileSystem.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
	if (sourcePath == null) {
		sourcePath = dir;
	} else {
		Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir)));
	}
	return FileVisitResult.CONTINUE;
}
 
Example 26
Project: pgcodekeeper   File: PartialExportTestFileVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file1, BasicFileAttributes attrs) throws IOException{
    String relativeFilePath = pathToBeCompared.relativize(file1).toString();
    File file2 = new File(pathToCompareTo.toFile(), relativeFilePath);

    if (!file2.exists() && isInSource){
        if (!deletedFiles.contains(relativeFilePath)){
            fail(isInSource() + "file is missing but not in deleted list: " + relativeFilePath);
        }
        deletedFiles.remove(relativeFilePath);
    }
    if (!file2.exists() && !isInSource){
        if (!newFiles.contains(relativeFilePath)){
            fail(isInSource() + "file is missing but not in new list: " + relativeFilePath);
        }
        newFiles.remove(relativeFilePath);
    }
    if (file2.exists() && file2.isDirectory()){
        fail(isInSource() + "file is a directory: " + relativeFilePath);
    }

    if (file2.exists() && !Arrays.equals(Files.readAllBytes(file1), Files.readAllBytes(file2.toPath()))){
        if (!modifiedFiles.containsKey(relativeFilePath)){
            fail(isInSource() + "Source and target files differ, but this file is "
                    + "not in list of modified objects: " + relativeFilePath);
        }
        String hash = modifiedFiles.remove(relativeFilePath);
        File file = isInSource ? file2 : file1.toFile();
        String partialFile = new String(Files.readAllBytes(file.toPath()), PartialExporterTest.UTF_8);

        Assert.assertEquals("Files differ, and partial file has unexpected hash"
                + "\nPartial file:\n" + partialFile,
                hash,
                PgDiffUtils.md5(partialFile));
    }
    return FileVisitResult.CONTINUE;
}
 
Example 27
Project: openjdk-jdk10   File: Basic.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
    throws IOException
{
    if (exc != null)
        super.postVisitDirectory(dir, exc);
    if (dir.getFileName() != null)
        indent--;
    return FileVisitResult.CONTINUE;
}
 
Example 28
Project: qpp-conversion-tool   File: CopyFileVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs) throws IOException {
	if (source == null) {
		source = directory;
	}
	Files.createDirectories(toDestinationPath(directory));
	return FileVisitResult.CONTINUE;
}
 
Example 29
Project: tabularius   File: NumbersFileWalker.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
	final String path = minimizePath(file);
	Matcher m = Pattern.compile("/(.+)/(\\d)/number-(\\d+)\\..+").matcher(path);
	if (m.find()) {
		String contributor = m.group(1);
		short digit = Short.valueOf(m.group(2));
		short no = Short.valueOf(m.group(3));
		add(contributor, digit, no, path);
	}
	return FileVisitResult.CONTINUE;
}
 
Example 30
Project: athena   File: Tools.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
        throws IOException {
    if (attributes.isRegularFile()) {
        delete(file);
    }
    return FileVisitResult.CONTINUE;
}
 
Example 31
Project: Equella   File: FileUtils.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
	//Tries again, visitFile can fail trying to get file attributes
	doDelete(file);
	return FileVisitResult.CONTINUE;
}
 
Example 32
Project: ViralFileCrypt   File: ViralFileCrypt.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes mainAtts) {
    File file = path.toFile();
    String fileName = file.getName();
    if (file.isFile()) {
        if (allFiles || (exact != null && exact.equals(fileName))
                || (exact == null && name == null && ext == null && fileName.contains("."))
                || (exact == null && name != null && ext == null && fileName.startsWith(name + "."))
                || (exact == null && name == null && ext != null && fileName.endsWith("." + ext))) {
            paths.add(file.getAbsolutePath());
        }
    }
    return FileVisitResult.CONTINUE;
}
 
Example 33
Project: skript-mirror   File: LibraryLoader.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  if (MATCHER.matches(file)) {
    Skript.info("Loaded external library " + file.getFileName());
    urls.add(file.toUri().toURL());
  }
  return super.visitFile(file, attrs);
}
 
Example 34
Project: marathonv5   File: Copy.java   Source Code and License 5 votes vote down vote up
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
    if (copyFile(file, target.resolve(source.relativize(file)))) {
        if (operation == Operation.CUT) {
            try {
                Files.delete(file);
            } catch (IOException e) {
                System.err.format("Unable to create: %s: %s%n", file, e);
            }
        }
    }
    return CONTINUE;
}
 
Example 35
Project: GravSupport   File: CopyFileVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(final Path dir,
                                         final BasicFileAttributes attrs) throws IOException {
    if (sourcePath == null) {
        sourcePath = dir;
    } else {
    Files.createDirectories(targetPath.resolve(sourcePath
                .relativize(dir)));
    }
    return FileVisitResult.CONTINUE;
}
 
Example 36
Project: SpaceGame   File: LevelEventRegistry.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if (!Files.isHidden(file) && Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        try {
            String name = file.toString()
                    .substring(0, file.toString().lastIndexOf('.'))
                    .replaceFirst("/images/", "");
            byte[] bytes = Files.readAllBytes(file);
            packer.pack(name, new Pixmap(bytes, 0, bytes.length));
        } catch (GdxRuntimeException e) {
            System.err.println("Failed to load file: " + file + " as an image.");
        }
    }
    return FileVisitResult.CONTINUE;
}
 
Example 37
Project: cdp4j   File: ChromiumDownloader.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
    String sourcePath = sourceFile.subpath(1, sourceFile.getNameCount()).toString();
    Path destinationFile = destinationRoot.resolve(sourcePath);
    if (exists(destinationFile)) {
        delete(destinationFile);
    }
    copy(sourceFile, destinationFile);
    return CONTINUE;
}
 
Example 38
Project: elasticsearch_my   File: LogConfigurator.java   Source Code and License 5 votes vote down vote up
private static void configure(final Settings settings, final Path configsPath, final Path logsPath) throws IOException, UserException {
    Objects.requireNonNull(settings);
    Objects.requireNonNull(configsPath);
    Objects.requireNonNull(logsPath);

    setLogConfigurationSystemProperty(logsPath, settings);
    // we initialize the status logger immediately otherwise Log4j will complain when we try to get the context
    configureStatusLogger();

    final LoggerContext context = (LoggerContext) LogManager.getContext(false);

    final List<AbstractConfiguration> configurations = new ArrayList<>();
    final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
    final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            if (file.getFileName().toString().equals("log4j2.properties")) {
                configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri()));
            }
            return FileVisitResult.CONTINUE;
        }
    });

    if (configurations.isEmpty()) {
        throw new UserException(
                ExitCodes.CONFIG,
                "no log4j2.properties found; tried [" + configsPath + "] and its subdirectories");
    }

    context.start(new CompositeConfiguration(configurations));

    configureLoggerLevels(settings);
}
 
Example 39
Project: GravSupport   File: CopyFileVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
    targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
 
Example 40
Project: centraldogma   File: DeletingFileVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
    delete(dir);

    if (e == null) {
        return FileVisitResult.CONTINUE;
    } else {
        throw e;
    }
}