2011-07-07 3 views
0

背景(スキップすることができます):基本的なGroovyスクリプトエンジンのセットアップ

は、私は最近、Javaで軽量サーバーを書いた新しいポートで接続し、クライアントが接続しているとき、それはソケットまで彼らに自分のスレッドを与えるためのポーリング閉じます。さて、クライアントが接続されたら、何をする必要があるのか​​は、XMLファイル要求を特別な方法で準備することです。クライアントがfile1.xmlを要求した場合、サーバーはfile1.xmlを読み込み、JSONに解析してjsonオブジェクトをクライアントに送信する必要があります。

問題特定(今読んで始めてください): JavaのJSONオブジェクトにXMLファイルを解析する必要があります。私はこの仕事のためにGROOVYに勧められました。私のMacとubuntuの両方のパーティションにインストールするのは簡単でしたが、インライングルーヴィーの作業をすることはできません。その理由はほとんどありません。

test.groovy

output = "Hello ${input}!" 

test.java

import groovy.lang.Binding; 
import groovy.util.GroovyScriptEngine; 

String[] roots = new String[] { "/home/nick/Documents" }; 
GroovyScriptEngine gse = new GroovyScriptEngine(roots); 
Binding binding = new Binding(); 
binding.setVariable("input", "world"); 
gse.run("test.groovy", binding); 
System.out.println(binding.getVariable("output")); 
を:ここで私は(この時点で、私はちょうど埋め込まれたグルーヴィーな作業を取得しようとしている)今テストするんですよ

これらのファイルはいずれも私の/home/nick/Documentsフォルダにあります。私がコンパイルしようとすると:

test.java:4: class, interface, or enum expected 
String[] roots = new String[] { "/home/nick/Documents" }; 
^ 
test.java:5: class, interface, or enum expected 
GroovyScriptEngine gse = new GroovyScriptEngine(roots); 
^ 
test.java:6: class, interface, or enum expected 
Binding binding = new Binding(); 
^ 
test.java:7: class, interface, or enum expected 
binding.setVariable("input", "world"); 
^ 
test.java:8: class, interface, or enum expected 
gse.run("test.groovy", binding); 
^ 
test.java:9: class, interface, or enum expected 
System.out.println(binding.getVariable("output")); 
^ 
6 errors 

私は、コンパイル段階で何かを間違ってやってる感じ:

javac test.java 

私は6つのエラーが発生します。このコンパイルと実行をどうすればできますか?非常に多くのtest.javaとして

+0

は、ScriptEngineのは、本当にすべてのスクリプトの依存関係を搭載したエンジンであり、プロジェクトのために? – djangofan

答えて

4

を高く評価し

ヘルプのGroovyスクリプトのJavaクラスではなく、あなたは(首都TTest.javaに改称)クラス内のコードをラップする必要があります。また、キャッチする必要があるか、いくつかの例外を投げる:

import groovy.lang.Binding; 
import groovy.util.GroovyScriptEngine; 
import groovy.util.ResourceException ; 
import groovy.util.ScriptException ; 
import java.io.IOException ; 

public class Test { 
    public static void main(String[] args) throws IOException, ResourceException, ScriptException { 
    String[] roots = new String[] { "." }; 
    GroovyScriptEngine gse = new GroovyScriptEngine(roots); 
    Binding binding = new Binding(); 
    binding.setVariable("input", "world"); 
    gse.run("test.groovy", binding); 
    System.out.println(binding.getVariable("output")); 
    } 
} 

次に、あなたがそうでなければ、あなたが記入する必要があります、ワイルドカードパスを使用してJava 6の必要です(クラスパス上にグルーヴィーで、このJavaクラスをコンパイルする必要がありますgroovy-all-*.jarへの完全なパス):

javac -cp $GROOVY_HOME/embeddable/*:. Test.java 

、あまりにも正しいクラスパスでそれを実行します。だから、