Search in sources :

Example 11 with ActionContext

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

the class StructrScriptEngine method eval.

@Override
public Object eval(final String script, final ScriptContext context) throws ScriptException {
    try {
        final ActionContext actionContext = (ActionContext) get("_actionContext");
        final GraphObject entity = (GraphObject) get("_entity");
        return Functions.evaluate(actionContext, entity, script);
    } catch (UnlicensedException | FrameworkException fex) {
        // wrap FrameworkException in ScriptException and re-throw
        throw new ScriptException(fex);
    }
}
Also used : ScriptException(javax.script.ScriptException) UnlicensedException(org.structr.common.error.UnlicensedException) FrameworkException(org.structr.common.error.FrameworkException) ActionContext(org.structr.schema.action.ActionContext) GraphObject(org.structr.core.GraphObject)

Example 12 with ActionContext

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

the class StructrScriptable method get.

@Override
public Object get(final String name, Scriptable start) {
    if ("get".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1 && parameters[0] != null) {
                    try {
                        return wrap(context, thisObject, null, actionContext.evaluate(entity, parameters[0].toString(), null, null, 0));
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                } else if (parameters.length > 1) {
                    // execute builtin get function
                    final Function<Object, Object> function = Functions.get("get");
                    try {
                        final Object[] unwrappedParameters = new Object[parameters.length];
                        int i = 0;
                        // unwrap JS objects
                        for (final Object param : parameters) {
                            unwrappedParameters[i++] = unwrap(param);
                        }
                        return wrap(context, scope, null, function.apply(actionContext, entity, unwrappedParameters));
                    } catch (FrameworkException fex) {
                        exception = fex;
                    }
                    return null;
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("clear".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                actionContext.clear();
                return null;
            }
        }, null, 0, 0);
    }
    if ("this".equals(name)) {
        return wrap(this.scriptingContext, start, null, entity);
    }
    if ("me".equals(name)) {
        return wrap(this.scriptingContext, start, null, actionContext.getSecurityContext().getUser(false));
    }
    if ("vars".equals(name)) {
        NativeObject nobj = new NativeObject();
        for (Map.Entry<String, Object> entry : actionContext.getAllVariables().entrySet()) {
            nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
        }
        return nobj;
    }
    if ("include".equals(name) || "render".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length > 0 && parameters[0] != null) {
                    try {
                        final Function func = Functions.get(name);
                        if (func != null) {
                            actionContext.print(func.apply(actionContext, entity, parameters));
                        }
                        return null;
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("includeJs".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1) {
                    final String fileName = parameters[0].toString();
                    final String source = actionContext.getJavascriptLibraryCode(fileName);
                    // use cached / compiled source code for JS libs
                    Scripting.compileOrGetCached(context, source, fileName, 1).exec(context, scope);
                } else {
                    logger.warn("Incorrect usage of includeJs function. Takes exactly one parameter: The filename of the javascript file!");
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("batch".equals(name)) {
        return new IdFunctionObject(new BatchFunctionCall(actionContext, this), null, 0, 0);
    }
    if ("cache".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                final CacheExpression cacheExpr = new CacheExpression();
                Object retVal = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        cacheExpr.add(new ConstantExpression(parameters[i]));
                    }
                    retVal = cacheExpr.evaluate(actionContext, entity);
                } catch (FrameworkException ex) {
                    exception = ex;
                }
                return retVal;
            }
        }, null, 0, 0);
    }
    if ("slice".equals(name)) {
        return new IdFunctionObject(new SliceFunctionCall(actionContext, entity, scriptingContext), null, 0, 0);
    }
    if ("doPrivileged".equals(name) || "do_privileged".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                // backup security context
                final SecurityContext securityContext = StructrScriptable.this.actionContext.getSecurityContext();
                try {
                    // replace security context with super user context
                    actionContext.setSecurityContext(SecurityContext.getSuperUserInstance());
                    if (parameters != null && parameters.length == 1) {
                        final Object param = parameters[0];
                        if (param instanceof Script) {
                            final Script script = (Script) param;
                            return script.exec(context, scope);
                        } else {
                        // ...
                        }
                    } else {
                    // ...
                    }
                    return null;
                } finally {
                    // restore saved security context
                    StructrScriptable.this.actionContext.setSecurityContext(securityContext);
                }
            }
        }, null, 0, 0);
    }
    // execute builtin function?
    final Function<Object, Object> function = Functions.get(CaseHelper.toUnderscore(name, false));
    if (function != null) {
        return new IdFunctionObject(new FunctionWrapper(function), null, 0, 0);
    }
    return null;
}
Also used : SecurityContext(org.structr.common.SecurityContext) Context(org.mozilla.javascript.Context) ActionContext(org.structr.schema.action.ActionContext) Script(org.mozilla.javascript.Script) FrameworkException(org.structr.common.error.FrameworkException) ConstantExpression(org.structr.core.parser.ConstantExpression) IdFunctionCall(org.mozilla.javascript.IdFunctionCall) Scriptable(org.mozilla.javascript.Scriptable) CacheExpression(org.structr.core.parser.CacheExpression) NativeObject(org.mozilla.javascript.NativeObject) Function(org.structr.schema.action.Function) GrantFunction(org.structr.core.function.GrantFunction) SecurityContext(org.structr.common.SecurityContext) NativeObject(org.mozilla.javascript.NativeObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) GraphObject(org.structr.core.GraphObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap)

Example 13 with ActionContext

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

the class SystemTest method testRollbackOnError.

@Test
public void testRollbackOnError() {
    final ActionContext ctx = new ActionContext(securityContext, null);
    /**
     * first the old scripting style
     */
    TestOne testNode = null;
    try (final Tx tx = app.tx()) {
        testNode = createTestNode(TestOne.class);
        testNode.setProperty(TestOne.aString, "InitialString");
        testNode.setProperty(TestOne.anInt, 42);
        tx.success();
    } catch (FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception");
    }
    try (final Tx tx = app.tx()) {
        Scripting.replaceVariables(ctx, testNode, "${ ( set(this, 'aString', 'NewString'), set(this, 'anInt', 'NOT_AN_INTEGER') ) }");
        fail("StructrScript: setting anInt to 'NOT_AN_INTEGER' should cause an Exception");
        tx.success();
    } catch (FrameworkException expected) {
    }
    try {
        try (final Tx tx = app.tx()) {
            assertEquals("Property value should still have initial value!", "InitialString", testNode.getProperty(TestOne.aString));
            tx.success();
        }
    } catch (FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception");
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) TestOne(org.structr.core.entity.TestOne) ActionContext(org.structr.schema.action.ActionContext) Test(org.junit.Test)

Example 14 with ActionContext

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

the class ScriptingTest method testStructrScriptBatchFunction.

@Test
public void testStructrScriptBatchFunction() {
    try (final Tx tx = app.tx()) {
        createTestNodes(TestOne.class, 1000);
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception.");
    }
    try (final Tx tx = app.tx()) {
        final ActionContext ctx = new ActionContext(securityContext, null);
        Scripting.evaluate(ctx, null, "${batch(each(find('TestOne'), set(data, 'name', 'test')), 100)}", "test");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception: " + fex.getMessage());
    }
    try (final Tx tx = app.tx()) {
        final ActionContext ctx = new ActionContext(securityContext, null);
        Scripting.evaluate(ctx, null, "${batch(delete(find('TestOne')), 100)}", "test");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception: " + fex.getMessage());
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ActionContext(org.structr.schema.action.ActionContext) StructrTest(org.structr.common.StructrTest) Test(org.junit.Test)

Example 15 with ActionContext

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

the class ScriptingTest method testSystemProperties.

@Test
public void testSystemProperties() {
    try {
        final Principal user = createTestNode(Principal.class);
        // create new node
        TestOne t1 = createTestNode(TestOne.class, user);
        final SecurityContext userContext = SecurityContext.getInstance(user, AccessMode.Frontend);
        final App userApp = StructrApp.getInstance(userContext);
        try (final Tx tx = userApp.tx()) {
            final ActionContext userActionContext = new ActionContext(userContext, null);
            assertEquals("node should be of type TestOne", "TestOne", Scripting.replaceVariables(userActionContext, t1, "${(get(this, 'type'))}"));
            try {
                assertEquals("setting the type should fail", "TestTwo", Scripting.replaceVariables(userActionContext, t1, "${(set(this, 'type', 'TestThree'), get(this, 'type'))}"));
                fail("setting a system property should fail");
            } catch (FrameworkException fx) {
            }
            assertEquals("setting the type should work after setting it with unlock_system_properties_once", "TestFour", Scripting.replaceVariables(userActionContext, t1, "${(unlock_system_properties_once(this), set(this, 'type', 'TestFour'), get(this, 'type'))}"));
            tx.success();
        }
    } catch (FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception");
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) TestOne(org.structr.core.entity.TestOne) ActionContext(org.structr.schema.action.ActionContext) Principal(org.structr.core.entity.Principal) StructrTest(org.structr.common.StructrTest) Test(org.junit.Test)

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