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工具类的更多相关文章

  1. 一个".java"的源文件中,是否可以包含多个类?(除了匿名内部类),有什么限制?

    # 二.一个".java"的源文件中,是否可以包含多个类?(除了匿名内部类),有什么限制?   - 可以包含多个类   - 条件:其它类不能用private.public.prot ...

  2. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

  3. 一个Java编写的小玩意儿---多人在线聊天工具

    这个在线聊天工具小项目使用JAVA编写,用JAVA来做图形界面本来就是出了名的低效和丑陋.不过这不是重点.写这个小项目的目的在于串一串J2SE的知识,把当时写这个项目的时候的思路梳理一下.时间有点久了 ...

  4. Java并发包线程池之Executors、ExecutorCompletionService工具类

    前言 前面介绍了Java并发包提供的三种线程池,它们用处各不相同,接下来介绍一些工具类,对这三种线程池的使用. Executors Executors是JDK1.5就开始存在是一个线程池工具类,它定义 ...

  5. 《Java并发编程的艺术》第6/7/8章 Java并发容器与框架/13个原子操作/并发工具类

    第6章 Java并发容器和框架 6.1  ConcurrentHashMap(线程安全的HashMap.锁分段技术) 6.1.1 为什么要使用ConcurrentHashMap 在并发编程中使用Has ...

  6. Java的精确整数计算-Bigdecimal学习总结和工具类

    随笔:随着最近工作需要,回首需要涉及到一些精确的数据计算,就需要用到Bigdecimal,索性就趁着闲暇之余整理收集一下关于Bigdecimal的使用方法,由于时间的原因,整理的并不是特别详细,但相信 ...

  7. Java使用Zxing生成、解析二维码工具类

    Zxing是Google提供的关于条码(一维码.二维码)的解析工具,提供了二维码的生成与解析的方法. 1.二维码的生成 (1).将Zxing-core.jar 包加入到classpath下. (2). ...

  8. AppDir【创建缓存目录】【建议使用这个工具类】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 创建缓存目录 public static String APP_CACHE = "";// /storage/e ...

  9. Java中常用的加密方式(附多个工具类)

    一.Java常用加密方式 Base64加密算法(编码方式) MD5加密(消息摘要算法,验证信息完整性) 对称加密算法 非对称加密算法 数字签名算法 数字证书 二.分类按加密算法是否需要key被分为两类 ...

随机推荐

  1. datatables 自定义排序

    参考:https://datatables.net/examples/plug-ins/sorting_manual $.fn.dataTable.ext.type.order['salary-gra ...

  2. Mac 修改hostname

    mac终端上输入命令: sudo scutil --set HostName newname # 实例 sudo scutil --set HostName master

  3. elasticsearch 7版本 基础操作

    elasticsearch 7版本 基础操作 首先我们浏览器http://localhost:5601/进入 kibana里的Console中输入 首先让我们在 Console 中输入: PUT t1 ...

  4. MySQL Replication--修复从库上单个数据库的数据

    问题描述 由于运维失误,从库未及时设置read_only,导致从库上某库数据被修改,由于整个实例数据量较大,重做成本较高,而该数据库数据较少,因此考虑如何修复该数据库的数据. 操作前提 1.复制使用位 ...

  5. 批量导入数据到InnoDB表速度优化

    1.使用Load data: 2. SET autocommit=0; ... SQL import statements ... COMMIT; 3. SET unique_checks=0; .. ...

  6. 学习python的日常7

    ---恢复内容开始--- 正则表达式: 在正则表达式中,用\d可以匹配一个数字,\w可以匹配一个字母或数字,'.'可以匹配任意字符,用*表示任意个字符,用+表示至少一个字符,用?表示0个货一个字符,用 ...

  7. linux kernel相关学习资料的收集与周边

    <<linux内核设计与实现>>读了一遍.穿线作用比较好. 收获一个网站,和三本书 https://kernelnewbies.org/ https://book.douban ...

  8. LFS7.10——构造临时Linux系统

    参考:LFS编译——准备Host系统 前言 在准备好Host环境后,接下来构造一个临时Linux系统.该系统包含****构建所需要的工具.构造临时Linux系统分两步: 构建一个宿主系统无关的新工具链 ...

  9. MySQL 5.7主从复制实战篇

    MySQL 5.7主从复制实战篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.安装MySQL数据库并启动 1>.在MySQL官方下载相应的安装包(https://dev ...

  10. react native 手动打包jsbundle文件

    1 在项目目录/android/app/src/main下建一个文件夹assets 2 react-native bundle --platform android --dev false --ent ...