一個Java Jenkins工具類,支援建立,構建,帶引數構建,刪除JenkinsJob,停止Jenkins Job任務等
阿新 • • 發佈:2019-01-30
Jenkins是一個很強大的持續整合的工具,除了在Jenkins的頁面上我們可以去構建我們的job,我們也可以通過java程式碼來通過呼叫jenkins的api來做一些事情,使得我們的java web專案更加便捷,下面是我的一個工具類。
package com.vip.webpagetest.utils; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import static com.jayway.restassured.path.json.JsonPath.with; public class JenkinsUtil { private static final Logger logger = LoggerFactory.getLogger(JenkinsUtil.class); String jenkinsBaseUrl = ClassPathPropertiesUtils.getProperty("jenkins.baseurl"); String userName = ClassPathPropertiesUtils.getProperty("jenkins.userName"); String apiToken = ClassPathPropertiesUtils.getProperty("jenkins.apiToken"); private CloseableHttpClient httpClient = HttpClientPool.getHttpClient(); /** * 建立Jenkins Job * * @param jobName * @throws Exception */ public void creatJenkinsJob(String jobName) { if (isJenkinsJobExist(jobName)) { logger.info("已經存在job:" + jobName); } else { HttpPost httpPost = new HttpPost(jenkinsBaseUrl + "/createItem?name=" + jobName); Resource resource = new ClassPathResource("config.xml"); try { InputStream fileInput = resource.getInputStream(); InputStreamEntity entity = new InputStreamEntity(fileInput); entity.setContentEncoding("UTF-8"); entity.setContentType("text/xml"); httpPost.setEntity(entity); httpClient.execute(httpPost, this.getHttpClientContext()); } catch (Exception e) { e.printStackTrace(); } logger.info("成功建立job:" + jobName); } } /** * 查詢是否存在名為jobName的job * * @param jobName * @return * @throws Exception */ public boolean isJenkinsJobExist(String jobName) { HttpGet httpGet = new HttpGet(jenkinsBaseUrl + "/api/json"); CloseableHttpResponse rsp = null; try { rsp = httpClient.execute(httpGet, this.getHttpClientContext()); HttpEntity entity = rsp.getEntity(); String result = EntityUtils.toString(entity); List<String> jobList = with(result).getList("jobs.name"); for (String job : jobList) { if (jobName.equals(job)) { return true; } } } catch (Exception e) { logger.error(null, e); return false; } return false; } /** * 刪除Jenkins Job * * @param jobName * @throws Exception */ public void deleteJenkinsJob(String jobName) { if (!isJenkinsJobExist(jobName)) { logger.info("不存在job:" + jobName); } else { HttpPost httpPost = new HttpPost(jenkinsBaseUrl + "/job/" + jobName + "/doDelete"); try { httpClient.execute(httpPost, this.getHttpClientContext()); } catch (Exception e) { e.printStackTrace(); } } } /** * 構建觸發Jenkins Job * * @param jobName * @throws Exception */ public boolean buildJenkinsJob(String jobName) { if (!isJenkinsJobExist(jobName)) { logger.info("不存在job:" + jobName); return false; } else { HttpPost httpPost = new HttpPost(jenkinsBaseUrl + "/job/" + jobName + "/build"); try { httpClient.execute(httpPost, this.getHttpClientContext()); } catch (Exception e) { e.printStackTrace(); return false; } } return true; } /** * 帶引數的構建 * * @param jobName * @param parameters * @return */ public boolean buildJenkinsJobWithParameters(String jobName, Map<String, String> parameters) { if (!isJenkinsJobExist(jobName)) { logger.info("不存在job:" + jobName); return false; } else { HttpPost httpPost = new HttpPost(jenkinsBaseUrl + "/job/" + jobName + "/buildWithParameters"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String key : parameters.keySet()) { formparams.add(new BasicNameValuePair(key, parameters.get(key))); } UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); CloseableHttpResponse rsp = null; try { httpPost.setEntity(urlEntity); rsp = httpClient.execute(httpPost, this.getHttpClientContext()); } catch (Exception e) { logger.error(null, e); return false; } return true; } } /** * 終止Jenkins Job構建 * * @param jobName * @return * @throws Exception */ public boolean stopJenkinsJob(String jobName) { if (!isJenkinsJobExist(jobName)) { logger.info("不存在job:" + jobName); return false; } else { HttpPost httpPost = new HttpPost(jenkinsBaseUrl + "/job/" + jobName + "/api/json"); CloseableHttpResponse resp = null; try { resp = httpClient.execute(httpPost, this.getHttpClientContext()); HttpEntity entity = resp.getEntity(); String result = EntityUtils.toString(entity); int buildNumber = with(result).get("lastBuild.number"); HttpPost stopJenkinsRequest = new HttpPost( jenkinsBaseUrl + "/job/" + jobName + "/" + buildNumber + "/stop"); httpClient.execute(stopJenkinsRequest, this.getHttpClientContext()); } catch (Exception e) { e.printStackTrace(); return false; } return true; } } private HttpClientContext getHttpClientContext() { HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(this.getCredentialsProvider()); // httpClientContext.setAuthCache(this.getAuthCache()); return httpClientContext; } private CredentialsProvider getCredentialsProvider() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(userName, apiToken)); return credsProvider; } public static void main(String[] args) throws Exception { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("domain", "xxx"); parameters.put("run_id", "222"); JenkinsUtil test = new JenkinsUtil(); test.buildJenkinsJobWithParameters("xxx", parameters); } }