J tricks - Little JIRA Tricks
  • Home
  • Plugins ↓
    • JQL Tricks Plugin
      • JQL Tricks Plugin - Cloud
        • JQLT Cloud Installation
        • JQLT Cloud Configuration
        • JQLT Cloud Usage
        • JQLT Cloud License
        • JQLT Cloud FAQ
      • JQL Tricks Plugin - DC
        • JQLT DC Installation
        • JQLT DC Configuration
        • JQLT DC Usage
          • JQLT Issue Functions
          • JQLT Subtask Functions
          • JQLT Links Functions
          • JQLT Development Functions
          • JQLT Worklog Functions
          • JQLT Project Functions
          • JQLT Component Functions
          • JQLT Version Functions
          • JQLT Group Functions
          • JQLT User Functions
          • JQLT Date Functions
        • JQLT DC License
        • JQLT DC FAQ
        • JQLT DC Known Issues
        • JQLT DC Performance
      • JQL Tricks Cloud Migration
    • Simplified Planner
      • J-Planner Installation
      • J-Planner Configuration
      • J-Planner Usage
        • Creating a plan
        • Editing a plan
        • Deleting a plan
        • Viewing a plan
        • Modifying a plan
      • J-Planner FAQ
    • Atla-Search Plugin
      • Atla-Search Installation
      • Atla-Search Configuration
      • Atla-Search Usage
      • Atla-Search License
      • Atla-Search FAQ
    • Heroku for Compass App
      • Heroku for Compass Installation
      • Heroku for Compass Configuration
      • Heroku for Compass Usage
    • Copy to subtask Plugin
    • All Plugins
  • Tutorials
  • The Book
  • Contact Us
  • Home
  • Plugins ↓
    • JQL Tricks Plugin
      • JQL Tricks Plugin - Cloud
        • JQLT Cloud Installation
        • JQLT Cloud Configuration
        • JQLT Cloud Usage
        • JQLT Cloud License
        • JQLT Cloud FAQ
      • JQL Tricks Plugin - DC
        • JQLT DC Installation
        • JQLT DC Configuration
        • JQLT DC Usage
          • JQLT Issue Functions
          • JQLT Subtask Functions
          • JQLT Links Functions
          • JQLT Development Functions
          • JQLT Worklog Functions
          • JQLT Project Functions
          • JQLT Component Functions
          • JQLT Version Functions
          • JQLT Group Functions
          • JQLT User Functions
          • JQLT Date Functions
        • JQLT DC License
        • JQLT DC FAQ
        • JQLT DC Known Issues
        • JQLT DC Performance
      • JQL Tricks Cloud Migration
    • Simplified Planner
      • J-Planner Installation
      • J-Planner Configuration
      • J-Planner Usage
        • Creating a plan
        • Editing a plan
        • Deleting a plan
        • Viewing a plan
        • Modifying a plan
      • J-Planner FAQ
    • Atla-Search Plugin
      • Atla-Search Installation
      • Atla-Search Configuration
      • Atla-Search Usage
      • Atla-Search License
      • Atla-Search FAQ
    • Heroku for Compass App
      • Heroku for Compass Installation
      • Heroku for Compass Configuration
      • Heroku for Compass Usage
    • Copy to subtask Plugin
    • All Plugins
  • Tutorials
  • The Book
  • Contact Us

Java REST Client for JIRA using Jersey

5/6/2012

64 Comments

 
Let us face it! REST is the order of the day. And Atlassian just underlined that statement with the release of JIRA5.

With JIRA5, a lot of the operations can be done using the REST API and here is the full list of operations supported.
There are so many ways to invoke the rest APIs. The Atlassian developer documentation is a good start. It gives you a good explanation on the input parameters needed for the various operations, if not fully clear from the API documentation.

But if you are yet unsure on how to invoke these REST operations from a Java client, read on...

Before boring you further, I must say that the best Java client for JIRA REST APIs is JRJC - The JIRA Rest Java Client supported by Atlassian. But at least for now, it doesn't support all the Issue CRUD methods. I must add that it won't be long before they are added (or is available when you re reading it!).

Still, what if you want to create another client? Without the dependency on something like JRJC? Let us look at a rather simple option - Using Jersey to write a REST Client.

I have mentioned about JRJC in my book but the following part is probably missing from the book. Considering the JIRA5 REST capabilities, it is never too late to write something about it, is it?

As mentioned before, I am just going to look at Jersey and see how we can write a simple client. Let us start with creating a simple maven project. Following is the dependency that needs to be added for using the jersey client libraries.

<dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.8</version>
</dependency>

Change the version as appropriate!

Consider a simple scenario. We need to get a list of all projects in a JIRA instance. As per the API docs, the REST url is /rest/api/2/project and it is a GET operation. Following are the steps:

  1. Choose the authentication style. We are going to use the basic authentication as that is the simplest to explain. But if you are interested, there is an explanation of OAuth dance here.
  2. Create the basic authentication String. We will be using it in the REST call.

    String auth = new String(Base64.encode("username:password"));

  3. Instantiate a Jersey Client and create a Web resource that is capable of building requests to send to the REST resource and process responses returned from the resource.

    Client client = Client.create();
    WebResource webResource = client.resource("http://localhost:8080/rest/api/2/project");

    Here the url used is the base url of JIRA + the rest resource url.

  4. Obtain the response using the webResource after setting the required parameters like authentication type, media type etc.

    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").get(ClientResponse.class);

                
As you can see, we have set the basic authentication parameters in the header which includes the authentication String we created in Step 2. You can add even custom values in the header as long as the server can use it but in our case that is not required.

The media type we used is application/json as that is the one supported by JIRA REST methods.

We are also using the get method here and accepts the response into the ClientResponse class.

That's it! We have sent the request and got the response. It is now only a matter of making sure the response is what is expected. The easiest thing to do is to check the status code in the response. For example, a response code in the 200 range is normally successful where as 401, for example, indicates invalid authentication error!

A good list of status codes can be found here.

You can get the status code and check it like this:

int statusCode = response.getStatus();
if (statusCode == 401) {
    throw new AuthenticationException("Invalid Username or Password");
}

And what is the status code is fine? If you are expecting a response, like in our case - list of projects, we can get the result as shown:

String response = response.getEntity(String.class);

Here the response will be in json format since that is what is given back by JIRA. Remember, the media type we set was application/json!

A sample output is here:

[
    {
        "self": "http://localhost:8080/rest/api/2/project/DEMO",
        "id": "10000",
        "key": "DEMO",
        "name": "DEMO",
        "avatarUrls": {
            "16x16": "http://localhost:8080/secure/projectavatar?size=small&pid=10000&avatarId=10011",
            "48x48": "http://localhost:8080/secure/projectavatar?pid=10000&avatarId=10011"
        }
    },
    {
        "self": "http://localhost:8080/rest/api/2/project/TEST",
        "id": "10001",
        "key": "TEST",
        "name": "TEST",
        "avatarUrls": {
            "16x16": "http://localhost:8080/secure/projectavatar?size=small&pid=10001&avatarId=10011",
            "48x48": "http://localhost:8080/secure/projectavatar?pid=10001&avatarId=10011"
        }
    }
]

As you can see, the response here is a JSON array and you can now extract the details from here as you wish! Here is small example of extracting the key and name.

We will use JSON in java for this. The dependency to be added is:

<dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
</dependency>

You can simply extract the key and name as follows:

JSONArray projectArray = new JSONArray(jsonResponse);
for (int i = 0; i < projectArray.length(); i++) {
    JSONObject proj = projectArray.getJSONObject(i);
    System.out.println("Key:"+proj.getString("key")+", Name:"+proj.getString("name"));
}

So, that was a simple GET example. How about creating/updating/deleting an issue? I have taken these examples because they use POST/PUT/DELETE operations.

Creating an issue

As per the docs, we need to POST the fields required to create the issue to the REST resource. The url is http://localhost:8080/rest/api/2/issue and the simple json input with just summary, project and issuetype details will be something like this:

{"fields":{"project":{"key":"DEMO"},"summary":"REST Test","issuetype":{"name":"Bug"}}}

Everything else remains the same expect that we will be using post method with the above data.

private static String invokePostMethod(String auth, String url, String data) throws AuthenticationException, ClientHandlerException {
    Client client = Client.create();
    WebResource webResource = client.resource(url);
    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").post(ClientResponse.class, data);
    int statusCode = response.getStatus();
    if (statusCode == 401) {
        throw new AuthenticationException("Invalid Username or Password");
    }
    return response.getEntity(String.class);
}

Updating an issue

The url will have the issue key we need to edit: http://localhost:8080/rest/api/2/issue/DEMO-13. A simple example of json data to change the assignee will be:

{"fields":{"assignee":{"name":"test"}}}

Everything else remains same except that we use the PUT method:

private static void invokePutMethod(String auth, String url, String data) throws AuthenticationException, ClientHandlerException {
    Client client = Client.create();
    WebResource webResource = client.resource(url);
    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").put(ClientResponse.class, data);
    int statusCode = response.getStatus();
    if (statusCode == 401) {
        throw new AuthenticationException("Invalid Username or Password");
    }
}

Note that we are not returning any response here since the REST method doesn't return anything. The status code of 204 indicates 'No Content'.

Deleting an issue

As you would expect, this doesn't need any additional data as the url has the issue key in it: http://localhost:8080/rest/api/2/issue/DEMO-13. The operation is DELETE as opposed to PUT.

private static void invokeDeleteMethod(String auth, String url) throws AuthenticationException, ClientHandlerException {
    Client client = Client.create();
    WebResource webResource = client.resource(url);
    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").delete(ClientResponse.class);
    int statusCode = response.getStatus();
    if (statusCode == 401) {
        throw new AuthenticationException("Invalid Username or Password");
    }
}


Well, that wraps up the basics. Everything else is just an extension of this. https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Tutorials has a whole lot of examples with data for each operation. Also attached to this post is the Java project we used for this post.

Don't forget to have a look at the JIRA Development Cookbook.
rest-client.zip
File Size: 5 kb
File Type: zip
Download File

64 Comments
parthi
5/9/2012 10:42:02 pm

Nice 1 Jobin

keep them coming please

Reply
J-Tricks
5/10/2012 01:11:22 am

Thanks Parthi. Glad you liked it :)

Reply
Fcornejo
6/25/2012 09:48:04 pm

Great job, it helped me a lot. Thanks!

Reply
Daniel
7/11/2012 02:22:51 pm

How would you go about attaching a file to an issue using jersey?

Reply
frank
7/23/2012 11:46:17 pm

Very nice examples, thanks a lot!

Reply
mike
8/3/2012 05:58:20 am

Thanks for the nice article. I am able to use rest api to get project information however stuck while trying to update an issue :(
my url:
http://jira.xxx.intra:8080/rest/api/latest/issue/ABC-111
my data:
{"fields":{"assignee":{"name":"MG Reader"}}}
but when I want to update the issue with this data, I get a response status of 405 Method Not Allowed.. what can be issue..

Reply
J-Tricks
8/6/2012 09:52:16 am

Do you have "Assign Issue" permission for the issue? Are you able to do this operation from UI when logged in as the user you are trying from REST?

Reply
mike
8/6/2012 11:10:34 am

yea.. everything is good but now I know the reason.. many of the put/post methods are not supported before jira 5.0.x and I have jira old version.. so now I am using Soap client..

thanks :)

Reply
Chandramohan M
10/3/2012 08:08:11 am

Hi,

I was able to create an issue through REST JSON but I would like to create an issue with attachment. Which api should I use? and how should I mention the attachment file in the code? I have mentioned my code below.

Code:

String auth = new String(Base64.encode("admin:admin"));

Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8090/rest/api/2/issue/createmeta");
ClientResponse response1 = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").get(ClientResponse.class);
JSONObject json = new JSONObject();
JSONObject objProject =new JSONObject();
JSONObject objTemp =new JSONObject();
objTemp.put("key", "TES");
objProject.put("project", objTemp.toString());
objProject.put("summary", "Testing Rest ");
objProject.put("description", "Descibing what REst can do ");
//json.put("fields", objProject.toString());
//json.put("summary", "Testing Rest ");
objTemp =new JSONObject();
objTemp.put("name", "Bug");
//JSONObject objIssuetype =new JSONObject();
objProject.put("issuetype", objTemp.toString());
//data = "{"fields":{"project":{"key":"DEMO" }, "summary":"REST Test ","issuetype": {"name":"Bug" }}}";
// {"fields":{"project":{"TP" :"TestProj"}, "summary":"Testing Rest ","issuetype": {"name":"Bugwa"}}}
json.put("fields", objProject.toString());
String data =json.toString();

private static String invokePostMethod(String auth, String url, String data) throws ClientHandlerException {
Client client = Client.create();
WebResource webResource = client.resource(url);

ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").post(ClientResponse.class, data);
int statusCode = response.getStatus();

Reply
daeyong.park
10/29/2012 07:45:56 pm

Cool!!

Reply
sridhar
11/2/2012 06:14:45 am

I working on Rest api to get the issue details based on jira cook book and i am getting this error when trying to access jira from a standalone java application.

Exception in thread "main" com.atlassian.jira.rest.client.RestClientException: org.codehaus.jettison.json.JSONException: JSONObject["summary"] is not a JSONObject.
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:75)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.getAndParse(AbstractJerseyRestClient.java:80)
at com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:109)
at dst.App.main(App.java:34)
Caused by: org.codehaus.jettison.json.JSONException: JSONObject["summary"] is not a JSONObject.
at org.codehaus.jettison.json.JSONObject.getJSONObject(JSONObject.java:458)
at com.atlassian.jira.rest.client.internal.json.JsonParseUtil.getNestedString(JsonParseUtil.java:116)
at com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:141)
at com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:54)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient$1.call(AbstractJerseyRestClient.java:85)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:54)
... 3 more

Reply
J-Tricks
11/2/2012 06:23:11 am

How is your json object constructed? Maybe you can post the code here?

Reply
Kannan
9/19/2015 02:11:14 am

import java.net.URI;
import java.util.Iterator;
import com.atlassian.jira.rest.*;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.domain.BasicIssue;
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.domain.IssueLink;
import com.atlassian.jira.rest.client.domain.SearchResult;
import com.atlassian.jira.rest.client.internal.jersey.JerseyJiraRestClientFactory;

public class Trial {

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

JerseyJiraRestClientFactory f = new JerseyJiraRestClientFactory();
JiraRestClient jc = f.createWithBasicHttpAuthentication(new URI("JIRA_URL"), "JIRA_User", "JIRA_Pwd");

System.err.println("here1");

SearchResult r = jc.getSearchClient().searchJql("type = Epic ORDER BY RANK ASC", null);

for (BasicIssue issue : r.getIssues()) {
System.err.println("here ------------------------");
System.out.println(issue.getKey());

Issue i = jc.getIssueClient().getIssue(issue.getKey(), null);
System.err.println(i.getComments());

}

Iterator<BasicIssue> it = r.getIssues().iterator();
while (it.hasNext()) {

System.err.println("here2");

Issue issue = jc.getIssueClient().getIssue(((BasicIssue)it.next()).getKey(), null);
System.err.println("here3");
System.out.println("Epic: " + issue.getKey() + " " + issue.getSummary());
System.err.println("here4");
Iterator<IssueLink> itLink = issue.getIssueLinks().iterator();
while (itLink.hasNext()) {
System.err.println("here5");
IssueLink issueLink = (IssueLink)itLink.next();
Issue issueL = jc.getIssueClient().getIssue((issueLink).getTargetIssueKey(), null);

System.out.println(issueLink.getIssueLinkType().getDescription() + ": " + issueL.getKey() + " " + issueL.getSummary() + " " + issueL.getField("Story Points").getValue());

}

}

}

}


I am getting the following error:
Exception in thread "main" com.atlassian.jira.rest.client.RestClientException: org.codehaus.jettison.json.JSONException: JSONObject["summary"] is not a JSONObject.
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:75)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.getAndParse(AbstractJerseyRestClient.java:80)
at com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:108)
at Trial.main(Trial.java:26)
Caused by: org.codehaus.jettison.json.JSONException: JSONObject["summary"] is not a JSONObject.
at org.codehaus.jettison.json.JSONObject.getJSONObject(JSONObject.java:458)
at com.atlassian.jira.rest.client.internal.json.JsonParseUtil.getNestedString(JsonParseUtil.java:115)
at com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:140)
at com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:53)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient$1.call(AbstractJerseyRestClient.java:85)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:54)
... 3 more

Sivanandam
2/1/2013 01:09:38 am

Hi,
I am getting the following error while running the code.

In the Line : ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").get(ClientResponse.class);

Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method accept(MediaType[]) in the type RequestBuilder is not applicable for the arguments (String)

Reply
J-Tricks
2/4/2013 11:11:25 am

What version of Jersey client is it?

Reply
Mizan
2/3/2013 08:21:54 pm

Hi JTricks ,
Thanks for providing this tutorial , I need to know whether I can create a customfield which will display value from the JSON array return by a Rest call ?
Thank you

Reply
J-Tricks
2/4/2013 11:12:40 am

Sorry, I didn't understand. You can get any custom fields value via REST. What is different here?

Reply
Mizan
2/4/2013 05:17:28 pm

I have Vertigo SLA plugin installed , they provide some REST api ( https://confluence.valiantys.com/display/VSLA/REST+Access+Guide#RESTAccessGuide-Authorizations ) using this I can get Remaining value of the SLA customfield .
I need this value in a separate customfield so that It appears in the issue navigator/gadgets , At present this value is not shown in any report/gadget .
Can i create a new customfield type which can get this value OR any other way i can get it in the customfield ?
Thanks :)

J-Tricks
2/5/2013 02:13:06 pm

You should probably create a Scripted field. Script runner plugin provides one.

Mizan
2/5/2013 04:15:54 pm

Thank you J-Tricks , I will try this .

magento website developer link
6/16/2013 09:17:06 pm

I admire your thoughts and your way of expressing and putting it in front of readers "Java client" is really something that I have seen after a long time. We need more writers like you. This is perfect blog for anyone who is looking for topics like this. It has got it all, information, benefits and overview.

Reply
Suresh M
6/23/2013 11:41:18 pm

It was too cool. and helped me really. thanks

Reply
mizan
7/8/2013 12:31:34 am

Hi JTricks ,
Can I use JRJC /Rest in the post function I am developing ? This new post function creates issues on a remote JIRA instance .
Thanks :)

Reply
J-Tricks
7/8/2013 01:34:58 am

Haven't tried it but I don't see an issue with that!

If that doesn't work (due to some conflicts), use the Jersey method explained above. That will surely work.

Reply
website link
9/1/2013 07:41:48 pm

A good blog always comes-up with new and exciting information about "Java - Exception handling" and while reading I have experience that this blog is really have all those quality that characterize a blog to be a good one.

Joey
7/8/2013 08:49:27 am

J-Tricks,

I keep getting this error for some reason...

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:503)
at com.jtricks.JTricksRESTClient.invokeGetMethod(JTricksRESTClient.java:56)
at com.jtricks.JTricksRESTClient.main(JTricksRESTClient.java:24)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:240)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 21 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 27 more

I'm using version 1.17.1... I didn't change any of the code much besides the BASE_URL (obviously).

Reply
J-Tricks
7/8/2013 09:38:58 am

This comes when you are connecting to an HTTPS connection. Make sure you import the public certificate of you JIRA instance to the keystore of the application which is using this code.

See https://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services. The principle is same.

Reply
opencart developer link
8/8/2013 01:32:02 am

Oh my God I was unaware of the facts you mentioned in your article "Java developer". It is so helpful that I am sure everyone will praise you for sharing this information. Wonderful work. This is something I was searching for many days. My thirst has been quenched now after reading your article. I am highly thankful to you for writing this article.

Reply
Miroslav Ignjatovic link
9/26/2013 11:25:10 pm

Nice helper

Reply
Lukas
10/2/2013 02:32:34 am

Hello there,

i am also trying to create a rest client. Everything is working fine but i cant get the versions, always getting 404 error: My code is:

Client client2 = Client.create();
WebResource web2 = client2.resource("http://myinstance.com:8080/rest/api/latest/project/One/versions/");
ClientResponse response2 = web2.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").get(ClientResponse.class);
String result2 = response2.getEntity(String.class);

I am just wondering because i can access all other directories. I am working with Jira 4.3.2 and using this documentation: https://docs.atlassian.com/jira/REST/latest/#d2e3195

Got any clue?

Best regards!

Reply
J-Tricks
10/2/2013 03:11:27 am

Use the documentation for 4.3.2 :)

https://docs.atlassian.com/jira/REST/4.3.2/#id152601

Reply
Lukas
10/2/2013 05:24:35 am

Jesus Christ... i am so bad ^^
Thanks a lot ;)

alekhya
2/12/2014 05:24:31 pm

Hi,
I am getting the following error while running the code.

In the Line : ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").get(ClientResponse.class);

Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method accept(MediaType[]) in the type RequestBuilder is not applicable for the arguments (String)

Reply
J-Tricks
2/13/2014 02:12:20 am

Makes ure you are using the right version and also the correct classes (check the import statements) ;)

You can compare with the attached source code.

Reply
alekhya
3/3/2014 07:21:26 pm

i have added all th eimports still the same error

alekhya
3/3/2014 07:28:20 pm

the same error with the source code also could not parse the accept() method

cseppd
3/2/2014 05:34:18 pm

My code:
Client client = Client.create();
WebResource webResource = lient.resource("http://localhost:8088/pSalesRESTfulWS/rest");
ClientResponse response=webResource.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);

But get error:

Reply
J-Tricks
3/6/2014 03:40:23 pm

Sorry, you are missing the error!

Reply
cseppd
3/11/2014 12:30:09 am

My code: Client client = Client.create();
WebResource webResource = client.resource("http://222.222.222.40:8088/pSalesRESTfulWS/rest/MRTerritory/001472");
ClientResponse response = (ClientResponse)webResource.accept(new MediaType[]{MediaType.APPLICATION_JSON_TYPE}).get(ClientResponse.class);
error: in 2nd line-cannot access URI
webResource = client.resource("http://222.222.222.40:8088/pSalesRESTfulWS/rest/MRTerritory/001472");
class file for java.net.URI not found

Reply
J-Tricks
3/11/2014 01:39:17 am

class file for java.net.URI not found.

Do you have all the dependencies in the project? Looks like URI class is not in classpath!

Reply
cseppd
3/13/2014 02:45:21 am

In 3rd line:ClientResponse response = (ClientResponse)webResource.accept(new MediaType[]{MediaType.APPLICATION_JSON_TYPE}).get(ClientResponse.class); Get error: No suitable method found for accept(MediaType).Plz hlp..

s3
3/17/2014 10:35:46 am

Hi, I downloaded the code provided above and when I try and do an atlas-run I get the error message:

cannot find symbol
symbol : method accept(java.lang.String)
location: interface com.sun.jersey.api.client.RequestBuilder

I'm runing jdk 6 45, not sure why I'm getting the error.

Reply
Sharath
10/28/2014 05:22:49 am

Just the thing i was looking for...thanks a lot!

Reply
Melek
1/15/2015 10:43:03 pm

Nice tutorials!! Thanks a lot it's simple and clear to understand :)

Reply
pritam
2/16/2015 04:25:26 am

I want to import issues from an excel file to jira website.The file must be passed from an interface which is built using eclipse.The contents in the excel file must be used to create and update issues.Could you please guide me how I can achieve this.

Reply
Ameya
4/6/2015 08:23:44 pm

Hi
I need to create Java client for JIRA api.
Basically i am creating UI which will interact with JIRA cloud.
I need all basic steps to accomplish this.

Reply
J-Tricks
4/7/2015 01:32:54 am

Well, the basic steps are in this tutorial ;) Where are you stuck?

Reply
Ameya
4/8/2015 10:10:11 pm

Thanx. Using you tutorial it worked

Ameya
4/9/2015 10:24:05 pm

Till yesterday i had atlassian link which i used for jira rest api.
In short i replaced localhost link with mine.
But now my trial period is over.
So my question is how i can user localhost and what are the other requirements to run on localhost?
Is it possible to do?

J-Tricks
4/10/2015 01:56:07 am

Code should be the same, except the URL, username/password changes. Assuming you already have JIRA set up locally.

Ameya
4/10/2015 02:07:09 am

I didnt had any setup yet.
Would you shared what needs to be configure(setup) to use JIRA rest api locally?

J-Tricks
4/10/2015 02:41:07 am

You need to install JIRA locally. See https://confluence.atlassian.com/display/JIRA/JIRA+Installation+and+Upgrade+Guide

mateen link
6/25/2015 10:50:29 pm

Thanks alot for the post, but i want to know why is the udpate method returning any data. If try to get the data following is the exception i receive but the issue is updated

com.sun.jersey.api.client.UniformInterfaceException: PUT https://bighalf.atlassian.net/rest/api/2/issue/BH-174 returned a response status of 204 No Content

Reply
Neha Agrawal
10/9/2015 02:57:28 am

Hi.. Is anyone know how to create jira webservices or wsdl file for connection with JIRA, creating the issue and query the issue ?

Please guide me for this.. its really urgent

Reply
J-Tricks
10/9/2015 07:30:15 am

SOAP API is removed in JIRA 7/ we strongly recommend you to try REST.

Reply
Mario Günter link
2/15/2016 04:38:28 am

GREAT! Thanks for sharing!

Reply
Kannan
2/25/2016 11:44:10 am

Hi,
Could you please provide an example to "Add a Comment". Thanks.

Reply
testreddy
10/25/2016 01:24:42 am

I am getting 400 BAD Request URL, when trying to create a new issue using JIRA REST API.
I am using the JIRA v1000.456.2 server.
String url = "https://soctronicstest.atlassian.net/rest/api/2/issue";
WebResource webResource = client.resource(url);
String data = "{\"fields\":{\"project\":{\"name\":\"TestProject1\"},\"summary\":\"REST Test\",\"issuetype\":{\"name\":\"Bug\"},\"reporter\":{\"name\":\"testreddy\"}}}";
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").post(ClientResponse.class, data);
---------------
we get response.getStatus() = 400 error code.
Please solve it and help me with this problem.

Reply
J-Tricks
10/26/2016 10:10:11 pm

400 is a valid response code. You will get it when the input is invalid (e.g. missing required fields, invalid field values, and so forth). Check the response text to find out the error!

Reply
Raj Rathore
12/28/2016 06:37:06 am

can anyone suggest how to add attachments to new issues from the issues obtained from jql.

Eg:-

JQL = project = ABC AND issuetype=Bug AND status not in ("Resolved","Closed") AND program = Test
(program is a select list field)

If it returns 10 issues I am creating new 10 issues copying data from respective issue.

I'm through with my implementation but only thing which is hampering my progress is the attachment field.

how can I add attachments from one issue to another issue??

Reply
Chris
3/21/2017 10:46:54 am

Wow.

This tutorial showed me EXACTLY what I needed.

This is not the first time I have spent days searching on Google, Atlassian Answers, Atlassian documentation, etc with no luck at all. In the end I always end up finding a really short and correct explanation on this site. Even your old blog posts are more accurate today then much of the new information provided by Atlassian themselves when it comes to development.

Thank you so much Jobin!

Reply
Rashmi
8/6/2017 01:03:24 pm

Hi , I am working on JIRA Rest API with OAUTH. Please let me know if anyone has the working code on the same ?

Reply
Mopendra
7/30/2018 03:07:56 am

Hi,
This code is working fine for creating issue thanks for that, just want to know how to attach file in JIRA?

Reply
Ismael Garnica
5/29/2021 07:47:38 am

Thank you so much! Helped me a lot.

Reply

Your comment will be posted after it is approved.


Leave a Reply.

    Enter your email address:

    Author

    Jobin Kuruvilla - Works in Adaptavist as Head of DevOps Professional Services. 

    Author of JIRA Development Cookbook and JIRA 5.x Development Cookbook.


    RSS Feed

    Categories

    All
    Acive Objects
    Ajs
    Book
    Components
    Condition
    Custom Fields
    Customization
    Events
    Gadgets
    Javascript
    Jql
    Listener
    Mail
    Permissions
    Plugin Framework
    Post Function
    Properties
    Remote Invocation
    Reporting
    Rest
    Scheduled Tasks
    Search
    Services
    Soap
    Summit
    User Interface
    Validator
    Webwork Actions
    Workflow

    Archives

    October 2016
    August 2016
    March 2016
    January 2016
    December 2015
    May 2014
    December 2013
    November 2013
    July 2013
    June 2013
    April 2013
    October 2012
    September 2012
    August 2012
    July 2012
    May 2012
    March 2012
    February 2012
    January 2012
    December 2011
    November 2011
    June 2011
    May 2011
    April 2011
    March 2011
    February 2011
    January 2011
    November 2010
    October 2010
    September 2010
    August 2010

SUPPORT
APPS
TUTORIALS
THE BOOK
© J-Tricks