Search code examples
groovygroovy-grape

propagate grape dependencies for multiple classes


I have this class located in file StreamingPOIWriter.groovy

@Grapes([
    @Grab(group='org.apache.poi', module='poi', version='3.14'),
    @Grab(group='org.apache.poi', module='poi-ooxml', version='3.14'),
    @Grab(group='org.apache.poi', module='poi-ooxml-schemas', version='3.14')
])

import org.apache.poi.xslf.usermodel.XMLSlideShow
import org.apache.poi.xslf.usermodel.XSLFSlide

class StreamingPOIWriter {

    XMLSlideShow presentation

    def withPresentation() {
        presentation = new XMLSlideShow()
        this
    }

    def write(filename) {
        presentation.write(new FileOutputStream(filename))
    }

    def withSlide() {
        XSLFSlide slide = presentation.createSlide()
        this
    }
}

I compiled it using groovyc.

But when I decided to create its instance in another file - script.groovy

new StreamingPOIWriter()
    .withPresentation()
        .withSlide()
            .write("presentation.pptx")

When I find to run it using groovy script.groovy I get this error

Caught: java.lang.NoClassDefFoundError: org/apache/poi/xslf/usermodel/XMLSlideShow
java.lang.NoClassDefFoundError: org/apache/poi/xslf/usermodel/XMLSlideShow
        at script.run(script.groovy:2)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.xslf.usermodel.XMLSlideShow
        ... 1 more

It seems it's unable to find dependencies required by StreamingPOIWriter. How to propagate them to script.groovy?

StreamingPOIWriter.groovy and script.groovy are in the same folder.


Solution

  • Well, this is not how Grapes were intended. They were intended to, as you probably found out, run single scripts. If you really want to do what you are doing now, add the @Grapes annotation to script.groovy also.

    Otherwise, if you're building something a bit more complex, I'd recommend using Gradle instead. gradle init, and in your case probably gradle init --type groovy-library is your friend.