Java鏈接Jira,建立、修改、刪除工單信息

還不瞭解Jira是什麼的同窗能夠看一下這篇文章:http://www.javashuo.com/article/p-fduihrop-m.htmlhtml

 

本篇文章主要介紹如何使用Java操做Jira,包括獲取鏈接,建立、修改、刪除工單信息java

 

一、獲取Jira鏈接並執行請求:

/**
     * 執行shell腳本
     *
     * @param command
     * @return
     * @throws IOException
     */
    private static String executeShell(String command) throws IOException {
        StringBuffer result = new StringBuffer();
        Process process = null;
        InputStream is = null;
        BufferedReader br = null;
        String line = null;
        try {
            //windows平臺下用cmd發生請求
            if (osname.indexOf("windows") >= 0) {
                process = new ProcessBuilder("cmd.exe", "/c", command).start();
                System.out.println("cmd.exe /c " + command); //安裝Cygwin,使windows能夠執行linux命令
            } else {
                //linux平臺下執行請求
                process = new ProcessBuilder("/bin/sh", "-c", command).start();
                System.out.println("/bin/sh -c " + command);
            }

            is = process.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((line = br.readLine()) != null) {
                System.out.println(line);
                result.append(line);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            //關閉鏈接
            br.close();
            process.destroy();
            is.close();
        }

        //返回結果
        return result.toString();
    }

  

 

二、獲取得到工單信息:

/**
     * 活動工單信息
     *
     * @param issueKey
     *            工單key
     * @return
     * @throws IOException
     */
    public static String getIssue(String issueKey) throws IOException {

        /**
         * jira的請求格式:
         * curl -u 用戶名:密碼 -X 請求類型 --data @文件的路徑 -H "Content-Type: application/json" 請求路徑
         * 
         * 官方示例:curl -u admin:admin -X POST --data @data.txt -H "Content-Type: application/json" http://localhost:8080/jira/rest/api/2/issue/
         *
         *  注意:--data後面的 @符合必定不能少
         */

        String command = "curl -D- -u " + user + ":" + pwd
                + " -X GET -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/issue/" + issueKey + "\"";

        String issueSt = executeShell(command);

        return issueSt;

    }

  

 

三、建立工單信息:

/**
     * 建立工單
     *
     * @param projectKey
     *            項目key
     * @param issueType
     *            工單類型 name
     * @param description
     *            工單描述
     * @param summary
     *            工單主題
    //     * @param assignee
     *            工單負責人
     *          
     * @return
     * @throws IOException
     */
    public static String createIssue(String projectKey, String issueType,String user,
                                     String description, String summary) throws IOException {

        String command="curl -D- -u " + user + ":" + pwd
                + " -X POST  --data @E:\\data.json -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/issue/\"";

        String issueSt = executeShell(command);

        if (!issueSt.contains("errorMessages")) {
            System.out.println("success");
        }else {
            System.out.println("error");
        }
        return issueSt;
    }

  

這裏建立工單信息的文件我存放在了我電腦E盤根目錄下面,名字爲data.jsonlinux

data.json的內容以下shell

{
    "fields": {
        "summary": "test008", 
        "issuetype": {
            "name": "Task"
        },
        "project": {
            "key": "MIN"
        },
        "description": "測試008",
        "assignee": {
            "name": "jwg"
        }
    }
}

  

  1. summary:工單主題
  2. issuetype:問題類型,問題類型是jira項目中存在的類型
  3. project:工單所屬項目,工單所屬項目是Jira中已經建立的項目
  4. description:工單描述,一些描述信息
  5. assignee:工單負責人,這個工單的負責人是誰

 

注意:data.json格式必須爲json格式

 

四、更新工單信息:

/**
     * 更新工單
     *
     * @param issueKey
     *            工單key
     * @param map
     *            工單參數map,key爲參數名稱,value爲參數值,參數值必須自帶雙引號 好比: map.put("assignee",
     *            "{\"name\":\"username\"}"); map.put("summary",
     *            "\"summary00002\"");
     * @return
     * @throws IOException
     */
    public static String editIssue(String issueKey, Map<String, String> map)
            throws IOException {

        StringBuffer fieldsB = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            fieldsB.append("\"").append(entry.getKey()).append("\":")
                    .append(entry.getValue()).append(",");
        }
        String fields = fieldsB.toString();
        fields = fields.substring(0, fields.length() - 1);

        String command = "curl -D- -u " + user + ":" + pwd
                + " -X PUT   --data '{\"fields\": { " + fields
                + "}}' -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/issue/" + issueKey + "\"";

        String issueSt = executeShell(command);

        return issueSt;
    }

  

 

五、查詢工單信息:

/**
     * 查詢工單
     * @param jql
     * assignee=username
     * assignee=username&startAt=2&maxResults=2
     * assignee=username+order+by+duedate
     * project=projectKey+order+by+duedate&fields=id,key
     * @return
     * @throws IOException
     */
    public static String searchIssues(String jql) throws IOException{
        String command = "curl -D- -u " + user + ":" + pwd
                + " -X GET -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/search?jql=" + jql + "\"";

        String issueSt = executeShell(command);

        return issueSt;
    }

  

 

六、爲工單增長註釋:

/**
     * 爲工單增長註釋說明
     * @param issueKey 工單key

     *
     */
    public static String addComments(String issueKey,String comments) throws IOException{
        String command = "curl -D- -u " + user + ":" + pwd
                + " -X PUT   --data '{\"update\": { \"comment\": [ { \"add\": { \"body\":\""+comments+"\" } } ] }}' -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/issue/" + issueKey + "\"";

        String issueSt = executeShell(command);

        return issueSt;
    }

  

 

七、刪除工單:

/**
     * 刪除工單
     * @param issueKey 工單key
     * @return
     * @throws IOException
     */
    public static String deleteIssueByKey(String issueKey) throws IOException{
        String command = "curl -D- -u " + user + ":" + pwd
                + " -X DELETE -H \"Content-Type: application/json\" \"" + uri
                + "/rest/api/2/issue/" + issueKey + "\"";

        String issueSt = executeShell(command);

        return issueSt;
    }

  

 

八、上傳附件:

/**
     * 上傳附件
     * @param issueKey 工單key
     * @param filepath 文件路徑
     * @return
     * @throws IOException
     */
    public static String addAttachment(String issueKey,String filepath) throws IOException{
        String command = "curl -D- -u " + user + ":" + pwd
                + " -X POST -H \"X-Atlassian-Token: nocheck\"  -F \"file=@"+filepath+"\" \"" + uri
                + "/rest/api/2/issue/" + issueKey + "/attachments\"";

        String issueSt = executeShell(command);

        return issueSt;
    }

  

 

項目的完整代碼以下:json

  1 import java.io.BufferedReader;
  2 import java.io.IOException;
  3 import java.io.InputStream;
  4 import java.io.InputStreamReader;
  5 import java.util.Map;
  6 
  7 /**
  8  * JIRA REST API 工具類
  9  * https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials
 10  * https://docs.atlassian.com/jira/REST/7.0-SNAPSHOT/
 11  * @author 用代碼征服天下
 12  *
 13  */
 14 public class JiraTest {
 15 
 16     public static void main(String[] args) throws IOException {
 17         // TODO Auto-generated method stub
 18         //獲取工單信息,參數爲問題名稱
 19         JiraAPIUtil.getIssue("OAM-5402");
 20 
 21         JiraAPIUtil.createIssue("MIN", "Task", "jwg", "工單描述","工單主題");
 22 //
 23 //         Map<String,String> map = new HashMap<String,String>();
 24 //         map.put("assignee", "{\"name\":\"username\"}");
 25 //         map.put("summary", "\"summary00002\"");
 26 //         JiraAPIUtil.editIssue("MIN-1", map);
 27 
 28         JiraAPIUtil.searchIssues("assignee=username");
 29         System.out.println("*****************************");
 30         JiraAPIUtil.searchIssues("assignee=username+order+by+duedate");
 31         System.out.println("*****************************");
 32 
 33         JiraAPIUtil.addComments("MIN-1", "123456哈哈哈哈");
 34         JiraAPIUtil.deleteIssueByKey("NQCP-38");
 35         JiraAPIUtil.addAttachment("NQCP-39", "d://myfile01.json");  //linux路徑:   /home/boss/myfile.txt
 36         JiraAPIUtil.addComments("createmeta", "123456哈哈哈哈");
 37     }
 38 
 39     static String uri = "http://localhost:8080"; //Jira服務器地址
 40     static String user = "jwg";//Jira用戶名
 41     static String pwd = "jwg123456";//Jira密碼
 42     static String osname = System.getProperty("os.name").toLowerCase(); //獲取操做系統名稱
 43 
 44     /**
 45      * 執行shell腳本
 46      *
 47      * @param command
 48      * @return
 49      * @throws IOException
 50      */
 51     private static String executeShell(String command) throws IOException {
 52         StringBuffer result = new StringBuffer();
 53         Process process = null;
 54         InputStream is = null;
 55         BufferedReader br = null;
 56         String line = null;
 57         try {
 58             //windows平臺下用cmd發生請求
 59             if (osname.indexOf("windows") >= 0) {
 60                 process = new ProcessBuilder("cmd.exe", "/c", command).start();
 61                 System.out.println("cmd.exe /c " + command); //安裝Cygwin,使windows能夠執行linux命令
 62             } else {
 63                 //linux平臺下執行請求
 64                 process = new ProcessBuilder("/bin/sh", "-c", command).start();
 65                 System.out.println("/bin/sh -c " + command);
 66             }
 67 
 68             is = process.getInputStream();
 69             br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 70 
 71             while ((line = br.readLine()) != null) {
 72                 System.out.println(line);
 73                 result.append(line);
 74             }
 75 
 76         } catch (Exception e) {
 77             // TODO Auto-generated catch block
 78             e.printStackTrace();
 79         } finally {
 80             //關閉鏈接
 81             br.close();
 82             process.destroy();
 83             is.close();
 84         }
 85 
 86         //返回結果
 87         return result.toString();
 88     }
 89 
 90     /**
 91      * 活動工單信息
 92      *
 93      * @param issueKey
 94      *            工單key
 95      * @return
 96      * @throws IOException
 97      */
 98     public static String getIssue(String issueKey) throws IOException {
 99 
100         /**
101          * jira的請求格式:
102          * curl -u 用戶名:密碼 -X 請求類型 --data @文件的路徑 -H "Content-Type: application/json" 請求路徑
103          *
104          * 官方示例:curl -u admin:admin -X POST --data @data.txt -H "Content-Type: application/json" http://localhost:8080/jira/rest/api/2/issue/
105          *
106          *  注意:--data後面的 @符合必定不能少
107          */
108 
109         String command = "curl -D- -u " + user + ":" + pwd
110                 + " -X GET -H \"Content-Type: application/json\" \"" + uri
111                 + "/rest/api/2/issue/" + issueKey + "\"";
112 
113         String issueSt = executeShell(command);
114 
115         return issueSt;
116 
117     }
118 
119     /**
120      * 建立工單
121      *
122      * @param projectKey
123      *            項目key
124      * @param issueType
125      *            工單類型 name
126      * @param description
127      *            工單描述
128      * @param summary
129      *            工單主題
130     //     * @param assignee
131      *            工單負責人
132      *            工單參數map,key爲參數名稱,value爲參數值,參數值必須自帶雙引號 好比: map.put("assignee",
133      *            "{\"name\":\"username\"}"); map.put("summary",
134      *            "\"summary00002\"");
135      * @return
136      * @throws IOException
137      */
138     public static String createIssue(String projectKey, String issueType,String user,
139                                      String description, String summary) throws IOException {
140 
141         String command="curl -D- -u " + user + ":" + pwd
142                 + " -X POST  --data @E:\\data.json -H \"Content-Type: application/json\" \"" + uri
143                 + "/rest/api/2/issue/\"";
144 
145         String issueSt = executeShell(command);
146 
147         if (!issueSt.contains("errorMessages")) {
148             System.out.println("success");
149         }else {
150             System.out.println("error");
151         }
152         return issueSt;
153     }
154 
155 
156 
157 
158 
159 
160     /**
161      * 更新工單
162      *
163      * @param issueKey
164      *            工單key
165      * @param map
166      *            工單參數map,key爲參數名稱,value爲參數值,參數值必須自帶雙引號 好比: map.put("assignee",
167      *            "{\"name\":\"username\"}"); map.put("summary",
168      *            "\"summary00002\"");
169      * @return
170      * @throws IOException
171      */
172     public static String editIssue(String issueKey, Map<String, String> map)
173             throws IOException {
174 
175         StringBuffer fieldsB = new StringBuffer();
176         for (Map.Entry<String, String> entry : map.entrySet()) {
177             fieldsB.append("\"").append(entry.getKey()).append("\":")
178                     .append(entry.getValue()).append(",");
179         }
180         String fields = fieldsB.toString();
181         fields = fields.substring(0, fields.length() - 1);
182 
183         String command = "curl -D- -u " + user + ":" + pwd
184                 + " -X PUT   --data '{\"fields\": { " + fields
185                 + "}}' -H \"Content-Type: application/json\" \"" + uri
186                 + "/rest/api/2/issue/" + issueKey + "\"";
187 
188         String issueSt = executeShell(command);
189 
190         return issueSt;
191     }
192 
193 
194 
195     /**
196      * 查詢工單
197      * @param jql
198      * assignee=username
199      * assignee=username&startAt=2&maxResults=2
200      * assignee=username+order+by+duedate
201      * project=projectKey+order+by+duedate&fields=id,key
202      * @return
203      * @throws IOException
204      */
205     public static String searchIssues(String jql) throws IOException{
206         String command = "curl -D- -u " + user + ":" + pwd
207                 + " -X GET -H \"Content-Type: application/json\" \"" + uri
208                 + "/rest/api/2/search?jql=" + jql + "\"";
209 
210         String issueSt = executeShell(command);
211 
212         return issueSt;
213     }
214 
215 
216     /**
217      * 爲工單增長註釋說明
218      * @param issueKey 工單key
219 
220      *
221      */
222     public static String addComments(String issueKey,String comments) throws IOException{
223         String command = "curl -D- -u " + user + ":" + pwd
224                 + " -X PUT   --data '{\"update\": { \"comment\": [ { \"add\": { \"body\":\""+comments+"\" } } ] }}' -H \"Content-Type: application/json\" \"" + uri
225                 + "/rest/api/2/issue/" + issueKey + "\"";
226 
227         String issueSt = executeShell(command);
228 
229         return issueSt;
230     }
231 
232 
233     /**
234      * 刪除工單
235      * @param issueKey 工單key
236      * @return
237      * @throws IOException
238      */
239     public static String deleteIssueByKey(String issueKey) throws IOException{
240         String command = "curl -D- -u " + user + ":" + pwd
241                 + " -X DELETE -H \"Content-Type: application/json\" \"" + uri
242                 + "/rest/api/2/issue/" + issueKey + "\"";
243 
244         String issueSt = executeShell(command);
245 
246         return issueSt;
247     }
248 
249 
250     /**
251      * 上傳附件
252      * @param issueKey 工單key
253      * @param filepath 文件路徑
254      * @return
255      * @throws IOException
256      */
257     public static String addAttachment(String issueKey,String filepath) throws IOException{
258         String command = "curl -D- -u " + user + ":" + pwd
259                 + " -X POST -H \"X-Atlassian-Token: nocheck\"  -F \"file=@"+filepath+"\" \"" + uri
260                 + "/rest/api/2/issue/" + issueKey + "/attachments\"";
261 
262         String issueSt = executeShell(command);
263 
264         return issueSt;
265     }
266 
267 }
Jira完整代碼
相關文章
相關標籤/搜索