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);
}
Related
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;
}
Thanks to this valuable site, I found useful tips since 08/2017 to retrieve cookies and crumbs for Yahoo Finance site in order to solve my bulk quote download problem.
Nevertheless my program (written in Java) doesn't work anymore since end of May 2018.
I get the following error message :
CookieHandler retrieved cookie:
GUCS="AX62rEgH";$Path="/";$Domain=".yahoo.com" Added cookie using
cookie handler getContent on quote failed: java.io.IOException: Server
returned HTTP response code: 401 for URL:
https://query1.finance.yahoo.com/v7/finance/download/AC.PA?period1=1526594400&period2=1527631200&interval=1d&events=history&crumb=null
I think that the crumb search is failing..
FYI : I am a Java programmer "amateur" since 2003
Please advise if anybody knows how to solve this problem
Thanks to Maxzoom and Dave for their prompt answer. I apologize for the lack of details in my question.For that reason I am adding the complete java method I was using successfully until last month, thanks on one hand to the code of Serge dated Aug 27 2017
Since the method is too long in the comment page I will paste in a new answer Here is the method below:
public static String getQuote3(String quoteString, String stock) throws IOException {
int curByte;
char curChar;
String curQuote,z;
boolean priceFlag;
z="rr";
//////////////Search for cookies
try {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL quoteURL = new URL("https://fr.finance.yahoo.com/quote"+stock+"/history?p="+stock);
URLConnection con = quoteURL.openConnection();
con.getContent();
// get cookies from underlying CookieStore
CookieStore cookieJar = manager.getCookieStore();
java.util.List <HttpCookie> cookies = cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
//now you can search for the crumb in the yahoo site:
String crumb = null;
InputStream inStream = con.getInputStream();
InputStreamReader irdr = new InputStreamReader(inStream);
BufferedReader rsv = new BufferedReader(irdr);
Pattern crumbPattern = Pattern.compile(".*\"CrumbStore\":\\{\"crum\":\"([^\"]+)\"\\}.*");
String line = null;
while (crumb == null && (line = rsv.readLine()) != null) {
Matcher matcher = crumbPattern.matcher(line);
if (matcher.matches() && matcher.group(1).length()< 12)
crumb = matcher.group(1);
if(crumb!= null)
{
System.out.println ("crumb= " + crumb) ;
}
}
rsv.close();
String quoteUrls = quoteString + crumb;
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John Doe");
// add cookie to CookieStore for a particular URL quoteURL = new URL(quoteUrls);
try {
cookieJar.add(quoteURL.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
} catch(Exception e) {
System.out.println("Unable to set cookie using CookieHandler");
e.printStackTrace();
}
con.connect();
try {
DataInputStream quoteStream = new DataInputStream(quoteURL.openStream());
priceFlag = false;
curQuote = "";
while( (curByte = quoteStream.read()) != -1) {
curChar = (char) curByte;
curQuote += curChar;
}
System.out.println(curQuote);
priceFlagn = true;
return curQuote;
} catch (IOException e) {
System.err.println("getContent on quote failed: " + e);
priceFlagn = false;
}
} catch (MalformedURLException e) {
System.err.println("Yikes. URL exception");
}
return z;
}
I am trying to make a web proxy for HTTP communication between server and client. The GET method is working fine but I am POST method part is not working. I am sure I have missed out something. I want to know what have I missed or not implemented.
// request from client is handle from here
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
break;
}
if (cnt == 0) {
System.out.println("inputLine "+inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//hum inputline sy URL nikaal rahay hai
if(tokens[0]=="POST")
{
f=1;
}
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
BufferedReader rd = null;
try {
//yaha sy hum ab server ko request send karay gy
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
HttpURLConnection huc = (HttpURLConnection) conn;
conn.setDoInput(true);
conn.setDoOutput(false);
// now we will get the response from the server
if (f == 1) {
huc.setDoOutput(true);
huc.setInstanceFollowRedirects(false);
huc.setRequestMethod("POST");
huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty("charset", "utf-8");
}
InputStream is = null;
if (conn.getContentLength() > 0)
{
try {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
} catch (IOException ioe) {
System.out.println(
"********* IO EXCEPTION **********: " + ioe);
}
}
What is the error you are getting on the post? And what is a sample GET request that is being passed into your code?
When I use a simple GET request, the code fails because the urlToCall does not have the host or protocol. The below code worked for me, but I would highly suggest you change your code to not hide the exceptions that are being thrown because they will have important information about what is going wrong with your code.
if (cnt == 1) {
System.out.println("host: " + inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = "HTTP://" + tokens[1] + urlToCall;
}
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
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