Class Evaluator


  • public class Evaluator
    extends java.lang.Object
    This class is used to evaluate mathematical, string, Boolean and functional expressions. It is the main entry point into the JEval API.

    The following types of expressions are supported:
    • mathematical Expression involving numbers. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place.
    • string String can also be added together, compared, etc...
    • Boolean Expression that evaluate to true (1.0) and false (0.0).
    • functional Custom functions can be created or there are many Math and String functions that JEval supplies with this class.
    The following operators are supported:
    • ( open parentheses
    • ) closed parentheses
    • + addition (for numbers and strings)
    • - subtraction
    • * multiplication
    • / division
    • % modulus
    • + unary plus
    • - unary minus
    • = equal (for numbers and strings)
    • != not equal (for numbers and strings)
    • < less than (for numbers and strings)
    • <= less than or equal (for numbers and strings)
    • > greater than (for numbers and strings)
    • >= greater than or equal (for numbers and strings)
    • && boolean and
    • || boolean or
    • ! boolean not
    Allows for prebuilt and custom functions.
    • JEval already comes with many functions which represent most of the methods in the Math and String classes in the standard JDK.
    • Thirty-nine math and string functions come built in. See the net.sourceforge.jeval.functions.math and net.sourceforge.jeval.functions.string packages for details on these ready to use functions. You can choose to not load these functions if we you want to gain a small improvement in performance.
    • Functions must be followed by an open parentheses and a closed parentheses which contain any required parameters.
    • For more details on functions, see the Function class and the test classes.
    Allows for variables.
    • Variable must be enclosed by a pound sign and open brace #{ and a closed brace }. i.e. expression = "#{a} + #{b}"
    • Two math variables come built in. The E and PI variables represent the same value as the Math.E and Math.PI constants in the standard Java SDK. You can choose not to load these variables.
    Notes on expression parsing:
    • Spaces are ignored when parsing expressions.
    • The order of precedence used by this class is as follows from highest to lowest.
    • The expression is evaluated as one or more subexpressions. Subexpressions within open parentheses and closed parentheses are evaluated before other parts of the expression.
    • Inner most subexpression are evaluated first working outward.
    • Subexpressions at the same level are evaluated from left to right.
    • When evaluating expressions and subexpressions, operators are evaluated with the following precedence listed below.
    • Operators with with the same precedence are evaluated from left to right.
    • Once the expression is parsed, Variables are replaced with their values. The evaluator has its own internal variable map that it used to resolve variable values. All of the variable related methods on the evaluator refer to this internal map. You can choose to set you own variable resolver on your evaluator instance. If you do this, then variables resolved by your resolver will override any variables in the evaluator's internal variable map.
    • Functions are then executed and replaced with their results. Function arguments are each individually evaluated as subexpressions that are comma separated. This gives you the ability to use nested functions in your expressions. You can choose not to evaluate function arguments as expressions and instead let the functions handle the arguments themselves. This in effect turns off nested expressions, unless you code nested expression support into your own custom functions.
    • Once all variables and functions are resolved, then the parsed expression and subexpressions are evaluated according to operator precedence.
    Operator precedence:
    • + unary plus, - unary minus, ! boolean not
    • * multiplication, / division, % modulus
    • + addition, - subtraction
    • < less than, <= less than or equal, > greater than, >= greater than or equal
    • = equal, != not equal
    • && boolean and
    • || boolean or
    Function and variable names may not break any of the following rules:
    • cannot start with a number
    • cannot contain an operator (see the above list of operators)
    • cannot contain a quote character - single or double
    • cannot contain a brace character - open or closed
    • cannot contain one of the following special characters: #, ~ , ^ !
    Other Notes:
    • This class is not thread safe.
    • Allows for the quote character (single or double) to be specified at run time. Quote characters are required for specifying string values.
    • Expressions can contain different types of expressions within the same expression. However, Numeric and string types cannot be mixed in a left / right operand pair.
    • An expression can be parsed before being evaluated by calling the parse() method. This may save on response time if parsing takes more than a few seconds. However, parsing is usually very fast, so this is probably not needed.
    • If an expression does not change, it will not be parsed each time the expression is evaluated. Therefore, variables values can change and the expression can be evaluated again without having to re-parse the expression.
    • Nested functions calls are supported. Nested function support can be turned off to improve performance. Custom functions can be coded to handle nested calls instead if desired.
    • The string used to start variables, "#{", cannot appear in an expression.
    • See the evaluate methods in this class, JUnit tests and samples for more details.
    • Constructor Summary

      Constructors 
      Constructor Description
      Evaluator()
      The default constructor.
      Evaluator​(char quoteCharacter, boolean loadMathVariables, boolean loadMathFunctions, boolean loadStringFunctions, boolean processNestedFunctions)
      The main constructor for Evaluator.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void clearFunctions()
      Removes all of the functions at one time.
      void clearVariables()
      Removes all of the variables at one time.
      java.lang.String evaluate()
      This method evaluates mathematical, boolean or functional expressions.
      java.lang.String evaluate​(boolean keepQuotes, boolean wrapStringFunctionResults)
      This method evaluates mathematical, boolean or functional expressions.
      java.lang.String evaluate​(java.lang.String expression)
      This method evaluates mathematical, boolean or functional expressions.
      java.lang.String evaluate​(java.lang.String expression, boolean keepQuotes, boolean wrapStringFunctionResults)
      This method evaluates mathematical, boolean or functional expressions.
      boolean getBooleanResult​(java.lang.String expression)
      This method is a simple wrapper around the evaluate(String) method.
      Function getFunction​(java.lang.String functionName)
      Returns a funtion from the list of functions.
      java.util.Map<java.lang.String,​Function> getFunctions()
      Rturns the map of functions currently set on this object.
      boolean getLoadMathFunctions()
      Returns the value used during construction of this object to specify if math functions should be loaded.
      boolean getLoadStringFunctions()
      Returns the value used during construction of this object to specify if string functions should be loaded.
      double getNumberResult​(java.lang.String expression)
      This method is a simple wrapper around the evaluate(String) method.
      boolean getProcessNestedFunctions()
      Returns the value used during construction of this object to specify if nested functions should be processed.
      char getQuoteCharacter()
      Returns the current quote character in use.
      VariableResolver getVariableResolver()
      Returns the variable resolver.
      java.util.Map<java.lang.String,​java.lang.String> getVariables()
      Rturns the map of variables currently set on this object.
      java.lang.String getVariableValue​(java.lang.String variableName)
      Returns the value for a variable in the list of variables.
      protected boolean isExpressionString​(java.lang.String expressionString)
      Determines if given text represents a valid string expression or not.
      boolean isLoadMathVariables()
      Returns the value used during construction of this object to specify if math variables should be loaded.
      void isValidName​(java.lang.String name)
      This method verifies if a function or variable name is valid or not.
      void parse​(java.lang.String expression)
      This method parses a mathematical, boolean or functional expressions.
      protected java.lang.String processNestedFunctions​(java.lang.String arguments)
      This method process nested function calls that may be in the arguments passed into a higher level function.
      void putFunction​(Function function)
      Adds a function to the list of functions to use when evaluating expressions.
      void putVariable​(java.lang.String variableName, java.lang.String variableValue)
      Adds or replaces a variable to the list of variables to use when evaluating expressions.
      void removeFunction​(java.lang.String functionName)
      Removes the function from the list of functions to use when evaluating expressions.
      void removeVaraible​(java.lang.String variableName)
      Removes the variable from the list of variables to use when evaluating expressions.
      java.lang.String replaceVariables​(java.lang.String expression)
      Replaces the variables in the expression with the values of the variables for this instance of the evaluator.
      void setFunctions​(java.util.Map<java.lang.String,​Function> functions)
      Sets the map of functions for this object.
      void setQuoteCharacter​(char quoteCharacter)
      Sets the quote character to use when evaluating expressions.
      void setVariableResolver​(VariableResolver variableResolver)
      Sets the variable resolver for this class.
      void setVariables​(java.util.Map<java.lang.String,​java.lang.String> variables)
      Sets the map of variables for this object.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • Evaluator

        public Evaluator()
        The default constructor. This constructor calls the five parameter Evaluator constructor and passes in the following default values: SINGLE_QUOTE, true, true, true and true.
      • Evaluator

        public Evaluator​(char quoteCharacter,
                         boolean loadMathVariables,
                         boolean loadMathFunctions,
                         boolean loadStringFunctions,
                         boolean processNestedFunctions)
        The main constructor for Evaluator.
        Parameters:
        quoteCharacter - The quote character to use when evaluating expression.
        loadMathVariables - Indicates if the standard Math variables should be loaded or not.
        loadMathFunctions - Indicates if the standard Math functions should be loaded or not.
        loadStringFunctions - Indicates if the standard String functions should be loaded or not.
        processNestedFunctions - Indicates if nested function calls should be processed or not.
        Throws:
        java.lang.IllegalArgumentException - when the quote character is not a valid quote character
    • Method Detail

      • getQuoteCharacter

        public char getQuoteCharacter()
        Returns the current quote character in use.
        Returns:
        The quote character in use.
      • setQuoteCharacter

        public void setQuoteCharacter​(char quoteCharacter)
        Sets the quote character to use when evaluating expressions.
        Parameters:
        quoteCharacter - The quote character to use when evaluating expressions.
        Throws:
        java.lang.IllegalArgumentException - when the quote character is not a valid quote character
      • putFunction

        public void putFunction​(Function function)
        Adds a function to the list of functions to use when evaluating expressions.
        Parameters:
        function - The function being added.
        Throws:
        java.lang.IllegalArgumentException - when the function name is not valid or the function name is already in use
      • getFunction

        public Function getFunction​(java.lang.String functionName)
        Returns a funtion from the list of functions. If the function is not found in the list of functions, then null will be returned.
        Parameters:
        functionName - The name of the function to retrieve the value for.
        Returns:
        The value for a function in the list of function.
      • removeFunction

        public void removeFunction​(java.lang.String functionName)
        Removes the function from the list of functions to use when evaluating expressions.
        Parameters:
        functionName - The name of the function to remove.
      • clearFunctions

        public void clearFunctions()
        Removes all of the functions at one time.
      • getFunctions

        public java.util.Map<java.lang.String,​Function> getFunctions()
        Rturns the map of functions currently set on this object.
        Returns:
        the map of functions currently set on this object.
      • setFunctions

        public void setFunctions​(java.util.Map<java.lang.String,​Function> functions)
        Sets the map of functions for this object.
        Parameters:
        functions - The map of functions for this object.
      • putVariable

        public void putVariable​(java.lang.String variableName,
                                java.lang.String variableValue)
        Adds or replaces a variable to the list of variables to use when evaluating expressions. If the variable already exists, then its value will be overlaid.
        Parameters:
        variableName - The name of the variable being set.
        variableValue - The value for the variable being set.
      • getVariableValue

        public java.lang.String getVariableValue​(java.lang.String variableName)
                                          throws EvaluationException
        Returns the value for a variable in the list of variables. If the variable cannot be found in the list of variables, then null will be returned.
        Parameters:
        variableName - The name of the variable to retrieve the value for.
        Returns:
        The value for a variable in the list of variables.
        Throws:
        EvaluationException - if the variable name cannot be resolved
      • removeVaraible

        public void removeVaraible​(java.lang.String variableName)
        Removes the variable from the list of variables to use when evaluating expressions.
        Parameters:
        variableName - The name of the variable to remove.
      • clearVariables

        public void clearVariables()
        Removes all of the variables at one time.
      • getVariables

        public java.util.Map<java.lang.String,​java.lang.String> getVariables()
        Rturns the map of variables currently set on this object.
        Returns:
        the map of variables currently set on this object.
      • setVariables

        public void setVariables​(java.util.Map<java.lang.String,​java.lang.String> variables)
        Sets the map of variables for this object.
        Parameters:
        variables - The map of variables for this object.
      • getVariableResolver

        public VariableResolver getVariableResolver()
        Returns the variable resolver. The variable resolver can be used by the user to resolve their own variables. Variables in the variable resolver override any variables that are in this classes internal variable map.
        Returns:
        The variable resolver.
      • setVariableResolver

        public void setVariableResolver​(VariableResolver variableResolver)
        Sets the variable resolver for this class. Varaibles resolved by the variable resolver will override any variables in this class's internal variable map.
        Parameters:
        variableResolver - The variable resolver for this class.
      • evaluate

        public java.lang.String evaluate​(java.lang.String expression)
                                  throws EvaluationException
        This method evaluates mathematical, boolean or functional expressions. See the class description and test classes for more information on how to write an expression. If quotes exist around a string expression, then they will be left in the result string. Function will also have their results wrapped with the appripriate quote characters.
        Parameters:
        expression - The expression to evaluate.
        Returns:
        The result of the evaluated. expression. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place.
        Throws:
        EvaluationException - when an error is found while evaluating the expression
      • evaluate

        public java.lang.String evaluate()
                                  throws EvaluationException
        This method evaluates mathematical, boolean or functional expressions. See the class description and test classes for more information on how to write an expression. The expression used will be the one previously specified when using the parse method. If the parse method has not been called before calling this method, then an exception will be thrown. If quotes exist around a string expression, then they will be left in the result string. Function will also have their results wrapped with the appropriate quote characters.
        Returns:
        The result of the evaluated. expression. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place.
        Throws:
        EvaluationException - when an error is found while evaluating the expression
      • evaluate

        public java.lang.String evaluate​(java.lang.String expression,
                                         boolean keepQuotes,
                                         boolean wrapStringFunctionResults)
                                  throws EvaluationException
        This method evaluates mathematical, boolean or functional expressions. See the class description and test classes for more information on how to write an expression.
        Parameters:
        expression - The expression to evaluate.
        keepQuotes - Indicates if the the quotes should be kept in the result or not. This is only for string expression that are enclosed in quotes prior to being evaluated.
        wrapStringFunctionResults - Indicates if the results from functions that return strings should be wrapped in quotes. The quote character used will be whatever is the current quote character for this object.
        Returns:
        The result of the evaluated expression. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place.
        Throws:
        EvaluationException - when an error is found while evaluating the expression
      • evaluate

        public java.lang.String evaluate​(boolean keepQuotes,
                                         boolean wrapStringFunctionResults)
                                  throws EvaluationException
        This method evaluates mathematical, boolean or functional expressions. The expression used will be the one previously specified when using the parse method. If the parse method has not been called before calling this method, then an exception will be thrown. See the class description and test classes for more information on how to write an expression.
        Parameters:
        keepQuotes - Indicates if the the quotes should be kept in the result or not. This is only for string expressions that are enclosed in quotes prior to being evaluated.
        wrapStringFunctionResults - Indicates if the results from functions that return strings should be wrapped in quotes. The quote character used will be whatever is the current quote character for this object.
        Returns:
        The result of the evaluated expression. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place.
        Throws:
        EvaluationException - when an error is found while evaluating the expression
      • getBooleanResult

        public boolean getBooleanResult​(java.lang.String expression)
                                 throws EvaluationException
        This method is a simple wrapper around the evaluate(String) method. Its purpose is to return a more friendly boolean return value instead of the string "1.0" (for true) and "0.0" (for false) that is normally returned.
        Parameters:
        expression - The expression to evaluate.
        Returns:
        A boolean value that represents the result of the evaluated expression.
        Throws:
        EvaluationException - when an error is found while evaluating the expression; also thrown if the result cannot be converted to a boolean value
      • getNumberResult

        public double getNumberResult​(java.lang.String expression)
                               throws EvaluationException
        This method is a simple wrapper around the evaluate(String) method. Its purpose is to return a more friendly double return value instead of the string number that is normally returned.
        Parameters:
        expression - The expression to evaluate.
        Returns:
        A double value that represents the result of the evaluated expression.
        Throws:
        EvaluationException - when an error is found while evaluating the expression; also thrown if the result cannot be converted to a boolean value
      • parse

        public void parse​(java.lang.String expression)
                   throws EvaluationException
        This method parses a mathematical, boolean or functional expressions. When the expression is eventually evaluated, as long as the expression has not changed, it will not have to be reparsed. See the class description and test classes for more information on how to write an expression.
        Parameters:
        expression - The expression to evaluate.
        Throws:
        EvaluationException - when an error is found while evaluating the expression
      • isExpressionString

        protected boolean isExpressionString​(java.lang.String expressionString)
                                      throws EvaluationException
        Determines if given text represents a valid string expression or not. Valid string expression must start and end with a quote character as defined by the current evaluation context.
        Parameters:
        expressionString - The string being evaluated.
        Returns:
        True if the string is a valid string and false if not.
        Throws:
        EvaluationException - on incorrect syntax of string expression
      • isValidName

        public void isValidName​(java.lang.String name)
                         throws java.lang.IllegalArgumentException
        This method verifies if a function or variable name is valid or not. Function and variable names must follow these rules...
        • must not start with a number
        • must not contain an operator (see the above list of operators)
        • must not contain a quote character - single or double
        • must not contain a brace character - open or closed
        • must not contain one of the following special characters: #, ~ , ^ !
        Parameters:
        name - The function or variable name being validated.
        Throws:
        java.lang.IllegalArgumentException - if the name is invalid
      • replaceVariables

        public java.lang.String replaceVariables​(java.lang.String expression)
                                          throws EvaluationException
        Replaces the variables in the expression with the values of the variables for this instance of the evaluator.
        Parameters:
        expression - The expression being processed.
        Returns:
        A new expression with the variables replaced with their values.
        Throws:
        EvaluationException - is an error is encountered while processing the expression
      • processNestedFunctions

        protected java.lang.String processNestedFunctions​(java.lang.String arguments)
                                                   throws EvaluationException
        This method process nested function calls that may be in the arguments passed into a higher level function.
        Parameters:
        arguments - The arguments to process.
        Returns:
        The arguments with any nested function calls evaluated.
        Throws:
        EvaluationException - thrown if an error occurs
      • isLoadMathVariables

        public boolean isLoadMathVariables()
        Returns the value used during construction of this object to specify if math variables should be loaded.
        Returns:
        the loadMathVariables
      • getLoadMathFunctions

        public boolean getLoadMathFunctions()
        Returns the value used during construction of this object to specify if math functions should be loaded.
        Returns:
        the loadMathFunctions
      • getLoadStringFunctions

        public boolean getLoadStringFunctions()
        Returns the value used during construction of this object to specify if string functions should be loaded.
        Returns:
        the loadStringFunctions
      • getProcessNestedFunctions

        public boolean getProcessNestedFunctions()
        Returns the value used during construction of this object to specify if nested functions should be processed.
        Returns:
        the processNestedFunctions