jira 二次开发Client方式提交Issues携带文件上传附件

项目需要的jar包下载地址:https://maven.atlassian.com/maven-public/com/atlassian/util/concurrent/atlassian-util-concurrent/3.0.0/  jiraRestClient项目jar包

jsp前端页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="/style/alogin.css" rel="stylesheet" type="text/css" />
<title>创建ISSUES页面</title>
   <script src="/jquery-easyui-1.3.3/jquery.min.js"></script>
   <script src="/js/ajaxfileupload.js"></script>
</head>
<body>
<form id="form1" name="uploadFileForm" enctype="multipart/form-data">
   <div class="MAIN">
      <h4  >bug提交系统</h4>
      <ul style="width: 5700px;height: 400px; margin-top: 200px;">
         <li style="margin-top: 6px;">
               <span style="width: 20px">项目:</span>
               <select id="projectIds">
               <c:forEach items="${requestScope.porjectList}" var="pj">
                  <option value="${pj.key }">${pj.name }</option>
               </c:forEach>
               </select>
            </li>
         </li>

         <li style="margin-top: 6px;">
         <span style="width: 20px">Summary:</span>
            <input type="text" name="summary" id="summary" style="margin-left: 8px;" >
          </li>
         <li style="margin-top: 6px;">
         <span style="width: 20px">description:</span>
            <input type="text" name="description" id="description"  style="margin-left: 8px;" >
          </li>
         <div style="display: block">
         <li style="margin-top: 6px;">
            <span style="width: 20px">Priority:</span>
            <select id="priority" name="priority"  >
               <option  value="1">Highest</option>
               <option  value="2">High</option>
               <option  value="3">Medium</option>
               <option  value="4">Low</option>
               <option  value="5">Lowest</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Test Type:</span>
            <select name="testtype" id="testtype">
               <option value="10215">VPM_Crowd Test</option>
               <option value="10216">VPM_CTA Test</option>
               <option value="10217">VPM_CTS Test</option>
               <option value="10218">VPM_Smoking Test</option>
               <option value="10219">VPM_R&amp;D Special Test</option>
               <option value="10220">VPM_Field Test</option>
               <option value="10221">VPM_System Test</option>
               <option value="10222">VPM_Validation Test</option>
               <option value="10223">VPM_Validation Special Test</option>
               <option value="10224">VPM_UE Test</option>
               <option value="10225">VPM_Carrier Test(internal)</option>
               <option value="10226">VPM_Carrier Test(Formal)</option>
               <option value="10227">VPM_End User Test</option>
               <option value="10228">VPM_Unit Test</option>
               <option value="10229">VPM_lteration Test</option>
               <option value="10230">VPM_Free Test</option>
               <option value="10231">MFG_Trial-produce Test</option>
               <option value="10232">TCC_Lab Test</option>
               <option value="10233">VPM_LQA Test</option>
               <option value="10234">TCC_Baseline</option>
               <option value="10235">TCC_Tear down</option>
               <option value="10236">TCC_Environment Endurance Test</option>
               <option value="10237">TCC_Mechanical Stress Test</option>
               <option value="10238">TCC_Surface Endurace Test</option>
               <option value="10239">TCC_Baseband test</option>
               <option value="10240">TCC_Radio Frequency test</option>
               <option value="10241">VPM_CVAA</option>
               <option value="10242">VPM_Stability Test</option>
               <option value="10243">SW_UI Test</option>
               <option value="10244">SW_Trial-produce</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Affects Version:</span>
            <select name="versions" id="versions">
               <option value="15736">V1</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Importance:</span>
            <select   name="importance" id="importance">
               <option value="10100">Blocker(S1)</option>
               <option value="10101">Critical(S2)</option>
               <option value="10102">Major(S3)</option>
               <option value="10103">Minor(S4)</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Bug Type:</span>
            <select  name="bugType" id="bugType">
               <option value="10123">New Appeared</option>
               <option value="10124">New Detected</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Bug Range:</span>
            <select  name="bugRange" id="bugRange">
               <option value="10125">Common</option>
               <option value="10126">Device Specific</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Component/s:</span>
            <select id="component" name="component">
               <option title="Jenkins设置  - Jenkins设置页面问题" value="10609">Jenkins设置</option>
               <option title="Slave管理  - Slave管理页面问题" value="10607">Slave管理</option>
               <option title="测试任务列表  - 测试任务列表页面问题" value="10606">测试任务列表</option>
               <option title="测试模块管理  - 测试模块管理页面问题" value="10604">测试模块管理</option>
               <option title="测试用例管理  - 测试用例管理页面问题" value="10603">测试用例管理</option>
               <option title="测试项目列表  - 测试项目列表页面问题" value="10605">测试项目列表</option>
               <option title="站点管理员  - 站点管理员页面问题" value="10602">站点管理员</option>
               <option title="站点管理员组  - 站点管理员组页面问题" value="10601">站点管理员组</option>
               <option title="邮件系统设置  - 邮件系统设置页面问题" value="10608">邮件系统设置</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">Product:</span>
            <select name="product" id="product">
               <option value="10313">NULL</option>
            </select>
         </li>
         <li style="margin-top: 6px;">
            <span style="width: 20px">HW status:</span>
            <select class="select cf-select" name="hwStatws" id="hwStatws">
               <option value="10148">EVT</option>
               <option value="10149">DVT1</option>
               <option value="10150">DVT2</option>
               <option value="10151">DVT3</option>
               <option value="10152">PVT1</option>
               <option value="10153">PVT2</option>
               <option value="10154">PVT3</option>
               <option value="10155">SOVP1</option>
               <option value="10156">SOVP2</option>
               <option value="10157">SS</option>
               <option value="10158">MP</option>
               <option value="10159">DVT</option>
               <option value="10160">PVT</option>
            </select>
         </li>
         </div>
         <li style="margin-top: 6px;">
            <span style="width: 20px">附件:</span>
            <input type="file" name="uploadFile" id="jfPath" >
         </li>

      </ul>
   </div>
</form>
<span class="btn" id="btn">  <button style="margin-left: 500px;margin-top: -20px;background-color: #00ee00;">提交</button></span>
<script>    $(function () {
    $('#btn').click(function() {
        $.ajaxFileUpload({
            async: true,
            url: "/jira/add",
            type: 'post',
            dataType: 'json',
            fileElementId:'jfPath',
            data: {
                jfPath: $("#jfPath").val(),
                jfName: $("#jfPath").val(),
                projectName:$("#projectIds").val(),
                jiraProject:$("#projectIds").val(),
                summary:$("#summary").val(),
                description:$("#description").val(),
                hwStatus:$("#hwStatws").val(),
                component:$("#component").val(),
                bugType:$("#bugType").val(),
                bugRange:$("#bugRange").val(),
                testType:$("#testtype").val(),
                importance:$("#importance").val(),
                version:$("#versions").val(),
                products:$("#product").val(),
                priority:$("#priority").val(),
            },
            success: function(result){
                alert(result.msg);
            },
            error: function() {
                alert("提交bug出现问题了");
            }
        });
    });

})

</script>
</body>
</html>

上传文件依赖的js ajaxsfileupload.js

jQuery.extend({
    createUploadIframe: function(id, uri)
    {
        //create frame
        var frameId = 'jUploadFrame' + id;

        if(window.ActiveXObject) {
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if(typeof uri== 'boolean'){
                io.src = 'javascript:false';
            }
            else if(typeof uri== 'string'){
                io.src = uri;
            }
        }
        else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function(id, fileElementId, data)
    {
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);

        //增加文本参数的支持
        if (data) {
            for (var i in data) {
                $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
            }
        }

        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');
        return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout      
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
        {
            var io = document.getElementById(frameId);
            try
            {
                if(io.contentWindow)
                {
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }else if(io.contentDocument)
                {
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            }catch(e)
            {
                jQuery.handleError(s, xml, null, e);
            }
            if ( xml || isTimeout == "timeout")
            {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
                {  try
                {
                    $(io).remove();
                    $(form).remove();

                } catch(e)
                {
                    jQuery.handleError(s, xml, null, e);
                }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 )
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try
        {
            // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if(form.encoding)
            {
                form.encoding = 'multipart/form-data';
            }
            else
            {
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return {abort: function () {}};

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if (type == "json" || type == "JSON") {
            var reg = /<pre.+?>(.+)<\/pre>/g;
            var result = data.match(reg);
            data = $.parseJSON(RegExp.$1);
            return data;
        }
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
        //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    },

    handleError: function( s, xhr, status, e )      {
// If a local callback was specified, fire it
        if ( s.error ) {
            s.error.call( s.context || s, xhr, status, e );
        }

        // Fire the global callback
        if ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
        }
    }
});

实体类:JiraBug

package com.cn.jira.entity;

import java.util.Calendar;


public class JiraBug  implements java.io.Serializable {

   private String bugId;

   private String bugKey;

   private String projectName;

   private String jiraProject;

   private String hunter;

   private String affectsVersion;

   private Calendar created;

   private String component;

   private String bugRange;

   private String repetitionProbability;

   private String bugType;

   private String testType;

   private String importance;

   private String importanceType;

   private String hwStatus;

   private String ueImpactLevel;

   private String appVersion;

   private String coreVersion;

   private String caseId;

   private String city;

   private String products;

   private String needVerifyProducts;

   private String summary;

   private String description;

   private String ueas;

   private String comment;

   private String status;

   private String jfName;
   private String jfPath;

   public String getJfName() {
      return jfName;
   }

   public String getJfPath() {
      return jfPath;
   }

   public void setJfName(String jfName) {
      this.jfName = jfName;
   }

   public void setJfPath(String jfPath) {
      this.jfPath = jfPath;
   }

   /**
    * @return the bugKey
    */
   public String getBugKey() {
      return bugKey;
   }

   /**
    * @param bugKey the bugKey to set
    */
   public void setBugKey(String bugKey) {
      this.bugKey = bugKey;
   }

   public String getComment() {
      return comment;
   }

   public void setComment(String comment) {
      this.comment = comment;
   }

   public String getBugId() {
      return bugId;
   }

   public void setBugId(String bugId) {
      this.bugId = bugId;
   }

   public String getProjectName() {
      return projectName;
   }

   public void setProjectName(String projectName) {
      this.projectName = projectName;
   }

   public String getJiraProject() {
      return jiraProject;
   }

   public void setJiraProject(String jiraProject) {
      this.jiraProject = jiraProject;
   }

   public String getHunter() {
      return hunter;
   }

   public void setHunter(String hunter) {
      this.hunter = hunter;
   }

   public String getAffectsVersion() {
      return affectsVersion;
   }

   public void setAffectsVersion(String affectsVersion) {
      this.affectsVersion = affectsVersion;
   }

   public Calendar getCreated() {
      return created;
   }

   public void setCreated(Calendar created) {
      this.created = created;
   }

   public String getComponent() {
      return component;
   }

   public void setComponent(String component) {
      this.component = component;
   }

   public String getBugRange() {
      return bugRange;
   }

   public void setBugRange(String bugRange) {
      this.bugRange = bugRange;
   }

   public String getRepetitionProbability() {
      return repetitionProbability;
   }

   public void setRepetitionProbability(String repetitionProbability) {
      this.repetitionProbability = repetitionProbability;
   }

   public String getBugType() {
      return bugType;
   }

   public void setBugType(String bugType) {
      this.bugType = bugType;
   }

   public String getTestType() {
      return testType;
   }

   public void setTestType(String testType) {
      this.testType = testType;
   }

   public String getImportance() {
      return importance;
   }

   public void setImportance(String importance) {
      this.importance = importance;
   }

   public String getImportanceType() {
      return importanceType;
   }

   public void setImportanceType(String importanceType) {
      this.importanceType = importanceType;
   }

   public String getHwStatus() {
      return hwStatus;
   }

   public void setHwStatus(String hwStatus) {
      this.hwStatus = hwStatus;
   }

   public String getUeImpactLevel() {
      return ueImpactLevel;
   }

   public void setUeImpactLevel(String ueImpactLevel) {
      this.ueImpactLevel = ueImpactLevel;
   }

   public String getAppVersion() {
      return appVersion;
   }

   public void setAppVersion(String appVersion) {
      this.appVersion = appVersion;
   }

   public String getCoreVersion() {
      return coreVersion;
   }

   public void setCoreVersion(String coreVersion) {
      this.coreVersion = coreVersion;
   }

   public String getCaseId() {
      return caseId;
   }

   public void setCaseId(String caseId) {
      this.caseId = caseId;
   }

   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }

   public String getProducts() {
      return products;
   }

   public void setProducts(String products) {
      this.products = products;
   }

   public String getNeedVerifyProducts() {
      return needVerifyProducts;
   }

   public void setNeedVerifyProducts(String needVerifyProducts) {
      this.needVerifyProducts = needVerifyProducts;
   }

   public String getSummary() {
      return summary;
   }

   public void setSummary(String summary) {
      this.summary = summary;
   }

   public String getDescription() {
      return description;
   }

   public void setDescription(String description) {
      this.description = description;
   }

   /**
    * @return the ueas
    */
   public String getUeas() {
      return ueas;
   }

   /**
    * @param ueas the ueas to set
    */
   public void setUeas(String ueas) {
      this.ueas = ueas;
   }

   /**
    * @return the status
    */
   public String getStatus() {
      return status;
   }

   /**
    * @param status the status to set
    */
   public void setStatus(String status) {
      this.status = status;
   }

}
controller文件代码

package com.cn.jira.controller;


import com.atlassian.jira.rest.client.JiraRestClient;
import com.cn.jira.commons.Response;
import com.cn.jira.entity.JiraBug;
import com.cn.jira.utils.JiraApi;

import com.cn.jira.utils.MediaTypes;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping({ "/jira" })
public class JiraController {

   public static final JiraRestClient restClient = JiraApi.getRestClient();

   @RequestMapping(value = "add", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
   @ResponseBody
   public Response addIssuceMethod (MultipartFile uploadFile, HttpServletRequest request, JiraBug jiraBug) {
      if((uploadFile!=null)&&(uploadFile.getSize()<=0)){
         return  Response.error( "300","请选择上传文件!");
      }

      try {
            File file = new File(uploadFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file);
            System.out.println(jiraBug.getJfName());
            String returnIssueKey  = JiraApi.addIssueComplex(restClient,jiraBug,file);
            System.out.println("bug提交成功-"+returnIssueKey);
            return Response.ok("200","bug提交成功-"+returnIssueKey);
         } catch (Exception e) {
            e.printStackTrace();
            return  Response.error("300","bug提交错误请稍后再试!");
         }
   }

   @RequestMapping("/addJsp")
   public ModelAndView home(){
      List<Map<String,String>> allProjectList = new ArrayList<Map<String,String>>();
      try {
         allProjectList = JiraApi.getAllProjects(restClient);
      } catch (InterruptedException e) {
         e.printStackTrace();
      } catch (ExecutionException e) {
         e.printStackTrace();
      }
      //addIssue
      return new ModelAndView("addIssue","porjectList",allProjectList);
   }

}
api工具调用

package com.cn.jira.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import com.cn.jira.config.SecurityUtils;
import com.cn.jira.entity.JiraBug;
import com.cn.jira.entity.MssStaff;
import org.joda.time.DateTime;
import com.atlassian.jira.rest.client.IssueRestClient;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.SearchRestClient;
import com.atlassian.jira.rest.client.domain.BasicComponent;
import com.atlassian.jira.rest.client.domain.BasicIssue;
import com.atlassian.jira.rest.client.domain.BasicProject;
import com.atlassian.jira.rest.client.domain.Comment;
import com.atlassian.jira.rest.client.domain.Field;
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.domain.Project;
import com.atlassian.jira.rest.client.domain.SearchResult;
import com.atlassian.jira.rest.client.domain.Transition;
import com.atlassian.jira.rest.client.domain.Version;
import com.atlassian.jira.rest.client.domain.input.ComplexIssueInputFieldValue;
import com.atlassian.jira.rest.client.domain.input.IssueInput;
import com.atlassian.jira.rest.client.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;
import com.google.common.collect.Lists;

public class JiraApi {

    public static String BaseURL = "http://tbjira.lenovo.com:8081/issue";
    public static MssStaff mssStaffs = SecurityUtils.newStaff;
    public static String User ="username";
    public static String Password ="password";
    private static URI jiraServerUri = URI.create("http://tbjira.lenovo.com:8081/issue/rest/api/2/");
    private static String jiraAttachementUri = "http://tbjira.lenovo.com:8081/issue/rest/api/2/issue/{key}/attachments";
    private static boolean quiet = false;
    private static final long TASK_TYPE_ID = 3L; // JIRA magic value
    private static final DateTime DUE_DATE = new DateTime();
    private static final String PRIORITY = "Highest";
    public static JiraRestClient jiraRestClient = null;

    public static JiraRestClient getRestClient(){
       if(jiraRestClient==null){
           try {
               final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
               jiraServerUri = new URI(BaseURL);
               jiraRestClient= (JiraRestClient) factory.createWithBasicHttpAuthentication(jiraServerUri, User,Password);

           } catch (URISyntaxException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           } finally {

           }
       }
           return  jiraRestClient;
    }

    public static void main(String[] args) throws InterruptedException,
            ExecutionException, Exception {

        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        URI jiraServerUri;
        try {
            jiraServerUri = new URI(BaseURL);
            final JiraRestClient restClient = (JiraRestClient) factory.createWithBasicHttpAuthentication(jiraServerUri, User,Password);
            getAllProjects(restClient);
//            getProject(restClient, "DEMO");
//            getIssue(restClient, "FEEDBACK-14");
//            getIssueFields(restClient, "FEEDBACK-27");
//            addIssue(restClient, "FEEDBACK", "AAAAB");
//            JiraBug jiraBug = new JiraBug();
//            jiraBug.setSummary(DUE_DATE.toString()+"ccccAAAA");
//            jiraBug.setJiraProject("TLAUTOTEST");
//            File file = new File("E:\\cc.txt");
//            addIssueComplex(restClient,jiraBug,file);
             
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }
    
    
    private static void println(Object o) {
        if (!quiet) {
            System.out.println(o);
        }
    }

    private static void parseArgs(String[] argsArray) throws URISyntaxException {
        final List<String> args = Lists.newArrayList(argsArray);
        if (args.contains("-q")) {
            quiet = true;
            args.remove(args.indexOf("-q"));
        }

        if (!args.isEmpty()) {
            jiraServerUri = new URI(args.get(0));
        }
    }

    private static Transition getTransitionByName(
            Iterable<Transition> transitions, String transitionName) {
        for (Transition transition : transitions) {
            if (transition.getName().equals(transitionName)) {
                return transition;
            }
        }
        return null;
    }

    // 得到所有项目信息
        public static List<Map<String,String>> getAllProjects(final JiraRestClient restClient)  throws InterruptedException, ExecutionException {
        List<Map<String,String>> lstResult=new ArrayList<Map<String,String>>();

            Promise<Iterable<BasicProject>> list = restClient.getProjectClient().getAllProjects();
            Iterable<BasicProject> a = list.get();
            Iterator<BasicProject> it = a.iterator();
            while (it.hasNext()) {
                Map dataMap = new HashMap();
                BasicProject projectss = it.next();
                dataMap.put("key", projectss.getKey());
                dataMap.put("name", projectss.getName());
                lstResult.add(dataMap);
            }
                return  lstResult;
    }

    // 得到单一项目信息
    private static Project getProject(final JiraRestClient restClient,
            String porjectKEY) throws InterruptedException, ExecutionException {
        try {

            Project project = restClient.getProjectClient()
                    .getProject(porjectKEY).get();
            System.out.println(project);
             return project;
        } finally {
        }
    }

    // 得到单一问题信息
    private static void getIssue(final JiraRestClient restClient,
            String issueKEY) throws InterruptedException, ExecutionException {
        try {

            Promise<Issue> list = restClient.getIssueClient()
                    .getIssue(issueKEY);
            Issue issue = list.get();
            System.out.println(issue);

        } finally {
        }
    }
    
    // 创建问题
    public static BasicIssue createIssue(final JiraRestClient jiraRestClient,
            IssueInput newIssue) {
        BasicIssue basicIssue = jiraRestClient.getIssueClient()
                .createIssue(newIssue).claim();
        return basicIssue;
    }
    
    //添加备注到问题
    public static void addCommentToIssue(final JiraRestClient jiraRestClient,Issue issue, String comment) {
        IssueRestClient issueClient = jiraRestClient.getIssueClient();
        issueClient.addComment(issue.getCommentsUri(), Comment.valueOf(comment)).claim();
    }
    
    
    //删除问题,目前找不到对应API
    public static void deleteIssue(final JiraRestClient jiraRestClient, Issue issue) {
        IssueRestClient issueClient = jiraRestClient.getIssueClient();
        //issueClient.deleteIssue(issue.getKey(), false).claim();
    }

    //通过标题获取问题
    public static Iterable findIssuesByLabel(final JiraRestClient jiraRestClient, String label) {
        SearchRestClient searchClient = jiraRestClient.getSearchClient();
        String jql = "labels%3D"+label;
        SearchResult results = ((SearchRestClient) jiraRestClient).searchJql(jql).claim();
        return results.getIssues();
    }

    //通过KEY获取问题
    public static Issue findIssueByIssueKey(final JiraRestClient jiraRestClient, String issueKey) {
        SearchRestClient searchClient = jiraRestClient.getSearchClient();
        String jql = "issuekey = \"" + issueKey + "\"";
        SearchResult results = searchClient.searchJql(jql).claim();
        return (Issue) results.getIssues().iterator().next();
    }

    // 创建问题 :仅有简单问题名称
    private static void addIssue(final JiraRestClient restClient,
            String porjectKEY, String issueName) throws InterruptedException,
            ExecutionException {
        try {
            IssueInputBuilder builder = new IssueInputBuilder(porjectKEY,TASK_TYPE_ID, issueName);
            builder.setDescription("issue description");
            final IssueInput input = builder.build();

            try {
                // create issue
                final IssueRestClient client = restClient.getIssueClient();
                final BasicIssue issue = client.createIssue(input).claim();
                final Issue actual = client.getIssue(issue.getKey()).claim();
                System.out.println(actual);
            } finally {
                if (restClient != null) {
                    // restClient.close();
                }
            }

        } finally {
        }
    }

    // 创建问题 :包含自定义字段
    public static String addIssueComplex(final JiraRestClient restClient, JiraBug jiraBug,File file) throws InterruptedException,ExecutionException, FileNotFoundException {
       String returnIssueKey = "";
        try {
            IssueInputBuilder builder = new IssueInputBuilder(jiraBug.getJiraProject(),TASK_TYPE_ID, jiraBug.getSummary());
            builder.setSummary(jiraBug.getSummary());
            builder.setProjectKey(jiraBug.getJiraProject());
            
            builder.setDescription("issue aaaaaaaaa");
            builder.setFieldValue("issuetype", ComplexIssueInputFieldValue.with("name", "Bug"));
            builder.setFieldValue("priority", ComplexIssueInputFieldValue.with("name", PRIORITY));
            //单行文本
            builder.setFieldValue("customfield_10107", ComplexIssueInputFieldValue.with("id", "10148"));
            builder.setFieldValue("customfield_10121", ComplexIssueInputFieldValue.with("id", "10215"));
            builder.setFieldValue("customfield_10100", ComplexIssueInputFieldValue.with("id", "10103"));
            builder.setFieldValue("customfield_10200", ComplexIssueInputFieldValue.with("id", "10313"));
            builder.setFieldValue("customfield_10102", ComplexIssueInputFieldValue.with("id", "10123"));
            builder.setFieldValue("customfield_10103", ComplexIssueInputFieldValue.with("id", "10125"));
            builder.setAffectedVersions(getProject(restClient, jiraBug.getJiraProject()).getVersions());
            builder.setComponents(getProject(restClient, jiraBug.getJiraProject()).getComponents());
             
            final IssueInput input = builder.build();
            try {
               final IssueRestClient client = restClient.getIssueClient();
               final BasicIssue issue = client.createIssue(input).claim();

               InputStream finInputStream = new FileInputStream(file);
               String newAttchentUrl = jiraAttachementUri.replace("{key}", issue.getKey());
               URI newFileUrl = URI.create(newAttchentUrl);
                client.addAttachment(newFileUrl, finInputStream, file.getName());
                final Issue actual = client.getIssue(issue.getKey()).claim();
                returnIssueKey = issue.getKey();
                System.out.println("提交bug返回key:"+issue.getKey());
            } finally {
                if (restClient != null) {
                    // restClient.close();
                }
            }
             

        } finally {
        }
        return returnIssueKey;
    }
    
    //获取问题的所有字段
    private static void getIssueFields(final JiraRestClient restClient,
            String issueKEY) throws InterruptedException, ExecutionException {
        try {

            Promise<Issue> list = restClient.getIssueClient()
                    .getIssue(issueKEY);
            Issue issue = list.get();
            Iterable<Field> fields = issue.getFields();
            Iterator<Field> it = fields.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }

        } finally {
        }
    }

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值