How add dependencies into groovy script?

780 views Asked by At

I try to add HttpBuilder into groovy script, but can do it only manually (Alt+Ctrl+Shift+S add dependencie). But when I start script I have error in line of creating new httpbuilder instance java.lang.ClassNotFoundException: org.apache.http.client.HttpClient. I manualy add HttpClient, butClassNotFoundException: net.sf.json.JSONObject and so on. But when I add Ini library it works fine.

I also tried to use @Grab

main()
def main() {
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
    def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org')    

And have compilation error Error:Groovyc: While compiling GroovyTests: java.lang.RuntimeException: Error grabbing Grapes -- [download failed: net.sf.json-lib#json-lib;2.3!json-lib.jar]

And net in def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org') is red and Cannot resolve a symbol 'net' error

will be glad to any help

1

There are 1 answers

9
Matias Bjarland On

Since you have now installed the groovy executables as per the comments, the following code:

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://jsonplaceholder.typicode.com')
def res  = http.get(path: '/users')

println "Number of users: ${res.size()}"

should now run and print:

─➤ groovy solution.groovy
Number of users: 10

─➤ 

(tested on Groovy Version: 2.5.8 JVM: 1.8.0_232 Vendor: AdoptOpenJDK OS: Linux)

One thing that might be disrupting the artifact resolution is if you have a custom grapeConfig.xml file. This file (if it exists) should be under <user home dir>/.groovy/grapeConfig.xml and the default text that groovy uses if no grapeConfig.xml file is present can be found here:

https://github.com/apache/groovy/blob/master/src/resources/groovy/grape/defaultGrapeConfig.xml

In addition, if you need to debug grapes downloads, you should try the following flags (again as mentioned in the comments):

─➤ groovy -Dgroovy.grape.report.downloads=true -Divy.message.logger.level=4 yourGroovyScript.groovy

which should print information on what grapes are actually doing when the resolution fails.

What does your groovy -v look like? i.e. what version of groovy and what jdk are you on?