views:

61

answers:

4

Is it possible to execute groovy code dynamically loaded in java application. For example there is a database table which contains small pieces of groovy code, like:

def test(${val_to_insert_from_java}){
    if (${val_to_insert_from_java} > 10){
        return true;
    }
    return false;
}

Where ${val_to_insert_from_java} is a placeholder for some real value which gonna be inserted during execution of java code, like:

String groovyFuncSource = getFromDb();
groovyFuncSource.replace(${val_to_insert_from_java}, 9);
Object result = <evaluate somehow groovyFuncSource>;

Is there is a way to evaluate such piece of Groovy code? Or may be you advise me some other approach how to implemnt this.

A: 

Yes, you can use the Groovy script engine to evaluate Groovy source code at execution time - and of course that source code can be the result of string replacements.

From what I remember, there are various ways you can accomplish this, which will have different pros and cons.

<plug> See chapter 11 of Groovy in Action for more details. </plug>

Jon Skeet
A: 

From Java 6 you can use Java Scripting API to do that. Java scripting API allows you to use various scripting languages within Java apps.

You can find more about Java Scripting here.

Piotr
+1  A: 

An alternative would be to use JavaScript instead of Groovy. Why? Because the Rhino JavaScript engine already comes with the JDK. So if you aren't already using Groovy in your projects, it's one less dependency.

Michael Borgwardt
Hm, nice idea considering that I haven't used Groovy in project. Thanks.
Vladimir
+2  A: 

Yes, you can do this.

See the link http://groovy.codehaus.org/Embedding+Groovy

You may want to use caution with this approach, because executing code stored in a database will introduce security flaws in your application. For example, some code maliciously inserted as text in your database could do ... almost anything unless you're checking it.

matsuzine