com.serena.rlc.provider.jira.client.JiraClient.java Source code

Java tutorial

Introduction

Here is the source code for com.serena.rlc.provider.jira.client.JiraClient.java

Source

/*
 *
 * Copyright (c) 2015 SERENA Software, Inc. All Rights Reserved.
 *
 * This software is proprietary information of SERENA Software, Inc.
 * Use is subject to license terms.
 *
 */

package com.serena.rlc.provider.jira.client;

import com.serena.rlc.provider.domain.SessionData;
import com.serena.rlc.provider.jira.domain.Project;
import com.serena.rlc.provider.jira.domain.Issue;
import com.serena.rlc.provider.jira.exception.JiraClientException;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.*;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.*;

/**
 * @author klee
 */

@Component
public class JiraClient {
    private static final Logger logger = LoggerFactory.getLogger(JiraClient.class);

    public static String DEFAULT_HTTP_CONTENT_TYPE = "application/json";

    private String jiraUrl;
    private String jiraUsername;
    private String jiraPassword;
    private String jiraProject;
    private SessionData session;

    public JiraClient() {

    }

    public JiraClient(SessionData session, String url, String username, String password, String project) {
        this.session = session;
        this.jiraUrl = url;
        this.jiraUsername = username;
        this.jiraPassword = password;
        this.jiraProject = project;
    }

    public SessionData getSession() {
        return session;
    }

    public void setSession(SessionData session) {
        this.session = session;
    }

    public String getJiraUrl() {
        return jiraUrl;
    }

    public void setJiraUrl(String url) {
        this.jiraUrl = url;
    }

    public String getJiraUsername() {
        return jiraUsername;
    }

    public void setJiraUsername(String username) {
        this.jiraUsername = username;
    }

    public String getJiraPassword() {
        return jiraPassword;
    }

    public void setJiraPassword(String password) {
        this.jiraPassword = password;
    }

    public String getJiraProject() {
        return jiraProject;
    }

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

    public void createConnection(SessionData session, String url, String username, String password) {
        this.session = session;
        this.jiraUrl = url;
        this.jiraUsername = username;
        this.jiraPassword = password;
    }

    public void createConnection(SessionData session, String url, String username, String password,
            String project) {
        this.session = session;
        this.jiraUrl = url;
        this.jiraUsername = username;
        this.jiraPassword = password;
        this.jiraProject = project;
    }

    public List<Issue> getIssues(String projectId, List<String> statusFilters, String titleFilter,
            Integer resultLimit) throws JiraClientException {
        logger.debug("Using JIRA URL: " + this.jiraUrl);
        logger.debug("Using JIRA Credentials: " + this.jiraUsername + ":" + this.jiraPassword);
        logger.debug("Using JIRA Project: " + projectId);
        logger.debug("Using JIRA Status Filter: "
                + (statusFilters != null && !statusFilters.isEmpty() ? statusFilters.toString() : "none defined"));
        logger.debug("Using JIRA Title Filter: "
                + (titleFilter != null && !titleFilter.isEmpty() ? titleFilter : "none defined"));
        logger.debug("Limiting results to: " + resultLimit.toString());

        String jqlQuery = "rest/api/latest/search?jql=project=" + projectId;
        if (titleFilter != null && !titleFilter.isEmpty()) {
            jqlQuery += "+AND+summary~" + titleFilter;
        }
        if (statusFilters != null && !statusFilters.isEmpty()) {
            jqlQuery += "+AND+status+in+(";
            for (String status : statusFilters) {
                jqlQuery += "%22" + status.replaceAll(" ", "%20") + "%22,";
            }
            // remove last comma if it exists
            if (jqlQuery.endsWith(","))
                jqlQuery = jqlQuery.substring(0, jqlQuery.length() - 1);
            jqlQuery += ")";
        }
        logger.debug("Using JIRA JQL Query:" + jqlQuery);

        logger.debug("Retrieving JIRA Issues");
        String issResponse = processGet(session, getJiraUrl(), jqlQuery);
        logger.debug(issResponse);

        List<Issue> issues = Issue.parse(issResponse);
        return issues;

    }

    public Issue getIssue(String issueId) throws JiraClientException {
        logger.debug("Using JIRA URL: " + this.jiraUrl);
        logger.debug("Using JIRA Project: " + this.jiraProject);
        logger.debug("Using JIRA Credentials: " + this.jiraUsername + ":" + this.jiraPassword);
        logger.debug("Using JIRA Issue Id: " + issueId);

        logger.debug("Retrieving JIRA Issue");
        String issueResponse = processGet(session, getJiraUrl(), "rest/api/2/issue/" + issueId);
        logger.debug(issueResponse);

        Issue issue = Issue.parseSingle(issueResponse);
        return issue;
    }

    public List<Project> getProjects() throws JiraClientException {
        logger.debug("Using JIRA URL: " + this.jiraUrl);
        logger.debug("Using JIRA Credentials: " + this.jiraUsername + ":" + this.jiraPassword);

        logger.debug("Retrieving JIRA Projects");
        String projResponse = processGet(session, getJiraUrl(), "rest/api/2/project");
        logger.debug(projResponse);

        List<Project> projects = Project.parse(projResponse);
        return projects;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Execute a put request
     *
     * @param url
     * @return Response body
     * @throws JiraClientException
     */
    private String processPut(SessionData session, String restUrl, String url, String putData)
            throws JiraClientException {
        String uri = restUrl + url;

        logger.debug("Start executing JIRA PUT request to url=\"{}\" with payload={}", uri);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut(uri);
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword());
        putRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        putRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        putRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
        String result = "";

        try {
            putRequest.setEntity(new StringEntity(putData));

            HttpResponse response = httpClient.execute(putRequest);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw createHttpError(response);
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            StringBuilder sb = new StringBuilder(1024);
            String output;
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }

            logger.debug("End executing JIRA PUT request to url=\"{}\" and receive this result={}", uri, sb);

            return sb.toString();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new JiraClientException("Server not available", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }

    /**
     * Execute a get request
     *
     * @param url
     * @return Response body
     * @throws JiraClientException
     */
    protected String processGet(SessionData session, String jiraUrl, String url) throws JiraClientException {
        String uri = jiraUrl + url;

        logger.debug("Start executing JIRA GET request to url=\"{}\"", uri);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(uri);
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword());
        getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        getRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        getRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
        String result = "";

        try {
            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw createHttpError(response);
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            StringBuilder sb = new StringBuilder(1024);
            String output;
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            result = sb.toString();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new JiraClientException("Server not available", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        logger.debug("End executing JIRA GET request to url=\"{}\" and receive this result={}", uri, result);

        return result;
    }

    /**
     * @param path
     * @return
     */
    private String encodePath(String path) {
        String result;
        URI uri;
        try {
            uri = new URI(null, null, path, null);
            result = uri.toASCIIString();
        } catch (Exception e) {
            result = path;
        }
        return result;
    }

    private JiraClientException createHttpError(HttpResponse response) {
        String message;
        try {
            StatusLine statusLine = response.getStatusLine();
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line;
            StringBuffer responsePayload = new StringBuffer();
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                responsePayload.append(line);
            }

            message = String.format(" request not successful: %d %s. Reason: %s", statusLine.getStatusCode(),
                    HttpStatus.getStatusText(statusLine.getStatusCode()), responsePayload);

            logger.debug(message);

            if (new Integer(HttpStatus.SC_UNAUTHORIZED).equals(statusLine.getStatusCode())) {
                return new JiraClientException("Invalid credentials provided.");
            } else if (new Integer(HttpStatus.SC_NOT_FOUND).equals(statusLine.getStatusCode())) {
                return new JiraClientException("JIRA: Request URL not found.");
            } else if (new Integer(HttpStatus.SC_BAD_REQUEST).equals(statusLine.getStatusCode())) {
                return new JiraClientException("JIRA: Bad request. " + responsePayload);
            }
        } catch (IOException e) {
            return new JiraClientException("JIRA: Can't read response");
        }

        return new JiraClientException(message);
    }

    static public void main(String[] args) {
        JiraClient jc = new JiraClient(null, "http://serenadeploy:9090/", "admin", "admin", null);

        System.out.println("Retrieving JIRA Projects...");
        String projResponse = null;
        try {
            projResponse = jc.processGet(null, jc.getJiraUrl(), "rest/api/2/project");
        } catch (JiraClientException e) {
            System.out.print(e.toString());
        }
        System.out.println(projResponse);

        System.out.println("Retrieving JIRA Issues for projects...");
    }
}