How to call java function in Jenkinsfile using Pipeline plugin in Jenkins

梦想与她 提交于 2019-12-10 09:34:01

问题


I am using pipeline plugin in jenkins. My Jenkinsfile has numToEcho =1,2,3,4 but I want to call Test.myNumbers() to get list of values.

  1. How can I call myNumbers() java function in Jenkinsfile?
  2. Or do I need to have a separate groovy script file and that file I should place inside java jar which has Test class?

My Jenkinsfile:

def numToEcho = [1,2,3,4] 

def stepsForParallel = [:]

for (int i = 0; i < numToEcho.size(); i++) {
def s = numToEcho.get(i)
    def stepName = "echoing ${s}"

    stepsForParallel[stepName] = transformIntoStep(s)
}
parallel stepsForParallel

def transformIntoStep(inputNum) {
    return {
        node {
            echo inputNum
        }
    }
}



import com.sample.pipeline.jenkins
public class Test{

public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
 }
}

回答1:


You could write your logic in a Groovy file, which you can keep in a Git repository, or in a Pipeline Shared Library, or elsewhere.

For example, if you had the file utils.groovy in your repository:

List<Integer> myNumbers() {
  return [1, 2, 3, 4, 5]
}
return this

In your Jenkinsfile, you could use it like this via the load step:

def utils
node {
  // Check out repository with utils.groovy
  git 'https://github.com/…/my-repo.git'

  // Load definitions from repo
  utils = load 'utils.groovy'
}

// Execute utility method
def numbers = utils.myNumbers()

// Do stuff with `numbers`…

Alternatively, you can check out your Java code and run it, and capture the output. Then you could parse that into a list, or whatever data structure you need for later in the pipeline. For example:

node {
  // Check out and build the Java tool  
  git 'https://github.com/…/some-java-tools.git'
  sh './gradlew assemble'

  // Run the compiled Java tool
  def output = sh script: 'java -jar build/output/my-tool.jar', returnStdout: true

  // Do some parsing in Groovy to turn the output into a list
  def numbers = parseOutput(output)

  // Do stuff with `numbers`…
}


来源:https://stackoverflow.com/questions/42781864/how-to-call-java-function-in-jenkinsfile-using-pipeline-plugin-in-jenkins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!