org.apache.commons.jexl3.JexlBuilder Java Examples

The following examples show how to use org.apache.commons.jexl3.JexlBuilder. 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: Jexl3ConfigEnvironmentPreprocessor.java    From spring-cloud-formula with Apache License 2.0 7 votes vote down vote up
@PostConstruct
public void init() {
    jexlEngine = new JexlBuilder().create();
    // 支持的参数
    // 1. 启动参数
    // 2. 测试配置变量
    // 3. 系统属性
    PropertySource<?> ps = environment.getPropertySources().get("systemProperties");
    Map<Object, Object> source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });

    // 4. 环境变量
    ps = environment.getPropertySources().get("systemEnvironment");
    source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });
}
 
Example #2
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testCtorBlock() throws Exception {
    String expr = "new('" + Foo.class.getName() + "', '42')";
    JexlScript script = JEXL.createScript(expr);
    Object result;
    result = script.execute(null);
    Assert.assertEquals("42", ((Foo) result).getName());

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

    script = sjexl.createScript(expr);
    try {
        result = script.execute(null);
        Assert.fail("ctor should not be accessible");
    } catch (JexlException.Method xmethod) {
        // ok, ctor should not have been accessible
        LOGGER.info(xmethod.toString());
    }
}
 
Example #3
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodBlock() throws Exception {
    String expr = "foo.Quux()";
    JexlScript script = JEXL.createScript(expr, "foo");
    Foo foo = new Foo("42");
    Object result;
    result = script.execute(null, foo);
    Assert.assertEquals(foo.Quux(), result);

    JexlSandbox sandbox = new JexlSandbox();
    sandbox.block(Foo.class.getName()).execute("Quux");
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).strict(true).safe(false).create();

    script = sjexl.createScript(expr, "foo");
    try {
        result = script.execute(null, foo);
        Assert.fail("Quux should not be accessible");
    } catch (JexlException.Method xmethod) {
        // ok, Quux should not have been accessible
        LOGGER.info(xmethod.toString());
    }
}
 
Example #4
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBlock() throws Exception {
    String expr = "foo.alias";
    JexlScript script = JEXL.createScript(expr, "foo");
    Foo foo = new Foo("42");
    Object result;
    result = script.execute(null, foo);
    Assert.assertEquals(foo.alias, result);

    JexlSandbox sandbox = new JexlSandbox();
    sandbox.block(Foo.class.getName()).read("alias");
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).strict(true).safe(false).create();

    script = sjexl.createScript(expr, "foo");
    try {
        result = script.execute(null, foo);
        Assert.fail("alias should not be accessible");
    } catch (JexlException.Property xvar) {
        // ok, alias should not have been accessible
        LOGGER.info(xvar.toString());
    }
}
 
Example #5
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetBlock() throws Exception {
    String expr = "foo.alias = $0";
    JexlScript script = JEXL.createScript(expr, "foo", "$0");
    Foo foo = new Foo("42");
    Object result;
    result = script.execute(null, foo, "43");
    Assert.assertEquals("43", result);

    JexlSandbox sandbox = new JexlSandbox();
    sandbox.block(Foo.class.getName()).write("alias");
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).strict(true).safe(false).create();

    script = sjexl.createScript(expr, "foo", "$0");
    try {
        result = script.execute(null, foo, "43");
        Assert.fail("alias should not be accessible");
    } catch (JexlException.Property xvar) {
        // ok, alias should not have been accessible
        LOGGER.info(xvar.toString());
    }
}
 
Example #6
Source File: JexlRowFactory.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public JexlRowFactory(Map<String, String> customFields, JoinHandler joinHandler) {
  this.joinHandler = joinHandler;
  this.expressions = new HashMap<>();
  Map<String, Object> ns = Maps.newHashMap();
  ns.put("Json", JsonEncoder.class); // make method Json:stringify available in expressions
  ns.put("Math", Math.class); // make all methods of Math available
  ns.put("Integer", Integer.class); // make method Integer
  JexlEngine jexl = new JexlBuilder().namespaces(ns).create();
  StringBuilder result = new StringBuilder();
  customFields.forEach((key, value) -> {
    try {
      expressions.put(key, jexl.createExpression(value));
      result.append("      ").append(key).append(": ").append(value).append("\n");
    } catch (Exception e) { // Catch the runtime exceptions
      LOG.error("Could not compile expression '{}'", value);
      LOG.error("Exception thrown", e);
    }
  });
  this.stringRepresentation = result.toString();
}
 
Example #7
Source File: ExtractCCDAAttributes.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    getLogger().debug("Loading packages");
    final StopWatch stopWatch = new StopWatch(true);

    // Load required MDHT packages
    System.setProperty( "org.eclipse.emf.ecore.EPackage.Registry.INSTANCE",
            "org.eclipse.emf.ecore.impl.EPackageRegistryImpl" );
    CDAPackage.eINSTANCE.eClass();
    HITSPPackage.eINSTANCE.eClass();
    CCDPackage.eINSTANCE.eClass();
    ConsolPackage.eINSTANCE.eClass();
    IHEPackage.eINSTANCE.eClass();
    stopWatch.stop();
    getLogger().debug("Loaded packages in {}", new Object[] {stopWatch.getDuration(TimeUnit.MILLISECONDS)});

    // Initialize JEXL
    jexl = new JexlBuilder().cache(1024).debug(false).silent(true).strict(false).create();
    jexlCtx = new MapContext();

    getLogger().debug("Loading mappings");
    loadMappings(); // Load CDA mappings for parser

}
 
Example #8
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 #9
Source File: JexlUtils.java    From syncope with Apache License 2.0 6 votes vote down vote up
private static JexlEngine getEngine() {
    synchronized (LOG) {
        if (JEXL_ENGINE == null) {
            JEXL_ENGINE = new JexlBuilder().
                    uberspect(new SandboxUberspect()).
                    loader(new EmptyClassLoader()).
                    namespaces(Map.of("syncope", new SyncopeJexlFunctions())).
                    cache(512).
                    silent(false).
                    strict(false).
                    create();
        }
    }

    return JEXL_ENGINE;
}
 
Example #10
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodNoJexl() throws Exception {
    Foo foo = new Foo("42");
    String[] exprs = {
        "foo.cantCallMe()",
        "foo.tryMe()",
        "foo.tryMeARiver()",
        "foo.callMeNot()",
        "foo.NONO",
        "new('org.apache.commons.jexl3.SandboxTest$Foo', 'one', 'two')"
    };
    JexlScript script;
    Object result;

    JexlEngine sjexl = new JexlBuilder().strict(true).safe(false).create();
    for (String expr : exprs) {
        script = sjexl.createScript(expr, "foo");
        try {
            result = script.execute(null, foo);
            Assert.fail("should have not been possible");
        } catch (JexlException.Method | JexlException.Property xjm) {
            // ok
            LOGGER.info(xjm.toString());
        }
    }
}
 
Example #11
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllow() throws Exception {
    Foo foo = new Foo("42");
    String expr = "foo.alias";
    JexlScript script;
    Object result;

    JexlSandbox sandbox = new JexlSandbox();
    sandbox.allow(Foo.class.getName()).read("alias");
    sandbox.get(Foo.class.getName()).read().alias("alias", "ALIAS");
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).safe(false).strict(true).create();

    script = sjexl.createScript(expr, "foo");
    result = script.execute(null, foo);
    Assert.assertEquals(foo.alias, result);

    script = sjexl.createScript("foo.ALIAS", "foo");
    result = script.execute(null, foo);
    Assert.assertEquals(foo.alias, result);
}
 
Example #12
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetAllow() throws Exception {
    Foo foo = new Foo("42");
    String expr = "foo.alias = $0";
    JexlScript script;
    Object result;

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

    script = sjexl.createScript(expr, "foo", "$0");
    result = script.execute(null, foo, "43");
    Assert.assertEquals("43", result);
    Assert.assertEquals("43", foo.alias);
}
 
Example #13
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 #14
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 #15
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Test
public void testCtorAllow() throws Exception {
    String expr = "new('" + Foo.class.getName() + "', '42')";
    JexlScript script;
    Object result;

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

    script = sjexl.createScript(expr);
    result = script.execute(null);
    Assert.assertEquals("42", ((Foo) result).getName());
}
 
Example #16
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodAllow() throws Exception {
    Foo foo = new Foo("42");
    String expr = "foo.Quux()";
    JexlScript script;
    Object result;

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

    script = sjexl.createScript(expr, "foo");
    result = script.execute(null, foo);
    Assert.assertEquals(foo.Quux(), result);
}
 
Example #17
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);
    }
}
 
Example #18
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 #19
Source File: ScriptStepTest.java    From gp2srv with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testEval() {
	Assert.assertTrue(new ScriptStep(ScriptStepType.STOP, null, null, "true").evalCondition(new JexlBuilder().create(), jexlContext));
	Assert.assertFalse(new ScriptStep(ScriptStepType.STOP, null, null, "false").evalCondition(new JexlBuilder().create(), jexlContext));
	CameraService cameraService = Mockito.mock(CameraService.class);
	CameraConfigEntryBean cceb = new CameraConfigEntryBean(0, "prop", "prop", "", CameraConfigEntryType.TEXT, null, null, "val", null, null);
	Map<String, CameraConfigEntryBean> ccebMap = new HashMap<String, CameraConfigEntryBean>();
	ccebMap.put("prop", cceb);
	Mockito.when(cameraService.getConfigAsMap()).thenReturn(ccebMap);
	ScriptStep unit = new ScriptStep(ScriptStepType.CAMPROP_SET, "prop", "2+2", "true");
	Assert.assertEquals(cceb, unit.getConfigEntryForEval(cameraService));
	jexlContext.clear();
	Assert.assertEquals(4, unit.evalExpression(new JexlBuilder().create(), jexlContext, cceb));
	Assert.assertEquals(cceb, jexlContext.get("__camprop"));
}
 
Example #20
Source File: JexlClaimsMapper.java    From cxf with Apache License 2.0 5 votes vote down vote up
public JexlClaimsMapper() {
    // jexl.setCache(512);
    // jexl.setLenient(false);

    Map<String, Object> functions = new HashMap<>();
    functions.put("claims", new ClaimUtils());
    functions.put("LOG", LOG);
    jexlEngine = new JexlBuilder().silent(false).namespaces(functions).create();
}
 
Example #21
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 #22
Source File: Jexl3ConfigEnvironmentPreprocessorTest.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void testCache() {
    JexlEngine engine = new JexlBuilder().cache(100).create();

    JexlExpression expr = engine.createExpression("a = 3 ? 1 : 3");
    JexlExpression expr2 = engine.createExpression("a = 3 ? 1 : 3");
    assertSame(expr, expr2);
}
 
Example #23
Source File: MethodPropertyTest.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
/**
 * An example for method access.
 */
public static void example(final 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();

    /*
     * The Java equivalents of foo and number for comparison and checking
     */
    Foo foo = new Foo();
    Integer number = 10;

    jc.set("foo", foo);
    jc.set("number", number);

    /*
     *  access a method w/o args
     */
    JexlExpression e = jexl.createExpression("foo.getFoo()");
    Object o = e.evaluate(jc);
    out.print("value returned by the method getFoo() is : ", o, foo.getFoo());

    /*
     *  access a method w/ args
     */
    e = jexl.createExpression("foo.convert(1)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1));

    e = jexl.createExpression("foo.convert(1+7)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+7));

    e = jexl.createExpression("foo.convert(1+number)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+ number));

    /*
     * access a property
     */
    e = jexl.createExpression("foo.bar");
    o = e.evaluate(jc);
    out.print("value returned for the property 'bar' is : ", o, foo.get("bar"));

}
 
Example #24
Source File: Engine.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a JEXL engine using the provided {@link JexlBuilder}.
 * @param conf the builder
 */
public Engine(JexlBuilder conf) {
    // options:
    this.options = conf.options().copy();
    this.strict = options.isStrict();
    this.safe = options.isSafe();
    this.silent = options.isSilent();
    this.cancellable = option(conf.cancellable(), !silent && strict);
    options.setCancellable(cancellable);
    this.debug = option(conf.debug(), true);
    this.collectMode = conf.collectMode();
    this.stackOverflow = conf.stackOverflow() > 0? conf.stackOverflow() : Integer.MAX_VALUE;
    // core properties:
    JexlUberspect uber = conf.uberspect() == null ? getUberspect(conf.logger(), conf.strategy()) : conf.uberspect();
    ClassLoader loader = conf.loader();
    if (loader != null) {
        uber.setClassLoader(loader);
    }
    JexlSandbox sandbox = conf.sandbox();
    if (sandbox == null) {
        this.uberspect = uber;
    } else {
        this.uberspect = new SandboxUberspect(uber, sandbox);
    }
    this.logger = conf.logger() == null ? LogFactory.getLog(JexlEngine.class) : conf.logger();
    this.arithmetic = conf.arithmetic() == null ? new JexlArithmetic(this.strict) : conf.arithmetic();
    options.setMathContext(arithmetic.getMathContext());
    options.setMathScale(arithmetic.getMathScale());
    options.setStrictArithmetic(arithmetic.isStrict());
    this.functions = conf.namespaces() == null ? Collections.<String, Object>emptyMap() : conf.namespaces();
    // parsing & features:
    JexlFeatures features = conf.features() == null? DEFAULT_FEATURES : conf.features();
    this.expressionFeatures = new JexlFeatures(features).script(false);
    this.scriptFeatures = new JexlFeatures(features).script(true);
    this.charset = conf.charset();
    // caching:
    this.cache = conf.cache() <= 0 ? null : new SoftCache<Source, ASTJexlScript>(conf.cache());
    this.cacheThreshold = conf.cacheThreshold();
    if (uberspect == null) {
        throw new IllegalArgumentException("uberspect can not be null");
    }
}
 
Example #25
Source File: Engine.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an engine with default arguments.
 */
public Engine() {
    this(new JexlBuilder());
}
 
Example #26
Source File: JexlEngine.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public JexlEngine() {
  super(new JexlBuilder().uberspect(new SandboxJexlUberspect()));
}
 
Example #27
Source File: MethodPropertyTest.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
/**
 * An example for method access.
 */
public static void example(final 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();

    /**
     * The Java equivalents of foo and number for comparison and checking
     */
    Foo foo = new Foo();
    Integer number = new Integer(10);

    jc.set("foo", foo);
    jc.set("number", number);

    /*
     *  access a method w/o args
     */
    JexlExpression e = jexl.createExpression("foo.getFoo()");
    Object o = e.evaluate(jc);
    out.print("value returned by the method getFoo() is : ", o, foo.getFoo());

    /*
     *  access a method w/ args
     */
    e = jexl.createExpression("foo.convert(1)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1));

    e = jexl.createExpression("foo.convert(1+7)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+7));

    e = jexl.createExpression("foo.convert(1+number)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+number.intValue()));

    /*
     * access a property
     */
    e = jexl.createExpression("foo.bar");
    o = e.evaluate(jc);
    out.print("value returned for the property 'bar' is : ", o, foo.get("bar"));

}
 
Example #28
Source File: TemplateEngine.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
public void addFunctions(String namespace, Object functions) {
    this.functions.put(namespace, functions);
    jexlEngine = new JexlBuilder().namespaces(this.functions).create();
}
 
Example #29
Source File: JexlProvider.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public JexlProvider() {
    engine = new JexlBuilder().create();
}
 
Example #30
Source File: CEPRuleMQ.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
private static boolean hitRuleEngine(CEPRule rule, WeEvent eventMessage) throws BrokerException {
    // String payload, WeEvent eventMessage, String condition
    String payload = rule.getPayload();
    String condition = rule.getConditionField();
    try {
        String eventContent = new String(eventMessage.getContent());
        // all parameter must be the same
        if (CommonUtil.checkJson(eventContent, payload) && (StringUtils.isEmpty(condition))) {
            // if the condition is empty, just return all message
            return true;
        } else if (CommonUtil.checkJson(eventContent, payload)) {
            List<String> eventContentKeys = CommonUtil.getKeys(payload);
            Map event = JsonHelper.json2Object(eventContent, Map.class);
            JexlEngine jexl = new JexlBuilder().create();
            JexlContext context = setContext(event, eventContentKeys);

            // check the expression ,if match then true
            log.info("condition:{},systemFunctionMessage:{}", condition, rule.getFunctionArray());
            if (!StringUtils.isEmpty(rule.getFunctionArray())) {
                String[][] systemFunctionDetail = SystemFunctionUtil.stringConvertArray(rule.getFunctionArray());
                if (0 != systemFunctionDetail.length) {
                    condition = SystemFunctionUtil.analysisSystemFunction(systemFunctionDetail, eventContent, condition);
                    log.info("condition:{}", condition);
                }
            }

            boolean checkFlag = (Boolean) jexl.createExpression(condition).evaluate(context);
            log.info("payload:{},eventContent:{},condition:{},hit rule:{}", payload, eventContent, condition, checkFlag);
            return checkFlag;
        }
        log.info("payload:{},eventContent:{},condition:{},hit rule:false", payload, eventContent, condition);
        return false;
    } catch (Exception e) {
        if (handleTheEqual(eventMessage, condition)) {
            log.info("single equal match");
            return true;
        } else {
            log.info("error number");
            return false;
        }

    }
}