Tuesday, April 9, 2013

How to create jobs in Jenkins and build them through REST API - simple java program


If you wish to create / build a jenkins job remotely from your code using REST API. Then read through!

Here is a simple java program to create a job in Jenkins through REST API.
You can find more details about the APIs at http://yourjenkinsserver/api (e.g http://localhost:8080/api, if your jenkins server is running on your localhost on port 8080 :)

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class NetClientPost {
        public static void main(String[] args) {      String actionType= args[0];      switch(actionType){      case "create":          int responseCodeNewJob = new NetClientPost().createJob("NewSuccess");          System.out.println("The response code is: "+responseCodeNewJob);          break;      case "build":          HttpResponse responseCodeBuildJob = new NetClientPost().buildJob("NewSuccess");          System.out.println("The response code is: "+responseCodeBuildJob);          break;      }
}         public int createJob(String jobName)     {         int responseCode=00;          try {                             URL url = new URL("http://YOURJENKINSURL?name="+jobName);                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();                 conn.setDoOutput(true);                 conn.setRequestMethod("POST");                 conn.setRequestProperty("Content-Type", "application/xml");         //the config file could be found in your ~/.jenkins/jobs/JOBNAME 
//folder if you have already configured a job through jenkins UI
//If you dont' have , I have kept a sample config file content at the end of this post.
//please have a look and modify accordingly
                String input = "ContentOfConfigXML";                                 OutputStream os = conn.getOutputStream();                 os.write(input.getBytes());                 os.flush();                 responseCode= conn.getResponseCode();                BufferedReader br = new BufferedReader(new InputStreamReader(                         (conn.getInputStream())));                         String output;                 System.out.println("Output from Server .... \n");                 while ((output = br.readLine()) != null) {                     System.out.println(output);                 }                                 conn.disconnect();         } catch (MalformedURLException e) {                        e.printStackTrace();                      } catch (IOException e) {                        e.printStackTrace();                     }          return responseCode;     }         public HttpResponse buildJob(String jobName)     {         HttpResponse responseCode=null;         URL url;         try {                      HttpClient client = new DefaultHttpClient();             HttpGet get = new HttpGet("http://YOURJENKINSURL/job/"+jobName+"/build");             responseCode=client.execute(get);                     } catch (MalformedURLException e) {             // TODO Auto-generated catch block             e.printStackTrace();         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }                 return responseCode;     } }
Here is the sample config file content.Copy paste and modify according to your way
<?xml version='1.0' encoding='UTF-8'?> <maven2-moduleset plugin='maven-plugin@1.505'> <actions/> <description>Test Job</description> <keepDependencies>false</keepDependencies> <properties/> <scm class='hudson.scm.NullSCM'/> <assignedNode>TestSlave</assignedNode> <canRoam>false</canRoam> <disabled>true</disabled> <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding> <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding> <triggers class='vector'/> <concurrentBuild>false</concurrentBuild> <aggregatorStyleBuild>true</aggregatorStyleBuild> <incrementalBuild>false</incrementalBuild> <perModuleEmail>true</perModuleEmail> <ignoreUpstremChanges>false</ignoreUpstremChanges> <archivingDisabled>false</archivingDisabled> <resolveDependencies>false</resolveDependencies> <processPlugins>false</processPlugins> <mavenValidationLevel>-1</mavenValidationLevel> <runHeadless>false</runHeadless> <disableTriggerDownstreamProjects>false</disableTriggerDownstreamProjects> <settings class='jenkins.mvn.DefaultSettingsProvider'/> <globalSettings class='jenkins.mvn.DefaultGlobalSettingsProvider'/> <reporters/> <publishers/> <buildWrappers/> <prebuilders/> <postbuilders/> <runPostStepsIfResult> <name>FAILURE</name> <ordinal>2</ordinal> <color>RED</color> </runPostStepsIfResult> </maven2-moduleset>
For More details on Jenkins Remote Access APIs visit:


Please Comment if you find this useful or if you have a better solution.
Cheers!




3 comments:

  1. Hey,

    Can you let me know if we can generate the XML File programatically from form parameters and then submit the XML to the server?

    ReplyDelete
  2. or is there a way to include this file in our jenkins plugin code? Where do we have to place this?

    ReplyDelete