How to resolve Default parser issue? - rest-assured

Hi i am getting the following error when trying to run a post req. Are there any dependencies that are missing ?
Exception in thread "main" java.lang.IllegalStateException: Cannot invoke the path method because no content-type was present in the response and no default parser has been set.
You can specify a default parser using e.g.:
RestAssured.defaultParser = Parser.JSON;
String a= "80820221";
String body= "{\n" +
" \"request\": {\n" +
" \"id\": \"" + a + "\",\n" +
" \"id2\": \"800002400434\",\n" +
" \"id3\": \"\",\n" +
" \"id4\": \"WEB\"\n" +
" }\n" +
"}";
RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
// Setting Base URI
reqBuilder.setBaseUri(base);
// Setting Base Path
reqBuilder.setBasePath(basePath");
reqBuilder.setContentType(ContentType.JSON);
// Getting RequestSpecification reference using builder() method
RequestSpecification reqSpec = reqBuilder.build();
Response response = RestAssured.given(reqSpec).body(body).log().all().when().post().then().log().all().extract().response();
int status = response.getStatusCode();
System.out.println(status);
**String successMessage = response.getBody().path("response.status")**;
System.out.println(successMessage);
it is giving errror in the above line
i am expecting 200 response. In postman it is giving 200 but in script it is returning 400 and unable to get the response body

Related

OAuth 1.0 A Invalid Signature when requesting request token (SalesForce/JIRA Integration)

I've been trying my darndest to avoid asking a question. I'm recieving an invalid signature error when trying to request a request token from JIRA from within Salesforce. The response I'm getting is:
08:15:24:201 USER_DEBUG [30]|DEBUG|
oauth_problem=signature_invalid
&oauth_signature=RaOPaBPznmS7aDUuJN1pOclcyHWP4uRYYx4j%2F%2BdtKB1SD4l1JcCCys3P3RAa8P7377MwLsIMBtkHfL62jaXr5LV30RndjVUSlCsVl3h47CvinHgDtTMwWGukQJXhOmSsLPvccCqD7qsRmiQnnjSJCwd9YKJEi2cxNcwMqhnceqAwJdzn3RD%2FBBeNpf3G97wqWhJx%2FtyEhQGk35OTu00fhtw%2BIX025STN3iiGNbyANlmoImAGWqAJeqJOPUVva7TR2OAInysL9%2BHmYkQTOcb7a9sn5rRWUqE4Jua6EoVyPgzJnSgZ4pFEIMzU0eTWQqhSFdQwOdnoq5EQU8W%2BPJM8uA%3D%3D
&oauth_signature_base_string=POST%26https%253A%252F%252F.atlassian.net%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_consumer_key%253D3MVG9KI2HHAq33RwCPH5bNzAHbOgfiicjJ6HjvVfNhGU8aWXGl6ps.vsEzobCPqRXuDcmeV2Baw%25253D%25253D%2526oauth_nonce%253D-6826921263934288296%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1492182924
&oauth_signature_method=RSA-SHA1
The code I'm using to try to generate the signature is:
// GitHub OAuth Playground: https://github.com/jesperfj/sfdc-oauth-playground/blob/master/OAuth/src/classes/OAuth.cls
// OAuth Bible: http://oauthbible.com/
// Static Values
String consumerKey = '3MVG9KI2HHAq33RwCPH5bNzAHbOgfiicjJ6HjvVfNhGU8aWXGl6ps.vsEzobCPqRXuDcmeV2Baw==';
String endpoint = 'https://<AtlassianSiteName>.atlassian.net/plugins/servlet/oauth/request-token';
// Params
String callbackParam = '&oauth_callback=' + EncodingUtil.urlEncode('https://localhost/', 'UTF-8');
String consumerKeyParam = '&oauth_consumer_key=' + EncodingUtil.urlEncode(consumerKey, 'UTF-8');
String signatureMethodParam = '&oauth_signature_method=RSA-SHA1';
String timestampParam = '&oauth_timestamp=' + String.valueOf(DateTime.now().getTime()/1000);
String nonceParam = '&oauth_nonce=' + String.valueOf(crypto.getRandomLong());
String versionParam = '&oauth_version=1.0';
String paramString = consumerKeyParam + nonceParam + signatureMethodParam + timestampParam + versionParam + callbackParam;
// Get baseString
String baseString = 'POST&' + encodingUtil.urlEncode(endpoint, 'UTF-8') + paramString;
system.debug(baseString);
blob sig = crypto.signWithCertificate('RSA-SHA1', blob.ValueOf(baseString), 'SelfSignedCert_26Oct2015_184625');
String signature = EncodingUtil.urlEncode(EncodingUtil.base64encode(sig), 'UTF-8');
httpRequest req = new httprequest();
http http = new http();
req.setEndPoint(endpoint);
req.setMethod('GET');
req.setBody(paramString +
'&oauth_signature=' + signature);
httpresponse res = http.send(req);
system.debug(res.getBody());
Note: Yes I understand that I probably shouldn't be sharing some of this information but these are my personal test orgs that contain nothing important and I'm not providing the SSL used. You'll notice some comments at the top of my code containing a few urls to my favorite resources that have gotten me this far. These are not the only resources I've used, just the most useful ones.

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;
}

Grails SOAP request with httpbuilder throws SAXParseException

when I post a Soap request with HttpBuilder, I get an exception.
My Code:
def reqxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <web:GetWeather xmlns:web=\"http://www.webserviceX.NET\">\n" +
" <web:CityName>Berlin</web:CityName>\n" +
" <web:CountryName>Germany</web:CountryName>\n" +
" </web:GetWeather>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>"
def http = new HTTPBuilder("http://www.webservicex.com/globalweather.asmx?WSDL")
http.request(Method.POST, ContentType.XML) {
body = reqxml
response.success = { resp, xml ->
println (xml)
}
response.failure = {resp, xml ->
println "Error"
}
}
This code throws a SAXParseException with the message Content is not allowed in prolog.
Happens at the http.request method.

Titanium Studio to Grails imge post

I am trying to POST an image to my grails application and I'm not having much luck.
My titanium code is:
function upload(){
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info(picMedia + " : " +message.value);
Ti.API.info('IN ERROR ' + e.error);
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e){
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST', 'http://localhost:8080/FYP/Profile/appUploader');
// send the data
xhr.send({
media: picMedia,
message: message.value,
});
}
My grails code is as follows:
def appUploader(){
println "MEDAI PARAMS: " + params.media
def f = request.getFile('media') ;
println "HERE: " + f
if (request.getFile(params.media).getOriginalFilename()) {
println "FROM APP: " + request.getFile('myFile').getOriginalFilename()
return
}
}
Im getting error from the mobile app and error on the "if" line in the web app.
What am i doing wrong?
we had the same problem in one of our apps. The difficulty is that titanium is not really able to handle binary files in that case.
We did the following:
create base64 encoded string of the image on client side
post this string to the backend
decode base64 to image again
We analyzed a lot of network traffic and in most cases titanium tries to send the file but due to javascript its alway converted into some kind of ascii and this is not usable by the server side.

Updating issue with JIRA rest api 4.4

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.

Resources