Example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor

List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor

Introduction

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

Prototype

protected SimpleFileVisitor() 

Source Link

Document

Initializes a new instance of this class.

Usage

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  www .  ja  v a 2s  . 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:org.roda.core.storage.fs.FSUtils.java

/**
 * Deletes a directory/file/*from   w w  w  .j a v  a 2 s. co  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:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsNotWorkingDir() throws IOException {
    tmp.newFolder("dir");
    tmp.newFile("dir/file.txt");
    tmp.newFolder("dir/dir2");
    tmp.newFile("dir/dir2/file2.txt");

    final ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    filesystem.walkRelativeFileTree(Paths.get("dir"), new SimpleFileVisitor<Path>() {
        @Override//from w ww . j  av  a2s .  c o  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file.txt", "file2.txt"));
}

From source file:facs.utils.Billing.java

/**
 * Helper method. copies files and directories from source to target source and target can be
 * created via the command: FileSystems.getDefault().getPath(String path, ... String more) or
 * Paths.get(String path, ... String more) Note: overrides existing folders
 * /*from   w  ww . jav a2 s . c o m*/
 * @param source
 * @param target
 * @return true if copying was successful
 */
public boolean copy(final Path source, final Path target) {
    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        try {
                            Files.copy(dir, targetdir, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                        } catch (FileAlreadyExistsException e) {
                            if (!Files.isDirectory(targetdir)) {
                                throw e;
                            }
                        }

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, target.resolve(source.relativize(file)));
                        return FileVisitResult.CONTINUE;

                    }

                });
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.datafibers.kafka.connect.FileGenericSourceTask.java

/**
 * Looks for files that meet the glob criteria. If any found they will be added to the list of
 * files to be processed/*  w  w w . j  a va  2 s  .c  o m*/
 */
private void findMatch() {
    final PathMatcher globMatcher = FileSystems.getDefault().getPathMatcher("glob:".concat(glob));

    try {
        Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) throws IOException {
                if (globMatcher.matches(path)) {
                    if (!processedPaths.contains(path)) {
                        inProgressPaths.add(path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Deletes all the file of the client folder
 *///from   w  w  w  .  j a v a2 s .co  m
@RequestMapping(value = "/delete-all/{clientId}", method = RequestMethod.GET)
@ResponseBody
public String deleteFiles(@PathVariable("clientId") String clientId, HttpServletResponse response)
        throws IOException {

    int deletedFiles = 0;
    Path path = repoRoot.resolve(clientId);

    if (Files.notExists(path) || !Files.isDirectory(path)) {
        log.log(Level.WARNING, "Failed deleting files in " + path);
        response.setStatus(404);
        return "Failed deleting files in " + clientId;
    }

    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("Deleting repo file      :" + file);
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.log(Level.SEVERE, "Failed cleaning up dir: " + path);
        return "Failed deleting files in " + clientId;
    }
    return "Deleted files in dir " + clientId;
}

From source file:org.vpac.ndg.storage.util.TimeSliceUtil.java

public void cleanup(String timesliceId) {
    TimeSlice ts = timeSliceDao.retrieve(timesliceId);
    Path tsPath = getFileLocation(ts);
    try {//www .j  av  a 2  s.  com
        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;
                }

                Path backupTilePath = file.toAbsolutePath();
                try {
                    FileUtils.deleteIfExists(backupTilePath);
                    log.debug("CLEAN UP {}", backupTilePath);
                } 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:org.apache.jena.atlas.io.IO.java

/** Delete everything from a {@code Path} start point, including the path itself.
 * This function works on files or directories.
 * This function does not follow symbolic links.
 *///ww w .j  av a2 s.  com
public static void deleteAll(Path start) {
    // Walks down the tree and delete directories on the way backup.
    try {
        Files.walkFileTree(start, 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 e) throws IOException {
                if (e == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw e;
                }
            }
        });
    } catch (IOException ex) {
        IO.exception(ex);
        return;
    }
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Import an extracted CSAR from a directory
 * //  w  w w  .  j  a  v  a2 s.  co  m
 * @param path the root path of an extracted CSAR file
 * @param overwrite if true: contents of the repo are overwritten
 * @param asyncWPDParsing true if WPD should be parsed asynchronously to speed up the import.
 *        Required, because JUnit terminates the used ExecutorService
 * @throws InvalidCSARException
 * @throws IOException
 */
void importFromDir(final Path path, final List<String> errors, final boolean overwrite,
        final boolean asyncWPDParsing) throws IOException {
    Path toscaMetaPath = path.resolve("xml/TOSCA-Metadata/TOSCA.meta");
    if (!Files.exists(toscaMetaPath)) {
        toscaMetaPath = path.resolve("TOSCA-Metadata/TOSCA.meta");
    }

    if (!Files.exists(toscaMetaPath)) {
        errors.add("TOSCA.meta does not exist");
        return;
    }
    final TOSCAMetaFileParser tmfp = new TOSCAMetaFileParser();
    final TOSCAMetaFile tmf = tmfp.parse(toscaMetaPath);

    // we do NOT do any sanity checks, of TOSAC.meta
    // and just start parsing

    if (tmf.getEntryDefinitions() != null) {
        // we obey the entry definitions and "just" import that
        // imported definitions are added recursively
        Path defsPath = path.resolve(tmf.getEntryDefinitions());
        this.importDefinitions(tmf, defsPath, errors, overwrite, asyncWPDParsing);

        this.importSelfServiceMetaData(tmf, path, defsPath, errors);
    } else {
        // no explicit entry definitions found
        // we import all available definitions
        // The specification says (cos01, Section 16.1, line 2935) that all definitions are contained
        // in the "Definitions" directory
        // The alternative is to go through all entries in the TOSCA Meta File, but there is no
        // guarantee that this list is complete
        Path definitionsDir = path.resolve("Definitions");
        if (!Files.exists(definitionsDir)) {
            errors.add("No entry definitions defined and Definitions directory does not exist.");
            return;
        }
        final List<IOException> exceptions = new ArrayList<IOException>();
        Files.walkFileTree(definitionsDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                if (dir.endsWith("Definitions")) {
                    return FileVisitResult.CONTINUE;
                } else {
                    return FileVisitResult.SKIP_SUBTREE;
                }
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                try {
                    CSARImporter.this.importDefinitions(tmf, file, errors, overwrite, asyncWPDParsing);
                } catch (IOException e) {
                    exceptions.add(e);
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }
        });

        if (!exceptions.isEmpty()) {
            // something went wrong during parsing
            // we rethrow the exception
            throw exceptions.get(0);
        }
    }

    this.importNamespacePrefixes(path);
}

From source file:com.facebook.buck.util.ProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsWorkingDir() throws IOException {
    ProjectFilesystem projectFilesystem = new ProjectFilesystem(Paths.get("."));
    final ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    Path pathRelativeToProjectRoot = Paths.get("test/com/facebook/buck/util/testdata");
    projectFilesystem.walkRelativeFileTree(pathRelativeToProjectRoot, new SimpleFileVisitor<Path>() {
        @Override// www  . j  a  v a  2  s. co m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file", "a_file", "b_file", "b_c_file", "b_d_file"));
}