package org.yaac.server.egql.evaluator.function;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.yaac.server.egql.evaluator.EvaluationResult;
import org.yaac.server.egql.exception.EGQLException;
import org.yaac.server.egql.processor.ProcessData.ProcessDataRecord;
import org.yaac.shared.ErrorCode;
/**
* @author Max Zhu (thebbsky@gmail.com)
*
*/
public class FormatFunction extends Function {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void validate() throws EGQLException {
FunctionUtil.ensureParamSize(ops, 2);
}
@Override
public EvaluationResult evaluate(ProcessDataRecord record) {
EvaluationResult orig = ops.get(0).evaluate(record);
EvaluationResult format = ops.get(1).evaluate(record);
if (format.getPayload() instanceof String) {
if (orig.getPayload() instanceof Number) {
BigDecimal val = (BigDecimal) orig.getPayload();
String formattedVal =
new DecimalFormat((String) format.getPayload()).format(val);
return new EvaluationResult(formattedVal, orig, format);
} else if (orig.getPayload() instanceof Date) {
Date d = (Date) orig.getPayload();
String formattedDt =
new SimpleDateFormat((String) format.getPayload()).format(d);
return new EvaluationResult(formattedDt, orig, format);
} else {
return orig.withWarning(ErrorCode.W105);
}
} else {
return orig.withWarning(ErrorCode.W106);
}
}
}