How to create an issue in Jira using the REST API? - java

How to create an issue in Jira using the REST API? I have tried the examples using curl. But I need to create defect in Eclipse using Java and REST API.

You want to integrate JIRA into Eclipse?
See: https://confluence.atlassian.com/display/IDEPLUGIN/Working+with+JIRA+Issues+in+Eclipse
You want a custom application to create tickets automagically?
Probably you'll need a REST client using the jersey-client artifact, I think this is the easiest way.
Firstly, check out the REST API documentation: https://docs.atlassian.com/jira/REST/latest/
With the POST method you can push a JSON object depiciting a wannabe issue to the JIRA server. You just have to exactly know what fields you can and should fill in. If you send fields that are not on the create issue screen, or is required but you haven't specified them, you'll get an error.
You can find an example here: http://pastebin.com/JeucUZNG

Try this code
public static String invokePostMethod() throws AuthenticationException, ClientHandlerException, IOException
{
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/rest/api/latest/issue");
String data = "{"fields":{"project":{"key":"DEMO"},"summary":"REST Test","issuetype":{"name":"Bug"}}}";
String auth = new String(Base64.encode(Uname + ":" + Password));
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");
} else if (statusCode == 403) {
throw new AuthenticationException("Forbidden");
} else if (statusCode == 200 || statusCode == 201) {
System.out.println("Ticket Create succesfully");
} else {
System.out.print("Http Error : " + statusCode);
}
// ******************************Getting Responce body*********************************************
BufferedReader inputStream = new BufferedReader(new InputStreamReader(response.getEntityInputStream()));
String line = null;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
return response.getEntity(String.class);
}

try {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
String input = "{\"fields\":{\"project\":{\"key\":\"DEMO\"},\"summary\":\"REST Test\",\"description\": \"Creating of an issue using project keys and issue type names using the REST API\",\"issuetype\":{\"name\":\"Bug\"}}}";
WebResource resource = client.resource("http://localhost:8080/rest/api/2/issue");
ClientResponse response = resource.type("application/json").accept("application/json").post(ClientResponse.class,input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from server");
System.out.println(response.getEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
For more info:
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue
http://www.j-tricks.com/tutorials/java-rest-client-for-jira-using-jersey

Related

Using alfresco Rest-API inside my java app but cant find a way to make it

So Im trying to implement a syncronization between my Openbravo and alfresco, I just discovered the rest api for alfresco and with some dificulties I get the result i wanted (that was change some permisions of a folder) but now im facing a new problem, I have no clue how to make that call in java code, im not a good developer and I didnt study web, is there any tutorial or documentation on how to make that? I find alfresco a bit dificult since I cant find many tutorials. Thx for the help
I just figured out how to make it posible in a simple way
public String getToken() throws Exception {
HttpClient clientToken = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.build();
String OAuthToken = "";
String urlToken = "";
HttpPost httpPost = new HttpPost(urlToken);
JsonObject jsonCredentials = Json.createObjectBuilder().add("userId", "ad")
.add("password", "ad").build();
StringEntity entity = new StringEntity(jsonCredentials.toString());
httpPost.setEntity(entity);
HttpResponse response = clientToken.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 201) {
BufferedReader br = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String output = br.readLine();
if (!output.isEmpty()) {
JSONObject objetoJSON = new JSONObject(output);
OAuthToken = objetoJSON.getJSONObject("entry").getString("id");
} else {
log4j
.debug("The response is empty [Code " + response.getStatusLine().getStatusCode() + "]");
}
} else {
log4j.debug("Error retrieving token: " + response.getStatusLine().getStatusCode() + " => "
+ response.getStatusLine().getReasonPhrase());
}
clientToken.getConnectionManager().shutdown();
OAuthToken = Base64.getEncoder().encodeToString(OAuthToken.getBytes());
return OAuthToken;
}

How to update metadata for share point document via rest api using JAVA Apache httpclient?

I am trying to update metadata for Share Point library document via rest API using JAVA Apache HTTP client.
I am able to get Form Digest Value from SharePoint API context. However receiving error 500(Microsoft.SharePoint.SPException) on submitting post request to update metadata.
"errorcode: -2146232832, The object specified does not belong to a list."
Could you please review below code snippet and advise how I can resolve this issue? Please note that 'ABC%20API%20POC' is Sharepoint library (ABC API POC).
HttpPost post = new HttpPost("/_api/contextinfo");
post.setHeader("Accept", "application/json; odata=verbose");
post.setHeader("content-type", "application/json; odata=verbose");
CloseableHttpResponse responseDigest = httpclient.execute(target, post,context);
byte[] content = EntityUtils.toByteArray(responseDigest.getEntity());
String jsonString = new String(content, "UTF-8");
JSONObject json = new JSONObject(jsonString);
String formDigestValue = json.getJSONObject("d").getJSONObject("GetContextWebInformation").getString("FormDigestValue");
//post request to update the metadata
String updateJson = "{'__metadata': { 'type': 'SP.ListItem'}, 'TestColumn':'TestingValue'}";
String filename="/DocumentRepository/ABC%20API%20POC/upload2.txt";
// ABC%20API%20POC- is a library
HttpPost updateMetaDateRequest = new HttpPost("/_api/web/GetFileByServerRelativeUrl('"+ filename + "')/ListItemAllFields");
updateMetaDateRequest.setHeader("X-RequestDigest", formDigestValue);
updateMetaDateRequest.setHeader("X-HTTP-Method", "MERGE");
updateMetaDateRequest.setHeader("If-Match", "*");
updateMetaDateRequest.setHeader("Accept", "application/json; odata=verbose");
updateMetaDateRequest.setHeader("content-type", "application/json; odata=verbose");
updateMetaDateRequest.setEntity(new StringEntity(updateJson));
try {
CloseableHttpResponse updateMetaDateResponse = httpclient.execute(target,updateMetaDateRequest,context);
int rc = updateMetaDateResponse.getStatusLine().getStatusCode();
String reason = updateMetaDateResponse.getStatusLine().getReasonPhrase();
if (rc != 200) {
System.out.println("updateMetaDateResponse" + " failed " +reason +rc );
}
else {
System.out.println("updateMetaDateResponse:" + rc + reason);
}
}
finally {
// if (updateMetaDateResponse != null) updateMetaDateResponse.close();
}

How to pass header information as key value pair to consume rest service using jersey

I got a url of web service which returns values in json format but it needs header information in get request as key value pair e.g. I need to pass Emp_code as key and 'xyz' as value to get details of all employees in postman. Below is code which I tried
private static void getEmployees()
{
final Client client = new Client();
final WebResource webResource = client.resource("http://abc/springrestexample/employees");
final ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200)
{
throw new RuntimeException("Failed Http Error code " + response.getStatus());
}
final String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
}
In above code how should I pass header info (key-value) to get desired result.
You can add .header("KEY", "Value" ) after accept.Please check below
final Client client = new Client();
final WebResource webResource = client.resource("http://abc/springrestexample/employees");
final ClientResponse response = webResource.accept("application/json").header("KEY", "Value" ).get(ClientResponse.class);
if (response.getStatus() != 200)
{
throw new RuntimeException("Failed Http Error code " + response.getStatus());
}
final String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);

Creating a new "JIRA issue" using REST API in java

Hey guys i am really struggling with this, i would like to create new JIRA issues using java through the REST API but every example i have seen is incomplete or doesnt work for me like this one:
How to create an issue in jira using java rest api
Any help, sample code or link to the right direction would be greatly appreciated!
I think this sample code is helps u
This is totlly working for me
public static String invokePostMethod() throws AuthenticationException, ClientHandlerException, IOException {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/rest/api/latest/issue");
String data = "{"fields":{"project":{"key":"DEMO"},"summary":"REST Test","issuetype":{"name":"Bug"}}}";
String auth = new String(Base64.encode(Uname + ":" + Password));
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");
} else if (statusCode == 403) {
throw new AuthenticationException("Forbidden");
} else if (statusCode == 200 || statusCode == 201) {
System.out.println("Ticket Create succesfully");
} else {
System.out.print("Http Error : " + statusCode);
}
// ******************************Getting Responce body*********************************************
BufferedReader inputStream = new BufferedReader(new InputStreamReader(response.getEntityInputStream()));
String line = null;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
return response.getEntity(String.class);
}

How auto redirect in HttpClient (java, apache)

I create httpClient and set settings
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");
First request (get)
GetMethod first = new GetMethod("http://vk.com");
int returnCode = client.executeMethod(first);
BufferedReader br = null;
String lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
first.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(first.getResponseBodyAsStream(), Charset.forName("windows-1251")));
String readLine = "";
while (((readLine = br.readLine()) != null)) {
lineResult += readLine;
}
}
Response correct.
Second request (post):
PostMethod second = new PostMethod("http://login.vk.com/?act=login");
second.setRequestHeader("Referer", "http://vk.com/");
second.addParameter("act", "login");
second.addParameter("al_frame", "1");
second.addParameter("captcha_key", "");
second.addParameter("captcha_sid", "");
second.addParameter("expire", "");
second.addParameter("q", "1");
second.addParameter("from_host", "vk.com");
second.addParameter("email", email);
second.addParameter("pass", password);
returnCode = client.executeMethod(second);
br = null;
lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
second.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(second.getResponseBodyAsStream()));
String readLine = "";
while (((readLine = br.readLine()) != null)) {
lineResult += readLine;
}
}
this response is correct too, but I need to be redirected to Headers.Location.
I do not know how to get value from Headers Location or how to automatically enable redirection.
Due to design limitations HttpClient 3.x is unable to automatically handle redirects of entity enclosing requests such as POST and PUT. You either have to manually convert POST request to a GET upon redirect or upgrade to HttpClient 4.x, which can handle all types of redirects automatically.
In case of the 3.x version of HttpClient, you can also check if the response code is 301 or 302 and then use the Location header to re-post:
client.executeMethod(post);
int status = post.getStatusCode();
if (status == 301 || status == 302) {
String location = post.getResponseHeader("Location").toString();
URI uri = new URI(location, false);
post.setURI(uri);
client.executeMethod(post);
}
You just need to add this:
second.setFollowRedirects(true);
Also, you may use LaxRedirectStrategy

Categories