1 package com.github.mygreen.supercsv.expression;
2
3 import java.util.Map;
4 import java.util.Objects;
5
6 import org.apache.commons.jexl2.Expression;
7 import org.apache.commons.jexl2.JexlEngine;
8 import org.apache.commons.jexl2.MapContext;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11
12
13
14
15
16
17
18
19
20
21
22 public class ExpressionLanguageJEXLImpl implements ExpressionLanguage {
23
24 private static final Logger logger = LoggerFactory.getLogger(ExpressionLanguageJEXLImpl.class);
25
26 private final JexlEngine jexlEngine;
27
28 private final ObjectCache<String, Expression> expressionCache = new ObjectCache<>();
29
30 public ExpressionLanguageJEXLImpl() {
31 JexlEngine engine = new JexlEngine();
32 engine.setSilent(true);
33 this.jexlEngine = engine;
34 }
35
36
37
38
39
40 public ExpressionLanguageJEXLImpl(final JexlEngine jexlEngine) {
41 this.jexlEngine = jexlEngine;
42 }
43
44 @Override
45 public Object evaluate(final String expression, final Map<String, Object> values) {
46
47 Objects.requireNonNull(expression, "expression shoud not be null.");
48 Objects.requireNonNull(values, "values shoud not be null.");
49
50 if(logger.isDebugEnabled()) {
51 logger.debug("Evaluating JEXL expression: {}", expression);
52 }
53
54 try {
55 Expression expr = expressionCache.get(expression);
56 if (expr == null) {
57 expr = jexlEngine.createExpression(expression);
58 expressionCache.put(expression, expr);
59 }
60
61 return expr.evaluate(new MapContext((Map<String, Object>) values));
62
63 } catch(Exception ex) {
64 throw new ExpressionEvaluationException(String.format("Evaluating [%s] script with JEXL failed.", expression), ex,
65 expression, values);
66 }
67 }
68
69
70
71
72
73 public JexlEngine getJexlEngine() {
74 return jexlEngine;
75 }
76
77 }