0

I have to start Jenkins parameterized build programmatically using Jersey REST API and the values for the parameters must be provided as a JSON object. Any hint or example is welcome.

Kilátó
  • 363
  • 3
  • 9
  • 18

2 Answers2

1

So, seems like you have not tried it yourself. I can give you a fast 5 minute solution, that should be reworked to be clear and not so ugly, but it works :)

import java.util.ArrayList;
import java.util.List;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


public class JenkinsJob {
    public static void main(String[] args) {
        runParamJob("http://jenkins.host/", "SOME_JOB", "{\"object\":\"test\"}");
    }

    public static String runParamJob(String url, String jobName, String paramsJSON) {
        String USERNAME = "user";
        String PASSWORD = "pass";
        Client client = Client.create();
        client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(USERNAME, PASSWORD));
        WebResource webResource = client.resource(url + jobName + "/buildWithParameters?PARAMETER=" + paramsJSON);
        ClientResponse response = webResource.type("application/json").get(ClientResponse.class, paramsJSON);
        String jsonResponse = response.getEntity(String.class);
        client.destroy();
        System.out.println("Server response:" + jsonResponse);
        return jsonResponse;
    }
}
Stan E
  • 3,066
  • 15
  • 29
  • Hi Stanjer, I tested this example but has two problems: 1. the **get** method accepts only a class parameter and 2. the Jenkins throws the following exeption: **Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 88: http://myjenkins:8080/deployment/buildWithParameters?PARAMETER={"param0":"value0"}**. This job has a parameter named param0 and started with value value0 from the dashboard it is OK. – Kilátó May 21 '15 at 04:44
1

In order to use rest API for parameterized build you should use POST and not get according to Jenkins wiki. Here is an example. Make sure that the json you send is as instructed at the documentation. take this json for example:
{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}

You have two parameters with name and value for each. If I will use what was written at the former answer by @stanjer the json should look like that: {"parameter": [{"name":"object", "value":"test"}]}

In addition there is a good discussion about it here

I would not recommend to use USER:PASSWORD but use token that could be configured in Jenkins job UI. Here is a class that implements builder pattern for with/without parameters.

import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;





public class JenkinsTrigger {


private String host;
private String jenkinsToken;
private String jobParams;
private MultivaluedMap<String,String> queryParams = new MultivaluedMapImpl();
private Client client = Client.create();
private WebResource webResource;

private JenkinsTrigger(JenkinsTriggerBuilder jenkinsTriggerBuilder){
    this.host = jenkinsTriggerBuilder.host;
    this.jenkinsToken = jenkinsTriggerBuilder.jenkinsToken;
    this.jobParams = getJobParams(jenkinsTriggerBuilder.jobParams);
    webResource = client.resource(this.host);
    queryParams.add("token", jenkinsToken);
}

public void trigger(){

    ClientResponse response = webResource.path(this.host).queryParams(queryParams)
            .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .header("Content-type", "application/x-www-form-urlencoded")
            .post(ClientResponse.class, jobParams);
    if (response.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.toString());
    } else {
        System.out.println("Job Trigger: " + host);
    }
}

private String getJobParams(Map<String,String> jobParams){
    StringBuilder sb = new StringBuilder();
    sb.append("json={\"parameter\":[");
    jobParams.keySet().forEach(param -> {
        sb.append("{\"name\":\""+param+"\",");
        sb.append("\"value\":\""+ jobParams.get(param) + "\"},");
    });
    sb.setLength(sb.length() - 1);
    sb.append("]}");
    System.out.println("Job Parameters:" +  sb.toString());
    return sb.toString();
}


    public static class JenkinsTriggerBuilder {

        private String host;
        private String jenkinsToken;
        private Map<String,String> jobParams = null;

        public JenkinsTriggerBuilder(String host, String jenkinsToken){
            this.host = host;
            this.jenkinsToken = jenkinsToken;
        }

        public JenkinsTriggerBuilder jobParams(Map<String,String> jobParams){
            this.jobParams = jobParams;
            return this;
        }

        public JenkinsTrigger build(){
            return new JenkinsTrigger(this);
        }

    }
}

And here is usage sample:

Map<String, String> params = new HashMap<>();
params.put("ENV", "DEV103");
JenkinsTrigger trigger = new JenkinsTriggerBuilder("https://JENKINS_HOST/job/JOB_NAME/buildWithParameters","JOB_TOKEN").jobParams(params).build();
trigger.trigger();

best of luck

user2656851
  • 1,185
  • 3
  • 9
  • 15