Search code examples
groovyscriptengine

@Grab annotation working from JSR 223


I have a groovy script that I would to run automatically, ideally using JSR 223 (Scripting on the Java Platform).

The @Grab resolve process is working from console as well as when I execute it as external process. It however does not work using ScriptEngine from Groovy 1.8.6. The problem is that ScriptEngine will not respect the @Grab and I'm getting java.lang.ClassNotFoundException: org.apache.ivy.core.report.ResolveReport.

Anybody has solved this already?


Solution

  • This works for me:

    GrabTestJSR233.java:

    import javax.script.ScriptEngine ;
    import javax.script.ScriptEngineManager ;
    
    public class GrabTestJSR223 {
      public static void main( String[] args ) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager() ;
        ScriptEngine engine = factory.getEngineByName( "groovy" ) ;
        String script = "@Grab( 'commons-lang:commons-lang:2.6' )\n" +
                        "import org.apache.commons.lang.StringUtils\n"+
                        "\n" +
                        "println StringUtils.join( 'a', 'b', 'c' )" ;
    
        engine.eval( script ) ;
      }
    }
    

    Compile with:

    javac GrabTestJSR223.java
    

    Then, run with:

    java -cp $GROOVY_HOME/lib/*:. GrabTestJSR223
    

    And I get the output:

    abc