View Javadoc
1   package net.avcompris.commons3.api.tests;
2   
3   import static org.apache.commons.lang3.StringUtils.substringBeforeLast;
4   
5   import com.google.common.collect.ImmutableMap;
6   
7   public abstract class ExpressionUtils {
8   
9   	public static String compute(final String expression) {
10  
11  		return compute(expression, ImmutableMap.of());
12  	}
13  
14  	public static String compute(final String expression, final ImmutableMap<String, String> variables) {
15  
16  		try {
17  
18  			return Integer.toString(Integer.parseInt(expression));
19  
20  		} catch (final NumberFormatException e) {
21  
22  			// do nothing
23  		}
24  
25  		if (variables.containsKey(expression)) {
26  
27  			return variables.get(expression);
28  
29  		} else if (expression.startsWith("$") && variables.containsKey(expression.substring(1))) {
30  
31  			return variables.get(expression.substring(1));
32  		}
33  
34  		if (expression.endsWith(" + 1")) {
35  
36  			final String left = substringBeforeLast(expression, " + 1").trim();
37  
38  			if (variables.containsKey(left)) {
39  
40  				return Integer.toString(Integer.parseInt(variables.get(left)) + 1);
41  
42  			} else if (left.startsWith("$") && variables.containsKey(left.substring(1))) {
43  
44  				return Integer.toString(Integer.parseInt(variables.get(left.substring(1))) + 1);
45  			}
46  		}
47  
48  		return expression;
49  
50  		// throw new NotImplementedException("expression: " + expression);
51  	}
52  }