2

Having a JEXL expression, How can I parse it in order to dynamically add to JEXL context all the involved variables?

Example : Initial Expression:

Initial Expression = $VAR1 + $VAR2

VAR1 and VAR2 are other expressions

$VAR1 = 123 + 45
$VAR2 = 67 + 89

Even more VAR1 can have another depth level :

$VAR1 = 123 + 45 + $VAR3

So, before evaluate Initial expression , I need to add into the context VAR1 and VAR2 and VAR3, How can I do it in a dynamic way?

It is possible to use a JEXL parser? Or by catching the JEXL exception? Can you provide an example?

Regards

Osy
  • 1,613
  • 5
  • 21
  • 35

1 Answers1

0

You do not need to worry about it at all. JEXL handles it.

But, first and foremost thing, you should use Script evaluator, instead of Expression evaluator. Script evaluators do handle multiple statements nicely as well as support complex looping syntax.

See here

JexlScript

These allow you to use multiple statements and you can use variable assignments, loops, calculations, etc. More or less what can be achieved in Shell or JavaScript at its basic level. The result from the last command is returned from the script.

JxltEngine.Expression

These are ideal to produce "one-liner" text, like a 'toString()' on steroids. To get a calculation you use the EL-like syntax as in ${someVariable}. The expression that goes between the brackets behaves like a JexlScript, not an expression. You can use semi-colons to execute multiple commands and the result from the last command is returned from the script. You also have the ability to use a 2-pass evaluation using the #{someScript} syntax.

Now, try below:

String script =     
            "var var1 = 123 + 45;"
        +   "var var2 = 67 + 89;"
        +   "var var = var1 + var2;"
        +   "return var;";

JexlContext jexlContext = new MapContext();

JexlEngine jexlEngine=new JexlBuilder().create();

System.out.println(jexlEngine.createScript(script).execute(jexlContext); // 134
Pratik
  • 908
  • 2
  • 11
  • 34