Rhino:envjsとjQueryをつかう
Last-modified: 2013-08-24 (土) 02:14:21 (3897d)
Top / Rhino:envjsとjQueryをつかう
Rhino:envjsとjQueryをつかう †
RhinoでenvjsとjQueryをつかってJavaScript?を実行する汎用Javaコードを書いてみました。
コード †
コードは2つです。
- JSExecutor : Rhinoを実行するクラス
- JSExecutorRunner? : JSExecutorを実行するクラス。mainメソッドのみ。
JSExecutorRunner?を実行すると、JSExecutorが実行されるって感じです。
■JSExecutor.java
package rhinotest2; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Function; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.tools.shell.Global; public class JSExecutor { private Global global = null; private Context cx = null; private Scriptable scope = null; /** * コンストラクタ * Rhinoの初期化処理を実行 */ public JSExecutor() { // コンテキストの生成 cx = ContextFactory.getGlobal().enterContext(); // shellでしか使えない関数(print等)を使用するため、使用 global = new Global(); global.init(cx); // optimazationのレベルを指定。-1だと、Scriptを逐次解釈する。 // 1-9だと、レベルに応じて適切にclassファイルを生成する。 cx.setOptimizationLevel(-1); cx.setLanguageVersion(Context.VERSION_1_5); // スタンダードオブジェクトを生成。 // Javadocには「return: the initialized scope」と記載あり。 scope = cx.initStandardObjects(global); } /** * 指定されたパス、ファイル名のJavaScriptを実行する。 * @param path * @param filename * @throws IOException */ public void execScript(String path, String filename) throws IOException { Reader scriptReader = new FileReader(path + File.separator + filename); Script script = cx.compileReader(scriptReader, filename, 1, null); scriptReader.close(); script.exec(cx, scope); } /** * 引数に指定された関数名及び引数から、関数を実行する1行のJavaScript文を生成し、実行する。 * 以下の場合、実行行を以下のように組み立て、スクリプトとして実行する。 * jsFuncName:testFunc * args : ["test1","test2"] * => testFunc("test1","test2"); * @param jsFuncName : 関数名を指定 * @param args : 引数をString配列で指定、引数がない場合は空の配列もしくはnullも可 * @return * @throws NoSuchFunctionException */ @SuppressWarnings("static-access") public String execFunction(String jsFuncName, String[] args) throws NoSuchFunctionException { Object fObj = scope.get(jsFuncName,scope); if (!(fObj instanceof Function)) { throw new NoSuchFunctionException(); } Function f = (Function)fObj; Object result = f.call(cx, scope, scope, args); return cx.toString(result); } @SuppressWarnings("static-access") public String execFunction2(String jsFuncName, String[] args) { StringBuffer execLine = new StringBuffer(); execLine.append(jsFuncName + "(" ); if(args != null){ for(int i=0; i < args.length; i++){ execLine.append("\""); execLine.append(args[i]); execLine.append("\""); if (i != args.length -1){ execLine.append(","); } } } execLine.append(");"); Object result = cx.evaluateString(scope, execLine.toString(), "<cmd>", 1, null); return cx.toString(result); } /** * Rhinoのコンテキストをクローズする。 * RhinoのJavadocに、exit()しろってかいてあったので書いてみた。 */ public void contextExit(){ Context.exit(); } class NoSuchFunctionException extends Exception{ private static final long serialVersionUID = 1L; } }
■JSExecutorRunner?.java
package rhinotest2; import java.io.IOException; import rhinotest2.JSExecutor.NoSuchFunctionException; public class JSExecutorRunner { /** * @param args * @throws IOException * @throws NoSuchFunctionException */ public static void main(String[] args) throws IOException, NoSuchFunctionException { JSExecutor rhino = null; try { rhino = new JSExecutor(); final String RESOURCE_PATH = "bin/resources"; rhino.execScript(RESOURCE_PATH, "env.rhino.1.2.js"); rhino.execScript(RESOURCE_PATH, "jquery-1.3.2.js"); rhino.execScript(RESOURCE_PATH, "sample2.js"); System.out.println("This output is java(println) : " + rhino.execFunction("sample", new String[] { "http://www.hiihah.info","args2" })); } finally { rhino.contextExit(); } } }
■sample2.js
function sample(args1,args2){ print("args1 : " + args1); print("args2 : " + args2); window.location = args1; print('title from document:' + document.title); print('title from jQuery :' + $('#header a').text()); return $('#header a').text(); };
実行してみる。 †
実行するとこんな感じの出力になります。
[ Envjs/1.6 (Rhino; U; Linux amd64 2.6.32-131.0.15.el6.x86_64; en-US; rv:1.7.0.rc2) Resig/20070309 PilotFish/1.2.13 ] args1 : http://www.hiihah.info args2 : args2 title from document:FrontPage - HiiHahWIKI - making some notes for... - title from jQuery :HiiHahWIKI - making some notes for... - This output is java(println) : HiiHahWIKI - making some notes for... -
できたーw