一个Java Jenkins工具类,支持创建,构建,带参数构建,删除JenkinsJob,停止Jenkins Job任务等
2017-09-25 18:27
537 查看
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); } }
相关文章推荐
- jenkins执行构建任务报错之java.lang.NoSuchFieldError: DEFAULT_USER_SETTINGS_FILE
- 一个用JAVA创建的验证码工具类
- 如何用一个Java工具类构建sql语句
- java上机 第五周 任务3 创建一个圆形类
- Jenkins基础入门-10-新建一个执行java程序的Jenkins Job
- 译:Apache Maven-简化java的构建过程--比apache ant更多(2) 创建一个简单的maven项目
- C#File类常用的文件操作方法(创建、移动、删除、复制等) File类,是一个静态类,主要是来提供一些函数库用的。静态实用类,提供了很多静态的方法,支持对文件的基本操作,包括创建,拷贝,移动,删除和
- Java并发(基础知识)—— 创建、运行以及停止一个线程
- Jenkins 配置一个构建任务中的“构建”步奏,失败后不执行下一步
- java上机 第五周 任务1 创建一个三角形类
- quartz 2.x 定时任务创建,修改,删除,执行的工具类
- 一个java操作ini格式文件的工具类,支持增删查改,不过由于项目所需,只做了针对单行的操作。写得不好求指教。
- 依靠NSOutputStream,NSURLSession,NSURLSessionDataTask创建一个支持断点下载的任务
- HBase的javaApi一个应用(创建删除表等)
- jenkins 构建脚本时javac编译出错自动停止任务
- 创建、删除文件或目录java工具类
- Java Excel操作工具类,创建一个Excel,只需一行代码。
- Java连接HBASE数据库,创建一个表,删除一张表,修改表,输出插入,修改,数据删除,数据获取,显示表信息,过滤查询,分页查询,地理hash
- java上机 第五周 任务2 创建一个梯形类
- [转载]让PHP支持大型项目-构建JSP、PHP与JAVA融为一体的开发环境