Search in sources :

Example 1 with ConstantExpression

use of org.structr.core.parser.ConstantExpression 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 2 with ConstantExpression

use of org.structr.core.parser.ConstantExpression in project structr by structr.

the class Functions method evaluate.

public static Object evaluate(final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException, UnlicensedException {
    final String expressionWithoutNewlines = expression.replace('\n', ' ').replace('\r', ' ');
    final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines));
    tokenizer.eolIsSignificant(true);
    tokenizer.ordinaryChar('.');
    tokenizer.wordChars('_', '_');
    tokenizer.wordChars('.', '.');
    tokenizer.wordChars('!', '!');
    Expression root = new RootExpression();
    Expression current = root;
    Expression next = null;
    String lastToken = null;
    int token = 0;
    int level = 0;
    while (token != StreamTokenizer.TT_EOF) {
        token = nextToken(tokenizer);
        switch(token) {
            case StreamTokenizer.TT_EOF:
                break;
            case StreamTokenizer.TT_EOL:
                break;
            case StreamTokenizer.TT_NUMBER:
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER");
                }
                next = new ConstantExpression(tokenizer.nval);
                current.add(next);
                lastToken += "NUMBER";
                break;
            case StreamTokenizer.TT_WORD:
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval);
                }
                next = checkReservedWords(tokenizer.sval);
                Expression previousExpression = current.getPrevious();
                if (tokenizer.sval.startsWith(".") && previousExpression != null && previousExpression instanceof FunctionExpression && next instanceof ValueExpression) {
                    final FunctionExpression previousFunctionExpression = (FunctionExpression) previousExpression;
                    final ValueExpression valueExpression = (ValueExpression) next;
                    current.replacePrevious(new FunctionValueExpression(previousFunctionExpression, valueExpression));
                } else {
                    current.add(next);
                }
                lastToken = tokenizer.sval;
                break;
            case '(':
                if (((current == null || current instanceof RootExpression) && next == null) || current == next) {
                    // an additional bracket without a new function,
                    // this can only be an execution group.
                    next = new GroupExpression();
                    current.add(next);
                }
                current = next;
                lastToken += "(";
                level++;
                break;
            case ')':
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken);
                }
                current = current.getParent();
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
                }
                lastToken += ")";
                level--;
                break;
            case '[':
                // bind directly to the previous expression
                next = new ArrayExpression();
                current.add(next);
                current = next;
                lastToken += "[";
                level++;
                break;
            case ']':
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken);
                }
                current = current.getParent();
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
                }
                lastToken += "]";
                level--;
                break;
            case ';':
                next = null;
                lastToken += ";";
                break;
            case ',':
                next = current;
                lastToken += ",";
                break;
            default:
                if (current == null) {
                    throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval);
                }
                current.add(new ConstantExpression(tokenizer.sval));
                lastToken = tokenizer.sval;
        }
    }
    if (level > 0) {
        throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
    }
    return root.evaluate(actionContext, entity);
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) ConstantExpression(org.structr.core.parser.ConstantExpression) FunctionValueExpression(org.structr.core.parser.FunctionValueExpression) GroupExpression(org.structr.core.parser.GroupExpression) FunctionExpression(org.structr.core.parser.FunctionExpression) NoneExpression(org.structr.core.parser.NoneExpression) IsExpression(org.structr.core.parser.IsExpression) AnyExpression(org.structr.core.parser.AnyExpression) EachExpression(org.structr.core.parser.EachExpression) GroupExpression(org.structr.core.parser.GroupExpression) ArrayExpression(org.structr.core.parser.ArrayExpression) FunctionExpression(org.structr.core.parser.FunctionExpression) ValueExpression(org.structr.core.parser.ValueExpression) Expression(org.structr.core.parser.Expression) FilterExpression(org.structr.core.parser.FilterExpression) NullExpression(org.structr.core.parser.NullExpression) ConstantExpression(org.structr.core.parser.ConstantExpression) IfExpression(org.structr.core.parser.IfExpression) SliceExpression(org.structr.core.parser.SliceExpression) RootExpression(org.structr.core.parser.RootExpression) BatchExpression(org.structr.core.parser.BatchExpression) CacheExpression(org.structr.core.parser.CacheExpression) FunctionValueExpression(org.structr.core.parser.FunctionValueExpression) AllExpression(org.structr.core.parser.AllExpression) RootExpression(org.structr.core.parser.RootExpression) ValueExpression(org.structr.core.parser.ValueExpression) FunctionValueExpression(org.structr.core.parser.FunctionValueExpression) StringReader(java.io.StringReader) ArrayExpression(org.structr.core.parser.ArrayExpression) StreamTokenizer(java.io.StreamTokenizer)

Aggregations

FrameworkException (org.structr.common.error.FrameworkException)2 CacheExpression (org.structr.core.parser.CacheExpression)2 ConstantExpression (org.structr.core.parser.ConstantExpression)2 StreamTokenizer (java.io.StreamTokenizer)1 StringReader (java.io.StringReader)1 Map (java.util.Map)1 Context (org.mozilla.javascript.Context)1 IdFunctionCall (org.mozilla.javascript.IdFunctionCall)1 IdFunctionObject (org.mozilla.javascript.IdFunctionObject)1 NativeObject (org.mozilla.javascript.NativeObject)1 Script (org.mozilla.javascript.Script)1 Scriptable (org.mozilla.javascript.Scriptable)1 ScriptableObject (org.mozilla.javascript.ScriptableObject)1 SecurityContext (org.structr.common.SecurityContext)1 GraphObject (org.structr.core.GraphObject)1 GraphObjectMap (org.structr.core.GraphObjectMap)1 GrantFunction (org.structr.core.function.GrantFunction)1 AllExpression (org.structr.core.parser.AllExpression)1 AnyExpression (org.structr.core.parser.AnyExpression)1 ArrayExpression (org.structr.core.parser.ArrayExpression)1