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. LAMP环境搭建之编译安装指南(php-5.3.27.tar.gz)

    测试环境:CentOS release 6.5 (Final) 软件安装:httpd-2.2.27.tar.gz   mysql-5.1.72.tar.gz   php-5.3.27.tar.gz 1 ...

  2. Delphi-RzDbgrid-绘制表格式设置某行颜色或者其他格式-以及隔行换色的属性

    参考文章:https://www.cnblogs.com/OSKnown/p/8568740.html 在DbgridEh和原生的Dbgrid直接在DrawColumnCell事件中写重绘代码就好了, ...

  3. Anaconda-Jupyter notebook 如何安装 nbextensions

    系统环境:windows 安装过程中,再次遇到了一地鸡毛,经过不断查询方法,发现前辈大牛们好棒棒! Step1:确定是已经安装好anaconda Step2:要在anaconda prompt模式下运 ...

  4. MySQL Hardware--RAID级别查看

    MegaCli查看RAID级别: ## 查raid卡信息(生产商.电池信息及所支持的raid级别) /usr/local/sbin/MegaCli -AdpAllInfo -aALL |grep -E ...

  5. gitlab自带的Nginx与原Nginx冲突的解决方案

    gitlab 推荐方案2 默认情况下,gitlab使用自带的Nginx,占用80端口,这样就与系统原本安装的Nginx冲突.导致其中一个nginx无法启动 我的gitlab可以正常启动,当再部署一个接 ...

  6. c# Queue 类

  7. abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)

    Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...

  8. pandas速查手册(中文版)

    本文翻译自文章:Pandas Cheat Sheet - Python for Data Science 对于数据科学家,无论是数据分析还是数据挖掘来说,Pandas是一个非常重要的Python包.它 ...

  9. 《CoderXiaoban》第八次团队作业:Alpha冲刺5

    项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 Coderxiaoban团队 作业学习目标 (1)掌握软件测试基 ...

  10. 在eclipse运行一个项目报端口被占的问题

    1.端口被占问题解决方法. 我们运行javaweb项目的时候,如果不幸你的项目出现了上图的那种情况,不要慌,仅仅是端口被占了而已,只需要打开你tomcat里面的bin里面的shutdown.bat即可 ...