Java calls JAVASCRIPT:JS engine Rhino

Source: Internet
Author: User

Java calls Javascript:js engine Rhino javajavascripteclipse script sql

Some time ago, when browsing the Javaeye forum, I saw someone soliciting how to run mathematical expressions in Java.
The result is a variety of scenarios:
1.jakarta Commons Jexl.
2.Beanshell
3.Java Math Expression Parser Jep
4.parse Combinator jparsec
Script for 5.JDK 6.0
6. Using SQL
7. Write your own grammar analysis
If you write your own grammar analysis, no 2000 rows are estimated to be uncertain. Some people use SQL to run mathematical expressions and compare alternatives.
But as I learned some Java JavaScript engines in the previous period, the solution I gave was to use JavaScript to calculate.
Java is the more famous JS engine is Mozilla Open source rhino, but Jdk6 has already put it under the account, became the regular army.


public class Matheval
{
public static void Main (string[] args)
{
Context cx = Context.enter ();
Try
{
scriptable scope = Cx.initstandardobjects ();
String str = "9* (1+2)";
Object result = cx.evaluatestring (scope, str, NULL, 1, NULL);
Double res = context.tonumber (result);
System.out.println (RES);
}
Finally
{
Context.exit ();
}
}
}
Here's a summary of what you learned about rhino in the first time (adding scripting to your program is really cool):

One: Environment configuration and Operation JS script:
Download Rhino in http://www.mozilla.org/rhino/:
Add Js.jar to the system classpath
You can invoke the JS interpreter in interactive mode:
Java Org.mozilla.javascript.tools.shell.Main
You should then see the version number of the interpreter followed by the prompt js>
Use the following:
For example: There is a JS file:
D:\eclipse-workshop\rhinoExample\src\isPrime.js
The contents are as follows:


JS code
Function isprime (num)    
{   
    if (num <= 1 ) {   
        Print ("Please enter a positive integer >= 2.")    
        return false  
   }    
       
    var prime = true   
    var sqrroot = math.round (math.sqrt (num))    
        
    for (var n = 2; prime & n <= sqrroot; ++n) {   
        prime = (num% n! = 0)    
   }    
       
    return prime   
}  

How to run it:
1: At the command line, type:
Java Org.mozilla.javascript.tools.shell.Main
2: Under Js〉 type:
Load ("D:/eclipse-workshop/rhinoexample/src/isprime.js");
Note: yes "/" instead of "\"
3: Type:
IsPrime (77);
You can see that the returned result is false.
Type:
IsPrime (71); Returns true

To give an example, the script is as follows:

person = {
Name: "Mike squillace",
Age:37,
Position: "Software Engineer",
Getfirstname:function () {return this.name.split ("") [0]}
}
Person.getfirstname ()
JS produces swing example:
Load ("D:/eclipse-workshop/rhinoexample/src/swingapplication.js");
What do you think? Did you see the effect? Isn't it tough? Among them, Swingapplication.js is an example of Rhnio's own.


Rhino also has a debugger for JS script:
Rhino JavaScript Debugger:
Java org.mozilla.javascript.tools.debugger.Main [Options] [filename.js] [script-arguments]

Just run Java Org.mozilla.javascript.tools.debugger.Main and you'll see the debugger's interface.


In order to speed up the JS file run, you can compile it into a class file:
Compile
Java Org.mozilla.javascript.tools.jsc.Main d:/eclipse-workshop/rhinoexample/src/firstcompile.js
Compilation generates Firstcompile.class file
Run the class file under d:/eclipse-workshop/rhinoexample/src/:
Java firstcompile

Second: In practical applications, it is unavoidable to encounter the problem of how Java code accesses each other with JavaScript scripts:
This is one of the simplest examples: (Liveconnect.js is an example of Rhnio's own):
Load ("D:/eclipse-workshop/rhinoexample/src/liveconnect.js");

In the case of a complex point, there is no logic, pure technology display, hehe:
Jsfunction.java:

Java code
Package co.test;

Import org.mozilla.javascript.Function;

public class Jsfunction//extends Scriptableobject
{
private String name;

Private Function handle;

public void SetHandler (Function func)
{
This.handle = func;
}

Public Function GetHandler ()
{
return this.handle;
}


Public Jsfunction (String s)
{
THIS.name = s;
}

public static void print (String s)
{
System.out.println (s);
}

Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}

}

Jsexploration.java:

Java code
Package co.test;

Import Java.io.FileReader;
Import Java.io.LineNumberReader;

Import Org.mozilla.javascript.Context;
Import org.mozilla.javascript.Function;
Import org.mozilla.javascript.Scriptable;

public class Jsexploration
{
Private Context CX;

Private scriptable scope;

Public Jsexploration ()
{
this.cx = Context.enter ();
This.scope = Cx.initstandardobjects ();
}

Public Object runjavascript (String filename)
{
String jscontent = this.getjscontent (filename);
Object result = cx.evaluatestring (scope, jscontent, filename, 1, null);
return result;
}

private string Getjscontent (string filename)
{
LineNumberReader reader;
Try
{
reader = new LineNumberReader (new FileReader (filename));
String s = null;
StringBuffer sb = new StringBuffer ();
while ((s = reader.readline ()) = null)
{
Sb.append (s). Append ("\ n");
}
return sb.tostring ();
}
catch (Exception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
return null;
}
}


Public scriptable Getscope ()
{
return scope;
}

public static void Main (string[] args)
{
String filename = system.getproperty ("User.dir") + "/jsmap.js";
Jsexploration jsexploration = new Jsexploration ();
Object result = jsexploration.runjavascript (filename);
scriptable scope = Jsexploration.getscope ();
scriptable obj = (scriptable) scope.get ("obj", scope);
System.out.println ("obj.a = =" + Obj.get ("a", obj));
Scriptable B = (scriptable) obj.get ("B", obj);
System.out.println ("b[0] = =" + b.get (0, b));
Boolean flag = (Boolean) scope.get ("flag", scope);
SYSTEM.OUT.PRINTLN (flag);

scriptable myobj = (scriptable) scope.get ("obj", scope);
Boolean Myflag = (Boolean) scope.get ("flag", scope);
System.out.println (Myflag);

scriptable jsfunction = (scriptable) scope.get ("jsfunction", scope);
function FC = (function) jsfunction.get ("handler", jsfunction);
Object IsPrime = Fc.call (Context.getcurrentcontext (), Jsfunction, FC, new object[] {"This is my Test"});
}
}

JS Script: Jsmap.js

JS Code
var swingnames = Javaimporter ();

Swingnames.importpackage (Packages.java.lang);
Swingnames.importpackage (Packages.co.test);

obj = {a:1, b:[' x ', ' Y ']}
Next = IsPrime
Flag = IsPrime (5)
With (Swingnames) {
System.out.println ("in JavaScript");
Jsfunction.print ("in Jsfunction");
Jsfunction = new Jsfunction ("Lichunlei");
var name = Jsfunction.getname ();
System.out.println ("Get name from Java Source:" + name);
Jsfunction.sethandler (log);
}

JAVA.LANG.SYSTEM.OUT.PRINTLN ("not use Swingnames");
function IsPrime (num)
{
Java.lang.System.out.println ("in IsPrime (num)");
if (num <= 1) {
Java.lang.System.out.println ("Please enter a positive integer >= 2.")
return False
}

var prime = True
var sqrroot = Math.Round (math.sqrt (num))

for (var n = 2; prime & n <= sqrroot; ++n) {
Prime = (num% n! = 0)
}

Return prime
}

function log (msg)
{
Java.lang.System.out.println ("In function log:" + msg);
}

Java calls JAVASCRIPT:JS engine Rhino

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.