Updating issue with JIRA rest api 4.4 - jira

I am trying to update the fixVersion of an issue via the JIRA rest api. The JIRA version is 4.4.3#663-r165197. It is the instance hosted by codehaus, not sure if that makes a difference or not.
The request looks like:
curl -u [username]:[password] -X PUT -H 'Content-type: application/json' \
-d "http://jira.codehaus.org/rest/api/latest/issue/GEOS-[id]"
{
"update":{
"fixVersions":[
{
"set":[
{
"name":"2.2-beta3"
}
]
}
]
}
}
But I get back a 405, method not allowed error. Which makes sense if I look at the rest api docs for that version [1]. They seem to indicate there is no way to update an issue in this manner. BUt if I look at the docs for the latest version [2] they seem to indicate it is possible.
So I guess the question is how do I update an issue in this manner in JIRA 4.4? Or is it not possible?
Thanks!
[1] https://developer.atlassian.com/static/rest/jira/4.4.1.html#id151460
[2] http://docs.atlassian.com/jira/REST/latest/#id165544

For 4.4 you have to use the SOAP updateIssue method. 5.0 fixed this.

Prepare Json data as below(Here java as technology i had used), and pass using put method/API.
public static String generateJson(String customFieldId, Object value,
String attribute) {
if (isBlankOrNull(attribute)) {
return "\"" + customFieldId + "\":" + "\"" + value + "\"";
} else {
return "\"" + customFieldId + "\":{\"" + attribute + "\":\"" + ""
+ value + "\"}";
}
}
public static int invokePutMethod(String auth, String url, String data) {
int statusCode = 0;
try {
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);
statusCode = response.getStatus();
return statusCode;
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
// vjErrorLog.info(Level.INFO, e);
}
return statusCode;
}
attribute could be key, id, name, value etc,
In case of fix version or components, you may have one more way to prepare json data
return "\"" + customFieldId + "\":[{\"set\" :[{ \"" + attribute
+ "\" :" + "\"" + data + "\"}]}]";
and invoke put method with above json data.

Related

Jenkins Docker container - 403 no valid crumb was included in the request

I'm setting up my Jenkins server, and on simple requests in the web interface, like creating a folder, a pipeline, a job, etc., I periodically get the following error:
HTTP ERROR 403
Problem accessing /job/Mgmt/createItem. Reason:
No valid crumb was included in the request
The server is using the Jenkins/Jenkins container, orchestrated by Kubernetes on a cluster on AWS created with kops. It sits behind a class ELB.
Why might I be experiencing this? I thought the crumb was to combat certain CSRF requests, but all I'm doing is using the Jenkins web interface.
Enabling proxy compatibility may help to solve this issue.
Go to Settings -> Security -> Enable proxy compatibility in CSRF Protection section
Some HTTP proxies filter out information that the default crumb issuer uses to calculate the nonce value. If an HTTP proxy sits between your browser client and your Jenkins server and you receive a 403 response when submitting a form to Jenkins, checking this option may help. Using this option makes the nonce value easier to forge.
After a couple of hours of struggling, I was able to make it work with curl:
export JENKINS_URL=http://localhost
export JENKINS_USER=user
export JENKINS_TOKEN=mytoken
export COOKIE_JAR=/tmp/cookies
JENKINS_CRUMB=$(curl --silent --cookie-jar $COOKIE_JAR $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' -u $JENKINS_USER:$JENKINS_TOKEN)
echo $JENKINS_CRUMB
curl --cookie $COOKIE_JAR $JENKINS_URL/createItem?name=yourJob --data-binary #jenkins/config.xml -H $JENKINS_CRUMB -H "Content-Type:text/xml" -u $JENKINS_USER:$JENKINS_TOKEN -v
when calling the http://JENKINS_SERVER:JENKINS_PORT/JENKINS_PREFIX/crumbIssuer/api/json you receive a header ("Set-Cookie") to set a JSESSIONID, so you must supply it in the upcoming requests you issue,
the reason is that jenkins test for valid crumb in this manner: comparing the crumb you send in the request with a crumb it generates on the server side (using your session id),
you can see it in jenkins code: scroll down to method:
public boolean validateCrumb(ServletRequest request, String salt, String crumb)
it means you HAVE to include a session in the next requests (after fetching the crumb)!
so the curl --cookie must be used as ThiagoAlves stated in his solution
i use java so i used this next tester (HTTPClient would be prefered, but i wanted a simple java only example):
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class JobRunner
{
String jenkinsUser = "tester";
String jenkinsPassword = "1234"; // password or API token
String jenkinsServer = "localhost";
String jenkinsPort = "8080";
String jenkinsPrefix = "/jenkins";
String jSession = null;
String crumb = null;
HttpURLConnection connection = null;
String responseBody = "";
public void openConnection(String requestMethod, String relativeURL) throws Exception
{
// prepare the authentication string
String authenticationString = jenkinsUser + ":" + jenkinsPassword;
String encodedAuthenticationString = Base64.getEncoder().encodeToString(authenticationString.getBytes("utf-8"));
// construct the url and open a connection to it
URL url = new URL("http://" + jenkinsServer + ":" + jenkinsPort + jenkinsPrefix + relativeURL);
connection = (HttpURLConnection) url.openConnection();
// set the login info as a http header
connection.setRequestProperty("Authorization", "Basic " + encodedAuthenticationString);
// set the request method
connection.setRequestMethod(requestMethod);
}
public void readResponse() throws Exception
{
// get response body and set it in the body member
int responseCode = connection.getResponseCode();
switch (responseCode)
{
case 401:
System.out.println("server returned 401 response code - make sure your user/password are correct");
break;
case 404:
System.out.println("server returned 404 response code - make sure your url is correct");
break;
case 201:
case 200:
System.out.println("server returned " + responseCode + " response code");
InputStream responseBodyContent = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseBodyContent));
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null)
{
responseBody = responseBody + currentLine + "\n";
}
break;
default:
System.out.println("server returned error response code: " + responseCode);
break;
}
}
public void setSessionCookie() throws Exception
{
jSession = connection.getHeaderField("Set-Cookie");
System.out.println("jSession: " + jSession);
}
public void disconnect() throws Exception
{
if(connection!=null)
{
connection.disconnect();
connection = null;
responseBody = "";
}
}
public void getCrumb() throws Exception
{
try
{
openConnection("GET", "/crumbIssuer/api/json");
readResponse();
setSessionCookie();
int crumbIndex = responseBody.indexOf("crumb\":\"");
if(crumbIndex!=-1)
{
int crumbIndexEnd = responseBody.indexOf("\",\"", crumbIndex);
crumb = responseBody.substring(crumbIndex + "crumb\":\"".length(), crumbIndexEnd);
System.out.println(crumb);
}
}
finally
{
disconnect();
}
}
public void runJob() throws Exception
{
try
{
openConnection("POST", "/job/test/build");
connection.setDoOutput(true);
connection.setRequestProperty("Cookie", jSession);
connection.setRequestProperty("Jenkins-Crumb", crumb);
readResponse();
System.out.println("Post response: " + responseBody);
}
finally
{
disconnect();
}
}
public static void main(String[] args)
{
JobRunner jobRunner = new JobRunner();
try
{
jobRunner.getCrumb();
jobRunner.runJob();
}
catch (Exception err)
{
err.printStackTrace();
}
}
}

Quick blox - Signature generation issue

I am trying to use this link to get described response:
{
"session": {
"application_id": 2,
"created_at": "2012-04-03T07:34:48Z",
"device_id": null,
"id": 743,
"nonce": 1308205278,
"token": "0e7bc95d85c0eb2bf052be3d29d3df523081e87f",
"ts": 1333438438,
"updated_at": "2012-04-03T07:34:48Z",
"user_id": null
}
}
But now it say application not found:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
Can't go ahead to test another requests. This is a shell script I used for getting curl request:
timestamp=`date +%s`
body="application_id=HIDDENAPPLICATIONIDHERE&auth_key=HIDDENAUTHKEYHERE&nonce=2342546&timestamp=$timestamp"
signature=`echo -n $body | openssl sha -hmac HIDDENSECRETHERE`
body=$body"&signature="$signature
#echo $body
#echo $signature
#exit 0
curl -X POST \
-H "QuickBlox-REST-API-Version: 0.1.0" \
-d $body \
https://api.quickblox.com/session.xml
So there some info regrding this maybe I've created shell script to a wrong way:
HMAC-SHA function of the body of the request, with a key auth_secret.
Request body is formed as the sorted (sorting alphabetically, as
symbols, not as bytes) by increase the string array 'parameter=value',
separated with the symbol "&". For the parameters passed as a
user[id]=123 is used just such a line of user[id]=123
Also I've prepped a Swift project how to generate signature and get session, but still has the same error with no application found.
Any recommendation? Thanks
Please verify Application ID parameter because server return:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
For example generate signature (Java):
Random random = new Random();
String nonce = Integer.toString(random.nextInt());
long time = System.currentTimeMillis() / 1000;
String timestamp = Long.toString(time);
String signature;
String str = "application_id=" + applicationId + "&" + "auth_key=" + authKey + "&" + "nonce="
+ nonce + "&" + "timestamp=" + timestamp + "&" + "user[login]=" + adminLogin + "&" + "user[password]="
+ adminPassword;
signature = UtilsMethods.calculateHMAC_SHA(str, authSecret);
calculateHMAC_SHA:
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateHMAC_SHA(String data, String key) throws SignatureException {
String result = null;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] digest = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(digest.length * 2);
String s;
for (byte b : digest) {
s = Integer.toHexString(0xFF & b);
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
}
result = sb.toString();
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}

Twitter 4j - Get tweets by user ID - Processing

There seems to be many different tutorials and examples out there to allow for tweets to be pulled into Processing from one specific user.
And yet I'm still having problems getting any code to work. I have managed to get tweets by searching with hashtags, so the twitter4j library (latest) is working within Processing (also latest software). I still a complete coding novice...
I've found the following code to do exactly what I need, but unfortunately it isn't complete, where I'm assuming you need to declare your Consumer Keys and Access tokens... But I've no idea how to do this with this code. Is this something that someone is able to provide and explain?
Essentially, I need the full sketch... Any help would be greatly appreciated!
Code from elsewhere:
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken accessToken = new AccessToken(TWITTER_TOKEN,
TWITTER_TOKEN_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.showStatus(Long.parseLong(tweetID));
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
EDIT: This is how I've added the consumer/access keys - is this right?
twitter.setOAuthConsumer("MyConsumerKey", "MyConsumerSecret");
AccessToken accessToken = new AccessToken("MyAccessToken", "MyAccessTokenSecret");
twitter.setOAuthAccessToken(accessToken);
EDIT2: This is what I have now to get the User's tweets. But produced the error: 'cannot convert from ResponseList to Status'
String user="USER ID";
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("MY CONSUMER KEY", "MY CONSUMER KEY SECRET");
AccessToken accessToken = new AccessToken("MY TWITTER TOKEN", "MY TWITTER TOKEN SECRET");
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.getUserTimeline(user);
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
you need first to create a twitter app, to do so go to https://apps.twitter.com/, from there you can get all the infos needed to get your credentials.
in your code just replace the 'CONSUMER_KEY','CONSUMER_KEY_SECRET','Access Token','Access Token Secret' by the credentials.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("XXXXX")
.setOAuthConsumerSecret("XXXXXX")
.setOAuthAccessToken("XXXX-XXXXX")
.setOAuthAccessTokenSecret("XXXXXXX");
hope this help!

Cant connect to survey monkey API

I am trying to connect to the survey monekey API with this code, which is not working. It says "Invalid API key" even though I got the API from the API console.
public void fetch() {
String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" + apiKey;
System.out.println("request being sent");
System.out.println(url);
JSONObject obj = new JSONObject();
try {
// byte[] postDataBytes = obj.toJSONString().getBytes("UTF-8");
URL ourl = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) ourl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.getRequestProperty(obj.toString().getBytes("UTF-8").toString());
int k = conn.getResponseCode();
System.out.println("The response code received is " + k);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
output = br.readLine();
System.out.println(output);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's the error:
request being sent
https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=---API-KEY----
The response code received is 200
Output from Server ....
{"status":3,"errmsg":"Expected object or value"}
I just got this url from the API console.
Ensure you are using the API key associated with your developer account registered at http://developer.surveymonkey.com, not the sample API key the console uses to let you try requests. The sample api key is not meant to be used with apps, only on the API console.
That particular error is generated when an empty string is sent for the POST data. The API expects an empty object at minimum ("{}"). If the issue pointed out by Miles above was just a typo (using 'getRequestProperty' instead of 'setRequestProperty',) check if toString on an empty JSONObject is returning "" or "{}".

Oauth not working CX api

I'm trying to use the oauth for CX exposed api, I followed their documentation, still I'm getting HTTP "BAD REQUEST" error, Here is the code -
String method = "POST";
String code = "";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", code),
new NameValuePair("redirect_uri",URLEncoder.encode(CALLBACK_URL, "UTF-8"))
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
httpClient.executeMethod(httpMethod);
Thanks,
Hemant
I've tested the following slight modification of your code and it works. You might double check that
Your key has been approved (this shouldn't be the problem given the
error you are seeing).
You are using the correct ACCESS_TOKEN_ENDPOINT_URL
Try having the redirect_uri be the same for both the auth_code response and the token request
String method = "POST";
String authCode = "[AUTH-CODE-HERE]";
String CONSUMER_KEY="[YOUR-KEY-HERE]";
String CONSUMER_SECRET="[YOUR-SECRET-HERE]";
String ACCESS_TOKEN_ENDPOINT_URL="https://api.cx.com/1/oauth/token";
String REDIRECT_URI="[YOUR-REDIRECT-HERE]";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", authCode),
new NameValuePair("redirect_uri", REDIRECT_URI)
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
int responseCode = httpClient.executeMethod(httpMethod);
System.out.println(responseCode);
System.out.println(httpMethod.getResponseBodyAsString());
If you are still running into issues, can you post the result of the following line: System.out.println(httpMethod.getResponseBodyAsString());
The CX developer API has been discontinued.
Sorry for the inconvenience.

Resources