View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2015 Sebastian
3    * Thomschke.
4    *
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    *
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.expression;
14  
15  import java.util.Map;
16  
17  import net.sf.oval.exception.ExpressionEvaluationException;
18  
19  /**
20   * @author Sebastian Thomschke
21   */
22  public abstract class AbstractExpressionLanguage implements ExpressionLanguage
23  {
24  
25  	public boolean evaluateAsBoolean(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
26  	{
27  		final Object result = evaluate(expression, values);
28  		if (result == null) return false;
29  		if (result instanceof Boolean) return (Boolean) result;
30  		if (result instanceof Number) return ((Number) result).doubleValue() != 0.0;
31  		if (result instanceof CharSequence)
32  		{
33  			final CharSequence seq = (CharSequence) result;
34  			if (seq.length() == 0) return false;
35  			if (seq.length() == 1)
36  			{
37  				final char ch = seq.charAt(0);
38  				if (ch == '0') return false;
39  				if (ch == '1') return true;
40  			}
41  			final String str = seq.toString().toLowerCase();
42  			if (str.equals("true")) return true;
43  			if (str.equals("false")) return true;
44  		}
45  		throw new ExpressionEvaluationException("The script [" + expression + "] must return a boolean value but returned [" + result + "]");
46  	}
47  }