Search in sources :

Example 21 with ActionContext

use of org.structr.schema.action.ActionContext in project structr by structr.

the class SourcePattern method extractAndSetValue.

private void extractAndSetValue(final NodeInterface obj, final Document doc, final String selector, final String mappedType, final String mappedAttribute, final String mappedAttributeFunction, final SourcePage subPage) throws FrameworkException {
    // If the sub pattern has a mapped attribute, set the extracted value
    if (StringUtils.isNotEmpty(mappedAttribute)) {
        // Extract the value for this sub pattern's selector
        final String ex = doc.select(selector).text();
        final PropertyKey key = StructrApp.key(type(mappedType), mappedAttribute);
        if (StringUtils.isNotBlank(ex) && key != null) {
            Object convertedValue = ex;
            if (StringUtils.isNotBlank(mappedAttributeFunction)) {
                // input transformation requested
                ActionContext ctx = new ActionContext(securityContext);
                ctx.setConstant("input", convertedValue);
                convertedValue = Scripting.evaluate(ctx, null, "${" + mappedAttributeFunction + "}", " virtual property " + mappedAttribute);
            } else {
                // if no custom transformation is given, try input converter
                final PropertyConverter inputConverter = key.inputConverter(securityContext);
                if (inputConverter != null) {
                    convertedValue = inputConverter.convert(convertedValue);
                }
            }
            obj.setProperty(key, convertedValue);
        }
    // If the sub pattern has no mapped attribute but a sub page defined, query the patterns of the sub page
    } else if (subPage != null) {
        final String pageUrl = subPage.getProperty(SourcePage.url);
        final URI uri;
        try {
            uri = new URI(pageUrl);
        } catch (URISyntaxException ex) {
            throw new FrameworkException(422, "Unable to parse sub page url: " + pageUrl);
        }
        // This is the URL of the linked page derived from the enclosing selector
        final String subUrl = uri.getScheme() + "://" + uri.getAuthority() + doc.select(selector).attr("href");
        // Extract the content of the linked page
        final String subContent = getContent(subUrl);
        // Parse the content into a document
        final Document subDoc = Jsoup.parse(subContent);
        final List<SourcePattern> subPagePatterns = subPage.getProperty(SourcePage.patterns);
        // Loop through all patterns of the sub page
        for (final SourcePattern subPagePattern : subPagePatterns) {
            final Map<String, Object> params = new HashMap<>();
            params.put("document", subDoc);
            params.put("object", obj);
            subPagePattern.extract(params);
        // final String subPagePatternSelector = subPagePattern.getProperty(SourcePattern.selectorProperty);
        // 
        // 
        // // Extract
        // final String subEx = subDoc.select(subPagePatternSelector).text();
        // final String subPagePatternType = subPagePattern.getProperty(SourcePattern.mappedTypeProperty);
        // 
        // if (subPagePatternType != null) {
        // 
        // 
        // final Elements subParts = subDoc.select(subPagePatternSelector);
        // 
        // final Long j = 1L;
        // 
        // for (final Element subPart : subParts) {
        // 
        // final NodeInterface subObj = create(subPagePatternType);
        // 
        // final List<SourcePattern> subPagePatternPatterns = subPagePattern.getProperty(SourcePattern.subPatternsProperty);
        // 
        // for (final SourcePattern subPageSubPattern : subPagePatternPatterns) {
        // 
        // 
        // final String subPagePatternSelector = subPageSubPattern.getProperty(SourcePattern.selectorProperty);
        // 
        // 
        // 
        // final String subPageSubPatternSelector = subPagePatternSelector + ":nth-child(" + j + ") > " + subPagePatternSelector;
        // 
        // extractAndSetValue(subObj, subDoc, subSelector, mappedType, subPatternMappedAttribute);
        // 
        // 
        // final String subSubEx = subDoc.select(subPageSubPatternSelector).text();
        // 
        // if (subSubEx != null && subSubEx != = '' && subPageSubPattern.mappedAttribute != null) {
        // 
        // final PropertyKey key = StructrApp.key(type(mappedType), subPatternMappedAttribute);
        // if (key != null) {
        // 
        // subObj.setProperty(key, subSubEx);
        // }
        // 
        // }
        // 
        // final String subPagePatternMappedAttribute = subPagePattern.getProperty(SourcePattern.mappedAttributeProperty);
        // 
        // final PropertyKey key = StructrApp.key(type(mappedType), subPagePatternMappedAttribute);
        // if (key != null) {
        // 
        // obj.setProperty(key, subSubEx);
        // }
        // 
        // }
        // 
        // } else {
        // 
        // if (subEx != null && subEx != = '' && subPagePattern.mappedAttribute != null) {
        // obj[subPagePattern.mappedAttribute] = subEx;
        // }
        }
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) URISyntaxException(java.net.URISyntaxException) ActionContext(org.structr.schema.action.ActionContext) Document(org.jsoup.nodes.Document) URI(java.net.URI) PropertyConverter(org.structr.core.converter.PropertyConverter) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 22 with ActionContext

use of org.structr.schema.action.ActionContext in project structr by structr.

the class File method getInputStream.

static InputStream getInputStream(final File thisFile) {
    final java.io.File fileOnDisk = thisFile.getFileOnDisk();
    try {
        final FileInputStream fis = new FileInputStream(fileOnDisk);
        final SecurityContext securityContext = thisFile.getSecurityContext();
        if (thisFile.isTemplate()) {
            boolean editModeActive = false;
            if (securityContext.getRequest() != null) {
                final String editParameter = securityContext.getRequest().getParameter("edit");
                if (editParameter != null) {
                    editModeActive = !RenderContext.EditMode.NONE.equals(RenderContext.editMode(editParameter));
                }
            }
            if (!editModeActive) {
                final String content = IOUtils.toString(fis, "UTF-8");
                // close input stream here
                fis.close();
                try {
                    final String result = Scripting.replaceVariables(new ActionContext(securityContext), thisFile, content);
                    String encoding = "UTF-8";
                    final String cType = getContentType();
                    if (cType != null) {
                        final String charset = StringUtils.substringAfterLast(cType, "charset=").trim().toUpperCase();
                        try {
                            if (!"".equals(charset) && Charset.isSupported(charset)) {
                                encoding = charset;
                            }
                        } catch (IllegalCharsetNameException ice) {
                            logger.warn("Charset is not supported '{}'. Using 'UTF-8'", charset);
                        }
                    }
                    return IOUtils.toInputStream(result, encoding);
                } catch (Throwable t) {
                    logger.warn("Scripting error in {}:\n{}\n{}", thisFile.getUuid(), content, t.getMessage());
                }
            }
        }
        return fis;
    } catch (IOException ex) {
        logger.warn("Unable to open input stream for {}: {}", fileOnDisk.getPath(), ex.getMessage());
    }
    return null;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) SecurityContext(org.structr.common.SecurityContext) IOException(java.io.IOException) ActionContext(org.structr.schema.action.ActionContext) FileInputStream(java.io.FileInputStream)

Example 23 with ActionContext

use of org.structr.schema.action.ActionContext in project structr by structr.

the class FunctionProperty method setProperty.

@Override
public Object setProperty(SecurityContext securityContext, GraphObject obj, T value) throws FrameworkException {
    try {
        final ActionContext ctx = new ActionContext(securityContext);
        ctx.setConstant("value", value);
        return (T) Scripting.evaluate(ctx, obj, "${".concat(writeFunction).concat("}"), "setProperty(" + jsonName + ")");
    } catch (Throwable t) {
        logger.warn("Exception while evaluating write function in Function property \"{}\"", jsonName());
    }
    return null;
}
Also used : ActionContext(org.structr.schema.action.ActionContext)

Example 24 with ActionContext

use of org.structr.schema.action.ActionContext in project structr by structr.

the class SimpleMessagingTest method test01.

@Test
public void test01() {
    try (final Tx tx = app.tx()) {
        MessageClient client1 = app.create(MessageClient.class, "client1");
        MessageSubscriber sub = app.create(MessageSubscriber.class, "sub");
        List<MessageSubscriber> subList = new ArrayList<>();
        subList.add(sub);
        client1.setProperty(StructrApp.key(MessageClient.class, "subscribers"), subList);
        sub.setProperty(StructrApp.key(MessageSubscriber.class, "topic"), "test");
        sub.setProperty(StructrApp.key(MessageSubscriber.class, "callback"), "set(this, 'name', retrieve('message'))");
        Scripting.replaceVariables(new ActionContext(securityContext, null), client1, "${{Structr.log('Sending message'); Structr.get('this').sendMessage('test','testmessage');}}");
        assertEquals("testmessage", sub.getName());
        tx.success();
    } catch (FrameworkException ex) {
        fail("Exception during test: " + ex.getMessage());
    }
}
Also used : MessageSubscriber(org.structr.messaging.engine.entities.MessageSubscriber) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ArrayList(java.util.ArrayList) ActionContext(org.structr.schema.action.ActionContext) MessageClient(org.structr.messaging.engine.entities.MessageClient) Test(org.junit.Test)

Example 25 with ActionContext

use of org.structr.schema.action.ActionContext in project structr by structr.

the class LocalizationTest method testLocalizationWithoutDomain.

@Test
public void testLocalizationWithoutDomain() {
    final PropertyKey<String> localizedName = StructrApp.key(Localization.class, "localizedName");
    final PropertyKey<String> domain = StructrApp.key(Localization.class, "domain");
    final PropertyKey<String> locale = StructrApp.key(Localization.class, "locale");
    // create
    try (final Tx tx = app.tx()) {
        app.create(Localization.class, new NodeAttribute<>(Localization.name, "test1"), new NodeAttribute<>(locale, "de"), new NodeAttribute<>(localizedName, "test1-de-no_domain"));
        app.create(Localization.class, new NodeAttribute<>(Localization.name, "test2"), new NodeAttribute<>(locale, "de"), new NodeAttribute<>(domain, "ExistingDomain"), new NodeAttribute<>(localizedName, "test2-de-ExistingDomain"));
        app.create(Localization.class, new NodeAttribute<>(Localization.name, "test3"), new NodeAttribute<>(locale, "de_DE"), new NodeAttribute<>(localizedName, "test3-de_DE-no_domain"));
        app.create(Localization.class, new NodeAttribute<>(Localization.name, "test4"), new NodeAttribute<>(locale, "de_DE"), new NodeAttribute<>(domain, "ExistingDomain"), new NodeAttribute<>(localizedName, "test4-de_DE-ExistingDomain"));
        tx.success();
    } catch (FrameworkException fex) {
        fail("Unexpected exception.");
    }
    try (final Tx tx = app.tx()) {
        final ActionContext ctx = new ActionContext(securityContext);
        ctx.setLocale(new Locale("de"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1')}", "test"));
        assertEquals("Invalid localization result", "test2-de-ExistingDomain", Scripting.evaluate(ctx, null, "${localize('test2', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test2", Scripting.evaluate(ctx, null, "${localize('test2', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test2", Scripting.evaluate(ctx, null, "${localize('test2')}", "test"));
        assertEquals("Invalid localization result", "test3", Scripting.evaluate(ctx, null, "${localize('test3', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test3", Scripting.evaluate(ctx, null, "${localize('test3', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test3", Scripting.evaluate(ctx, null, "${localize('test3')}", "test"));
        assertEquals("Invalid localization result", "test4", Scripting.evaluate(ctx, null, "${localize('test4', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test4", Scripting.evaluate(ctx, null, "${localize('test4', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test4", Scripting.evaluate(ctx, null, "${localize('test4')}", "test"));
        tx.success();
    } catch (UnlicensedException | FrameworkException fex) {
        fail("Unexpected exception.");
    }
    try (final Tx tx = app.tx()) {
        final ActionContext ctx = new ActionContext(securityContext);
        ctx.setLocale(new Locale("de", "DE"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test1-de-no_domain", Scripting.evaluate(ctx, null, "${localize('test1')}", "test"));
        assertEquals("Invalid localization result", "test2-de-ExistingDomain", Scripting.evaluate(ctx, null, "${localize('test2', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test2", Scripting.evaluate(ctx, null, "${localize('test2', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test2", Scripting.evaluate(ctx, null, "${localize('test2')}", "test"));
        assertEquals("Invalid localization result", "test3-de_DE-no_domain", Scripting.evaluate(ctx, null, "${localize('test3', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test3-de_DE-no_domain", Scripting.evaluate(ctx, null, "${localize('test3', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test3-de_DE-no_domain", Scripting.evaluate(ctx, null, "${localize('test3')}", "test"));
        assertEquals("Invalid localization result", "test4-de_DE-ExistingDomain", Scripting.evaluate(ctx, null, "${localize('test4', 'ExistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test4", Scripting.evaluate(ctx, null, "${localize('test4', 'NonexistingDomain')}", "test"));
        assertEquals("Invalid localization result", "test4", Scripting.evaluate(ctx, null, "${localize('test4')}", "test"));
        tx.success();
    } catch (UnlicensedException | FrameworkException fex) {
        fail("Unexpected exception.");
    }
}
Also used : Locale(java.util.Locale) UnlicensedException(org.structr.common.error.UnlicensedException) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ActionContext(org.structr.schema.action.ActionContext) Test(org.junit.Test) StructrTest(org.structr.common.StructrTest)

Aggregations

ActionContext (org.structr.schema.action.ActionContext)44 FrameworkException (org.structr.common.error.FrameworkException)38 Tx (org.structr.core.graph.Tx)34 Test (org.junit.Test)33 StructrTest (org.structr.common.StructrTest)22 TestOne (org.structr.core.entity.TestOne)13 UnlicensedException (org.structr.common.error.UnlicensedException)11 GraphObject (org.structr.core.GraphObject)7 NodeInterface (org.structr.core.graph.NodeInterface)7 LinkedList (java.util.LinkedList)6 List (java.util.List)6 PropertyMap (org.structr.core.property.PropertyMap)6 Date (java.util.Date)5 SecurityContext (org.structr.common.SecurityContext)5 GraphObjectMap (org.structr.core.GraphObjectMap)4 Principal (org.structr.core.entity.Principal)4 SchemaNode (org.structr.core.entity.SchemaNode)4 PropertyKey (org.structr.core.property.PropertyKey)4 StructrUiTest (org.structr.web.StructrUiTest)4 SimpleDateFormat (java.text.SimpleDateFormat)3