org.mvel2.ParserContext Java Examples

The following examples show how to use org.mvel2.ParserContext. 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: PatternBuilder.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private FieldValue getFieldValue(RuleBuildContext context,
                                 ValueType vtype,
                                 String value) {
    try {
        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;

        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        ParserConfiguration pconf = data.getParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);

        Object o = MVELSafeHelper.getEvaluator().executeExpression(MVEL.compileExpression(value, pctx));
        if (o != null && vtype == null) {
            // was a compilation problem else where, so guess valuetype so we can continue
            vtype = ValueType.determineValueType(o.getClass());
        }

        return context.getCompilerFactory().getFieldFactory().getFieldValue(o, vtype);
    } catch (final Exception e) {
        // we will fallback to regular preducates, so don't raise an error
    }
    return null;
}
 
Example #2
Source File: MVELExprAnalyzer.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static Class<?> getExpressionType(PackageBuildContext context,
                                         Map<String, Class< ? >> declCls,
                                         RuleConditionElement source,
                                         String expression) {
    MVELDialectRuntimeData data = ( MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData( "mvel" );
    ParserConfiguration conf = data.getParserConfiguration();
    conf.setClassLoader( context.getKnowledgeBuilder().getRootClassLoader() );
    ParserContext pctx = new ParserContext( conf );
    pctx.setStrongTyping(true);
    pctx.setStrictTypeEnforcement(true);
    for (Map.Entry<String, Class< ? >> entry : declCls.entrySet()) {
        pctx.addInput(entry.getKey(), entry.getValue());
    }
    for (Declaration decl : source.getOuterDeclarations().values()) {
        pctx.addInput(decl.getBindingName(), decl.getDeclarationClass());
    }
    try {
        return MVEL.analyze( expression, pctx );
    } catch (Exception e) {
        log.warn( "Unable to parse expression: " + expression, e );
    }
    return null;
}
 
Example #3
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 #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: 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 #6
Source File: PayloadExpressionEvaluator.java    From chancery with Apache License 2.0 5 votes vote down vote up
PayloadExpressionEvaluator(@Nonnull String template) {
    if (template == null) {
        System.err.println("wuuut");
    }
    final ParserContext parserContext = new ParserContext();
    parserContext.addImport("iso", ISODateTimeFormat.class);
    parserContext.addImport("dtf", DateTimeFormat.class);
    compiledTemplate = TemplateCompiler.compileTemplate(template, parserContext);
}
 
Example #7
Source File: MvelExecutionContextBuilder.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static MvelExecutionContext build(Decision decision, Map<String, Object> inputVariables,
    Map<String, Method> customExpressionFunctions, Map<Class<?>, PropertyHandler> propertyHandlers) {

  MvelExecutionContext executionContext = new MvelExecutionContext();

  // initialize audit trail
  executionContext.setAuditContainer(DecisionExecutionAuditUtil.initializeRuleExecutionAudit(decision, inputVariables));

  ParserContext parserContext = new ParserContext();

  // add custom functions to context
  if (customExpressionFunctions != null && !customExpressionFunctions.isEmpty()) {
    for (Map.Entry<String, Method> config : customExpressionFunctions.entrySet()) {
      parserContext.addImport(config.getKey(), config.getValue());
    }
  }

  executionContext.setParserContext(parserContext);

  if (propertyHandlers != null) {
    for (Class<?> variableClass : propertyHandlers.keySet()) {
      executionContext.addPropertyHandler(variableClass, propertyHandlers.get(variableClass));
    }
  }
  
  DecisionTable decisionTable = (DecisionTable) decision.getExpression();
  
  preProcessInputVariables(decisionTable, inputVariables);

  executionContext.setStackVariables(inputVariables);

  logger.debug("Execution Context created");

  return executionContext;
}
 
Example #8
Source File: MVELInitializer.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private MVELInitializer() {
	MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; // forcing to use PropertyHandler
       MathProcessor.COMPARE_WITH_PRECISION = true;
       OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); //Workaround for MVEL-291 "Custom property handler optimization fails with RuntimeException unable to compileShared"
	PropertyHandlerFactory.registerPropertyHandler(IMessage.class, new IMessagePropertyHandler());
	PropertyHandlerFactory.registerPropertyHandler(Map.class, new MapPropertyHandler());

	ctx = new ParserContext();
	ctx.addImport(LocalDateTime.class);
	ctx.addImport(LocalDate.class);
	ctx.addImport(LocalTime.class);
	ctx.addImport(BigDecimal.class);
	ctx.addImport(SailfishURI.class);
	ctx.addImport(Objects.class);
}
 
Example #9
Source File: JbpmBpmn2TestCase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
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);
    }
 
Example #10
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 #11
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 #12
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 #13
Source File: MVELConsequenceBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDebugSymbolCount() {
    String expr = "System.out.println( \"a1\" );\n" + "System.out.println( \"a2\" );\n" + "System.out.println( \"a3\" );\n" + "System.out.println( \"a4\" );\n";

    ParserContext context = new ParserContext();
    context.setDebugSymbols( true );
    context.addImport( "System",
                       System.class );
    context.setStrictTypeEnforcement( true );
    //context.setDebugSymbols( true );
    context.setSourceFile( "mysource" );

    ExpressionCompiler compiler = new ExpressionCompiler( expr, context );
    Serializable compiledExpression = compiler.compile();

    String s = DebugTools.decompile( compiledExpression );

    System.out.println( "s " + s );

    int fromIndex = 0;
    int count = 0;
    while ( (fromIndex = s.indexOf( "DEBUG_SYMBOL",
                                    fromIndex + 1 )) > -1 ) {
        count++;
    }
    assertEquals( 4,
                  count );

}
 
Example #14
Source File: QueryArgument.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Expression( List<Declaration> declarations, String expression, ParserContext parserContext ) {
    this.declarations = declarations;
    this.expression = expression;
    this.parserContext = parserContext;
    init();
}
 
Example #15
Source File: MVELCompilationUnit.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Serializable getCompiledExpression(ParserConfiguration conf, Object evaluationContext) {
    final ParserContext parserContext = new ParserContext( conf, evaluationContext );
    if ( MVELDebugHandler.isDebugMode() ) {
        parserContext.setDebugSymbols( true );
    }

    parserContext.setStrictTypeEnforcement( strictMode );
    parserContext.setStrongTyping( strictMode );
    parserContext.setIndexAllocation( true );

    if ( INTERCEPTORS != null ) {
        parserContext.setInterceptors(INTERCEPTORS);
    }

    parserContext.addIndexedInput( inputIdentifiers );

    String identifier = null;
    String type = null;
    try {
        for ( int i = 0, length = inputIdentifiers.length; i < length; i++ ) {
            identifier = inputIdentifiers[i];
            type = inputTypes[i];
            Class< ? > cls = loadClass( conf.getClassLoader(),
                                        inputTypes[i] );
            parserContext.addInput( inputIdentifiers[i],
                                    cls );
        }
    } catch ( ClassNotFoundException e ) {
        throw new RuntimeException( "Unable to resolve class '" + type + "' for identifier '" + identifier );
    }

    parserContext.setSourceFile( name );

    String[] varNames = parserContext.getIndexedVarNames();

    ExecutableStatement stmt = (ExecutableStatement) compile( expression, parserContext );

    Set<String> localNames = parserContext.getVariables().keySet();

    parserContext.addIndexedLocals(localNames);

    String[] locals = localNames.toArray(new String[localNames.size()]);
    String[] allVars = new String[varNames.length + locals.length];

    System.arraycopy(varNames, 0, allVars, 0, varNames.length);
    System.arraycopy(locals, 0, allVars, varNames.length, locals.length);

    this.varModel = new SimpleVariableSpaceModel(allVars);
    this.allVarsLength = allVars.length;

    return stmt;
}
 
Example #16
Source File: MVELInitializer.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public ParserContext getCtx() {
	return ctx;
}
 
Example #17
Source File: QueryElementBuilder.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private ParserContext getParserContext(RuleBuildContext context) {
    MVELDialectRuntimeData data = ( MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData( "mvel" );
    ParserConfiguration conf = data.getParserConfiguration();
    conf.setClassLoader( context.getKnowledgeBuilder().getRootClassLoader() );
    return new ParserContext( conf );
}
 
Example #18
Source File: MvelExecutionContext.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public ParserContext getParserContext(){
    return parserContext;
}
 
Example #19
Source File: MvelExecutionContext.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public void setParserContext(ParserContext parserContext) {
    this.parserContext = parserContext;
}
 
Example #20
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 #21
Source File: SurveyDefinitionPageController.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
					 @Valid SurveyDefinitionPage surveyDefinitionPage, 
					 BindingResult bindingResult, 
					 Principal principal,
					 Model uiModel, 
					 HttpServletRequest httpServletRequest) {
	log.info("update(): handles PUT");
	try{
		User user = userService.user_findByLogin(principal.getName());
		if(!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionPage.getSurveyDefinition().getId(), user) &&
		   !securityService.userBelongsToDepartment(surveyDefinitionPage.getSurveyDefinition().getDepartment().getId(), user)	) {
			log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr());
			return "accessDenied";	
		}
		if(proceed != null){
			if (bindingResult.hasErrors()) {
				populateEditForm(uiModel, surveyDefinitionPage,user);
				return "settings/surveyDefinitionPages/update";
			}
			//validate VisibilityExpression
			boolean isValid =  true; 
			ParserContext ctx = new ParserContext();
			ctx.setStrongTyping(true); 
			ctx.addInput("surveyDefinition", SurveyDefinition.class);
			uiModel.asMap().clear();
			surveyDefinitionPage =surveySettingsService.surveyDefinitionPage_merge(surveyDefinitionPage);
			return "settings/surveyDefinitionPages/saved";

		}else{

			return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(surveyDefinitionPage.getSurveyDefinition().getId().toString(), httpServletRequest);


		}

	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example #22
Source File: PatternBuilder.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected void setInputs(RuleBuildContext context,
                         ExprBindings descrBranch,
                         Class<?> thisClass,
                         String expr) {
    MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
    ParserConfiguration conf = data.getParserConfiguration();

    conf.setClassLoader(context.getKnowledgeBuilder().getRootClassLoader());

    final ParserContext pctx = new ParserContext(conf);
    pctx.setStrictTypeEnforcement(false);
    pctx.setStrongTyping(false);
    pctx.addInput("this", thisClass);
    pctx.addInput("empty", boolean.class); // overrides the mvel empty label
    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;

    try {
        MVEL.analysisCompile(expr, pctx);
    } catch (Exception e) {
        // There is a problem in setting the inputs for this expression, but it will be
        // reported during expression analysis, so swallow it at the moment
        return;
    }

    if (!pctx.getInputs().isEmpty()) {
        for (String v : pctx.getInputs().keySet()) {
            // in the following if, we need to check that the expr actually contains a reference
            // to an "empty" property, or the if will evaluate to true even if it doesn't 
            if ("this".equals(v) || (PropertyTools.getFieldOrAccessor(thisClass,
                                                                      v) != null && expr.matches("(^|.*\\W)empty($|\\W.*)"))) {
                descrBranch.getFieldAccessors().add(v);
            } else if ("empty".equals(v)) {
                // do nothing
            } else if (!context.getPkg().getGlobals().containsKey(v)) {
                descrBranch.getRuleBindings().add(v);
            } else {
                descrBranch.getGlobalBindings().add(v);
            }
        }
    }
}