Advertisement
koshinae

JiraRestClient in Java - Example

Feb 23rd, 2015
5,843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.81 KB | None | 0 0
  1. /**
  2.  * README: https://docs.atlassian.com/jira/REST/latest/
  3.  * Dependencies: [org.apache.commons] commons-codec-1.6, [com.sun.jersey] jersey-client-1.19, [org.json] json-20090211 and their dependencies.
  4.  */
  5. package com.example.jira.restclient;
  6.  
  7. import com.sun.jersey.api.client.Client;
  8. import com.sun.jersey.api.client.ClientResponse;
  9. import com.sun.jersey.api.client.WebResource;
  10. import com.sun.jersey.api.client.config.ClientConfig;
  11. import com.sun.jersey.api.client.config.DefaultClientConfig;
  12. import com.sun.jersey.client.urlconnection.HTTPSProperties;
  13. import java.security.KeyManagementException;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.security.SecureRandom;
  16. import java.security.cert.X509Certificate;
  17. import javax.naming.AuthenticationException;
  18. import javax.net.ssl.HostnameVerifier;
  19. import javax.net.ssl.HttpsURLConnection;
  20. import javax.net.ssl.SSLContext;
  21. import javax.net.ssl.SSLSession;
  22. import javax.net.ssl.TrustManager;
  23. import javax.net.ssl.X509TrustManager;
  24. import org.apache.commons.codec.binary.Base64;
  25. import org.json.JSONException;
  26. import org.json.JSONObject;
  27.  
  28. /**
  29.  *
  30.  * @author Koshinae - http://stackoverflow.com/users/357403/koshinae
  31.  */
  32. public class JiraRestClient {
  33.  
  34.     /**
  35.      *
  36.      * @param args
  37.      */
  38.     public static void main(String... args) {
  39.         try {
  40.             JiraRestClient jrc = new JiraRestClient("https://jira.example.com", "user", "p4ss");
  41.             String issue = jrc.getIssue("PROJ-954");
  42.             System.out.println(issue);
  43.         } catch (JiraRestClientException | JSONException ex) {
  44.             System.err.println(ex);
  45.         }
  46.     }
  47.  
  48.     private static String getAuth(String username, String password) {
  49.         try {
  50.             String s = username + ":" + password;
  51.             byte[] byteArray = s.getBytes();
  52.             String auth;
  53.             auth = Base64.encodeBase64String(byteArray);
  54.  
  55.             return auth;
  56.         } catch (Exception ignore) {
  57.             return "";
  58.         }
  59.     }
  60.  
  61.     private final String host;
  62.     private final String authHeader;
  63.  
  64.     /**
  65.      *
  66.      * @param host The server's URL.
  67.      * @param username User for logging in.
  68.      * @param password Password for logging in.
  69.      */
  70.     public JiraRestClient(String host, String username, String password) {
  71.         this.authHeader = getAuth(username, password);
  72.         if (host.endsWith("/")) {
  73.             this.host = host.substring(0, host.length() - 1);
  74.         } else {
  75.             this.host = host;
  76.         }
  77.     }
  78.  
  79.     public String getIssue(String issuekey) throws JiraRestClientException, JSONException {
  80.         JSONObject result = doREST("GET", "/rest/api/2/issue", issuekey + "?*all,-comment");
  81.  
  82.         // TODO: format the JSON object to your own favorite object format.
  83.         return result.toString();
  84.     }
  85.  
  86.     /**
  87.      *
  88.      * @param projectid The ID of the project.
  89.      * @param issuetypeid The ID if the IssueType.
  90.      * @param summary The Summary of the new issue.
  91.      * @param description The body of the new issue.
  92.      * @return JSON serialized message.
  93.      * @throws JiraRestClientException
  94.      * @throws JSONException
  95.      */
  96.     public String createIssue(Integer projectid, Integer issuetypeid, String summary, String description) throws JiraRestClientException, JSONException {
  97.         JSONObject fields = new JSONObject();
  98.         fields.put("project", new JSONObject().put("id", projectid.toString()));
  99.         fields.put("issuetype", new JSONObject().put("id", issuetypeid.toString()));
  100.         fields.put("summary", "Test from JiraRestClient");
  101.         fields.put("description", "Lorem ipsum...");
  102.  
  103.         JSONObject issue = new JSONObject();
  104.         issue.put("fields", fields);
  105.  
  106.         JSONObject result = doREST("POST", "/rest/api/2/issue", issue.toString());
  107.  
  108.         return result.toString();
  109.     }
  110.  
  111.        /**
  112.      *
  113.      * @param method The HTTP method defines if we want to fetch (GET), modify
  114.      * (PUT), add (POST), or remove (DELETE) entites.
  115.      * @param context The Resource you want to access.
  116.      * @param arg The Parameter(s) assembled to simply send it.
  117.      * @return A JSON object depicting the results, OR an exception detailing
  118.      * the problem.
  119.      * @throws JiraRestClientException
  120.      */
  121.     private JSONObject doREST(String method, String context, String arg) throws JiraRestClientException {
  122.         try {
  123.             ClientConfig config = getClientConfig();
  124.             Client client = Client.create(config);
  125.  
  126.             if (!context.endsWith("/")) {
  127.                 context = context.concat("/");
  128.             }
  129.  
  130.             WebResource webResource;
  131.             if ("GET".equalsIgnoreCase(method)) {
  132.                 webResource = client.resource(this.host + context + arg);
  133.             } else {
  134.                 webResource = client.resource(this.host + context);
  135.             }
  136.  
  137.             WebResource.Builder builder = webResource.header("Authorization", "Basic " + this.authHeader).type("application/json").accept("application/json");
  138.  
  139.             ClientResponse response;
  140.  
  141.             if ("GET".equalsIgnoreCase(method)) {
  142.                 response = builder.get(ClientResponse.class);
  143.             } else if ("POST".equalsIgnoreCase(method)) {
  144.                 response = builder.post(ClientResponse.class, arg);
  145.             } else {
  146.                 response = builder.method(method, ClientResponse.class);
  147.             }
  148.  
  149.             if (response.getStatus() == 401) {
  150.                 throw new AuthenticationException("HTTP 401 received: Invalid Username or Password.");
  151.             }
  152.  
  153.             String jsonResponse = response.getEntity(String.class);
  154.             JSONObject responseJson = new JSONObject(jsonResponse);
  155.  
  156.             return responseJson;
  157.         } catch (JSONException ex) {
  158.             throw new JiraRestClientException("JSON deserializing failed.", ex);
  159.         } catch (AuthenticationException ex) {
  160.             throw new JiraRestClientException("Login failed.", ex);
  161.         }
  162.     }
  163.  
  164.     /**
  165.      *
  166.      * @return A clientconfig accepting all hosts and all ssl certificates
  167.      * unconditionally.
  168.      */
  169.     private ClientConfig getClientConfig() {
  170.         try {
  171.             TrustManager[] trustAllCerts;
  172.             trustAllCerts = new TrustManager[]{
  173.                 new X509TrustManager() {
  174.                     @Override
  175.                     public X509Certificate[] getAcceptedIssuers() {
  176.                         return new X509Certificate[0];
  177.                     }
  178.  
  179.                     @Override
  180.                     public void checkClientTrusted(X509Certificate[] certs, String authType) {
  181.                     }
  182.  
  183.                     @Override
  184.                     public void checkServerTrusted(X509Certificate[] certs, String authType) {
  185.                     }
  186.                 }};
  187.  
  188.             // Ignore differences between given hostname and certificate hostname
  189.             HostnameVerifier hv = new HostnameVerifier() {
  190.                 @Override
  191.                 public boolean verify(String hostname, SSLSession session) {
  192.                     return true;
  193.                 }
  194.             };
  195.  
  196.             // Install the all-trusting trust manager
  197.             SSLContext sc = SSLContext.getInstance("SSL");
  198.             sc.init(null, trustAllCerts, new SecureRandom());
  199.  
  200.             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  201.             HttpsURLConnection.setDefaultHostnameVerifier(hv);
  202.  
  203.             HTTPSProperties prop = new HTTPSProperties(hv, sc);
  204.  
  205.             ClientConfig config = new DefaultClientConfig();
  206.             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, prop);
  207.  
  208.             return config;
  209.         } catch (NoSuchAlgorithmException | KeyManagementException e) {
  210.             System.err.println(e);
  211.         }
  212.  
  213.         return null;
  214.     }
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement