org.apache.commons.jexl3.JexlContext Java Examples

The following examples show how to use org.apache.commons.jexl3.JexlContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JexlUtils.java    From syncope with Apache License 2.0 6 votes vote down vote up
public static String evaluate(final String expression, final JexlContext jexlContext) {
    String result = StringUtils.EMPTY;

    if (StringUtils.isNotBlank(expression) && jexlContext != null) {
        try {
            JexlExpression jexlExpression = getEngine().createExpression(expression);
            Object evaluated = jexlExpression.evaluate(jexlContext);
            if (evaluated != null) {
                result = evaluated.toString();
            }
        } catch (Exception e) {
            LOG.error("Error while evaluating JEXL expression: " + expression, e);
        }
    } else {
        LOG.debug("Expression not provided or invalid context");
    }

    return result;
}
 
Example #2
Source File: MappingManagerImpl.java    From syncope with Apache License 2.0 6 votes vote down vote up
/**
 * Build __NAME__ for propagation.
 * First look if there is a defined connObjectLink for the given resource (and in
 * this case evaluate as JEXL); otherwise, take given connObjectKey.
 *
 * @param realm given any object
 * @param orgUnit external resource
 * @param connObjectKey connector object key
 * @return the value to be propagated as __NAME__
 */
private Name evaluateNAME(final Realm realm, final OrgUnit orgUnit, final String connObjectKey) {
    if (StringUtils.isBlank(connObjectKey)) {
        // LOG error but avoid to throw exception: leave it to the external resource
        LOG.warn("Missing ConnObjectKey value for {}: ", orgUnit.getResource());
    }

    // Evaluate connObjectKey expression
    String connObjectLink = orgUnit == null
            ? null
            : orgUnit.getConnObjectLink();
    String evalConnObjectLink = null;
    if (StringUtils.isNotBlank(connObjectLink)) {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addFieldsToContext(realm, jexlContext);
        evalConnObjectLink = JexlUtils.evaluate(connObjectLink, jexlContext);
    }

    return getName(evalConnObjectLink, connObjectKey);
}
 
Example #3
Source File: MappingManagerImpl.java    From syncope with Apache License 2.0 6 votes vote down vote up
/**
 * Build __NAME__ for propagation.
 * First look if there is a defined connObjectLink for the given resource (and in
 * this case evaluate as JEXL); otherwise, take given connObjectKey.
 *
 * @param any given any object
 * @param provision external resource
 * @param connObjectKey connector object key
 * @return the value to be propagated as __NAME__
 */
private Name evaluateNAME(final Any<?> any, final Provision provision, final String connObjectKey) {
    if (StringUtils.isBlank(connObjectKey)) {
        // LOG error but avoid to throw exception: leave it to the external resource
        LOG.warn("Missing ConnObjectKey value for {}: ", provision.getResource());
    }

    // Evaluate connObjectKey expression
    String connObjectLink = provision == null || provision.getMapping() == null
            ? null
            : provision.getMapping().getConnObjectLink();
    String evalConnObjectLink = null;
    if (StringUtils.isNotBlank(connObjectLink)) {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addFieldsToContext(any, jexlContext);
        JexlUtils.addPlainAttrsToContext(any.getPlainAttrs(), jexlContext);
        JexlUtils.addDerAttrsToContext(any, derAttrHandler, jexlContext);
        evalConnObjectLink = JexlUtils.evaluate(connObjectLink, jexlContext);
    }

    return getName(evalConnObjectLink, connObjectKey);
}
 
Example #4
Source File: Engine.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
/**
 * Compute a script options for evaluation.
 * <p>This calls processPragma(...).
 * @param script the script
 * @param context the context
 * @return the options
 */
protected JexlOptions options(ASTJexlScript script, JexlContext context) {
    final JexlOptions opts = options(context); 
    if (opts != options) {
        // when feature lexical, try hard to run lexical
        if (scriptFeatures.isLexical()) {
            opts.setLexical(true);
        }
        if (scriptFeatures.isLexicalShade()) {
            opts.setLexicalShade(true);
        }
    }
    if (script != null) {
       // process script pragmas if any
       processPragmas(script, context, opts);
    }
    return opts;
}
 
Example #5
Source File: JexlClaimsMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public ProcessedClaimCollection mapClaims(String sourceRealm, ProcessedClaimCollection sourceClaims,
    String targetRealm, ClaimsParameters parameters) {
    JexlContext context = new MapContext();
    context.set("sourceClaims", sourceClaims);
    context.set("targetClaims", new ProcessedClaimCollection());
    context.set("sourceRealm", sourceRealm);
    context.set("targetRealm", targetRealm);
    context.set("claimsParameters", parameters);

    JexlScript s = getScript();
    if (s == null) {
        LOG.warning("No claim mapping script defined");
        return new ProcessedClaimCollection(); // TODO Check if null or an exception would be more
                                               // appropriate
    }
    return (ProcessedClaimCollection)s.execute(context);
}
 
Example #6
Source File: MappingTest.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void anyConnObjectLink() {
    Realm realm = mock(Realm.class);
    when(realm.getFullPath()).thenReturn("/even");

    User user = mock(User.class);
    when(user.getUsername()).thenReturn("rossini");
    when(user.getRealm()).thenReturn(realm);
    assertNotNull(user);

    JexlContext jexlContext = new MapContext();
    JexlUtils.addFieldsToContext(user, jexlContext);

    String connObjectLink = "'uid=' + username + ',ou=people,o=isp'";
    assertEquals("uid=rossini,ou=people,o=isp", JexlUtils.evaluate(connObjectLink, jexlContext));

    connObjectLink = "'uid=' + username + realm.replaceAll('/', ',o=') + ',ou=people,o=isp'";
    assertEquals("uid=rossini,o=even,ou=people,o=isp", JexlUtils.evaluate(connObjectLink, jexlContext));
}
 
Example #7
Source File: Engine.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Override
public Object getProperty(JexlContext context, Object bean, String expr) {
    if (context == null) {
        context = EMPTY_CONTEXT;
    }
    // synthetize expr using register
    String src = trimSource(expr);
    src = "#0" + (src.charAt(0) == '[' ? "" : ".") + src;
    try {
        final Scope scope = new Scope(null, "#0");
        final ASTJexlScript script = parse(null, PROPERTY_FEATURES, src, scope);
        final JexlNode node = script.jjtGetChild(0);
        final Frame frame = script.createFrame(bean);
        final Interpreter interpreter = createInterpreter(context, frame, options);
        return interpreter.visitLexicalNode(node, null);
    } catch (JexlException xjexl) {
        if (silent) {
            logger.warn(xjexl.getMessage(), xjexl.getCause());
            return null;
        }
        throw xjexl.clean();
    }
}
 
Example #8
Source File: Engine.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Override
public void setProperty(JexlContext context, Object bean, String expr, Object value) {
    if (context == null) {
        context = EMPTY_CONTEXT;
    }
    // synthetize expr using register
    String src = trimSource(expr);
    src = "#0" + (src.charAt(0) == '[' ? "" : ".") + src + "=" + "#1";
    try {
        final Scope scope = new Scope(null, "#0", "#1");
        final ASTJexlScript script = parse(null, PROPERTY_FEATURES, src, scope);
        final JexlNode node = script.jjtGetChild(0);
        final Frame frame = script.createFrame(bean, value);
        final Interpreter interpreter = createInterpreter(context, frame, options);
        interpreter.visitLexicalNode(node, null);
    } catch (JexlException xjexl) {
        if (silent) {
            logger.warn(xjexl.getMessage(), xjexl.getCause());
            return;
        }
        throw xjexl.clean();
    }
}
 
Example #9
Source File: JexlUtils.java    From syncope with Apache License 2.0 6 votes vote down vote up
public static void addPlainAttrsToContext(
        final Collection<? extends PlainAttr<?>> attrs, final JexlContext jexlContext) {

    attrs.stream().filter(attr -> attr.getSchema() != null).forEach(attr -> {
        List<String> attrValues = attr.getValuesAsStrings();
        Object value;
        if (attrValues.isEmpty()) {
            value = StringUtils.EMPTY;
        } else {
            value = attrValues.size() == 1
                    ? attrValues.get(0)
                    : attrValues;
        }

        LOG.debug("Add attribute {} with value {}", attr.getSchema().getKey(), value);

        jexlContext.set(attr.getSchema().getKey(), value);
    });
}
 
Example #10
Source File: JexlUtils.java    From syncope with Apache License 2.0 6 votes vote down vote up
public static void addAttrsToContext(final Collection<Attr> attrs, final JexlContext jexlContext) {
    attrs.stream().filter(attr -> attr.getSchema() != null).forEach(attr -> {
        Object value;
        if (attr.getValues().isEmpty()) {
            value = StringUtils.EMPTY;
        } else {
            value = attr.getValues().size() == 1
                    ? attr.getValues().get(0)
                    : attr.getValues();
        }

        LOG.debug("Add attribute {} with value {}", attr.getSchema(), value);

        jexlContext.set(attr.getSchema(), value);
    });
}
 
Example #11
Source File: TemplateScript.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateScript prepare(JexlContext context) {
    final Engine jexl = jxlt.getEngine();
    JexlOptions options = jexl.options(script, context);
    Frame frame = script.createFrame((Object[]) null);
    TemplateInterpreter.Arguments targs = new TemplateInterpreter
            .Arguments(jxlt.getEngine())
            .context(context)
            .options(options)
            .frame(frame);
    Interpreter interpreter = new TemplateInterpreter(targs);
    TemplateExpression[] immediates = new TemplateExpression[exprs.length];
    for (int e = 0; e < exprs.length; ++e) {
        try {
            immediates[e] = exprs[e].prepare(interpreter);
        } catch (JexlException xjexl) {
            JexlException xuel = TemplateEngine.createException(xjexl.getInfo(), "prepare", exprs[e], xjexl);
            if (jexl.isSilent()) {
                jexl.logger.warn(xuel.getMessage(), xuel.getCause());
                return null;
            }
            throw xuel;
        }
    }
    return new TemplateScript(jxlt, prefix, source, script, immediates);
}
 
Example #12
Source File: JexlRowFactory.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getRawValue(String key) {
  if (data.containsKey(key)) {
    return data.get(key);
  } else if (expressions.containsKey(key)) {
    try {
      JexlContext jexlContext = new MapContext();
      jexlContext.set("v", data);
      Object result = expressions.get(key).evaluate(jexlContext);
      if (result != null) {
        return result.toString();
      } else {
        return null;
      }
    } catch (Throwable throwable) {
      LOG.info("Error during mapping", throwable);
      errorHandler.valueGenerateFailed(
        key,
        String.format("Could not execute expression '%s' for row with values: '%s.", expressions.get(key), data)
      );
      return null;
    }
  } else {
    return null;
  }
}
 
Example #13
Source File: JexlScriptEngine.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Override
public Object eval(final String script, final ScriptContext context) throws ScriptException {
    // This is mandated by JSR-223 (see SCR.5.5.2   Methods)
    if (script == null || context == null) {
        throw new NullPointerException("script and context must be non-null");
    }
    // This is mandated by JSR-223 (end of section SCR.4.3.4.1.2 - JexlScript Execution)
    context.setAttribute(CONTEXT_KEY, context, ScriptContext.ENGINE_SCOPE);
    try {
        JexlScript jexlScript = jexlEngine.createScript(script);
        JexlContext ctxt = new JexlContextWrapper(context);
        return jexlScript.execute(ctxt);
    } catch (Exception e) {
        throw new ScriptException(e.toString());
    }
}
 
Example #14
Source File: TemplateEngine.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates this expression.
 * @param frame the frame storing parameters and local variables
 * @param context the context storing global variables
 * @return the expression value
 * @throws JexlException
 */
protected final Object evaluate(Frame frame, JexlContext context) {
    try {
        JexlOptions options = options(context);
        TemplateInterpreter.Arguments args = new TemplateInterpreter
                .Arguments(jexl)
                .context(context)
                .options(options)
                .frame(frame);
        Interpreter interpreter = new TemplateInterpreter(args);
        return evaluate(interpreter);
    } catch (JexlException xjexl) {
        JexlException xuel = createException(xjexl.getInfo(), "evaluate", this, xjexl);
        if (jexl.isSilent()) {
            jexl.logger.warn(xuel.getMessage(), xuel.getCause());
            return null;
        }
        throw xuel;
    }
}
 
Example #15
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testCantSeeMe() throws Exception {
    JexlContext jc = new MapContext();
    String expr = "foo.doIt()";
    JexlScript script;
    Object result = null;

    JexlSandbox sandbox = new JexlSandbox(false);
    sandbox.allow(Foo.class.getName());
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).strict(true).safe(false).create();

    jc.set("foo", new CantSeeMe());
    script = sjexl.createScript(expr);
    try {
        result = script.execute(jc);
        Assert.fail("should have failed, doIt()");
    } catch (JexlException xany) {
        //
    }
    jc.set("foo", new Foo("42"));
        result = script.execute(jc);
    Assert.assertEquals(42, ((Integer) result).intValue());
}
 
Example #16
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
   public void testSandboxInherit0() throws Exception {
    Object result;
    JexlContext ctxt = null;
    List<String> foo = new ArrayList<String>();
    JexlSandbox sandbox = new JexlSandbox(false, true);
    sandbox.allow(java.util.List.class.getName());
    
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).safe(false).strict(true).create();
    JexlScript method = sjexl.createScript("foo.add(y)", "foo", "y");
    JexlScript set = sjexl.createScript("foo[x] = y", "foo", "x", "y");
    JexlScript get = sjexl.createScript("foo[x]", "foo", "x");

    result = method.execute(ctxt, foo, "nothing");
    Assert.assertEquals(true, result);
    result = null;
    result = get.execute(null, foo, 0);
    Assert.assertEquals("nothing", result);
    result = null;
    result = set.execute(null, foo, 0, "42");
    Assert.assertEquals("42", result);

    result = null;
    result = get.execute(null, foo, 0);
    Assert.assertEquals("42", result);
}
 
Example #17
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSandboxInherit1() throws Exception {
    Object result;
    JexlContext ctxt = null;
    Operation2 foo = new Operation2(12);
    JexlSandbox sandbox = new JexlSandbox(false, true);
    sandbox.allow(Operation.class.getName());
    sandbox.block(Operation.class.getName()).execute("nonCallable");
    //sandbox.block(Foo.class.getName()).execute();
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).safe(false).strict(true).create();
    JexlScript someOp = sjexl.createScript("foo.someOp(y)", "foo", "y");
    result = someOp.execute(ctxt, foo, 30);
    Assert.assertEquals(42, result);
    JexlScript nonCallable = sjexl.createScript("foo.nonCallable(y)", "foo", "y");
    try {
        result = nonCallable.execute(null, foo, 0);
        Assert.fail("should not be possible");
    } catch (JexlException xjm) {
        // ok
        LOGGER.info(xjm.toString());
    }
}
 
Example #18
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, String errorMessage) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(errorMessage));
  jexlContext.set("stageDef", context.getStageDefinition());
  jexlContext.set("stageConf", context.getStageConfiguration());
  return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}
 
Example #19
Source File: Closure.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Override
public Callable callable(JexlContext context, Object... args) {
    Frame local = frame != null? frame.assign(args) : null;
    return new Callable(createInterpreter(context, local)) {
        @Override
        public Object interpret() {
            return interpreter.runClosure(Closure.this, null);
        }
    };
}
 
Example #20
Source File: DerAttrHandlerImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Map<DerSchema, String> getValues(
    final GroupableRelatable<?, ?, ?, ?, ?> any, final Membership<?> membership, final Set<DerSchema> schemas) {

    Map<DerSchema, String> result = new HashMap<>(schemas.size());

    schemas.forEach(schema -> {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addPlainAttrsToContext(any.getPlainAttrs(membership), jexlContext);
        JexlUtils.addFieldsToContext(any, jexlContext);

        result.put(schema, JexlUtils.evaluate(schema.getExpression(), jexlContext));
    });

    return result;
}
 
Example #21
Source File: Script.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(JexlContext context) {
    checkCacheVersion();
    Frame frame = createFrame(null);
    Interpreter interpreter = createInterpreter(context, frame);
    return interpreter.interpret(script);
}
 
Example #22
Source File: GlobalVariableValidationAction.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@Override
boolean validateRaw(ActionContext actionContext, AndroidDeviceDriver androidDeviceDriver) {
  // Create or retrieve an engine
  JexlEngine jexl = new JexlBuilder().create();

  // Create an expression
  JexlExpression e = jexl.createExpression(expression);

  JexlContext jc = new MapContext();

  // To use advanced expression, need a converter to do the trick, the expression will be like
  // "uicdTypeConverter.toInt($uicd_var1) + uicdTypeConverter.toInt($uicd_var2)";
  if (expression.contains(TYPE_CONVERTER_OBJ_KEYWORD)) {
    jc.set(TYPE_CONVERTER_OBJ_KEYWORD, new UicdTypeConverter());
  }
  // Create a context and add data
  // jc.set("$uicd_var1", new String("adbcd"));
  // Set the displayStr so that we can see the result in the test details.
  displayStr = expandUicdGlobalVariableToJexl(expression, jc, actionContext);

  // Now evaluate the expression, getting the result
  boolean ret = false;
  try {
    Object o = e.evaluate(jc);
    ret = Boolean.parseBoolean(o.toString());
  } catch (Exception ex) {
    System.out.println(ex.getMessage());
  }
  displayStr = String.format("%s|validation result:%s", displayStr, ret);
  return ret;
}
 
Example #23
Source File: Script.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(JexlContext context, Object... args) {
    checkCacheVersion();
    Frame frame = createFrame(args != null && args.length > 0 ? args : null);
    Interpreter interpreter = createInterpreter(context, frame);
    return interpreter.interpret(script);
}
 
Example #24
Source File: TemplateInterpreter.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Override
protected Object visit(ASTJexlScript script, Object data) {
    if (script instanceof ASTJexlLambda && !((ASTJexlLambda) script).isTopLevel()) {
        return new Closure(this, (ASTJexlLambda) script) {
            @Override
            protected Interpreter createInterpreter(JexlContext context, Frame local) {
                JexlOptions opts = jexl.options(script, context);
                TemplateInterpreter.Arguments targs = new TemplateInterpreter.Arguments(jexl)
                        .context(context)
                        .options(opts)
                        .frame(local)
                        .expressions(exprs)
                        .writer(writer);
                return new TemplateInterpreter(targs);
            }
        };
    }
    // otherwise...
    final int numChildren = script.jjtGetNumChildren();
        Object result = null;
        for (int i = 0; i < numChildren; i++) {
        JexlNode child = script.jjtGetChild(i);
            result = child.jjtAccept(this, data);
            cancelCheck(child);
        }
        return result;
    }
 
Example #25
Source File: Engine.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a script pragmas.
 * <p>Only called from options(...)
 * @param script the script
 * @param context the context
 * @param opts the options
 */
protected void processPragmas(ASTJexlScript script, JexlContext context, JexlOptions opts) {
    Map<String, Object> pragmas = script.getPragmas();
    if (pragmas != null && !pragmas.isEmpty()) {
        JexlContext.PragmaProcessor processor =
                context instanceof JexlContext.PragmaProcessor
                ? (JexlContext.PragmaProcessor) context
                : null;
        Map<String, Object> ns = null;
        for(Map.Entry<String, Object> pragma : pragmas.entrySet()) {
            String key = pragma.getKey();
            Object value = pragma.getValue();
            if (value instanceof String) {
                if (PRAGMA_OPTIONS.equals(key)) {
                    // jexl.options
                    String[] vs = value.toString().split(" ");
                    opts.setFlags(vs);
                } else if (key.startsWith(PRAGMA_JEXLNS)) {
                    // jexl.namespace.***
                    String nsname = key.substring(PRAGMA_JEXLNS.length());
                    if (nsname != null && !nsname.isEmpty()) {
                        String nsclass = value.toString();
                        if (ns == null) {
                            ns = new HashMap<>(functions);
                        }
                        ns.put(nsname, nsclass);
                    }
                }
            }
            if (processor != null) {
                processor.processPragma(key, value);
            }
        }
        if (ns != null) {
            opts.setNamespaces(ns);
        }
    }
}
 
Example #26
Source File: TemplateScript.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluate(JexlContext context, Writer writer, Object... args) {
    final Engine jexl = jxlt.getEngine();
    JexlOptions options = jexl.options(script, context);
    Frame frame = script.createFrame(args);
    TemplateInterpreter.Arguments targs = new TemplateInterpreter
            .Arguments(jexl)
            .context(context)
            .options(options)
            .frame(frame)
            .expressions(exprs)
            .writer(writer);
    Interpreter interpreter = new TemplateInterpreter(targs);
    interpreter.interpret(script);
}
 
Example #27
Source File: InterpreterBase.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an interpreter base.
 * @param engine   the engine creating this interpreter
 * @param opts     the evaluation options
 * @param aContext the evaluation context
 */
protected InterpreterBase(Engine engine, JexlOptions opts, JexlContext aContext) {
    this.jexl = engine;
    this.logger = jexl.logger;
    this.uberspect = jexl.uberspect;
    this.context = aContext != null ? aContext : Engine.EMPTY_CONTEXT;
    this.cache = engine.cache != null;
    JexlArithmetic jexla = jexl.arithmetic;
    this.options = opts == null? engine.options(aContext) : opts;
    this.arithmetic = jexla.options(options);
    if (arithmetic != jexla && !arithmetic.getClass().equals(jexla.getClass())) {
        logger.warn("expected arithmetic to be " + jexla.getClass().getSimpleName()
                + ", got " + arithmetic.getClass().getSimpleName()
        );
    }
    if (this.context instanceof JexlContext.NamespaceResolver) {
        ns = ((JexlContext.NamespaceResolver) context);
    } else {
        ns = Engine.EMPTY_NS;
    }
    AtomicBoolean acancel = null;
    if (this.context instanceof JexlContext.CancellationHandle) {
        acancel = ((JexlContext.CancellationHandle) context).getCancellation();
    }
    this.cancelled = acancel != null? acancel : new AtomicBoolean(false);
    Map<String,Object> ons = options.getNamespaces();
    this.functions = ons.isEmpty()? jexl.functions : ons;
    this.functors = null;
    this.operators = new Operators(this);
}
 
Example #28
Source File: TemplateEngine.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares this expression.
 * @param frame the frame storing parameters and local variables
 * @param context the context storing global variables
 * @return the expression value
 * @throws JexlException
 */
protected final TemplateExpression prepare(Frame frame, JexlContext context) {
    try {
        Interpreter interpreter = jexl.createInterpreter(context, frame, jexl.options(context));
        return prepare(interpreter);
    } catch (JexlException xjexl) {
        JexlException xuel = createException(xjexl.getInfo(), "prepare", this, xjexl);
        if (jexl.isSilent()) {
            jexl.logger.warn(xuel.getMessage(), xuel.getCause());
            return null;
        }
        throw xuel;
    }
}
 
Example #29
Source File: ArrayTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * An example for array access.
 */
static void example(Output out) throws Exception {
    /*
     * First step is to retrieve an instance of a JexlEngine;
     * it might be already existing and shared or created anew.
     */
    JexlEngine jexl = new JexlBuilder().create();
    /*
     *  Second make a jexlContext and put stuff in it
     */
    JexlContext jc = new MapContext();

    List<Object> l = new ArrayList<Object>();
    l.add("Hello from location 0");
    Integer two = 2;
    l.add(two);
    jc.set("array", l);

    JexlExpression e = jexl.createExpression("array[1]");
    Object o = e.evaluate(jc);
    out.print("Object @ location 1 = ", o, two);

    e = jexl.createExpression("array[0].length()");
    o = e.evaluate(jc);

    out.print("The length of the string at location 0 is : ", o, 21);
}
 
Example #30
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoJexl312() throws Exception {
    JexlContext ctxt = new MapContext();
    
    JexlEngine sjexl = new JexlBuilder().safe(false).strict(true).create();
    JexlScript foo = sjexl.createScript("x.getFoo()", "x");
    try {
        foo.execute(ctxt, new Foo44());
        Assert.fail("should have thrown");
    } catch (JexlException xany) {
        Assert.assertNotNull(xany);
    }
}