2014年5月5日 星期一

透過 HttpClient 利用 JIRA Rest API 產生/修改 JIRA Issue


首先要下載兩個 lib,分別為 HttpClient 及JSON Simple
共有下面五個 jar file

httpclient-4.3.3.jar
httpclient-cache-4.3.3.jar
httpcore-4.3.2.jar
httpmime-4.3.3.jar
json-simple-1.1.1.jar

JIRA Rest API 可參考
https://docs.atlassian.com/jira/REST/6.2.4/

範例程式如下:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.ResponseHandler;
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.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JiraRestApiUsingHttpClient {
    private String hostURL = "http://[HOST_NAME]";
    private String restApiURL = "/rest/api/2";
    private String adminLoginURL = "http://[HOST_NAME]/login.jsp?os_username=[ADMIN_NAME]&os_password=[ADMIN_PASSWORD]";

    public String getJiraUser(String userLoginId) throws Exception {
        String url = this.hostURL + this.restApiURL + "/user?username=" + userLoginId;
       
        return this.getJiraResponse(url);
    }
   
    public String getJiraIssue(String issueKey) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String returnMessage = this.getJiraResponse(url);
        if (returnMessage.indexOf("errorMessages") > 0) {
            throw new Exception(returnMessage);
        }
        return this.getJiraResponse(url);
    }
   
    public String getIssueAssignee(String issueKey) throws Exception {
        String assignee = "";
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
        if (json.get("assignee") == null) {
            assignee = "Unassigned";
        } else {
            json = (JSONObject) new JSONParser().parse(json.get("assignee").toString());
            assignee = json.get("name").toString();
        }
       
        return assignee;
    }
   
    public String setIssueAssignee(String issueKey, String assignee) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey + "/assignee";
        String jsonData = "{\"name\": \"" + assignee + "\"}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssueReporter(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
        json = (JSONObject) new JSONParser().parse(json.get("reporter").toString());
       
        return json.get("name").toString();
    }
   
    public String setIssueReporter(String issueKey, String reporter) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"reporter\": {"
                    + "\"name\": \"" + reporter + "\""
                + "}"
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssueSummary(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
       
        return json.get("summary").toString();
    }
   
    public String setIssueSummary(String issueKey, String summary) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"summary\": \"" + summary + "\""
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssueDescription(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
       
        return json.get("description") == null ? "" : json.get("description").toString();
    }
   
    public String setIssueDescription(String issueKey, String description) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"description\": \"" + description + "\""
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String[] getIssueComponents(String issueKey) throws Exception {
        String[] returnStringArray = null;
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
       
        if (json.get("components") != null) {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(json.get("components").toString());
            returnStringArray = new String[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject arrayObj = (JSONObject) new JSONParser().parse(jsonArray.get(i).toString());
                returnStringArray[0] = arrayObj.get("name").toString();
                System.out.println(arrayObj.get("name").toString());
            }
        }
       
        return returnStringArray;
    }
   
    public String setIssueComponents(String issueKey, String components) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"components\": [{"
                    + "\"name\": \"" + components + "\""
                + "}]"
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssuePriority(String issueKey) throws Exception {
        String priority = null;
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
        if (json.get("priority") != null) {
            json = (JSONObject) new JSONParser().parse(json.get("priority").toString());
            priority = json.get("name").toString();
        }
       
        return priority;
    }
   
    public String setIssuePriority(String issueKey, String priority) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"priority\": {"
                    + "\"name\": \"" + priority + "\""
                + "}"
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssueType(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
        json = (JSONObject) new JSONParser().parse(json.get("issuetype").toString());
       
        return json.get("name").toString();
    }
   
    public String setIssueType(String issueKey, String issueType) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey;
        String jsonData = "{\"fields\": {"
                + "\"issuetype\": {"
                    + "\"name\": \"" + issueType + "\""
                + "}"
            + "}"
        + "}";
       
        return this.putJiraUpdatedData(url, jsonData);
    }
   
    public String getIssueStatus(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
        json = (JSONObject) new JSONParser().parse(json.get("status").toString());
       
        return json.get("name").toString();
    }
   
    public String getIssueResolution(String issueKey) throws Exception {
        String issue = this.getJiraIssue(issueKey);
        JSONObject json = (JSONObject) new JSONParser().parse(issue);
        json = (JSONObject) new JSONParser().parse(json.get("fields").toString());
       
        return json.get("resolution") == null ? "Unresolved" : json.get("resolution").toString();
    }
   
    public String addIssueComment(String issueKey, String comment) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/" + issueKey + "/comment";
        String jsonData = "{\"body\": \"" + comment + "\"}";
       
        return this.postJiraCreateData(url, jsonData);
    }
   
    public String createIssue(IssueInfo issueInfo) throws Exception {
        String url = this.hostURL + this.restApiURL + "/issue/";
        String jsonData = "{\"fields\": {"
                + "\"summary\": \"" + issueInfo.getSummary() + "\","
                + "\"description\": \"" + issueInfo.getSummary() + "\","
                + "\"project\": {"
                    + "\"key\": \"" + issueInfo.getJiraProject() + "\""
                + "},"
                + "\"reporter\": {"
                    + "\"name\": \"" + issueInfo.getReporter() + "\""
                + "},"
                + "\"assignee\": {"
                    + "\"name\": \"" + issueInfo.getAssignee() + "\""
                + "},"
                + "\"issuetype\": {"
                    + "\"name\": \"" + issueInfo.getIssuetype() + "\""
                + "}"
            + "}"
        + "}";
       
        return this.postJiraCreateData(url, jsonData);
    }
   
    private String getJiraResponse(String url) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username",
                "password"));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        try {
            HttpPost httpPost = new HttpPost(this.adminLoginURL);
            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse postResponse = httpclient.execute(httpPost);
            CloseableHttpResponse getResponse = httpclient.execute(httpGet);
            try {
                String bodyAsString = EntityUtils.toString(getResponse.getEntity());

                return bodyAsString;
            } finally {
                postResponse.close();
                getResponse.close();
            }
        } finally {
            httpclient.close();
        }
    }

    private String putJiraUpdatedData(String url, String jsonData) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username",
                "password"));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        try {
            HttpPost httpPost = new HttpPost(this.adminLoginURL);
            HttpPut httpPut = new HttpPut(url);
            StringEntity entity = new StringEntity(jsonData);
            entity.setContentType("application/json; charset=UTF-8");
            httpPut.setEntity(entity);
           
            CloseableHttpResponse postResponse = httpclient.execute(httpPost);
            CloseableHttpResponse putResponse = httpclient.execute(httpPut);
            try {
                String bodyAsString = putResponse.getStatusLine().toString();
 
                return bodyAsString;
            } finally {
                postResponse.close();
                putResponse.close();
            }
        } finally {
            httpclient.close();
        }
    }
   
    private String postJiraCreateData(String url, String jsonData) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username",
                "password"));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        try {
            HttpPost httpPost = new HttpPost(this.adminLoginURL);
            HttpPost createPost = new HttpPost(url);
            StringEntity entity = new StringEntity(jsonData);
            entity.setContentType("application/json; charset=UTF-8");
            createPost.setEntity(entity);
           
            CloseableHttpResponse postResponse = httpclient.execute(httpPost);
            CloseableHttpResponse createResponse = httpclient.execute(createPost);
           
            try {
                ResponseHandler<String> handler = new BasicResponseHandler();
                String responseBody = handler.handleResponse(createResponse);
                System.out.println(responseBody);
                return responseBody;
            } finally {
                postResponse.close();
                createResponse.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

沒有留言:

張貼留言