Wednesday, January 3, 2018

Jenkins Restful API with Java : Create, abort, build new jobs using API

3:18 PM


Jenkins RestFul APIs for Abort, Creating and Building a Job.

How to abort a Jenkins Job using REST API in java.


Below is the Java method to abort a jenkins Job using REST API.

Please note you can use your own api client to post this request.

Please change the IP and PORT according to your Jenkins IP and PORT.


public  String abortJob(String jobName, String buildNumber) {
  String abortURL = "http://192.168.1.1:8080/job/" + jobName + "/"+buildNumber+"/stop";
  Client client = Client.create();

  client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("taas", "taas"));
  WebResource webResource = client.resource(abortURL);
  ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, null);
  String jsonResponse = response.getEntity(String.class);
  client.destroy();
  return jsonResponse;

 }

How to get the list of all idle nodes from Jenkins using REST API in java.

Please change ip address with your jenkins IP and port

REQUEST TYPE : GET


public ArrayList<String> getIdleVmsList() {

  String response = callAPI("http://192.168.1.1:8080/computer/api/json");
  return parseResponse(response);

 }

 public ArrayList<String> parseResponse(String response) {

  ArrayList<String> idleVm = new ArrayList<String>();

  JSONObject stat = new JSONObject(response);
  JSONArray computer = stat.getJSONArray("computer");

  for (int i = 0; i < computer.length(); i++) {
   JSONObject info = (JSONObject) computer.get(i);
   info.getJSONObject("monitorData");
   String master = (String) info.get("displayName");
   Boolean vmOfflineStatus = (Boolean) info.get("offline");
   Boolean vmIdleStatus = (Boolean) info.get("idle");
   if (!vmOfflineStatus && vmIdleStatus && !master.equalsIgnoreCase("master")) {
    idleVm.add((String) info.get("displayName"));

   }

  }

  return idleVm;

 }

 public static String callAPI(String Url) {
  Client client = Client.create();
  try {
   client.addFilter(new HTTPBasicAuthFilter("username", "pwd"));
   WebResource webResource = client.resource(Url);
   ClientResponse response = webResource.get(ClientResponse.class);
   String jsonResponse = response.getEntity(String.class);

   client.destroy();
   return jsonResponse;
  } catch (Exception e) {
   return "couldnot call jenkins get API";
  }

 }

How to build a job using REST API. 


REST URL : http://192.168.1.1:8080/job/jobName/build?delay=0

METHOD TYPE : POST

where JobName is the name of your jenkins job.


Please contact us for more Restful web services of Jenkins. 

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy