I need to evaluate a expression in MVEL containing date. Basically, I need to add Certain number of days to a given date and get the value. When I am trying to evaluate the expression in MVEL, getting some exceptions.
Here is my code::
package Mvel;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
public class Mveldatetest {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("name", "xyz");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d1 = sdf.parse("02/10/2014");
m1.put("doj", d1);
//Date d2=sdf.parse("05/10/2014");
System.out.println("Given Date"+" "+d1);
final Calendar c = Calendar.getInstance();
c.setTime(d1);
System.out.println(c.getTime());
Date finaldate=(Date) MVEL.eval("c.add(Calendar.DAY_OF_MONTH, 4)",m1);
System.out.println(finaldate);
}
}
I am getting the following exception::
Exception in thread "main" [Error: unresolvable property or identifier: c]
[Near : {... c.add(Calendar.DAY_OF_MONTH, 4 ....}]
^
[Line: 1, Column: 1]
at org.mvel2.PropertyAccessor.getBeanProperty(PropertyAccessor.java:677)
at org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:179)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:146)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:126)
at org.mvel2.ast.ASTNode.getReducedValue(ASTNode.java:187)
at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterpreted(MVELInterpretedRuntime.java:106)
at org.mvel2.MVELInterpretedRuntime.parse(MVELInterpretedRuntime.java:49)
at org.mvel2.MVEL.eval(MVEL.java:165)
at Mvel.Mveldatetest.main(Mveldatetest.java:31)
You have to add c
to the context m1
. Also, Calender
is unknown, too, but you could just use c
instead (ugly, but works). Finally, note that add
returns void, i.e. it modifies c
in-place. Try this:
System.out.println(c.getTime());
m1.put("c", c);
MVEL.eval("c.add(c.DAY_OF_MONTH, 4)", m1);
System.out.println(c.getTime());
Output:
Thu Oct 02 00:00:00 CEST 2014
Mon Oct 06 00:00:00 CEST 2014