1
votes

I have just created a grails script to create database, but the code is in Java and I thought I could use that in grails script.

This is my script

import com.test.database.*
import com.test.constant.*
import org.neo4j.kernel.*

target(main: "The description of the script goes here!") {
    db = DataRepository.getInstance(new EmbeddedGraphDatabase(
        Constant.PROJECT_PATH + "/web-app/WEB-INF/resources/db"))

}

setDefaultTarget(main)

And my java classes are in src/java, but when I run the script I got this error

Error executing script DbCreate: No such property: DataRepository for class: DbCreate
No such property: DataRepository for class: DbCreate
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:387)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
Caused by: groovy.lang.MissingPropertyException: No such property: DataRepository for class: DbCreate
    at DbCreate$_run_closure1.doCall(DbCreate:11)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)

My question would be could I call user-defined java classes in grails script?

2
Can we assume that DataRepository.java is in one of the imports you have listed? - Michael J. Lee
I'm not sure that I import it right in Gant script. Is there other way to ensure that it's in the classpath? - toy

2 Answers

1
votes

You could load the class directly using the classLoader like this...

def dataRepo = classLoader.loadClass('path.to.DataRepository') 

Or you could also use...

includeTargets << grailsScript('_GrailsBootstrap') 

Which should load all you members.

0
votes

If you're using 1.3.6 or greater you can use http://grails.org/doc/latest/ref/Command%20Line/run-script.html and if you're using an older version of Grails you can get the script from http://naleid.com/blog/2010/12/03/grails-run-script-updated-for-grails-1-3-5/