1 package com.calipso.reportgenerator.reportcalculator.arithmetic; 2 3 import java.util.Map ; 4 import java.util.Collection ; 5 import java.io.Serializable ; 6 7 10 11 public abstract class ArithmeticExpression implements Serializable { 12 13 19 public static ArithmeticExpression newFrom(String expression) { 20 String exp = prepareExpression(expression); 21 Object [] tokens = getTokens(exp); 22 if (tokens.length == 1) { 23 return ValueArithmeticExp.newValueExpFrom(prepareExpression(tokens[0].toString())); 24 } else { 25 ArithmeticExpression subExp1 = ArithmeticExpression.newFrom(tokens[0].toString()); 26 ArithmeticExpression subExp2 = ArithmeticExpression.newFrom(tokens[2].toString()); 27 return OperationArithmeticExp.newOperationFrom(subExp1, tokens[1].toString(), subExp2); 28 } 29 } 30 31 36 private static String prepareExpression(String expression) { 37 String exp = expression.trim(); 38 if (exp.charAt(0) == '(' && exp.charAt(exp.length() - 1) == ')') { 39 if(!(exp.indexOf(")") < exp.indexOf("(", 1))){ 40 return exp.substring(1, exp.length() - 1); 41 } 42 } 43 return exp; 44 } 45 46 51 private static int indexOfOperator(String expression) { 52 int index = -1; 53 int alternateIndex = -1; 54 int parenthesis = 0; 55 for (int i = 0; i < expression.length(); i++) { 56 char current = expression.charAt(i); 57 if (current == '(') { 58 parenthesis++; 59 } else { 60 if (current == ')') { 61 parenthesis--; 62 } else { 63 if ((parenthesis == 0)) { 64 if (current == '+' || current == '-') { 65 index = i; 66 break; 67 } else { 68 if (current == '*' || current == '/') { 69 alternateIndex = i; 70 } 71 } 72 } 73 } 74 } 75 } 76 if (index == -1) { 77 index = alternateIndex; 78 } 79 return index; 80 } 81 82 90 private static Object [] getTokens(String expression) { 91 int index = indexOfOperator(expression); 92 if (index == -1) { 93 return new Object []{expression}; 94 } else { 95 Object [] array = new Object [3]; 96 array[0] = expression.substring(0, index); 97 array[1] = expression.substring(index, index +1); 98 array[2] = expression.substring(index + 1); 99 return array; 100 } 101 } 102 103 public abstract float value(Map context); 104 105 public void getVariables(Collection variables) { 106 } 108 } | Popular Tags |