Search in sources :

Example 1 with Localization

use of org.structr.core.entity.Localization in project structr by structr.

the class DeployCommand method exportLocalizations.

private void exportLocalizations(final Path target) throws FrameworkException {
    logger.info("Exporting localizations");
    final PropertyKey<String> localizedNameKey = StructrApp.key(Localization.class, "localizedName");
    final PropertyKey<String> domainKey = StructrApp.key(Localization.class, "domain");
    final PropertyKey<String> localeKey = StructrApp.key(Localization.class, "locale");
    final PropertyKey<String> importedKey = StructrApp.key(Localization.class, "imported");
    final List<Map<String, Object>> localizations = new LinkedList<>();
    final App app = StructrApp.getInstance();
    try (final Tx tx = app.tx()) {
        for (final Localization localization : app.nodeQuery(Localization.class).sort(Localization.name).getAsList()) {
            final Map<String, Object> entry = new TreeMap<>();
            localizations.add(entry);
            entry.put("name", localization.getProperty(Localization.name));
            entry.put("localizedName", localization.getProperty(localizedNameKey));
            entry.put("domain", localization.getProperty(domainKey));
            entry.put("locale", localization.getProperty(localeKey));
            entry.put("imported", localization.getProperty(importedKey));
            entry.put("visibleToAuthenticatedUsers", localization.getProperty(MailTemplate.visibleToAuthenticatedUsers));
            entry.put("visibleToPublicUsers", localization.getProperty(MailTemplate.visibleToPublicUsers));
        }
        tx.success();
    }
    try (final Writer fos = new OutputStreamWriter(new FileOutputStream(target.toFile()))) {
        getGson().toJson(localizations, fos);
    } catch (IOException ioex) {
        logger.warn("", ioex);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) IOException(java.io.IOException) TreeMap(java.util.TreeMap) LinkedList(java.util.LinkedList) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Localization(org.structr.core.entity.Localization) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PropertyMap(org.structr.core.property.PropertyMap) TreeMap(java.util.TreeMap) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) FileWriter(java.io.FileWriter)

Example 2 with Localization

use of org.structr.core.entity.Localization in project structr by structr.

the class DeployCommand method doImport.

// ----- private methods -----
private void doImport(final Map<String, Object> attributes) throws FrameworkException {
    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");
    // 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();
            info("Removing pages, templates and components");
            publishDeploymentProgressMessage(DEPLOYMENT_IMPORT_STATUS, "Removing pages, templates and components");
            if (tenantIdentifier != null) {
                app.cypher("MATCH (n:" + tenantIdentifier + ":DOMNode) DETACH DELETE n", null);
            } else {
                app.cypher("MATCH (n:DOMNode) 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);
        }
    }
    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());
        }
    }
    // 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);
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkSource(org.structr.web.entity.LinkSource) FileImportVisitor(org.structr.web.maintenance.deploy.FileImportVisitor) DecimalFormat(java.text.DecimalFormat) Page(org.structr.web.entity.dom.Page) PageImportVisitor(org.structr.web.maintenance.deploy.PageImportVisitor) SchemaImportVisitor(org.structr.web.maintenance.deploy.SchemaImportVisitor) Localization(org.structr.core.entity.Localization) DOMNode(org.structr.web.entity.dom.DOMNode) Path(java.nio.file.Path) FrameworkException(org.structr.common.error.FrameworkException) Tx(org.structr.core.graph.Tx) ComponentImportVisitor(org.structr.web.maintenance.deploy.ComponentImportVisitor) IOException(java.io.IOException) ActionContext(org.structr.schema.action.ActionContext) Date(java.util.Date) StructrModule(org.structr.module.StructrModule) PropertyMap(org.structr.core.property.PropertyMap) SecurityContext(org.structr.common.SecurityContext) TemplateImportVisitor(org.structr.web.maintenance.deploy.TemplateImportVisitor) Linkable(org.structr.web.entity.Linkable)

Example 3 with Localization

use of org.structr.core.entity.Localization in project structr by structr.

the class DeploymentTest method test29Localizations.

@Test
public void test29Localizations() {
    // setup
    try (final Tx tx = app.tx()) {
        app.create(Localization.class, new NodeAttribute<>(StructrApp.key(Localization.class, "name"), "localization1"), new NodeAttribute<>(StructrApp.key(Localization.class, "domain"), "domain1"), new NodeAttribute<>(StructrApp.key(Localization.class, "locale"), "de_DE"), new NodeAttribute<>(StructrApp.key(Localization.class, "localizedName"), "localizedName1"));
        app.create(Localization.class, new NodeAttribute<>(StructrApp.key(Localization.class, "name"), "localization2"), new NodeAttribute<>(StructrApp.key(Localization.class, "domain"), "domain2"), new NodeAttribute<>(StructrApp.key(Localization.class, "locale"), "en"), new NodeAttribute<>(StructrApp.key(Localization.class, "localizedName"), "localizedName2"));
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
        fail("Unexpected exception.");
    }
    // test
    doImportExportRoundtrip(true);
    // check
    try (final Tx tx = app.tx()) {
        final Localization localization1 = app.nodeQuery(Localization.class).and(Localization.name, "localization1").getFirst();
        final Localization localization2 = app.nodeQuery(Localization.class).and(Localization.name, "localization2").getFirst();
        Assert.assertNotNull("Invalid deployment result", localization1);
        Assert.assertNotNull("Invalid deployment result", localization2);
        Assert.assertEquals("Invalid Localization deployment result", "localization1", localization1.getProperty(StructrApp.key(Localization.class, "name")));
        Assert.assertEquals("Invalid Localization deployment result", "domain1", localization1.getProperty(StructrApp.key(Localization.class, "domain")));
        Assert.assertEquals("Invalid Localization deployment result", "de_DE", localization1.getProperty(StructrApp.key(Localization.class, "locale")));
        Assert.assertEquals("Invalid Localization deployment result", "localizedName1", localization1.getProperty(StructrApp.key(Localization.class, "localizedName")));
        Assert.assertEquals("Invalid Localization deployment result", true, localization1.getProperty(StructrApp.key(Localization.class, "visibleToPublicUsers")));
        Assert.assertEquals("Invalid Localization deployment result", true, localization1.getProperty(StructrApp.key(Localization.class, "visibleToAuthenticatedUsers")));
        Assert.assertEquals("Invalid Localization deployment result", "localization2", localization2.getProperty(StructrApp.key(Localization.class, "name")));
        Assert.assertEquals("Invalid Localization deployment result", "domain2", localization2.getProperty(StructrApp.key(Localization.class, "domain")));
        Assert.assertEquals("Invalid Localization deployment result", "en", localization2.getProperty(StructrApp.key(Localization.class, "locale")));
        Assert.assertEquals("Invalid Localization deployment result", "localizedName2", localization2.getProperty(StructrApp.key(Localization.class, "localizedName")));
        Assert.assertEquals("Invalid Localization deployment result", true, localization2.getProperty(StructrApp.key(Localization.class, "visibleToPublicUsers")));
        Assert.assertEquals("Invalid Localization deployment result", true, localization2.getProperty(StructrApp.key(Localization.class, "visibleToAuthenticatedUsers")));
        tx.success();
    } catch (FrameworkException fex) {
        fail("Unexpected exception.");
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Localization(org.structr.core.entity.Localization) Test(org.junit.Test) StructrUiTest(org.structr.web.StructrUiTest)

Aggregations

Localization (org.structr.core.entity.Localization)3 Tx (org.structr.core.graph.Tx)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 FrameworkException (org.structr.common.error.FrameworkException)2 App (org.structr.core.app.App)2 StructrApp (org.structr.core.app.StructrApp)2 PropertyMap (org.structr.core.property.PropertyMap)2 FileOutputStream (java.io.FileOutputStream)1 FileWriter (java.io.FileWriter)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 Path (java.nio.file.Path)1 DecimalFormat (java.text.DecimalFormat)1 Date (java.util.Date)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 Test (org.junit.Test)1