Debian Codegraph @

library/src/main/java/org/kravemir/svg/labels/utils/ExpressionEvaluator.java

raw
1 package org.kravemir.svg.labels.utils;
2
3 import org.apache.commons.jexl3.*;
4
5 import java.util.Collections;
6 import java.util.Map;
7 import java.util.regex.Matcher;
8 import java.util.regex.Pattern;
9
10 public class ExpressionEvaluator {
11
12 private Pattern p = Pattern.compile(
13 "\\$(?:([a-zA-Z]+)|\\{([a-zA-Z]+)})"
14 );
15
16 private JexlEngine jexl = new JexlBuilder().create();
17
18 public String evaluateExpression(String expression, Map<String,String> variables) {
19
20 Matcher m = p.matcher(expression);
21 StringBuffer sb = new StringBuffer();
22 while (m.find()) {
23 String variableName = m.group(1);
24 if(variableName == null)
25 variableName = m.group(2);
26
27 String value = variables.get(variableName);
28 if(value == null) {
29 throw new RuntimeException(String.format("There's no value for %s, in %s", variableName, variables));
30 }
31 m.appendReplacement(sb, value);
32 }
33 m.appendTail(sb);
34 return sb.toString();
35 }
36
37 public Object evaluateExpressionWithJEXL(String expression, Map<String,String> variables) {
38 // Create an expression
39 JexlExpression e = jexl.createExpression( expression );
40
41 // Create a context and add data
42 final JexlContext jc = new MapContext();
43 jc.set("instance", Collections.unmodifiableMap(variables));
44
45 // Now evaluate the expression, getting the result
46 return e.evaluate(jc);
47 }
48 }