1 16 package org.outerj.daisy.query.model.functions; 17 18 import org.outerj.daisy.query.model.AbstractFunction; 19 import org.outerj.daisy.query.model.QValueType; 20 import org.outerj.daisy.query.model.SqlGenerationContext; 21 import org.outerj.daisy.query.QueryContext; 22 import org.outerj.daisy.repository.query.QueryException; 23 import org.outerj.daisy.repository.query.EvaluationContext; 24 import org.outerj.daisy.repository.Document; 25 import org.outerj.daisy.repository.Version; 26 27 import java.util.Locale ; 28 import java.math.BigDecimal ; 29 30 public abstract class AbstractUnaryMathFunction extends AbstractFunction { 31 public void prepare(QueryContext context) throws QueryException { 32 super.prepare(context); 33 if (params.size() != 1) 34 throw new QueryException("\"" + getFunctionName() + "\" requires exactly one parameter."); 35 36 if (!AbstractBinaryMathFunction.isNumeric(getParam(0))) 37 throw new QueryException("\"" + getFunctionName() + "\" can only be performed on numeric expressions, which this is not: " + getParam(0).getExpression()); 38 } 39 40 public Object evaluate(QValueType valueType, EvaluationContext evaluationContext) throws QueryException { 41 BigDecimal value = AbstractBinaryMathFunction.toBigDecimal(getParam(0).evaluate(QValueType.DECIMAL, evaluationContext)); 42 return evaluate(value); 43 } 44 45 public Object evaluate(QValueType valueType, Document document, Version version, EvaluationContext evaluationContext) throws QueryException { 46 BigDecimal value = AbstractBinaryMathFunction.toBigDecimal(getParam(0).evaluate(QValueType.DECIMAL, document, version, evaluationContext)); 47 return evaluate(value); 48 } 49 50 private Object evaluate(BigDecimal value) { 51 return value == null ? null : performCalculation(value); 52 } 53 54 protected abstract Object performCalculation(BigDecimal value); 55 protected abstract String [] getSqlFunction(SqlGenerationContext context); 56 57 public void generateSqlValueExpr(StringBuffer sql, SqlGenerationContext context) throws QueryException { 58 String [] sqlFunction = getSqlFunction(context); 59 sql.append(' ').append(sqlFunction[0]); 60 super.generateSqlValueExpr(sql, context); 61 sql.append(sqlFunction[1]).append(' '); 62 } 63 64 public QValueType getValueType() { 65 return QValueType.DECIMAL; 66 } 67 68 public String getTitle(Locale locale) { 69 return getExpression(); 70 } 71 72 public QValueType getOutputValueType() { 73 return QValueType.DECIMAL; 74 } 75 76 public Object getOutputValue(Document document, Version version, EvaluationContext evaluationContext) throws QueryException { 77 return evaluate(null, document, version, evaluationContext); 78 } 79 } 80 | Popular Tags |