org.mvel2.MVEL.compileExpression()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(388)

本文整理了Java中org.mvel2.MVEL.compileExpression()方法的一些代码示例,展示了MVEL.compileExpression()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MVEL.compileExpression()方法的具体详情如下:
包路径:org.mvel2.MVEL
类名称:MVEL
方法名:compileExpression

MVEL.compileExpression介绍

[英]Compiles an expression and returns a Serializable object containing the compiled expression. The returned value can be reused for higher-performance evaluation of the expression. It is used in a straight forward way:

// Compile the expression 
Serializable compiled = MVEL.compileExpression("x * 10"); 
  
// Create a Map to hold the variables. 
Map vars = new HashMap(); 
  
// Create a factory to envelop the variable map 
VariableResolverFactory factory = new MapVariableResolverFactory(vars); 
  
int total = 0; 
for (int i = 0; i < 100; i++) { 
// Update the 'x' variable. 
vars.put("x", i); 
  
// Execute the expression against the compiled payload and factory, and add the result to the total variable. 
total += (Integer) MVEL.executeExpression(compiled, factory); 
} 
  
// Total should be 49500 
assert total == 49500;

The above example demonstrates a compiled expression being reused ina tight, closed, loop. Doing this greatly improves performance as re-parsing of the expression is not required, and the runtime can dynamically compileShared the expression to bytecode of necessary.
[中]编译表达式并返回包含已编译表达式的可序列化对象。返回的值可以重复使用,以便对表达式进行更高的性能评估。它的使用方式很简单:

// Compile the expression 
Serializable compiled = MVEL.compileExpression("x * 10"); 
  
// Create a Map to hold the variables. 
Map vars = new HashMap(); 
  
// Create a factory to envelop the variable map 
VariableResolverFactory factory = new MapVariableResolverFactory(vars); 
  
int total = 0; 
for (int i = 0; i < 100; i++) { 
// Update the 'x' variable. 
vars.put("x", i); 
  
// Execute the expression against the compiled payload and factory, and add the result to the total variable. 
total += (Integer) MVEL.executeExpression(compiled, factory); 
} 
  
// Total should be 49500 
assert total == 49500;

上面的示例演示了一个编译后的表达式在紧密的闭环中被重用。这样做可以极大地提高性能,因为不需要重新解析表达式,而且运行时可以动态地将表达式编译为必要的字节码。

代码示例

代码示例来源:origin: kiegroup/jbpm

@Override
public Object compile(String expression, Map<String, Object> parameters) {
  logger.debug("About to compile mvel expression {}", expression);
  ClassLoader classLoader = (ClassLoader) parameters.get("classloader");
  if (classLoader == null) {
    classLoader = this.getClass().getClassLoader();
  }
  ParserConfiguration config = new ParserConfiguration();
  config.setClassLoader(classLoader);
  ParserContext context = new ParserContext(config);
  if (parameters != null) {
    @SuppressWarnings("unchecked")
    Set<String> imports = (Set<String>)parameters.get("imports");
    if (imports != null) {
      for(String clazz : imports) {
        try {
          Class<?> cl = Class.forName(clazz, true, classLoader);
          context.addImport(cl.getSimpleName(), cl);
        } catch (ClassNotFoundException e) {
          logger.warn("Unable to load class {} due to {}", clazz, e.getException());
        };
      }
    }
  }
  return MVEL.compileExpression(expression, context);
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

ParserContext context = new ParserContext();
context.addImport("MVEL", MVEL.class);
context.addImport("MvelHelper", MvelHelper.class);
  exp = MVEL.compileExpression(modifiedRule, context);
  expressionCache.put(rule, exp);
Object test = MVEL.executeExpression(exp, mvelParameters);
if (test == null) {

代码示例来源:origin: org.drools/drools-compiler

public Object compiledExecute(final String ex) {
  final Serializable compiled = MVEL.compileExpression( ex );
  return MVEL.executeExpression( compiled,
                  new Object(),
                  new HashMap() );
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

ParserContext context = new ParserContext();
Serializable domainExp1 = MVEL.compileExpression("offer.type.equals(OfferType.FULFILLMENT_GROUP) and (($ in order.fulfillmentGroups if $.type.equals(FulfillmentType.PHYSICAL)) != empty)", context);
Boolean expressionOutcome1 = (Boolean)MVEL.executeExpression(domainExp1, domainVars);
assert expressionOutcome1 != null && expressionOutcome1;

代码示例来源:origin: org.mvel/mvel2

public void testElseIfCommentBugPreCompiled() throws Exception {
 // Comments can't appear before else if() - compilation works, but evaluation fails
 executeExpression(compileExpression("// This is never true\n" + "if (1==0) {\n"
   + "  // Never reached\n" + "}\n" + "// This is always true...\n" + "else if (1==1) {"
   + "  System.out.println('Got here!');" + "}\n"));
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

public static void exerciseWorkaround() {
  System.setProperty("mvel2.disable.jit", "true");
  String rule = "CollectionUtils.intersection(level1.level2.getMultiValueSkuAttributes()[\"TEST-VALID\"],[\"TEST-VALID\"]).size()>0";
  ParserContext context = new ParserContext();
  context.addImport("CollectionUtils", SelectizeCollectionUtils.class);
  Serializable exp = MVEL.compileExpression(rule, context);
  executeTestCase(exp, "TEST-INVALID");
  boolean response = executeTestCase(exp, "TEST-VALID");
  if (!response) {
    //With the workaround, we should never get here
    System.out.print("false");
  } else {
    //The expression should never be corrupted now that we've removed the overloaded method (this is the workaround)
    System.out.print("true");
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

ParserContext context = new ParserContext();
Serializable domainExp1 = MVEL.compileExpression("result = false; for (cat : currentItem.product.allParentCategories) {if (cat.name == 't-shirt') {result = true;}}; return result and order.subTotal.amount >= 50", context);
Boolean expressionOutcome1 = (Boolean)MVEL.executeExpression(domainExp1, domainVars);
assert expressionOutcome1 != null && expressionOutcome1;
Serializable domainExp2 = MVEL.compileExpression("($ in currentItem.product.allParentCategories if $.name == 't-shirt') != empty and order.subTotal.amount >= 50", context);
Boolean expressionOutcome2 = (Boolean)MVEL.executeExpression(domainExp2, domainVars);
assert expressionOutcome2 != null && expressionOutcome2;

代码示例来源:origin: org.mvel/mvel2

public void testMVEL222() throws IOException {
 String script = "for (int i= 0; i < 10; i++ ){ values[i] = 1.0; }";
 Map<String, Object> scriptVars = new HashMap<String, Object>();
 double[] values = new double[10];
 scriptVars.put("values", values);
 Serializable expression = MVEL.compileExpression(script);
 for (int i = 0; i < 6; i++) {
  scriptVars.put("values", values);
  MVEL.executeExpression(expression, scriptVars);
 }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

public static void exerciseFailure() {
  System.setProperty("mvel2.disable.jit", "true");
  String rule = "CollectionUtils.intersection(level1.level2.getMultiValueSkuAttributes()[\"TEST-VALID\"],[\"TEST-VALID\"]).size()>0";
  ParserContext context = new ParserContext();
  context.addImport("CollectionUtils", MvelTestOverloadUtils.class);
  Serializable exp = MVEL.compileExpression(rule, context);
  executeTestCase(exp, "TEST-INVALID");
  boolean response = executeTestCase(exp, "TEST-VALID");
  if (!response) {
    //We received the expected, corrupted expression state, so return true to validate the expected test results
    System.out.print("true");
  } else {
    //We did not receive the expected, corrupted expression state. This can happen sometimes, since the ordering of methods
    //returned from the call to Class#getMethods for SelectizeCollectionUtilsTest is undetermined. Return false
    //since we did not validate the expected test results in this run.
    System.out.print("false");
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Test
public void testOfferAppliesToSpecificItems() {
  DiscreteOrderItemImpl orderItem = new DiscreteOrderItemImpl();
  Sku sku = new SkuImpl();
  sku.setRetailPrice(new Money("1"));
  sku.setId(1234L);
  orderItem.setSku(sku);
  OfferImpl offer = new OfferImpl();
  offer.setType(OfferType.ORDER_ITEM);
  //Set up MVEL Context
  ParserContext context = new ParserContext();
  //Import OfferType into the MVEL context since it may be used
  context.addImport("OfferType", OfferType.class);
  context.addImport("FulfillmentType", FulfillmentType.class);
  //Compile the MVEL Expression
  Serializable domainExp1 = MVEL.compileExpression("offer.type == OfferType.ORDER_ITEM and (currentItem.sku.id in [1234, 2345, 5678])", context);
  //Add variables to a HashMap that should be passed in to execute the expression
  HashMap<String, Object> domainVars = new HashMap<>();
  domainVars.put("currentItem", orderItem);
  domainVars.put("offer", offer);
  //Execute the expression
  Boolean expressionOutcome1 = (Boolean)MVEL.executeExpression(domainExp1, domainVars);
  assert expressionOutcome1 != null && expressionOutcome1;
}

代码示例来源:origin: org.mvel/mvel2

public void testJIRA100b() {
 Serializable s = MVEL.compileExpression("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = " +
   "new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; ");
 assertEquals(new BigDecimal(20), executeExpression(s, new HashMap()));
}

代码示例来源:origin: kiegroup/jbpm

@Override
public Object getInstance(ObjectModel model, ClassLoader cl, Map<String, Object> contextParams) {
  Object instance = null;
  InternalRuntimeManager manager = null;
  if (contextParams.containsKey("runtimeManager")) {
    manager = (InternalRuntimeManager) contextParams.get("runtimeManager");
    instance = manager.getCacheManager().get(model.getIdentifier());
    if (instance != null) {
      return instance;
    }
  }
  ParserConfiguration config = new ParserConfiguration();
  config.setClassLoader(cl);
  ParserContext ctx = new ParserContext(config);
  if (contextParams != null) {
    for (Map.Entry<String, Object> entry : contextParams.entrySet()) {
      ctx.addVariable(entry.getKey(), entry.getValue().getClass());
    }
  }
  Object compiledExpression = MVEL.compileExpression(model.getIdentifier(), ctx);
  instance = MVELSafeHelper.getEvaluator().executeExpression( compiledExpression, contextParams );
  
  if (manager != null && instance instanceof Cacheable) {
    manager.getCacheManager().add(model.getIdentifier(), instance);
  }
  return instance;
}

代码示例来源:origin: org.drools/drools-compiler

@Test
public void test1() {
  final ParserContext pc = new ParserContext();
  pc.addInput("x", String.class);
  pc.setStrongTyping(true);
  final Object o = MVEL.compileExpression("x.startsWith('d')", pc);
  final Map vars = new HashMap();
  vars.put("x", "d");
  MVEL.executeExpression(o, vars);
  System.out.println(o);
}

代码示例来源:origin: org.mvel/mvel2

public void testMVEL238() throws IOException {
 String expr = new String(loadFromFile(new File("src/test/java/org/mvel2/tests/MVEL238.mvel")));
 Serializable s = MVEL.compileExpression(expr);
 System.out.println(MVEL.executeExpression(s, new HashMap()));
 System.out.println(MVEL.executeExpression(s, new HashMap()));
}

代码示例来源:origin: kiegroup/jbpm

public static Object eval(String str, Map<String, Object> vars) {
    ParserConfiguration pconf = new ParserConfiguration();
    pconf.addPackageImport("org.jbpm.services.task");
//        pconf.addPackageImport("org.jbpm.services.task.service");
    
    pconf.addPackageImport("org.jbpm.services.task.query");
    pconf.addPackageImport("java.util");
    
    for(String entry : getInputs().keySet()){
      pconf.addImport(entry, getInputs().get(entry));
    }
    ParserContext context = new ParserContext(pconf);
    Serializable s = MVEL.compileExpression(str.trim(), context);

    if( vars != null ) { 
    return MVELSafeHelper.getEvaluator().executeExpression(s, vars);
  }
    else { 
      return MVELSafeHelper.getEvaluator().executeExpression(s);
    }
  }
  public static String toString(Reader reader) throws IOException {

代码示例来源:origin: org.mvel/mvel2

private void testMVELUntyped(String text) {
  String str = IMPORTS + text;
  ParserContext pctx = new ParserContext();
  Map<String, Object> vars = new HashMap<String, Object>();
  Object o = MVEL.compileExpression(str, pctx);
  MVEL.executeExpression(o, vars);
}

代码示例来源:origin: org.mvel/mvel2

public Object compiledExecute(String ex) {
  Serializable compiled = MVEL.compileExpression(ex);
  Object first = MVEL.executeExpression(compiled, null, map);
  Object second = MVEL.executeExpression(compiled, null, map);

  if (first != null && !first.getClass().isArray())
   assertEquals(first, second);

  return second;
 }
}

代码示例来源:origin: kiegroup/jbpm

public Object eval(String str, Map vars) {
  ParserContext context = new ParserContext();
  context.addPackageImport("org.jbpm.task");
  context.addPackageImport("org.jbpm.task.service");
  context.addPackageImport("org.jbpm.task.query");
  context.addPackageImport("java.util");
  vars.put("now", new Date());
  return MVELSafeHelper.getEvaluator().executeExpression(MVEL.compileExpression(str, context),
      vars);
}

代码示例来源:origin: org.mvel/mvel2

private void testMVELTyped(String text) {
  String str = IMPORTS + text;
  ParserContext pctx = new ParserContext();
  pctx.setStrongTyping(true);
  Map<String, Object> vars = new HashMap<String, Object>();
  Object o = MVEL.compileExpression(str, pctx);
  MVEL.executeExpression(o, vars);
}

代码示例来源:origin: org.mvel/mvel2

public void testSimple2() {
 OptimizerFactory.setDefaultOptimizer("ASM");
 MVEL.executeExpression(
   MVEL.compileExpression("java.util.Collections.emptySet instanceof java.util.Set"));
}

相关文章