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. PowerDesigner 连接数据库,更新数据库;

    首先:以管理员身份运行Powerdesigner 一.连接服务器的某个数据库: 点击新建数据源图标 选择数据源类型:用户数据源:这里说是只用于当前机器,实际局域网里的都可以. Successfully ...

  2. Dubbo 高级特性实践-泛化调用

    引言 当后端Java服务用Dubbo协议作为RPC方案的基础,但部分消费方是前端Restful的PHP服务,不能直接调用,于是在中间架设了Router服务提供统一的基于HTTP的后端调用入口. 而Ro ...

  3. tp5 隐藏index.php

    原文——>链接 官方默认的.htaccess文件 <IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews Rewri ...

  4. 时间模块time和datetime的使用

    日期和时间 一 time模块 import time 时间的表示形式: 时间戳 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现 ...

  5. Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling

    Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapt ...

  6. docker的入门到放弃--docker基本命令

    docker的镜像中国:https://www.docker-cn.com/registry-mirror 1.搜索镜像 [root@localhost ~]# docker search tomca ...

  7. cookies插件 , axios插件,element-ui 插件

    vue-cookie插件 安装 >: cnpm install vue-cookies main.js配置 // 第一种方式 import cookies from 'vue-cookies' ...

  8. C#指针使用demo

    #region 使用指针检索数据值 //class program //{ // // 1.项目属性勾选“允许不安全代码” // // 2.使用unsafe 修饰符 // // 这里是将整个Main方 ...

  9. centos6.5下安装docker的过程办法

    转载:https://www.cnblogs.com/tymagic/p/10794477.html 在看了网上N多复制粘贴的文章,又尝试无效后,我把我最终成功的办法发出来,希望能帮到拼命干环境的你. ...

  10. Tomcat 部署多个web项目

    1.若Tomcat的端口设置为10000,则http://localhost:10000访问的目录是 webapps 2.Service.xml中host内配置Context标签,path+docba ...