/* Copyright (C) 2014-2015 A.Vontobel
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The license is in LICENCE-GPL.txt.
* If not, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
*/
package net.sf.drawj2d.cmd;
import org.hecl.*;
import java.math.BigDecimal;
import java.math.MathContext;
import com.udojava.evalex.Expression;
/**
* AssertCmd implements the "assert" command, which verifies that
* an assertion is fulfilled. Actually a mathematical expression is evaluated. If it returns
* not 1 (== true), an exception is raised.
* assert "$h > 200" InputCheck
*/
public class AssertCmd implements Command {
boolean debug = false;
public AssertCmd () {
}
@Override
public Thing cmdCode(Interp interp, Thing[] argv) throws HeclException {
assert argv.length > 0;
if (debug) System.out.println(argv[0].toString());
String msg = "";
String expression;
switch (argv.length - 1) {
case 2:
msg = StringThing.get(argv[2]);
case 1:
expression = StringThing.get(argv[1]);
break;
default:
throw new HeclException ("Illegal nb of arguments.");
}
// Calculate the mathematical value of the expression
Expression expr = new Expression(expression, MathContext.DECIMAL64);
// The expression is true if the result is 1.0
BigDecimal result = expr.eval();
// The comparision returns 0 in case of equality
boolean assertioniscorrect;
assertioniscorrect = result.compareTo(new BigDecimal(1)) == 0;
if (assertioniscorrect) {
// do nothing
if (debug) System.out.println("Correct assertion: " + expression);
} else {
System.err.println("Failed assertion: " + msg);
System.err.println(expression);
throw new HeclException ("Assertion failed!");
}
return null;
}
}
Ads help maintain this website.