亲宝软件园·资讯

展开

java jenkins构建历史 java代码获取jenkins数据,构建历史等信息方式

尤宗旭 人气:3

本篇文章主要介绍如何获取jenkins构建历史数据等信息,不包含java构建等操作。

1.jenkins所需jar,后续如有缺少可百度自行补齐。

 <!--jenkins所需jar包开始-->
 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
 <dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5</version>
 </dependency>

2.首先介绍下本次jenkins数据获取的方式,主要通过jenkins提供的rest api 接口获取数据,rest api 接口提供了获取数据展示的几种方式:

(1).XML API

(2).JSON API

(3).Python API

大家可以针对自己所有,通过以上几种方式去获取数据。

3.本次通过JSON API格式获取数据信息

(1).打开jenkins,找到rest api 进入。

(2).进入api展示如图,点击JSON API:

(3).点击JSON API数据结构展示如下,地址:http://localhost:8081/api/json?pretty=true,

可以看到以下json数据结构。同时,我们看到了自己所创建的jobs

(4).我们看到自己所创建的jobs,接下来就是对jobs下的详细信息进行获取,可以以tree的形式获取,地址:

http://localhost:8081/api/json?pretty=true&tree=jobs[*]

来获取所有job下的详细信息,通过下图我们可以发现,我们能获取到的信息都有哪些,我们可以根据自己所需去展示自己的数据,如下:

注:比如:我只想要上图中的属性:displayName、fullName、jobs我们的请求可以这样写:

展示效果如下:我们可以看到我们想要的属性,以及可以看到我想要的当前job下的allbuilds属性(当前工程构建下的所有工程构建情况)

(5).接下来就是获取jobs下的allbuilds属性,依照规则我们如下:

地址:

http://localhost:8081/api/json?pretty=true&tree=jobs[displayName[*],fullName[*],jobs[displayName[*],name[*],fullDisplayName[*],allBuilds[*]]]

这样我们就可以获取构建历史的详细信息:

1>.构建编号

2>.构建用时

3>.构建全路径

4>.构建结果

5>.构建时间

(6).以下是java代码实现,构建历史记录的获取

jenkins的MODEL:

package com.zkr.cxhjcxt.model;
import lombok.Data;
import java.util.Date;

/**
 * Created by youzongxu on 2018/9/27.
 */
@Data
public class JenkinsData extends BaseEntity<Long>{
  private static final long serialVersionUID = 2582107289140922375L;
  private String displayName;
  private String fullDisplayName;
  private String duration;
  private String fullname;
  private String sunfullname;
  private String result;
  private Date commitTime;
}

具体实现方法:

package com.zkr.cxhjcxt.timedutils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zkr.cxhjcxt.model.JenkinsData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * Created by youzongxu on 2018/9/28.
 */
@Slf4j
public class jenkinsutil {

  static String username = "";
  static String password = "";
  static String jenkinsUrl = "";

  public jenkinsutil(String u,String p,String url){
    username = u;
    password = p;
    jenkinsUrl = url;
  }

  /**
   * 获取数据
   * @return
   */
  public List<JenkinsData> getJenkinsData(){
    log.info("start");
    try {
      String urlString = jenkinsUrl + "/api/json?pretty=true&tree=jobs[jobs[allBuilds[building[*],description[*],displayName[*],fullDisplayName[*],estimatedDuration[*],duration[*],id[*],keepLog[*],number[*],queueId[*],result[*],timestamp[*]]]]";
      String jobsString = getJobs(urlString,username,password);
      if(StringUtils.isNotBlank(jobsString)){
        String builds1 = "["+jobsString+"]";
        JSONObject json = new JSONObject();
        List<Map<String, Object>> list = (List<Map<String, Object>>) json.parse(builds1);
        //获取项目名称
        String jobs = list.get(0).get("jobs").toString();
        List<JenkinsData> jenkinsDataLists = Lists.newArrayList();
        if(StringUtils.isNotBlank(jobs)){
          List<Map<String, Object>> jobs1 = (List<Map<String, Object>>) json.parse(jobs);
          for (Map<String, Object> s:jobs1) {
            String jobsx = s.get("jobs").toString();
            if(StringUtils.isNotBlank(jobsx)){
              List<Map<String, Object>> jobsxx = (List<Map<String, Object>>) json.parse(jobsx);
              for (Map<String, Object> s1 :jobsxx) {
                String allBuilds = s1.get("allBuilds").toString();
                if(StringUtils.isNotBlank(allBuilds)){
                  List<Map<String, Object>> jobsxxx = (List<Map<String, Object>>) json.parse(allBuilds);
                  for (Map<String, Object> s2 :jobsxxx) {
                    //开始
                    float duration = (float) ((int) s2.get("duration")/1000.0);
                    String result = s2.get("result").toString();
                    String displayName = s2.get("displayName").toString();
                    //处理项目名称---子项目名称
                    String fullDisplayName = s2.get("fullDisplayName").toString();
                    Long timestamp = Long.valueOf(s2.get("timestamp").toString()) ;
                    String fullname = StringUtils.isNotBlank(fullDisplayName)?fullDisplayName.substring(0,fullDisplayName.indexOf("»")):"";
                    String sunfullname = StringUtils.isNotBlank(fullDisplayName)?fullDisplayName.substring(fullDisplayName.indexOf("»")+1,fullDisplayName.indexOf("#")):"";
                    JenkinsData jenkinsData = new JenkinsData();
                    jenkinsData.setDisplayName(displayName);
                    jenkinsData.setCommitTime(new DateTime(timestamp).toDate());
                    jenkinsData.setDuration(String.valueOf(duration));
                    jenkinsData.setFullDisplayName(fullDisplayName);
                    jenkinsData.setFullname(fullname.trim());
                    jenkinsData.setSunfullname(sunfullname.trim());
                    jenkinsData.setResult(result);
                    jenkinsDataLists.add(jenkinsData);
                  }
                }
              }
            }
          }
        }
        return jenkinsDataLists;
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    log.info("end");
    return null;
  }

  /**
   * 执行语句,上面已经定义了成员变量,String username,String password可以不用传,我是后面有再次调用该方法,所以又传递了一遍,这里可以按照自己所需来处理。
   * @param urlString
   * @return
   * @throws IOException
   */
  public static String getJobs(String urlString,String username,String password)throws IOException{
    URI uri = URI.create(urlString);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpGet httpGet = new HttpGet(uri);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    HttpResponse response = httpClient.execute(host, httpGet, localContext);
    String result = EntityUtils.toString(response.getEntity());
    return result;
  }
}

以上这篇java代码获取jenkins数据,构建历史等信息方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论