How to use third-party libraries in Jenkins shared libraries?

Viewed 533

I want to use third-party libraries(HTTPBuilder) in Jenkins SharedLibraries. But occur error. Third-party libraries are cached in ~/.groovy/grapes/ on my Jenkins master aotumatically.

HttpRequest.goorvy

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.JSON
import groovyx.net.http.ContentType

def http = new HTTPBuilder('http://192.168.100.10:9100')

    def userExist
    @NonCPS
    public int searchUser(String userLogin) {
        http.request(GET, JSON) { req ->
            uri.path = '/sonarqube/api/users/search'
            headers.'User-Agent' = 'curl/7.60.0'
            headers.'Authorization' = "Basic $userPassBase64"
            headers.Accept = 'application/json'
            uri.query = [q: userLogin]

            response.success = { resp, reader ->
                assert resp.statusLine.statusCode == 200
                userExist = reader.paging.total
                return userExist
            }
        }
    }

Jenkins Pipeline

@Library('SharedLibraries') _

import com.test.jenkins.HttpRequest
AddUserSonarProject user = new AddUserSonarProject()


pipeline {
    agent { any }
    environment {
        userLogin = 'cycwll'
    }

    stages {
      stage('Pull Source code') {
        steps {
          script{
            user.searchUser(userLogin)
          }
        }
      }
}

in Jenkins console output

    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@25d9b671
**Caused: java.io.NotSerializableException: groovyx.net.http.HTTPBuilder**
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)

enter image description here

1 Answers

solution: put the declaration http into the method.

public int searchUser(String userLogin) {
   def http = new HTTPBuilder('http://192.168.100.10:9100')
   ....
}
Related