Sunday, August 15, 2010

Rhino JavaScript Tutorial, Rhino js using java code, JavaScript interface

Download js-1.6R7.jar from net. Or you can use this pom.xml to download this jar file
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.6R7 </version>
</dependency>

How to setup rhino js in console:

I have put my this above jar into D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar

creat one bat file like rhino.bat and put this command
java -classpath .;D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar org.mozilla.javascript.tools.shell.Main

save it.

Now double click on that batch file you will get
js> prompt.

now you can check bit code here
js> print('Binod')
Binod
js> 37+57
94
js>

for quiting:

quit();

js> quit();


You can open windows application using js
js> runCommand("notepad"); // It will open notepad
0
js> runCommand("mspaint");
0
js> runCommand("calc");
0
js> runCommand("cmd", "/C", "date /T")
Fri 08/13/2010

create one java script like abc.js
function check(name) {
for(i=0;i<10;i++){
print(name);
}

}


js> load("abc.js");
js> check("Binod");
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
js>

How to use the Rhino javascript embedded into java code



import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* @author Binod Suman
*/
public class Demo {


public static void main(String[] args) {
new Demo().check();
}

public void check(){
ScriptEngineManager engineMgr = new ScriptEngineManager();
ScriptEngine engine = engineMgr.getEngineByName("JavaScript");
try {
engine.eval("function sayHello(s,c) {" +" println('Hello, world! '+s+' '+c);" +"}");
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction("sayHello","Binod","Tecnotree");
} catch (ScriptException ex) { ex.printStackTrace();}
catch(Exception e){e.printStackTrace();}
}

}

Useful link:
http://www.mozilla.org/rhino/tutorial.html
Good Tutorial : http://www.mozilla.org/rhino/ScriptingJava.html
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/