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:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected void deleteFile(SyncFile sourceSyncFile, SyncFile targetSyncFile) throws Exception {

    if (sourceSyncFile.getUiEvent() == SyncFile.UI_EVENT_DELETED_LOCAL) {
        return;/*from   w w  w . j av  a2 s  . c  o m*/
    }

    sourceSyncFile.setModifiedTime(targetSyncFile.getModifiedTime());

    String event = targetSyncFile.getEvent();

    if (event.equals(SyncFile.EVENT_TRASH)) {
        sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_TRASHED_REMOTE);
    } else {
        sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_DELETED_REMOTE);
    }

    sourceSyncFile.setUserId(targetSyncFile.getUserId());
    sourceSyncFile.setUserName(targetSyncFile.getUserName());

    if (!sourceSyncFile.isUnsynced()) {
        SyncFileService.deleteSyncFile(sourceSyncFile);
    }

    Path sourceFilePath = Paths.get(sourceSyncFile.getFilePathName());

    if (FileUtil.notExists(sourceFilePath)) {
        return;
    }

    final Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

    if (sourceSyncFile.isFile()) {
        watcher.addDeletedFilePathName(sourceSyncFile.getFilePathName());

        FileUtil.deleteFile(sourceFilePath);

        return;
    }

    Files.walkFileTree(sourceFilePath, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

            if (ioe != null) {
                return super.postVisitDirectory(filePath, ioe);
            }

            watcher.addDeletedFilePathName(filePath.toString());

            FileUtil.deleteFile(filePath);

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            watcher.unregisterFilePath(filePath);

            return super.preVisitDirectory(filePath, basicFileAttributes);
        }

        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            watcher.addDeletedFilePathName(filePath.toString());

            FileUtil.deleteFile(filePath);

            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:it.polimi.diceH2020.launcher.Experiment.java

void wipeResultDir() throws IOException {
    Path result = Paths.get(settings.getResultDir());
    if (Files.exists(result)) {
        Files.walkFileTree(result, new SimpleFileVisitor<Path>() {
            @Override//ww w .java2 s.  com
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

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

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void deRegisterApp(String appId) {
    appId = appId.trim();//from  w w w . j  av  a2  s.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.structr.web.maintenance.DeployCommand.java

private void doImport(final Map<String, Object> attributes) throws FrameworkException {

    missingPrincipals.clear();/*  w  ww. j  a v a  2  s.co m*/

    final long startTime = System.currentTimeMillis();
    customHeaders.put("start", new Date(startTime).toString());

    final String path = (String) attributes.get("source");
    final SecurityContext ctx = SecurityContext.getSuperUserInstance();
    final App app = StructrApp.getInstance(ctx);

    ctx.setDoTransactionNotifications(false);
    ctx.disableEnsureCardinality();
    ctx.disableModificationOfAccessTime();

    final Map<String, Object> componentsConf = new HashMap<>();
    final Map<String, Object> templatesConf = new HashMap<>();
    final Map<String, Object> pagesConf = new HashMap<>();
    final Map<String, Object> filesConf = new HashMap<>();

    if (StringUtils.isBlank(path)) {

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

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

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

    if (!Files.isDirectory(source)) {

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

    final Map<String, Object> broadcastData = new HashMap();
    broadcastData.put("type", DEPLOYMENT_IMPORT_STATUS);
    broadcastData.put("subtype", DEPLOYMENT_STATUS_BEGIN);
    broadcastData.put("start", startTime);
    broadcastData.put("source", source);
    TransactionCommand.simpleBroadcastGenericMessage(broadcastData);

    // apply configuration
    final Path preDeployConf = source.resolve("pre-deploy.conf");
    if (Files.exists(preDeployConf)) {

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

            final String confSource = new String(Files.readAllBytes(preDeployConf), Charset.forName("utf-8"))
                    .trim();

            if (confSource.length() > 0) {

                info("Applying pre-deployment configuration from {}", preDeployConf);
                publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS,
                        "Applying pre-deployment configuration");

                Scripting.evaluate(new ActionContext(ctx), null, confSource, "pre-deploy.conf");
            } else {

                info("Ignoring empty pre-deployment configuration {}", preDeployConf);

            }

            tx.success();

        } catch (Throwable t) {
            logger.warn("", t);
            publishDeploymentWarningMessage("Exception caught while importing pre-deploy.conf", t.toString());
        }
    }

    // backup previous value of change log setting
    // temporary disable creation of change log
    final boolean changeLogEnabled = Settings.ChangelogEnabled.getValue();
    Settings.ChangelogEnabled.setValue(false);

    // read grants.json
    publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing resource access grants");

    final Path grantsConf = source.resolve("security/grants.json");
    if (Files.exists(grantsConf)) {

        info("Reading {}", grantsConf);
        importListData(ResourceAccess.class, readConfigList(grantsConf));
    }

    // read schema-methods.json
    final Path schemaMethodsConf = source.resolve("schema-methods.json");
    if (Files.exists(schemaMethodsConf)) {

        info("Reading {}", schemaMethodsConf);
        final String title = "Deprecation warning";
        final String text = "Found file 'schema-methods.json'. Newer versions store global schema methods in the schema snapshot file. Recreate the export with the current version to avoid compatibility issues. Support for importing this file will be dropped in future versions.";

        info(title + ": " + text);
        publishDeploymentWarningMessage(title, text);

        importListData(SchemaMethod.class, readConfigList(schemaMethodsConf));
    }

    // read mail-templates.json
    final Path mailTemplatesConf = source.resolve("mail-templates.json");
    if (Files.exists(mailTemplatesConf)) {

        info("Reading {}", mailTemplatesConf);
        publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing mail templates");

        importListData(MailTemplate.class, readConfigList(mailTemplatesConf));
    }

    // read widgets.json
    final Path widgetsConf = source.resolve("widgets.json");
    if (Files.exists(widgetsConf)) {

        info("Reading {}", widgetsConf);
        publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing widgets");

        importListData(Widget.class, readConfigList(widgetsConf));
    }

    // read localizations.json
    final Path localizationsConf = source.resolve("localizations.json");
    if (Files.exists(localizationsConf)) {

        final PropertyMap additionalData = new PropertyMap();

        // Question: shouldn't this be true? No, 'imported' is a flag for legacy-localization which
        // have been imported from a legacy-system which was replaced by structr.
        // it is a way to differentiate between new and old localization strings
        additionalData.put(StructrApp.key(Localization.class, "imported"), false);

        info("Reading {}", localizationsConf);
        publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing localizations");

        importListData(Localization.class, readConfigList(localizationsConf), additionalData);
    }

    // read files.conf
    final Path filesConfFile = source.resolve("files.json");
    if (Files.exists(filesConfFile)) {

        info("Reading {}", filesConfFile);
        filesConf.putAll(readConfigMap(filesConfFile));
    }

    // read pages.conf
    final Path pagesConfFile = source.resolve("pages.json");
    if (Files.exists(pagesConfFile)) {

        info("Reading {}", pagesConfFile);
        pagesConf.putAll(readConfigMap(pagesConfFile));
    }

    // read components.conf
    final Path componentsConfFile = source.resolve("components.json");
    if (Files.exists(componentsConfFile)) {

        info("Reading {}", componentsConfFile);
        componentsConf.putAll(readConfigMap(componentsConfFile));
    }

    // read templates.conf
    final Path templatesConfFile = source.resolve("templates.json");
    if (Files.exists(templatesConfFile)) {

        info("Reading {}", templatesConfFile);
        templatesConf.putAll(readConfigMap(templatesConfFile));
    }

    // import schema
    final Path schema = source.resolve("schema");
    if (Files.exists(schema)) {

        try {

            info("Importing data from schema/ directory");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing schema");

            Files.walkFileTree(schema, new SchemaImportVisitor(schema));

        } catch (IOException ioex) {
            logger.warn("Exception while importing schema", ioex);
        }
    }

    // import files
    final Path files = source.resolve("files");
    if (Files.exists(files)) {

        try {

            info("Importing files (unchanged files will be skipped)");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing files");

            FileImportVisitor fiv = new FileImportVisitor(files, filesConf);
            Files.walkFileTree(files, fiv);
            fiv.handleDeferredFiles();

        } catch (IOException ioex) {
            logger.warn("Exception while importing files", ioex);
        }
    }

    for (StructrModule module : StructrApp.getConfiguration().getModules().values()) {

        if (module.hasDeploymentData()) {

            info("Importing deployment data for module {}", module.getName());
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS,
                    "Importing deployment data for module " + module.getName());

            final Path moduleFolder = source.resolve("modules/" + module.getName() + "/");

            module.importDeploymentData(moduleFolder, getGson());
        }
    }

    // construct paths
    final Path templates = source.resolve("templates");
    final Path components = source.resolve("components");
    final Path pages = source.resolve("pages");
    final Path sitesConfFile = source.resolve("sites.json");

    // remove all DOMNodes from the database (clean webapp for import, but only
    // if the actual import directories exist, don't delete web components if
    // an empty directory was specified accidentially).
    if (Files.exists(templates) && Files.exists(components) && Files.exists(pages)) {

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

            final String tenantIdentifier = app.getDatabaseService().getTenantIdentifier();
            final String optionalTenantLabel = (tenantIdentifier != null) ? ":" + tenantIdentifier : "";

            info("Removing pages, templates and components");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS,
                    "Removing pages, templates and components");

            app.cypher("MATCH (n" + optionalTenantLabel + ":DOMNode) DETACH DELETE n", null);

            if (Files.exists(sitesConfFile)) {

                info("Removing sites");
                publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Removing sites");

                app.cypher("MATCH (n" + optionalTenantLabel + ":Site) DETACH DELETE n", null);
            }

            FlushCachesCommand.flushAll();

            tx.success();
        }

    } else {

        logger.info(
                "Import directory does not seem to contain pages, templates or components, NOT removing any data.");
    }

    // import templates, must be done before pages so the templates exist
    if (Files.exists(templates)) {

        try {

            info("Importing templates");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing templates");

            Files.walkFileTree(templates, new TemplateImportVisitor(templatesConf));

        } catch (IOException ioex) {
            logger.warn("Exception while importing templates", ioex);
        }
    }

    // import components, must be done before pages so the shared components exist
    if (Files.exists(components)) {

        try {

            info("Importing shared components");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing shared components");

            Files.walkFileTree(components, new ComponentImportVisitor(componentsConf));

        } catch (IOException ioex) {
            logger.warn("Exception while importing shared components", ioex);
        }
    }

    // import pages
    if (Files.exists(pages)) {

        try {

            info("Importing pages");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing pages");

            Files.walkFileTree(pages, new PageImportVisitor(pages, pagesConf));

        } catch (IOException ioex) {
            logger.warn("Exception while importing pages", ioex);
        }
    }

    // import sites
    if (Files.exists(sitesConfFile)) {

        info("Importing sites");
        publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Importing sites");

        importSites(readConfigList(sitesConfFile));
    }

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

        deferredPageLinks.forEach((String linkableUUID, String pagePath) -> {

            try {
                final DOMNode page = StructrApp.getInstance().get(DOMNode.class, linkableUUID);
                final Linkable linkedPage = StructrApp.getInstance().nodeQuery(Linkable.class)
                        .and(StructrApp.key(Page.class, "path"), pagePath).or(Page.name, pagePath).getFirst();

                ((LinkSource) page).setLinkable(linkedPage);

            } catch (FrameworkException ex) {
            }

        });

        deferredPageLinks.clear();

        tx.success();
    }

    // apply configuration
    final Path postDeployConf = source.resolve("post-deploy.conf");
    if (Files.exists(postDeployConf)) {

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

            final String confSource = new String(Files.readAllBytes(postDeployConf), Charset.forName("utf-8"))
                    .trim();

            if (confSource.length() > 0) {

                info("Applying post-deployment configuration from {}", postDeployConf);
                publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS,
                        "Applying post-deployment configuration");

                Scripting.evaluate(new ActionContext(ctx), null, confSource, "post-deploy.conf");

            } else {

                info("Ignoring empty post-deployment configuration {}", postDeployConf);

            }

            tx.success();

        } catch (Throwable t) {
            logger.warn("", t);
            publishDeploymentWarningMessage("Exception caught while importing post-deploy.conf", t.toString());
        }
    }

    if (!missingPrincipals.isEmpty()) {

        final String title = "Missing Principal(s)";
        final String text = "The following user(s) and/or group(s) are missing for grants or node ownership during deployment.<br>"
                + "Because of these missing grants/ownerships, the functionality is not identical to the export you just imported!<br><br>"
                + String.join(", ", missingPrincipals)
                + "<br><br>Consider adding these principals to your <a href=\"https://support.structr.com/article/428#pre-deployconf-javascript\">pre-deploy.conf</a> and re-importing.";

        info("\n###############################################################################\n"
                + "\tWarning: " + title + "!\n"
                + "\tThe following user(s) and/or group(s) are missing for grants or node ownership during deployment.\n"
                + "\tBecause of these missing grants/ownerships, the functionality is not identical to the export you just imported!\n\n"
                + "\t" + String.join(", ", missingPrincipals)
                + "\n\n\tConsider adding these principals to your 'pre-deploy.conf' (see https://support.structr.com/article/428#pre-deployconf-javascript) and re-importing.\n"
                + "###############################################################################");
        publishDeploymentWarningMessage(title, text);
    }

    // restore saved value
    Settings.ChangelogEnabled.setValue(changeLogEnabled);

    final long endTime = System.currentTimeMillis();
    DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    final String duration = decimalFormat.format(((endTime - startTime) / 1000.0)) + "s";

    customHeaders.put("end", new Date(endTime).toString());
    customHeaders.put("duration", duration);

    info("Import from {} done. (Took {})", source.toString(), duration);

    broadcastData.put("subtype", DEPLOYMENT_STATUS_END);
    broadcastData.put("end", endTime);
    broadcastData.put("duration", duration);
    TransactionCommand.simpleBroadcastGenericMessage(broadcastData);

}

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

/**
 * called every hour to clean up the repo
 */// ww w  .  j  a  v a  2 s.  c o  m
@Scheduled(cron = "12 27 */1 * * *")
public void cleanUpRepoFolder() {

    long now = System.currentTimeMillis();
    long expiredTime = now - FILE_EXPIRY_MS;

    try {
        Files.walkFileTree(getRepoRoot(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!dir.equals(getRepoRoot()) && isDirEmpty(dir)) {
                    log.info("Deleting repo directory :" + dir);
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (Files.getLastModifiedTime(file).toMillis() < expiredTime) {
                    log.info("Deleting repo file      :" + file);
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.log(Level.SEVERE, "Failed cleaning up repo: " + e.getMessage());
    }

    log.info(String.format("Cleaned up repo in %d ms", System.currentTimeMillis() - now));
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java

private void removeExistingPathAndRecalculateSpaceAndChecksum(Path path, OwncloudLocalQuotaImpl quota) {
    try {//from   w w  w .  j a  va 2 s.  com
        if (Files.isDirectory(path)) {
            log.debug("Remove Directory {} with all its Content and reduce the used Space of User {}",
                    path.toAbsolutePath().normalize(), quota.getUsername());
            Files.walkFileTree(path, new DeleteFileVisitor(quota::reduceUsed));
        } else {
            log.debug("Remove File {} and reduce the used Space of User {}", path.toAbsolutePath().normalize(),
                    quota.getUsername());
            quota.reduceUsed(Files.size(path));
            Files.delete(path);
        }
    } catch (IOException e) {
        val logMessage = String.format("Cannot remove Path %s", path.toAbsolutePath().normalize());
        log.error(logMessage, e);
        throw new OwncloudLocalResourceException(logMessage, e);
    } finally {
        checksumService.recalculateChecksum(path);
    }
}

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

private void loadSeriesInfoIds(Path root) throws IOException {
    Files.walkFileTree(root, new FileVisitor<Path>() {
        @Override/* ww w.  j  ava  2s  .c o 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.apache.openaz.xacml.pdp.test.TestBase.java

/**
 * This runs() the test instance. It first configure's itself and then walks the requests directory issue
 * each request to the PDP engine.//w  w  w.jav a2 s  .c om
 *
 * @throws java.io.IOException
 * @throws org.apache.openaz.xacml.util.FactoryException
 */
public void run() throws IOException, FactoryException {
    //
    // Configure ourselves
    //
    this.configure();
    //
    // Loop and run
    //
    int runs = 1;
    do {
        long lTimeStart = System.currentTimeMillis();
        logger.info("Run number: " + runs);
        //
        // Walk the request directory
        //
        Files.walkFileTree(Paths.get(this.directory.toString(), "requests"), this);
        long lTimeEnd = System.currentTimeMillis();
        logger.info("Run elapsed time: " + (lTimeEnd - lTimeStart) + "ms");
        //
        // Dump the stats
        //
        this.dumpStats();
        this.resetStats();
        //
        // Increment
        //
        runs++;
    } while ((this.loop == -1 ? true : runs <= this.loop));
}

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

@Test
public void clean_method_should_delete_and_log() throws Exception {
    //given/*from   w w  w  .  ja va2s . c  o  m*/
    final Path path = temporaryFolder.newFolder("afterClean").toPath();
    final Path licensePath = temporaryFolder.newFolder("licenses").toPath();
    platformSetup.init();

    //when
    systemOutRule.clearLog();
    platformSetup.clean();

    //then
    final String log = systemOutRule.getLogWithNormalizedLineSeparator();
    final String[] split = log.split("\n");
    assertThat(split).as("should log message").isNotEmpty();
    assertThat(split[split.length - 1]).as("should log message").contains("DEBUG")
            .endsWith("Execute DeleteAllConfigurationInTransaction transaction.");

    platformSetup.pull(path, licensePath);
    List<FullBonitaConfiguration> configurations = new ArrayList<>();
    Files.walkFileTree(path, new AllConfigurationResourceVisitor(configurations));
    assertThat(configurations).as("should remove all files").isEmpty();

    Files.walkFileTree(licensePath, new AllConfigurationResourceVisitor(configurations));
    assertThat(configurations).as("should remove all files").isEmpty();
}