Java Code Examples for org.mvel2.MVEL#compileExpression()

The following examples show how to use org.mvel2.MVEL#compileExpression() . 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: MvelExpressionExecutor.java    From activiti6-boot2 with Apache License 2.0 7 votes vote down vote up
public static Object executeOutputExpression(OutputClause outputClause, LiteralExpression outputEntry, MvelExecutionContext executionContext) {

        if (outputClause == null) {
            throw new IllegalArgumentException("output clause is required");
        }
        if (outputEntry == null) {
            throw new IllegalArgumentException("output entry is required");
        }

        // compile MVEL expression
        Serializable compiledExpression = MVEL.compileExpression(outputEntry.getText(), executionContext.getParserContext());

        // execute MVEL expression
        Object result = null;

        try {
            result = MVEL.executeExpression(compiledExpression, executionContext.getStackVariables());
        } catch (Exception ex) {
            logger.warn("Error while executing output entry: {}", outputEntry.getText(), ex);
            throw new ActivitiDmnExpressionException("error while executing output entry", outputEntry.getText(), ex);
        }

        return result;
    }
 
Example 2
Source File: MVELBeanCreator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T createBean(ClassLoader cl, String type, QualifierModel qualifier ) throws Exception {
    if (qualifier != null) {
        throw new IllegalArgumentException("Cannot use a qualifier without a CDI container");
    }

    ParserConfiguration config = new ParserConfiguration();
    config.setClassLoader(cl);
    ParserContext ctx = new ParserContext( config);
    if (parameters != null) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            ctx.addVariable(entry.getKey(), entry.getValue().getClass());
        }
    }

    Object compiledExpression = MVEL.compileExpression( type, ctx );
    return (T) MVELSafeHelper.getEvaluator().executeExpression( compiledExpression, parameters );
}
 
Example 3
Source File: MVELObjectClassFieldReader.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static void doCompile(MVELClassFieldReader target, MVELDialectRuntimeData runtimeData, Object evaluationContext) {
    Class cls;
    try {            
        cls = runtimeData.getRootClassLoader().loadClass( target.getClassName() );
    } catch ( ClassNotFoundException e ) {
        throw new IllegalStateException( "Unable to compile as Class could not be found '" + target.getClassName() + "'");
    }
    ParserContext context = new ParserContext(runtimeData.getParserConfiguration(), evaluationContext);
    context.addInput( "this", cls );
    context.setStrongTyping( target.isTypeSafe() );

    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
    MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true;
    MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;
    ExecutableStatement mvelExpression = (ExecutableStatement)MVEL.compileExpression( target.getExpression(), context);
    
    Class returnType = mvelExpression.getKnownEgressType();
    target.setExecutableStatement( mvelExpression );
    target.setFieldType( returnType );
    target.setValueType( ValueType.determineValueType( returnType ) );
    target.setEvaluationContext(evaluationContext);
}
 
Example 4
Source File: MVELDataTransformer.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 6
Source File: MVELCompilationUnit.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static Serializable compile( final String text,
                                     final ParserContext parserContext ) {
    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
    MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true;
    MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;   
    
    if ( MVELDebugHandler.isDebugMode() ) {
        parserContext.setDebugSymbols( true );
    }

    return MVEL.compileExpression( text.trim(),
                                   parserContext );
}
 
Example 7
Source File: MvelConditionEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public MvelConditionEvaluator(ParserConfiguration configuration,
                              String expression,
                              Declaration[] declarations,
                              EvaluatorWrapper[] operators,
                              String conditionClass) {
    this(null,
         configuration,
         (ExecutableStatement)MVEL.compileExpression(expression, new ParserContext(configuration)),
         declarations,
         operators,
         conditionClass);
}
 
Example 8
Source File: QueryArgument.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void init() {
    Map<String, Class> inputs = new HashMap<String, Class>();
    for (Declaration d : declarations) {
        inputs.put(d.getBindingName(), d.getDeclarationClass());
    }
    parserContext.setInputs(inputs);

    this.argumentClass = MVEL.analyze( expression, parserContext );
    this.mvelExpr = MVEL.compileExpression( expression, parserContext );
}
 
Example 9
Source File: StaticUtil.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static Serializable compileExpression(String expression) {
    Serializable compiledExpression = EXPRESSION_CACHE.get(expression);

    if(compiledExpression == null) {
        compiledExpression = MVEL.compileExpression(expression, MVELInitializer.getInstance().getCtx());
        EXPRESSION_CACHE.put(expression, compiledExpression);
    }

    return compiledExpression;
}
 
Example 10
Source File: MvelExpressionExecutor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static Boolean executeInputExpression(InputClause inputClause, UnaryTests inputEntry, MvelExecutionContext executionContext) {

        if (inputClause == null) {
            throw new IllegalArgumentException("input clause is required");
        }
        if (inputClause.getInputExpression() == null) {
            throw new IllegalArgumentException("input expression is required");
        }
        if (inputEntry == null) {
            throw new IllegalArgumentException("input entry is required");
        }
        
        for (Class<?> variableClass : executionContext.getPropertyHandlers().keySet()) {
            PropertyHandlerFactory.registerPropertyHandler(variableClass, executionContext.getPropertyHandlers().get(variableClass));
        }

        // check if variable is present MVEL execution context
        executionContext.checkExecutionContext(inputClause.getInputExpression().getText());

        // pre parse expression
        String parsedExpression = MvelConditionExpressionPreParser.parse(inputEntry.getText(), inputClause.getInputExpression().getText());

        // compile MVEL expression
        Serializable compiledExpression = MVEL.compileExpression(parsedExpression, executionContext.getParserContext());

        // execute MVEL expression
        Boolean result;

        try {
            result = MVEL.executeExpression(compiledExpression, executionContext.getStackVariables(), Boolean.class);
        } catch (Exception ex) {
            logger.warn("Error while executing input entry: {}", parsedExpression, ex);
            throw new ActivitiDmnExpressionException("error while executing input entry", parsedExpression, ex);
        }

        return result;
    }
 
Example 11
Source File: MvelRule.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 执行条件匹配后的操作
 */
@Override
public void execute(RuleContext ruleContext) {
    try {
        Serializable exp = MVEL.compileExpression(getAction(), ruleContext);
        MVEL.executeExpression(exp, ruleContext);
    } catch (Exception e) {
        throw new RuntimeException(String.format("后续操作[%s]执行发生异常:", getAction()), e);
    }
}
 
Example 12
Source File: ClassTests.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void testCompileExpression() {
    String expression = "foobar > 99";
    Serializable compiled = MVEL.compileExpression(expression);
    Map vars = new HashMap();
    vars.put("foobar", new Integer(100));
    Boolean result = (Boolean) MVEL.executeExpression(compiled, vars);
    Assertions.assertEquals(true, result);
}
 
Example 13
Source File: ExpressionProvider.java    From test-data-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Map<String, String> props) {
    Map<String, String> propsCopy = new HashMap<>(props);
    expr = propsCopy.remove(PropConst.EXPR);
    if (expr == null) {
        throw new IllegalArgumentException("Value does not specified or null");
    }
    if (!propsCopy.isEmpty()) {
        throw new IllegalArgumentException("Redundant props for " + getClass().getName() + ": " + propsCopy);
    }
    compiledExpression = MVEL.compileExpression(expr);
}
 
Example 14
Source File: RulesMVELCondition.java    From nifi with Apache License 2.0 4 votes vote down vote up
public RulesMVELCondition(String expression, boolean ignoreConditionErrors) {
    this.expression = expression;
    this.compiledExpression = MVEL.compileExpression(expression);
    this.ignoreConditionErrors = ignoreConditionErrors;
}
 
Example 15
Source File: MVELtest.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void main(String args[]) {
	ParserContext ctx = new ParserContext();
	ctx.setStrongTyping(true); 
	ctx.addInput("page", SurveyPage.class);

	//compile an expression 'str.toUpperCase()'
	String texpression = "e= page.questionAnswers[0].booleanAnswerValue;e==null? false:true;";
	
	
	try {
		ExecutableStatement ce = (ExecutableStatement) MVEL.compileExpression(texpression, ctx);
		Class returnType = ce.getKnownEgressType(); // returns java.lang.String in this case.
		System.out.println(returnType.toString());
		if (returnType.equals(Boolean.class)) {
			System.out.println("Pass");}
		else{
			System.out.println("No Pass");
			}
	}
	catch (Exception e) {
		System.out.println("Invalid Expression");
		System.out.println(e);
		
	} 
	
	
						  
	//String texpression = "survey.pages[0].questions[0].booleanAnswerValue";
	//Survey  survey =surveyService.Survey_findById((long) 5);
	Survey  survey = new Survey();
	
	//System.out.println(survey.getTypeName());
	//System.out.println(survey.getPages().first().getTitle());
	
	/*
	System.out.println("---------------->" + survey.getPages().first().getQuestions().get(0).getBooleanAnswerValue());				
	Map map = new HashMap();
	map.put("survey", survey);
	
	
	for (SurveyPage surveyPage : survey.getPages()){

			System.out.println(surveyPage.getOrder());
			Boolean pageVisibility = (Boolean) MVEL.eval(surveyPage.getVisibilityExpression(), map);
			System.out.println(pageVisibility);
			if (pageVisibility) {
				System.out.println(surveyPage.getOrder());
			}
	}
	
	*/
	
	
	
	/*
	 String expression = "age > 25 ? 2000 : 1000;";
         
	  		  
	  Map vars = new HashMap();
         vars.put("age", new Integer(24));

         // We know this expression should return a boolean.
         Integer result = (Integer) MVEL.eval(expression, vars);
         
         System.out.println(result);
           	  
    
         
         //compiled mode
         String expression2 = "foobar3 > 99";
         // Compile the expression.
         Serializable compiled = MVEL.compileExpression(expression2);

         Map vars2 = new HashMap();
         vars2.put("foobar", new Integer(100));

         // Now we execute it.
         Boolean result2 = (Boolean) MVEL.executeExpression(compiled, vars2);
         
         if (result2.booleanValue()) {
             System.out.println("It works!");
         }
         else{
       	  System.out.println("It does not work!");
         }
                   
         */
         
	
}
 
Example 16
Source File: ExpressionLanguageMVELImpl.java    From oval with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Object load(final String expression) {
   return MVEL.compileExpression(expression);
}
 
Example 17
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Object compiledExecute(final String ex) {
    final Serializable compiled = MVEL.compileExpression( ex );
    return MVEL.executeExpression( compiled,
                                   new Object(),
                                   new HashMap() );
}