一个java创建,删除,构建Jenkins等功能的JenkinsUtil工具类
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 true;
}
/**
* 删除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", "www.baidu.com");
parameters.put("run_id", "222");
JenkinsUtil test = new JenkinsUtil();
test.buildJenkinsJobWithParameters("www.vip.com", parameters);
}
}
一个java创建,删除,构建Jenkins等功能的JenkinsUtil工具类的更多相关文章
- 一个".java"的源文件中,是否可以包含多个类?(除了匿名内部类),有什么限制?
# 二.一个".java"的源文件中,是否可以包含多个类?(除了匿名内部类),有什么限制? - 可以包含多个类 - 条件:其它类不能用private.public.prot ...
- Java开发小技巧(五):HttpClient工具类
前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...
- 一个Java编写的小玩意儿---多人在线聊天工具
这个在线聊天工具小项目使用JAVA编写,用JAVA来做图形界面本来就是出了名的低效和丑陋.不过这不是重点.写这个小项目的目的在于串一串J2SE的知识,把当时写这个项目的时候的思路梳理一下.时间有点久了 ...
- Java并发包线程池之Executors、ExecutorCompletionService工具类
前言 前面介绍了Java并发包提供的三种线程池,它们用处各不相同,接下来介绍一些工具类,对这三种线程池的使用. Executors Executors是JDK1.5就开始存在是一个线程池工具类,它定义 ...
- 《Java并发编程的艺术》第6/7/8章 Java并发容器与框架/13个原子操作/并发工具类
第6章 Java并发容器和框架 6.1 ConcurrentHashMap(线程安全的HashMap.锁分段技术) 6.1.1 为什么要使用ConcurrentHashMap 在并发编程中使用Has ...
- Java的精确整数计算-Bigdecimal学习总结和工具类
随笔:随着最近工作需要,回首需要涉及到一些精确的数据计算,就需要用到Bigdecimal,索性就趁着闲暇之余整理收集一下关于Bigdecimal的使用方法,由于时间的原因,整理的并不是特别详细,但相信 ...
- Java使用Zxing生成、解析二维码工具类
Zxing是Google提供的关于条码(一维码.二维码)的解析工具,提供了二维码的生成与解析的方法. 1.二维码的生成 (1).将Zxing-core.jar 包加入到classpath下. (2). ...
- AppDir【创建缓存目录】【建议使用这个工具类】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 创建缓存目录 public static String APP_CACHE = "";// /storage/e ...
- Java中常用的加密方式(附多个工具类)
一.Java常用加密方式 Base64加密算法(编码方式) MD5加密(消息摘要算法,验证信息完整性) 对称加密算法 非对称加密算法 数字签名算法 数字证书 二.分类按加密算法是否需要key被分为两类 ...
随机推荐
- tp5 修改配置参数 view_replace_str 无效
原因: 缓存问题 找到 thinkphp\library\think\Template.php 找到 public function fetch($template, $vars = [], $c ...
- Vue 文档Demo01
Vue 1. Vue 基础 1. 声明式渲染 1. v-bind <!DOCTYPE html> <html> <head> <meta charset=&q ...
- Python——元组
是为了满足,某些值当被定义以后就不可修改或删除而出现的元组形式. 特点: 元组中的元素不可被修改或删除 没有独立的功能 可以进行嵌套,当嵌套方可以修改删除时,可以对嵌套方进行. 元组可以进行公共功能中 ...
- JAVA 的8种基本数据类型
整型 int 一般的数据 long 极大的数据 short 用于特定的场合,比如底层的文件处理或者需要控制占用存储单元空间量的大数组 byte 用于特定的场合,比如底层的文件处理或者需要控制占用存储单 ...
- ted演讲小总结(持续更新_12月15日)
目录 2019年12月1日 星期日 2019年12月2日 星期一 2019年12月3日 星期二 2019年12月8日 星期日 2019年12月15日 星期日(这个演讲相对来说不好理解,因为这类逻辑暂时 ...
- 神经网络(4)---神经网络是如何帮助我们学习复杂的nonlinear hypotheses
神经网络是如何一步步进行计算的,以及对计算过程的向量化 Z1(2),Z2(2),Z3(2) are just weighted linear combination of input value x1 ...
- 题解 UVa10892
题目大意 多组数据,每组数据给定一个整数 \(n\),求满足 \(LCM(x,y)=n\) 的不同无序整数对 \((x,y)\) 的数目. 分析 若有 \(LCM(x,y)=n\),则有 \(GCD( ...
- Spring入门(一)——IOC
1. IOC定义 Inversion of Control,减低计算机代码间的耦合度,对象的创建交给外部容器完成,不用再new了 2. 流程 2.1 创建Bean对象 package bean; pu ...
- flask入门脚本解释
创建一个最小的flask应用, 稍做编辑如下, 开启debug调试模式后, 服务器自动加载服务器的修改. 如何自己构建一个优雅的url呢 http方法介绍 http访问urls的方法有get, pos ...
- 洛谷 P1638 逛画展 题解
P1638 逛画展 题目描述 博览馆正在展出由世上最佳的 M 位画家所画的图画. wangjy想到博览馆去看这几位大师的作品. 可是,那里的博览馆有一个很奇怪的规定,就是在购买门票时必须说明两个数字, ...