ExpressionVariable.java
package org.microspace.evaluator;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import org.microspace.exception.IllegalOperationException;
/**
* A literal expression.
*
* @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
* @version 2017-10-16
*/
public class ExpressionVariable implements Expression {
private static final long serialVersionUID = 7007978235090311381L;
final String name;
String alias;
BigDecimal value;
boolean needsBracket;
public ExpressionVariable (String name) {
this.name = name;
this.alias = name;
}
@Override
public void setVariable(String variable, BigDecimal value, String alias) {
if (variable.equals(name)) {
this.value = value;
if (alias == null) {
this.alias = name;
} else {
this.alias = alias;
}
}
}
@Override
public void clear () {
this.alias = name;
this.value = null;
}
@Override
public BigDecimal calculate(int scale) {
if (value == null) {
throw new IllegalOperationException ("variable " + name + " is not set.");
}
return value;
}
@Override
public String format(EvaluatorFormat format, int scale, int accuracy) {
String lparen = needsBracket ? "( " : "";
String rparen = needsBracket ? " )" : "";
switch (format) {
case ID:
return lparen + alias + rparen;
case ID_AND_VALUE:
{
if (value == null) {
throw new IllegalOperationException ("variable " + name + " is not set.");
}
BigDecimal ret = value.round(new MathContext(accuracy, RoundingMode.HALF_UP));
return lparen + alias + "(" + ret.toString() + ")" + rparen;
}
case VALUE:
{
if (value == null) {
throw new IllegalOperationException ("variable " + name + " is not set.");
}
BigDecimal ret = value.round(new MathContext(accuracy, RoundingMode.HALF_UP));
return lparen + ret.toString() + rparen;
}
case ID_AND_VALUE_IF_SET:
{
if (value == null) {
return lparen + alias + rparen;
}
BigDecimal ret = value.round(new MathContext(accuracy, RoundingMode.HALF_UP));
return lparen + alias + "(" + ret.toString() + ")" + rparen;
}
default:
}
return "";
}
@Override
public void setNeedsBracket(boolean needsBracket) {
this.needsBracket = needsBracket;
}
}