Friday, April 2, 2010

javax.script how to use, groovy with java, java ScriptEngineManager, java ScriptEngine

Browse this URL for groove fundamental and getting started with groovy

Java 6 includes built-in support for JSR 223: Scripting for the Java Platform API classes. This framework can be used to host Script Engines in Java Applications.

Here is the code to how to use groovy script inside the java code

EvalScriptFile.java

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class EvalScriptFile {

public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("groovy");


try {
File script = new File("D:\\Nik\\Groovy_Example\\Second.gy");
Reader reader = new FileReader(script);
engine.eval(reader);
} catch (FileNotFoundException e) {
System.out.println("SOME ERROR 1 :: "+e);
e.printStackTrace();
} catch (ScriptException e) {
System.out.println("SOME ERROR 2 :: "+e);
e.printStackTrace();
}

}
}

Second.gy

class HelloWorld {

def name

def greet() { "Hello ${name}" }
}
def helloWorld = new HelloWorld()
helloWorld.name = "My name is groovy TEST "
println helloWorld.greet()


This below example is showing calling an invokable function:


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

public class Factorial {
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");
String fact = "def factorialFun(n) { n == 1 ? 1 : n * factorialFun(n - 1) }";
engine.eval(fact);
Invocable inv = (Invocable) engine;
Object[] params = { new Integer(6) };
Object result = inv.invokeFunction("factorialFun", params);
System.out.println("The factorial of 6 is "result);
}
}

You will get result after run is
The factorial of 6 is 720









No comments:

Post a Comment