Java application may run several script languages like Groovy .
Java uses the Nashron jar in order to execute javascript .
The following example demonstrates using Nashron to execute a simple java script.
The example demonstrates :
1.Transferring data from the java application to the javascript application
2.Reading the java script result
3.Calling from the Javascript to Java methods .
The project
The java wrapper code :
package playwithnashron;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;import javax.script.SimpleBindings;import jdk.nashorn.api.scripting.ScriptObjectMirror;public class PlayWithNashron {/**
* @param args the command line arguments*/public static void main(String[] args) throws ScriptException, InterruptedException {ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");nashorn.eval("print('This is java script call')");int NoOfThreads = 3 ;SimpleBindings simpleBindings = new SimpleBindings();simpleBindings.put("NoOfThreads", NoOfThreads);String thePath = "C:\\Learn\\Java\\PlayWithNashron\\src\\playwithnashron\\NashCode.js";ScriptObjectMirror RetValue = (ScriptObjectMirror)nashorn.eval(GetFileText ( thePath ) ,simpleBindings);for (Integer i = 0 ; i < RetValue.size() ; i ++ ){Thread theTrhead = (Thread) RetValue.getSlot (i);theTrhead.join();}System.out.println("After wait kiss very very ");}public static String GetFileText (String pPath ){StringBuilder RetValue = new StringBuilder();BufferedReader br = null;try {String sCurrentLine;br = new BufferedReader(new FileReader(pPath));while ((sCurrentLine = br.readLine()) != null) {RetValue.append(sCurrentLine + "\r\n");}} catch (IOException e) {e.printStackTrace();} finally {try {if (br != null)br.close();} catch (IOException ex) {ex.printStackTrace();}}return RetValue.toString();}}
The java script code
var Thread = Java.type("java.lang.Thread");var theThread = Java.extend(Thread,{run: function() {Thread.sleep ( 1000 );print("Message in abootle ");}});RetValue = [];for ( i = 0 ; i < NoOfThreads ; i ++ ){var th = new theThread();th.start();RetValue.push(th);}//Return the valueRetValue;
The result:
This is java script call
Message in abootle
Message in abootle
Message in abootle
After wait kiss very very
References:
http://www.infoq.com/articles/nashorn
https://avatar.java.net/download.html
אין תגובות:
הוסף רשומת תגובה