/** * Having a parser context that imports the classes speeds MVEL by up to 60%. */ protected ParserContext getParserContext() { if (parserContext == null) { parserContext = new ParserContext(); parserContext.addImport("MVEL", MVEL.class); parserContext.addImport("MvelHelper", MvelHelper.class); } return parserContext; }
@Override public Object apply(Object context) { return MVEL.eval(script, context); } }
/** * Create a new {@link MVELAction}. * * @param expression the action written in expression language */ public MVELAction(String expression) { this.expression = expression; compiledExpression = MVEL.compileExpression(expression); }
public static Object eval(String str, Map<String, Object> vars) { ParserConfiguration pconf = new ParserConfiguration(); pconf.addPackageImport("org.kie.internal.task.api.model"); pconf.addPackageImport("org.jbpm.services.task"); pconf.addPackageImport("org.jbpm.services.task.impl.model"); pconf.addPackageImport("org.jbpm.services.task.query"); pconf.addPackageImport("org.jbpm.services.task.internals.lifecycle"); pconf.addImport(Status.class); pconf.addImport(Allowed.class); pconf.addPackageImport("java.util"); 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); } }
@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; }
@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); }
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"); } }
@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; }
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); }
@Override public boolean evaluate(Facts facts) { try { return (boolean) MVEL.executeExpression(compiledExpression, facts.asMap()); } catch (Exception e) { LOGGER.debug("Unable to evaluate expression: '" + expression + "' on facts: " + facts, e); return false; } } }
@Override public Object run() { return MVEL.executeExpression(compiler.compile(), new HashMap()); } }, KiePolicyHelper.getAccessContext());
public static String fix(final String raw) { if ( raw == null || "".equals( raw.trim() )) { return raw; } MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( raw ); } }
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 {
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"); } }
@Override public void execute(Facts facts) { try { MVEL.executeExpression(compiledExpression, facts.asMap()); } catch (Exception e) { LOGGER.debug("Unable to evaluate expression: '" + expression + "' on facts: " + facts, e); } } }
/** * Create a new {@link MVELCondition}. * * @param expression the condition written in expression language */ public MVELCondition(String expression) { this.expression = expression; compiledExpression = MVEL.compileExpression(expression); }
@Test public void testBasicMVELFunctions() { //First, set up out functions HashMap<String, Object> functionMap = new HashMap<>(); StringBuffer functions = new StringBuffer("def any(x, y) { return x or y } def all(x, y) { return x and y } "); MVEL.eval(functions.toString(), functionMap); //This stores that functions in the map we pass in. HashMap<String, Object> vars = new HashMap<>(functionMap); //Now, we need to pass the functions in to our variable map vars.put("fg", "Hello"); StringBuffer expression = new StringBuffer(); expression.append("return all(fg == 'Hello', true)"); Boolean result = (Boolean)MVEL.eval(expression.toString(), vars); assert result != null && result; expression = new StringBuffer(); expression.append("return any(fg == 'Goodbye', false)"); Boolean result2 = (Boolean)MVEL.eval(expression.toString(), vars); assert result2 != null && ! result2; }
public static String processMacros(String consequence) { MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( delimitExpressions( consequence ) ); }
private static boolean executeTestCase(Serializable exp, String val) { final Map multiValueMap = new MultiValueMap(); multiValueMap.put(val, val); final Level2 level2 = new Level2() { @Override public Map getMultiValueSkuAttributes() { return multiValueMap; } }; Level1 level1 = new Level1() { @Override public Level2 getLevel2() { return level2; } }; Map parameters = new HashMap(); parameters.put("level1", level1); return (Boolean) MVEL.executeExpression(exp, parameters); }
public static String processMacros(String consequence) { MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( delimitExpressions( consequence ) ); }