Example usage for java.nio.file FileVisitor FileVisitor

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

Introduction

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

Prototype

FileVisitor

Source Link

Usage

From source file:org.structr.web.maintenance.DirectFileImportCommand.java

@Override
public void execute(final Map<String, Object> attributes) throws FrameworkException {

    indexer = StructrApp.getInstance(securityContext).getFulltextIndexer();

    final String sourcePath = getParameterValueAsString(attributes, "source", null);
    final String modeString = getParameterValueAsString(attributes, "mode", Mode.COPY.name()).toUpperCase();
    final String existingString = getParameterValueAsString(attributes, "existing", Existing.SKIP.name())
            .toUpperCase();/* w  w  w  .  ja  v  a 2  s.  co m*/
    final boolean doIndex = Boolean
            .parseBoolean(getParameterValueAsString(attributes, "index", Boolean.TRUE.toString()));

    if (StringUtils.isBlank(sourcePath)) {
        throw new FrameworkException(422,
                "Please provide 'source' attribute for deployment source directory path.");
    }

    if (!EnumUtils.isValidEnum(Mode.class, modeString)) {
        throw new FrameworkException(422, "Unknown value for 'mode' attribute. Valid values are: copy, move");
    }

    if (!EnumUtils.isValidEnum(Existing.class, existingString)) {
        throw new FrameworkException(422,
                "Unknown value for 'existing' attribute. Valid values are: skip, overwrite, rename");
    }

    // use actual enums
    final Existing existing = Existing.valueOf(existingString);
    final Mode mode = Mode.valueOf(modeString);

    final List<Path> paths = new ArrayList<>();

    if (sourcePath.contains(PathHelper.PATH_SEP)) {

        final String folderPart = PathHelper.getFolderPath(sourcePath);
        final String namePart = PathHelper.getName(sourcePath);

        if (StringUtils.isNotBlank(folderPart)) {

            final Path source = Paths.get(folderPart);
            if (!Files.exists(source)) {

                throw new FrameworkException(422, "Source path " + sourcePath + " does not exist.");
            }

            if (!Files.isDirectory(source)) {

                throw new FrameworkException(422, "Source path " + sourcePath + " is not a directory.");
            }

            try {

                try (final DirectoryStream<Path> stream = Files.newDirectoryStream(source, namePart)) {

                    for (final Path entry : stream) {
                        paths.add(entry);
                    }

                } catch (final DirectoryIteratorException ex) {
                    throw ex.getCause();
                }

            } catch (final IOException ioex) {
                throw new FrameworkException(422, "Unable to parse source path " + sourcePath + ".");
            }
        }

    } else {

        // Relative path
        final Path source = Paths.get(Settings.BasePath.getValue()).resolve(sourcePath);
        if (!Files.exists(source)) {

            throw new FrameworkException(422, "Source path " + sourcePath + " does not exist.");
        }

        paths.add(source);

    }

    final SecurityContext ctx = SecurityContext.getSuperUserInstance();
    final App app = StructrApp.getInstance(ctx);
    String targetPath = getParameterValueAsString(attributes, "target", "/");
    Folder targetFolder = null;

    ctx.setDoTransactionNotifications(false);

    if (StringUtils.isNotBlank(targetPath) && !("/".equals(targetPath))) {

        try (final Tx tx = app.tx()) {

            targetFolder = app.nodeQuery(Folder.class).and(StructrApp.key(Folder.class, "path"), targetPath)
                    .getFirst();
            if (targetFolder == null) {

                throw new FrameworkException(422, "Target path " + targetPath + " does not exist.");
            }

            tx.success();
        }
    }

    String msg = "Starting direct file import from source directory " + sourcePath + " into target path "
            + targetPath;
    logger.info(msg);
    publishProgressMessage(msg);

    paths.forEach((path) -> {

        try {

            final String newTargetPath;

            // If path is a directory, create it and use it as the new target folder
            if (Files.isDirectory(path)) {

                Path parentPath = path.getParent();
                if (parentPath == null) {
                    parentPath = path;
                }

                createFileOrFolder(ctx, app, parentPath, path,
                        Files.readAttributes(path, BasicFileAttributes.class), sourcePath, targetPath, mode,
                        existing, doIndex);

                newTargetPath = targetPath + PathHelper.PATH_SEP
                        + PathHelper.clean(path.getFileName().toString());

            } else {

                newTargetPath = targetPath;
            }

            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    return createFileOrFolder(ctx, app, path, file, attrs, sourcePath, newTargetPath, mode,
                            existing, doIndex);
                }

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

                @Override
                public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }
            });

        } catch (final IOException ex) {
            logger.debug("Mode: " + modeString + ", path: " + sourcePath, ex);
        }
    });

    msg = "Finished direct file import from source directory " + sourcePath + ". Imported " + folderCount
            + " folders and " + fileCount + " files.";
    logger.info(msg);

    publishProgressMessage(msg);
}

From source file:de.alexkamp.sandbox.ChrootSandbox.java

@Override
public void walkDirectoryTree(String basePath, final DirectoryWalker walker) throws IOException {
    final int baseNameCount = data.getBaseDir().toPath().getNameCount();

    File base = new File(data.getBaseDir(), basePath);

    Files.walkFileTree(base.toPath(), new FileVisitor<Path>() {
        @Override/* w  w  w  .j  av a  2 s  . c o  m*/
        public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                throws IOException {
            if (walker.visitDirectory(calcSubpath(path))) {
                return FileVisitResult.CONTINUE;
            }
            return FileVisitResult.SKIP_SUBTREE;
        }

        private String calcSubpath(Path path) {
            if (path.getNameCount() == baseNameCount) {
                return "/";
            }
            return "/" + path.subpath(baseNameCount, path.getNameCount()).toString();
        }

        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                throws IOException {
            String subpath = calcSubpath(path);
            if (walker.visitFile(subpath)) {
                try (InputStream is = Files.newInputStream(path)) {
                    walker.visitFileContent(subpath, is);
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
            if (walker.failed(e)) {
                return FileVisitResult.CONTINUE;
            } else {
                return FileVisitResult.TERMINATE;
            }
        }

        @Override
        public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:de.prozesskraft.pkraft.Waitinstance.java

/**
 * ermittelt alle process binaries innerhalb eines directory baumes
 * @param pathScandir/*from  ww w. j  a  v  a2 s .co m*/
 * @return
 */
private static String[] getProcessBinaries(String pathScandir) {
    final ArrayList<String> allProcessBinaries = new ArrayList<String>();

    // den directory-baum durchgehen und fuer jeden eintrag ein entity erstellen
    try {
        Files.walkFileTree(Paths.get(pathScandir), new FileVisitor<Path>() {
            // called after a directory visit is complete
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            // called before a directory visit
            public FileVisitResult preVisitDirectory(Path walkingDir, BasicFileAttributes attrs)
                    throws IOException {
                return FileVisitResult.CONTINUE;
            }

            // called for each file visited. the basic file attributes of the file are also available
            public FileVisitResult visitFile(Path walkingFile, BasicFileAttributes attrs) throws IOException {
                // ist es ein process.pmb file?
                if (walkingFile.endsWith("process.pmb")) {
                    allProcessBinaries.add(new java.io.File(walkingFile.toString()).getAbsolutePath());
                }

                return FileVisitResult.CONTINUE;
            }

            // called for each file if the visit failed
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return allProcessBinaries.toArray(new String[allProcessBinaries.size()]);
}

From source file:org.pentaho.di.core.plugins.PluginFolderTest.java

private void cleanTempDir(Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override//from  w  w w. jav a 2s . c o  m
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

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

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

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

    try {//w ww.  j ava 2 s  .  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");
}

From source file:majordodo.task.BrokerTestUtils.java

@After
public void brokerTestUtilsAfter() throws Exception {
    if (startBroker) {
        server.close();/*from   w  w  w  .  j  a  v  a  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:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void deRegisterApp(String appId) {
    appId = appId.trim();/*from   w ww  . j a  v a2s  . c  o  m*/
    // find and stop any running instances
    stopApp(appId);

    // remove app from mapping
    apps.remove(appId);

    // get app directory from config and remove files for app_id
    File configDir = getAppConfigDirectory();
    File appDir = new File(configDir.getAbsolutePath() + File.separator + appId);
    try {
        Files.walkFileTree(appDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (dir.toFile().delete()) {
                    return FileVisitResult.CONTINUE;
                } else {
                    return FileVisitResult.TERMINATE;
                }
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().delete()) {
                    return FileVisitResult.CONTINUE;
                } else {
                    return FileVisitResult.TERMINATE;
                }
            }

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

    appDir.delete();

    File appInfoFile = new File(configDir.getAbsolutePath() + File.separator + appId + CONFIG_FILE_EXT);
    appInfoFile.delete();

}

From source file:org.schedulesdirect.grabber.Grabber.java

private void loadSeriesInfoIds(Path root) throws IOException {
    Files.walkFileTree(root, new FileVisitor<Path>() {
        @Override//from w  w  w .ja  v a 2 s .  co  m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.SKIP_SUBTREE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String name = file.getFileName().toString();
            name = name.substring(0, name.lastIndexOf('.'));
            cachedSeriesIds.add(name);
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc != null)
                throw exc;
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void removeExpiredSchedules(FileSystem vfs) throws IOException, JSONException {
    final int[] i = new int[] { 0 };
    final Path root = vfs.getPath("schedules");
    Files.walkFileTree(root, new FileVisitor<Path>() {

        @Override//w ww .j  a  va  2  s  . c  o  m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return !Files.isSameFile(dir, root) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            try (InputStream ins = Files.newInputStream(file)) {
                JSONArray sched = Config.get().getObjectMapper()
                        .readValue(IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        .getJSONArray("programs");
                if (isScheduleExpired(sched)) {
                    Files.delete(file);
                    ++i[0];
                }
            }
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

    });
    LOG.info(String.format("Removed %d expired schedule(s).", i[0]));
}