com.ibm.tivoli.maximo.expression

Class Expression

  • java.lang.Object
    • com.ibm.tivoli.maximo.expression.Expression


  • public class Expression
    extends java.lang.Object

    EvalEx - Java Expression Evaluator

    Introduction

    EvalEx is a handy expression evaluator for Java, that allows to evaluate simple mathematical and boolean expressions.
    Key Features:
    • Uses BigDecimal for calculation and result
    • Single class implementation, very compact
    • No dependencies to external libraries
    • Precision and rounding mode can be set
    • Supports variables
    • Standard boolean and mathematical operators
    • Standard basic mathematical and boolean functions
    • Custom functions and operators can be added at runtime

    Examples

      BigDecimal result = null;
      
      Expression expression = new Expression("1+1/3");
      result = expression.eval():
      expression.setPrecision(2);
      result = expression.eval():
      
      result = new Expression("(3.4 + -4.1)/2").eval();
      
      result = new Expression("SQRT(a^2 + b^2").with("a","2.4").and("b","9.253").eval();
      
      BigDecimal a = new BigDecimal("2.4");
      BigDecimal b = new BigDecimal("9.235");
      result = new Expression("SQRT(a^2 + b^2").with("a",a).and("b",b).eval();
      
      result = new Expression("2.4/PI").setPrecision(128).setRoundingMode(RoundingMode.UP).eval();
      
      result = new Expression("random() > 0.5").eval();
     
      result = new Expression("not(x<7 || sqrt(max(x,9)) <= 3))").with("x","22.9").eval();
     

    Supported Operators

    Mathematical Operators
    OperatorDescription
    +Additive operator
    -Subtraction operator
    *Multiplication operator
    /Division operator
    %Remainder operator (Modulo)
    ^Power operator

    Boolean Operators*
    OperatorDescription
    =Equals
    ==Equals
    !=Not equals
    <>Not equals
    <Less than
    <=Less than or equal to
    >Greater than
    >=Greater than or equal to
    &&Boolean and
    ||Boolean or
    *Boolean operators result always in a BigDecimal value of 1 or 0 (zero). Any non-zero value is treated as a _true_ value. Boolean _not_ is implemented by a function.

    Supported Functions

    Function*Description
    NOT(expression)Boolean negation, 1 (means true) if the expression is not zero
    IF(condition,value_if_true,value_if_false)Returns one value if the condition evaluates to true or the other if it evaluates to false
    RANDOM()Produces a random number between 0 and 1
    MIN(e1,e2)Returns the smaller of both expressions
    MAX(e1,e2)Returns the bigger of both expressions
    ABS(expression)Returns the absolute (non-negative) value of the expression
    ROUND(expression,precision)Rounds a value to a certain number of digits, uses the current rounding mode
    FLOOR(expression)Rounds the value down to the nearest integer
    CEILING(expression)Rounds the value up to the nearest integer
    LOG(expression)Returns the natural logarithm (base e) of an expression
    LOG10(expression)Returns the common logarithm (base 10) of an expression
    SQRT(expression)Returns the square root of an expression
    SIN(expression)Returns the trigonometric sine of an angle (in degrees)
    COS(expression)Returns the trigonometric cosine of an angle (in degrees)
    TAN(expression)Returns the trigonometric tangens of an angle (in degrees)
    ASIN(expression)Returns the angle of asin (in degrees)
    ACOS(expression)Returns the angle of acos (in degrees)
    ATAN(expression)Returns the angle of atan (in degrees)
    SINH(expression)Returns the hyperbolic sine of a value
    COSH(expression)Returns the hyperbolic cosine of a value
    TANH(expression)Returns the hyperbolic tangens of a value
    RAD(expression)Converts an angle measured in degrees to an approximately equivalent angle measured in radians
    DEG(expression)Converts an angle measured in radians to an approximately equivalent angle measured in degrees
    *Functions names are case insensitive.

    Supported Constants

    ConstantDescription
    PIThe value of PI, exact to 100 digits
    TRUEThe value one
    FALSEThe value zero

    Add Custom Operators

    Custom operators can be added easily, simply create an instance of `Expression.Operator` and add it to the expression. Parameters are the operator string, its precedence and if it is left associative. The operators `eval()` method will be called with the BigDecimal values of the operands. All existing operators can also be overridden.
    For example, add an operator `x >> n`, that moves the decimal point of _x_ _n_ digits to the right:
     Expression e = new Expression("2.1234 >> 2");
     
     e.addOperator(e.new Operator(">>", 30, true) {
          @Override
         public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
             return v1.movePointRight(v2.toBigInteger().intValue());
         }
     });
     
     e.eval(); // returns 212.34
     

    Add Custom Functions

    Adding custom functions is as easy as adding custom operators. Create an instance of `Expression.Function`and add it to the expression. Parameters are the function name and the count of required parameters. The functions `eval()` method will be called with a list of the BigDecimal parameters. All existing functions can also be overridden.
    For example, add a function `average(a,b,c)`, that will calculate the average value of a, b and c:
     Expression e = new Expression("2 * average(12,4,8)");
     
     e.addFunction(e.new Function("average", 3) {
          @Override
         public BigDecimal eval(List parameters) {
             BigDecimal sum = parameters.get(0).add(parameters.get(1)).add(parameters.get(2));
             return sum.divide(new BigDecimal(3));
         }
     });
     
     e.eval(); // returns 16
     
    The software is licensed under the MIT Open Source license (see LICENSE file).
    • The *power of* operator (^) implementation was copied from [Stack Overflow](http://stackoverflow.com/questions/3579779/how-to-do-a-fractional-power-on-bigdecimal-in-java) Thanks to Gene Marin
    • The SQRT() function implementation was taken from the book [The Java Programmers Guide To numerical Computing](http://www.amazon.de/Java-Number-Cruncher-Programmers-Numerical/dp/0130460419) (Ronald Mak, 2002)
    • Field Detail

      • PI

        public static final java.math.BigDecimal PI
        Definition of PI as a constant, can be used in expressions as variable.
      • EXPLOGGER

        public static final MXLogger EXPLOGGER
    • Constructor Detail

      • Expression

        public Expression(java.lang.String expression,
                          ExpressionContext context)
        Creates a new expression instance from an expression string.
        Parameters:
        expression - The expression. E.g. "2.4*sin(3)/(2-4)" or "sin(y)>0 & max(z, 3)>3"
    • Method Detail

      • setLineNum

        public void setLineNum(int lineNum)
      • getLineNum

        public java.lang.Integer getLineNum()
      • isMBRMode

        public boolean isMBRMode()
      • setScriptContext

        public void setScriptContext(java.util.Map context)
      • getScriptContext

        public java.util.Map getScriptContext()
      • setGlobalVar

        public void setGlobalVar(java.lang.String varName,
                                 java.lang.Object value)
      • getGlobalVar

        public java.lang.Object getGlobalVar(java.lang.String varName)
      • hasGlobalVar

        public boolean hasGlobalVar(java.lang.String varName)
      • setLocalVar

        public void setLocalVar(java.lang.String varName,
                                java.lang.Object value)
      • getLocalVar

        public java.lang.Object getLocalVar(java.lang.String varName)
      • hasLocalVar

        public boolean hasLocalVar(java.lang.String varName)
      • resolveVar

        public java.lang.Object resolveVar(java.lang.String varName)
      • findAttributesInExpression

        public java.util.Set findAttributesInExpression()
      • validateAttributesInExpression

        public void validateAttributesInExpression()
      • validateEval

        public java.math.BigDecimal validateEval()
                                          throws MXException
        Evaluates the expression.
        Returns:
        The result of the expression.
        Throws:
        MXException
      • setPrecision

        public Expression setPrecision(int precision)
        Sets the precision for expression evaluation.
        Parameters:
        precision - The new precision.
        Returns:
        The expression, allows to chain methods.
      • setRoundingMode

        public Expression setRoundingMode(java.math.RoundingMode roundingMode)
        Sets the rounding mode for expression evaluation.
        Parameters:
        roundingMode - The new rounding mode.
        Returns:
        The expression, allows to chain methods.
      • getMathContext

        public java.math.MathContext getMathContext()
      • addOperator

        public Expression.Operator addOperator(Expression.Operator operator)
        Adds an operator to the list of supported operators.
        Parameters:
        operator - The operator to add.
        Returns:
        The previous operator with that name, or null if there was none.
      • addFunction

        public Function addFunction(Function function)
        Adds a function to the list of supported functions
        Parameters:
        function - The function to add.
        Returns:
        The previous operator with that name, or null if there was none.
      • addLazyFunction

        public LazyFunction addLazyFunction(LazyFunction function)
        Adds a lazy function function to the list of supported functions
        Parameters:
        function - The function to add.
        Returns:
        The previous operator with that name, or null if there was none.
      • setVariable

        public Expression setVariable(java.lang.String variable,
                                      java.math.BigDecimal value)
        Sets a variable value.
        Parameters:
        variable - The variable name.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • setVariable

        public Expression setVariable(java.lang.String variable,
                                      java.lang.String value)
        Sets a variable value.
        Parameters:
        variable - The variable to set.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • with

        public Expression with(java.lang.String variable,
                               java.math.BigDecimal value)
        Sets a variable value.
        Parameters:
        variable - The variable to set.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • and

        public Expression and(java.lang.String variable,
                              java.lang.String value)
        Sets a variable value.
        Parameters:
        variable - The variable to set.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • and

        public Expression and(java.lang.String variable,
                              java.math.BigDecimal value)
        Sets a variable value.
        Parameters:
        variable - The variable to set.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • with

        public Expression with(java.lang.String variable,
                               java.lang.String value)
        Sets a variable value.
        Parameters:
        variable - The variable to set.
        value - The variable value.
        Returns:
        The expression, allows to chain methods.
      • getExpressionTokenizer

        public java.util.Iterator getExpressionTokenizer()
        Get an iterator for this expression, allows iterating over an expression token by token.
        Returns:
        A new iterator instance for this expression.
      • toRPN

        public java.lang.String toRPN()
                               throws MXException
        Get a string representation of the RPN (Reverse Polish Notation) for this expression.
        Returns:
        A string with the RPN representation for this expression.
        Throws:
        MXException
      • getCalculatedValue

        public java.util.Map getCalculatedValue()
      • getExpValue

        public java.util.Map getExpValue()
      • getCalculatedValue

        public java.lang.Object getCalculatedValue(java.lang.Object key)
      • cacheValue

        public void cacheValue(java.lang.String key,
                               java.lang.Double value)
      • getCachedValue

        public java.lang.Double getCachedValue(java.lang.String key)
      • hasCachedValue

        public boolean hasCachedValue(java.lang.String key)
      • setAttrFormulaAttrName

        public void setAttrFormulaAttrName(java.lang.String attrName)
      • getAttrFormulaAttrName

        public java.lang.String getAttrFormulaAttrName()
      • setObjectFormulaInfo

        public void setObjectFormulaInfo(ObjectFormulaInfo objectFormulaInfo)
      • setExpValue

        public void setExpValue(java.lang.String key,
                                java.lang.Double value)
      • getExpValueMap

        public java.util.Map getExpValueMap()
      • getMetaData

        public java.lang.Object getMetaData(java.lang.String key)
      • getMetaDataMap

        public java.util.Map getMetaDataMap()
      • setMetaData

        public void setMetaData(java.lang.String key,
                                java.lang.Object value)
      • getErrorDataMap

        public java.util.Map getErrorDataMap()
      • setErrorData

        public void setErrorData(java.lang.String key,
                                 java.lang.Exception value)
      • isVar

        public boolean isVar(java.lang.String key)
      • shouldEval

        public boolean shouldEval()