本文共 5808 字,大约阅读时间需要 19 分钟。
packagecom.vip.webpagetest.utils;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.apache.http.Consts;importorg.apache.http.HttpEntity;importorg.apache.http.NameValuePair;importorg.apache.http.auth.AuthScope;importorg.apache.http.auth.UsernamePasswordCredentials;importorg.apache.http.client.CredentialsProvider;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.protocol.HttpClientContext;importorg.apache.http.entity.InputStreamEntity;importorg.apache.http.impl.client.BasicCredentialsProvider;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.core.io.ClassPathResource;importorg.springframework.core.io.Resource;import staticcom.jayway.restassured.path.json.JsonPath.with;public classJenkinsUtil {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
*
*@paramjobName
*@throwsException*/
public voidcreatJenkinsJob(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= newInputStreamEntity(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
*
*@paramjobName
*@return*@throwsException*/
public booleanisJenkinsJobExist(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 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
*
*@paramjobName
*@throwsException*/
public voiddeleteJenkinsJob(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
*
*@paramjobName
*@throwsException*/
public booleanbuildJenkinsJob(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;
}/*** 带参数的构建
*
*@paramjobName
*@paramparameters
*@return
*/
public boolean buildJenkinsJobWithParameters(String jobName, Mapparameters) {if (!isJenkinsJobExist(jobName)) {
logger.info("不存在job:" +jobName);return false;
}else{
HttpPost httpPost= new HttpPost(jenkinsBaseUrl + "/job/" + jobName + "/buildWithParameters");
List formparams = new ArrayList();for(String key : parameters.keySet()) {
formparams.add(newBasicNameValuePair(key, parameters.get(key)));
}
UrlEncodedFormEntity urlEntity= newUrlEncodedFormEntity(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构建
*
*@paramjobName
*@return*@throwsException*/
public booleanstopJenkinsJob(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= newHttpPost(
jenkinsBaseUrl+ "/job/" + jobName + "/" + buildNumber + "/stop");
httpClient.execute(stopJenkinsRequest,this.getHttpClientContext());
}catch(Exception e) {
e.printStackTrace();return false;
}return true;
}
}privateHttpClientContext getHttpClientContext() {
HttpClientContext httpClientContext=HttpClientContext.create();
httpClientContext.setCredentialsProvider(this.getCredentialsProvider());//httpClientContext.setAuthCache(this.getAuthCache());
returnhttpClientContext;
}privateCredentialsProvider getCredentialsProvider() {
CredentialsProvider credsProvider= newBasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY), newUsernamePasswordCredentials(userName, apiToken));returncredsProvider;
}public static void main(String[] args) throwsException {
Map parameters = new HashMap();
parameters.put("domain", "www.baidu.com");
parameters.put("run_id", "222");
JenkinsUtil test= newJenkinsUtil();
test.buildJenkinsJobWithParameters("www.vip.com", parameters);
}
}
转载地址:http://kqgyo.baihongyu.com/