I need to solve string equations in an android app, e.g. "3 + 4*(5 - log(100))". I have tried to use BeanShell for this, unfortunately I have some problems with the integer/decimal numbers. When I enter
Interpreter interpreter = new Interpreter();
String res = "9223372036854775807D";
interpreter.eval("result = " + res);
res = interpreter.get("result").toString();
res = new BigDecimal(res).stripTrailingZeros().toPlainString();
I get as result 9223372036854776000??
But when I use String res = "9223372036854775807D"; I get the correct 9223372036854775807.
I simply cannot suspitude all D to L because then I get wrong results when having somthing like 3L/2L -> 1 (but should be 1.5
Does anyone know how to handle huge numbers such as 9223372036854775807 or -9223372036854775808 or can anyone suggest an alternative to BeanShell?
Use MathEval download it from this link: http://tech.dolhub.com/code/matheval
have you tried JEP expression parser?
it is a Good mathematical expression parser purely written in Java and can parse trigonometric,logarithm functions, complex values and you can customize your own functions also...
Related
I want to convert $departureFromDate (format:yyyy-MM-dd) to date object so that I can perform increment operations on it. I have been trying to do it the following way:
#set($departureFromDate = "{{jsonPath request.body
'$.departureFromDate'}}")
#set($dateObj = $date.toDate('yyyy-MM-dd',"$departureFromDate"))
#set($calendar = $date.getCalendar())
$calendar.setTime($dateObj)
$calendar.add(6,5)
The above code works if give an actual date like:
#set($dateObj = $date.toDate('yyyy-MM-dd',"2018-09-22"))
But does not work when I try to use $departureFromDate
There are several problems in your code. First, as user7294900 noted, the right value of the first assignation seems quite weird. Then, you don't need to instanciate yourself a calendar (plus, you can write $date.calendar instead of $date.getCalendar(), and you don't need double quotes around string arguments).
#set($body = '{ "departureFromDate" : "2018-03-01" }')
$json.parse($body)
#set($departureFromDate = $json.departureFromDate)
#set($dateObj = $date.toDate('yyyy-MM-dd', $departureFromDate))
#set($calendar = $date.toCalendar($dateObj))
$calendar.add(6, 5)
The above code uses a JSON parsing tool, whose parse() method renders a json wrapper, that you shall provide in your context.
As a final advise, if you hadn't already thought of it, be sure to print $obj and $obj.class.name in your context as a trivial debugging technique if you don't understand what happens.
I have a legacy program (java 1.4) running under Tomcat/Jboss, however, i have copy it to a new server (java 1.7) and it throws the following exception.
java.lang.NumberFormatException: For input string: "0000000000000000009011,00"
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
java.lang.Double.valueOf(Double.java:504)
java.lang.Double.<init>(Double.java:597)
Since i don't have access to the source, is there any way to fix this? i haven't try with java 1.4 for the moment
You schould look to jvm parameters on old server. Your language parameters will change comma to dot actually so you do not need any code changes.
I think its not due to java version. Replace comma(,) with "" or period(.)
For example conside a string : String str = "0000000000000000009011,00";
Now you can try -
double result = Double.valueOf(str.replace(",", "."));
or
double result = Double.valueOf(str.replace(",", ""));
Rather use NumberFormat for parsing:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("0000000000000000009011,00");
double d = number.doubleValue();
This way you can select the right locale for the number representation. In the example above I used France - they use a comma for the decimal point.
I need to do a static analysis of Javascript files using Java. Here I need to check whether the Javascript file has any function calls to document.write() or reference to properties like innerHTML etc. Can I use javax.script.* package to achieve this? or Which Java api do I need to use for Parsing? Also can you provide examples for the same?
You can't statically analyze Javascript in the way you intend because Javascript is not a statically typed language.
You can check for document.write() but what if my code was this:
var whatever = document; whatever.write()
Or do you want to reject any function named write() even if it didn't write to the document?
Furthermore, Javascript has an eval function so you could always do:
var m = "ment";
eval("docu" + m + ".wri" + "te('hahahaha')");`.
How are you going to check for that?
Similarly, property access can be done in many ways.
Imagine this piece of code:
var x = document.children[0];
x.innerHTML = ...;
x["inner" + "HTML"] = ...;
var y = "inner";
x[y + "HTML"] = ...;
You're not going to be able to detect all those variants, and the hundreds more variants that you could make, using static analysis.
Like
String r = SomeThing.toExecString("new Object().toString()");
And when executed the value of r would be:
"new Object().toString() = java.lang.Object#c5e3974"
Is this even possible at all? Would it need a bunch of reflection? A built in compiler maybe?
ScriptEngine engine = new ScriptEngineManager().getEngineByName("beanshell");
Object result = engine.eval("new Object().toString();");
System.out.println(result);
You may get close to what you want using BeanShell. I ran the above code with Java 6 with BeanShell 2.0b4 and the JSR 223-based bsh-engine.jar engine on the classpath.
There is a great post here:
Generating Static Proxy Classes - http://www.javaspecialists.eu/archive/Issue180.html
Part one is enough for what you asked, I think
Don't know if you really wanted this. But your problem would be solved with this method:
String toExecString( String code ) {
return String.format(
"\"%s\" = %s#%x",
code,
code.getClass().getName(),
code.hashCode()
);
}
I'm looking for a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java, and I do not want to use the JEP library.
I have a String expression like: (x > 4 || x < 8 && p > 6) and my aim is to replace the variables with values.
Is there a way by which I can evaluate this expression?
Bear in mind that this can be any level deep so writing a parser would be very complex.
Use Apache Commons Jexl; which is exactly designed for such requirement.
http://commons.apache.org/jexl/
Using jexl (http://commons.apache.org/jexl/), you can accomplish this like this
JexlEngine jexl = new JexlEngine();
jexl.setSilent(true);
jexl.setLenient(true);
Expression expression = jexl.createExpression("(a || b && (c && d))");
JexlContext jexlContext = new MapContext();
//b and c and d should pass
jexlContext.set("b",true);
jexlContext.set("c",true);
jexlContext.set("d",true);
assertTrue((Boolean)expression.evaluate(jexlContext));
jexlContext = new MapContext();
//b and c and NOT d should be false
jexlContext.set("b",true);
jexlContext.set("c",true);
//note this works without setting d to false on the context
//because null evaluates to false
assertFalse((Boolean)expression.evaluate(jexlContext));
You could use the scripting engine in Java6 and the choose any of the popular scripting languages like Scala, Ruby, Python, Groovy, and Javascript. Than all you have to do is make sure the expression you want to evaluate is in the right language. Groovy is probably the easiest and will integrate best.
I have used this method successfully for a feature offering capabilities much like a formula / calculated column in a popular spreadsheet application.
Here is the latest resources for expression evaluation framework
The information page is at http://expressionoasis.vedantatree.com/
JUEL provides an implementation of Java's Unified Expression Language without being explicitly tied to JSP. Here's its Quick Start guide, expression evaluation (#3 on that page) is the part you're interested in.
Alternatively, Spring 3.0 provides its own (though somewhat similar) expression language. This option only makes sense if you're already using Spring, though - I wouldn't pull it in just for EL.
Try http://code.google.com/p/xpressionengine/ for open source implementation
I found the libraries listed here too complicated for my needs. I ended up using Fscript:
http://fscript.sourceforge.net/
There is a API available at http://lts.online.fr/dev/java/math.evaluator/
Example:
MathEvaluator m = new MathEvaluator("-5-6/(-2) + sqr(15+x)");
m.addVariable("x", 15.1d);
System.out.println( m.getValue() );
try Janino
http://docs.codehaus.org/display/JANINO/Home
It is very simple to use eg (taken from http://docs.codehaus.org/display/JANINO/Basic):
// Compile the expression once; relatively slow.
ExpressionEvaluator ee = new ExpressionEvaluator(
"c > d ? c : d", // expression
int.class, // expressionType
new String[] { "c", "d" }, // parameterNames
new Class[] { int.class, int.class } // parameterTypes
);
// Evaluate it with varying parameter values; very fast.
Integer res = (Integer) ee.evaluate(
new Object[] { // parameterValues
new Integer(10),
new Integer(11),
}
);
System.out.println("res = " + res);
You could try this library https://github.com/Shy-Ta/expression-evaluator-demo - the read me has a fair number of examples. The library uses java and groovy.
In addition to supporting this use case, it also supports a lot of other excel like functions. Also, it is very simple to add new functions as demonstrated in the example.
ExpressionsEvaluator evalExpr = ExpressionsFactory.create("(x > 4 || x < 8 && p > 6)");
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("x", 100);
variables.put("p", 10);
evalExpr.eval();