Example usage for java.nio.file Files walkFileTree

List of usage examples for java.nio.file Files walkFileTree

Introduction

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

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:org.bonitasoft.platform.setup.PlatformSetupIT.java

@Test
public void should_extract_configuration() throws Exception {
    final File destinationFolder = temporaryFolder.newFolder("setup");
    //given//  ww w .  j  av a 2s.  c  o m
    platformSetup.init();

    //when
    System.setProperty(BONITA_SETUP_FOLDER, destinationFolder.getAbsolutePath());
    platformSetup.pull();

    //then
    File folderContainingResultOfGet = destinationFolder.toPath().resolve(PLATFORM_CONF_FOLDER_NAME)
            .resolve("current").toFile();
    assertThat(folderContainingResultOfGet).as("should retrieve config files").exists().isDirectory();

    List<FullBonitaConfiguration> configurations = new ArrayList<>();
    AllConfigurationResourceVisitor allConfigurationResourceVisitor = new AllConfigurationResourceVisitor(
            configurations);
    Files.walkFileTree(destinationFolder.toPath(), allConfigurationResourceVisitor);

    assertThat(configurations).extracting("resourceName").containsOnly(
            "bonita-platform-community-custom.properties", "bonita-platform-custom.xml",
            "bonita-platform-init-custom.xml", "cache-config.xml", "platform-tenant-config.properties",
            "security-config.properties", "bonita-tenant-community-custom.properties",
            "bonita-tenants-custom.xml", "authenticationManager-config.properties",
            "compound-permissions-mapping.properties", "compound-permissions-mapping-custom.properties",
            "compound-permissions-mapping-internal.properties", "console-config.properties",
            "custom-permissions-mapping.properties", "dynamic-permissions-checks.properties",
            "dynamic-permissions-checks-custom.properties", "forms-config.properties",
            "resources-permissions-mapping.properties", "resources-permissions-mapping-custom.properties",
            "resources-permissions-mapping-internal.properties", "SamplePermissionRule.groovy.sample",
            "autologin-v6.json");
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);/*from  www . ja  va 2s  .c o  m*/
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:org.bonitasoft.platform.configuration.impl.ConfigurationServiceImpl.java

private void storeConfiguration(File configurationRootFolder, ConfigurationType type, long tenantId)
        throws PlatformException {
    final Path path = configurationRootFolder.toPath();
    List<BonitaConfiguration> bonitaConfigurations = new ArrayList<>();
    ConfigurationResourceVisitor configurationResourceVisitor = new ConfigurationResourceVisitor(
            bonitaConfigurations);//from  ww  w  .ja  v  a2 s .  com
    try {
        Files.walkFileTree(path, configurationResourceVisitor);
        storeConfiguration(bonitaConfigurations, type, tenantId);
    } catch (IOException e) {
        throw new PlatformException(e);
    }
}

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 .j ava2  s .co 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.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 {/*from  www. ja  va2s . 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:org.roda.core.storage.fs.FSUtils.java

/**
 * Deletes a directory/file/*from   w ww  .java 2  s  .  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:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 * //  w  w w .jav a2s  . co m
 * @param pathToProgramFile
 *            Where to look for the main file that will be compiled.
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @return List of string with the command for the process builder.
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @throws CompilerOutputFolderExistsException
 *             Due to slightly uncompatible CompileCheckerInterface this
 *             exception is in the declaration but it is never thrown.
 *             JavaCompileChecker uses this exception.
 */
private List<String> createCompilerInvocation(Path pathToProgramFile, String compilerName,
        List<String> compilerFlags)
        throws BadCompilerSpecifiedException, FileNotFoundException, CompilerOutputFolderExistsException {

    List<String> compilerInvocation = new LinkedList<>();
    // We need a compiler name. Without it we cannot compile anything and
    // abort.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        compilerInvocation.add(compilerName);
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing.
    if ((compilerFlags != null) && (!(compilerFlags.isEmpty()))) {
        compilerInvocation.addAll(compilerFlags);
    }

    // now we tell ghc to stop after compilation because we just want to
    // see if there are syntax errors in the code
    compilerInvocation.add("-c");

    // Check for the existence of the program file we are trying to
    // compile.
    if ((pathToProgramFile == null) || (pathToProgramFile.compareTo(Paths.get("")) == 0)) {
        throw new FileNotFoundException("No file to compile specified");
    } else {
        if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // we are supposed to compile a folder. Hence we'll scan for
            // lhs files and pass them to the compiler.
            RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]");
            try {
                Files.walkFileTree(pathToProgramFile, dirWalker);
            } catch (IOException e) {
                LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                        + " while building compiler invocation: " + e.getMessage());
            }
            for (Path matchedFile : dirWalker.getFoundFiles()) {
                compilerInvocation.add(matchedFile.toFile().getAbsolutePath());
            }

        } else if (Files.exists(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // if the file exists, just pass the file name, since the
            // compiler will
            // be confined to the directory the file is in a few lines
            // down.
            compilerInvocation.add(pathToProgramFile.toString());
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToProgramFile.toString() + "\"");
        }
    }
    return compilerInvocation;
}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

private void handlePathNew(Path path) throws InterruptedException {
    if (Files.isDirectory(path)) {
        log.debug("Detected new directory: {}", path);
        updateNotificationTimestamp = System.currentTimeMillis();

        try {//from  w ww . j  a  v  a2  s. c om
            Files.walkFileTree(path, trackingFileVisitor);

            checkInterrupted();
        } catch (IOException e) {
            // All IOException should be handled by the trackingFileVisitor instance. If there are IOException thrown 
            // here, than we have a bug.
            throw new RuntimeException("Unhandled IOException", e);
        }
    } else {
        log.debug("Detected new file: {}", path);
        updateNotificationTimestamp = System.currentTimeMillis();
    }
}

From source file:com.ejisto.util.IOUtils.java

@SafeVarargs
public static void unzipFile(File src, Path outputDirectory, FileVisitor<Path>... additionalVisitor)
        throws IOException {
    if (!Files.exists(outputDirectory)) {
        Files.createDirectories(outputDirectory);
    }/* w w  w  . ja va  2 s.  c  om*/
    if (!Files.isDirectory(outputDirectory)) {
        throw new IllegalStateException(outputDirectory.toUri() + " is not a directory");
    }
    try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:file:" + src.getAbsolutePath()),
            Collections.<String, Object>emptyMap())) {
        final Path srcRoot = fileSystem.getPath("/");
        FileVisitor<Path> visitor = new MultipurposeFileVisitor<>(new CopyFileVisitor(srcRoot, outputDirectory),
                additionalVisitor);
        Files.walkFileTree(srcRoot, visitor);
    }
}

From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("SchemaDist plugin started");

    try {//from w ww  .  ja v  a 2s  .  c o  m
        processArtifactItems();
    } catch (InvalidVersionSpecificationException e) {
        handleFailure(e);
    }
    final File outDir = initializeOutDir(outputDirectory);

    CatalogManager catalogManager = new CatalogManager();
    catalogManager.setVerbosity(999);

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist unpacking artifact " + artifact);
        File workDir = new File(workDirectory, artifact.getArtifactId());
        initializeOutDir(workDir);
        artifactItem.setWorkDir(workDir);
        unpack(artifactItem, workDir);

        if (translateSchemaLocation) {
            String catalogPath = artifactItem.getCatalog();
            File catalogFile = new File(workDir, catalogPath);
            if (!catalogFile.exists()) {
                throw new MojoExecutionException("No catalog file " + catalogPath + " in artifact " + artifact);
            }
            Catalog catalog = new Catalog(catalogManager);
            catalog.setupReaders();
            try {
                // UGLY HACK. On Windows, file names like d:\abc\def\catalog.xml eventually get treated very strangely
                // (resulting in names like "file:<current-working-dir>d:\abc\def\catalog.xml" that are obviously wrong)
                // Prefixing such names with "file:/" helps.
                String prefix;
                if (catalogFile.isAbsolute() && !catalogFile.getPath().startsWith("/")) {
                    prefix = "/";
                } else {
                    prefix = "";
                }
                String fileName = "file:" + prefix + catalogFile.getPath();
                getLog().debug("Calling parseCatalog with: " + fileName);
                catalog.parseCatalog(fileName);
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            } catch (IOException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            }
            artifactItem.setResolveCatalog(catalog);
        }
    }

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist processing artifact " + artifact);
        final File workDir = artifactItem.getWorkDir();
        FileVisitor<Path> fileVisitor = new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
                String fileName = filePath.getFileName().toString();
                if (fileName.endsWith(".xsd")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processXsd(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else if (fileName.endsWith(".wsdl")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processWsdl(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    getLog().debug("Skipping file " + filePath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }
        };
        try {
            Files.walkFileTree(workDir.toPath(), fileVisitor);
        } catch (IOException e) {
            throw new MojoExecutionException("Error processing files of artifact " + artifact, e);
        }

    }
    getLog().info("SchemaDist plugin finished");
}