Unexpected MVEL2 behavior

1.9k views Asked by At

I need to check if an expression is well written, so I decide to use MVEL2 to do this. I have an expression like

String expression = "(OPVAL == 'OPERATION') && (DAT > '12345')"

and an hash map like

Map<String, Object> vars = new HashMap<String, Object>();

{OPVAL = "OPERATION", DATA = "0"}

When I process it with MVEL,

(Boolean)MVEL.eval(expression, vars);

I'm expecting an exception because DAT is not mapped, instead MVEL2 library return only a FALSE condition.

If I use the expression like

String expression = (DAT > '15/11/2014') && (OPVAL == 'Operazione')

I get the expected exception, and another example where I get the exception is this:

String expression = (OPVAL != "Operazione") AND (DAT < "15/11/2014")

Could you please give me an explanation?

1

There are 1 answers

0
Ankur Singhal On BEST ANSWER

I got the same error in all the three cases.

unresolvable property or identifier: DAT

Remember - While evaluating expression, "(OPVAL == 'OPERATION') && (DAT > '12345')", MVEL uses AST tree structure to parse any given expression and then evaluate.

Also if (OPVAL == 'OPERATION') is false, then it will never evaluate (DAT > '12345') since there is a && operator between the two.

Carefully look once again, and play around with your expression, or move (DAT > '12345') in front, and then test.

FYI, refer below code

Case 1

public static void main(String args[]) throws Exception {
        String expression = "(OPVAL == 'OPERATION') && (DAT > '12345')";
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("OPVAL", "OPERATION1");
        vars.put("DATA", "0");
        System.out.println(MVEL.eval(expression, vars));
    }

Output

false

Since (OPVAL == 'OPERATION') evaluates to false.

Case 2

public static void main(String args[]) throws Exception {
        String expression = "(OPVAL == 'OPERATION') && (DAT > '12345')";
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("OPVAL", "OPERATION");
        vars.put("DATA", "0");
        System.out.println(MVEL.eval(expression, vars));
    }

output

Exception in thread "main" [Error: unresolvable property or identifier: DAT]
[Near : {... (OPVAL == 'OPERATION') && (DAT > '12345') ....}]

Since in this case, (OPVAL == 'OPERATION') evaluates to true, so it further traverses to evaluate (DAT > '12345').

hope it solves your confusion.