3
votes

I have the next Groovy code which I try to run in Jenkins Pipeline:

@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')

import static groovyx.net.http.HttpBuilder.configure

def astros = configure {
    request.uri = 'http://api.open-notify.org/astros.json'
}.get()

println "There are ${astros.number} astronauts in space right now."

astros.people.each { p->
    println " - ${p.name} (${p.craft})"
}

But everytime I get java.lang.NullPointerException: Cannot invoke method get() on null object error.

When I run it from my desktop, everything works as expected:

There are 6 astronauts in space right now.

In Jenkins:

There are null astronauts in space right now.

Debug output:

<groovyx.net.http.UriBuilder$Basic@4bc2413c scheme=http port=-1 host=api.open-notify.org path=/astros.json query=[:] fragment=null userInfo=null parent=groovyx.net.http.UriBuilder$ThreadSafe@69c6847a useRawValues=null>

What should I do to make it work?

3
Double check the version of Groovy being used as well as any differences between your classpath in both situations. - cjstehno
Paths are identical, versions of groovy also. - user54

3 Answers

0
votes

object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.

0
votes

Handle the null issue inside your code as follows (Use null safe operator and groovy truth concept.)

@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')

import static groovyx.net.http.HttpBuilder.configure
def astros = configure {
    request.uri = 'http://api.open-notify.org/astros.json'
}?.get() // added null safe operator here (will handle null pointer exception)

println "There are ${astros?.number} astronauts in space right now."
//iterate if astros value exists.
if(astros){
  astros.people.each { p->
    println " - ${p.name} (${p.craft})"
  }
}

// As you are having json, you need to parse that as follows.

  def slurper = new groovy.json.JsonSlurper()
  def result = slurper.parseText(astros)
  println result
  println result?.number
0
votes

I take it that you created a shared library and is trying to use this in a pipeline?

I have the same problem at the moment, I think it might be a limitation of the Groovy interpreter on Jenkins, similar to how the each loop didn't work until some time ago.

I've resorted to using this version of http-builder to circumvent that for now. I'll update this if I find a proper solution (please also post an answer if you find anything).