Java Code Examples for org.mvel2.ParserContext#setStrongTyping()

The following examples show how to use org.mvel2.ParserContext#setStrongTyping() . 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: 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 2
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 3
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 4
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);
            }
        }
    }
}
 
Example 5
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 6
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 7
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));
	}
}