001package com.randomnoun.common.jexl.eval.function;
002
003/* (c) 2013-2018 randomnoun. All Rights Reserved. This work is licensed under a
004 * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
005 */
006
007import java.util.List;
008
009import com.randomnoun.common.jexl.eval.EvalContext;
010import com.randomnoun.common.jexl.eval.EvalException;
011import com.randomnoun.common.jexl.eval.EvalFunction;
012import com.randomnoun.common.jexl.sql.SqlColumn;
013
014/** Defines a startsWith() function.
015 *
016 * Returns true if the first value starts with the second value.
017 *
018 * <p>The result of the function is of type Boolean.
019 */
020public class StartsWithFunction
021    implements EvalFunction
022{
023    /** Implements the function as per the class description. */
024    public Object evaluate(String functionName, EvalContext context, List<Object> arguments)
025        throws EvalException
026    {
027        String arg0;
028        if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
029        if (arguments.get(0) instanceof String) {
030            arg0 = (String) arguments.get(0);
031        } else if (arguments.get(0) instanceof SqlColumn) {
032            arg0 = ((SqlColumn) arguments.get(0)).getName();
033        } else {
034            throw new EvalException(functionName + "() parameter 1 must be a string or SqlColumn type; found " + arguments.get(0).getClass().getName());
035        }
036        if (!(arguments.get(1) instanceof String)) {
037            throw new EvalException(functionName + "() parameter 2 must be a string type; found " + arguments.get(1).getClass().getName());
038        }
039                    
040        String arg1 = (String)arguments.get(1);
041        if (arg0 == null) {
042            throw new EvalException(functionName + "() first parameter cannot be null");
043        }
044        if (arg1 == null) {
045            throw new EvalException(functionName + "() second parameter cannot be null");
046        }
047
048        return Boolean.valueOf(arg0.startsWith(arg1));
049    }
050}