Karate - missing double quotes in the response of Runner.runFeature() - java

I'm trying to get response in java after Runner.runFeature() execution however double quotes are removed from some of entities.
The feature file called is reading external json file.
Then dynamically changing values in karate and making post.
In output I see that the file have double quotes.
However after execution when I see in the response map double quotes are removed on some of objects.
Initial json file (sample.json):
{"d":{"ChangeRequestType":"AAA","AdditionalInformation":"bla","RequestReason":"test BP creation","BusinessPartner":{"BPCategory":"2","Description":"BLA","CentralData":{"Name1":"NYJKPEFB0818GR4","Name2":"NYJKPEFB0818GR4","NameOrg1":"LM60Q9ZBBXM4SHXWNJZK","NameOrg2":"LM60Q9ZBBXM4SHXWNJZK"},"TaxNumbers":[{"TaxNumberCategory":"XYZ","TaxNumberProperty":"999"}],"IdentificationNumbers":[{"IdentificationType":"BLA01","IDNumber":"123"}],"BankDetails":[{"BankdetailsID":"0001","BankNumber":"210","BankAccount":"12344","BankCountry":"DE","BankAccountName":"Hardcoded bank account"}],"Addresses":[{"AddressType":"1","PhysicalAddresses":[{"HouseNumber":"40","City":"Berlin","PostalCode":"1333","CountryKey":"DE","Street":"BLA"}]}]}}}
Feature file, reading external json file:
* def entityCreate = read('..//utils/sample.json')
Scenario:Post
------------------------------------------------------------------------------------------------------------
Creating unique BusinessPartner
Given url uri
And request entityCreate
When method post
Then status 201
Invoking feature file from JAVA class:
Map<String, Object> resultCreate = Runner.runFeature(getClass(), "/../odata/businesspartner/businessPartnerCreateTest.feature", null, true);
Result of getting result from Runner:
System.out.println(resultCreate.get("entityCreate").toString());
Result:
{d={ChangeRequestType=AAA, AdditionalInformation=bla, RequestReason=test BP creation, BusinessPartner={BPCategory=2, Description=BLA, CentralData={Name1=NYJKPEFB0818GR4, Name2=NYJKPEFB0818GR4, NameOrg1=LM60Q9ZBBXM4SHXWNJZK, NameOrg2=LM60Q9ZBBXM4SHXWNJZK}, TaxNumbers=[{"TaxNumberCategory":"ABC","TaxNumberProperty":"123"}], IdentificationNumbers=[{"IdentificationType":"ABC","IDNumber":"1234"}], BankDetails=[{"BankdetailsID":"0001","BankNumber":"210","BankAccount":"12345","BankCountry":"DE","BankAccountName":"Hardcoded bank account"}], Addresses=[{"AddressType":"1","PhysicalAddresses":[{"HouseNumber":"40","City":"Berlin","PostalCode":"1333","CountryKey":"DE","Street":"BLA"}]}]}}}
Some " " where removed and some remains.
Any help appreciated, I'm lost and most probably making silly mistake.

Most likely you are printing a string concatenation, behind the scenes the JSON is probably fine: https://github.com/intuit/karate#print
Otherwise, impossible to tell from what you have provided. Maybe you should follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Related

Convert XML to and from Java

I am trying to get the XML response from the rest API. And I am getting JSON response for all customers and XML for single customer from API. PFB the screen print for the case for both cases:
Case 1: When URL= http://localhost:8080/spring-crm-rest/api/customers/ then I am getting JSON response
JSON Response
Case 2: When URL = http://localhost:8080/spring-crm-rest/api/customers/1 then I am getting XML response
XML Response
Please find below the URL for the complete code to replicate the same at your end.
Link for the code: https://drive.google.com/file/d/1fd7DyUsfOvY4fX0nm6j4fzrwxHyg9ZGz/view?usp=sharing
Ok I think the reason why that happens is the following:
the path /spring-crm-rest/api/customers/ has return type List<Customer> -> default java List as top level -> json result
while /spring-crm-rest/api/customers/1 has return type Customer as top level which has the javax.xml.bind annotations -> xml result
Changing this may be a bit tricky but these are some possible things you can try:
specifically set the content type of the endpoint like this: #GetMapping(produces = {"application/json"})
removing the #Xml.* annotations -> spring will can serialize the class without any annotations but without them you have less of a control over the resulting json (e.g. renaming fields, etc). Depending on your usecase it might not be needed though

How to combine JSON values in the response using Java

I am currently working on a school project. We have a series of response templates in JSON format that will take values from the request and then return it accordingly in the response when run in postman.
e.g
Request:
{
"Application_id":123456
}
Response:
{ "Application_id: 123456, TIMESTAMP: 20220501}
I am able to get these values in the response but the issue I am running accross now is figuring out how to combine 2 values in the request into one like so:
Request:
{
"Application_id":123456
"user_id_first_six": 456789
"user_id_last_four": 1234
}
Expected Response:
{ "Application_id: 123456, TIMESTAMP: 20220501, combined_id:456789****1234}
what I have tried is to put combined_id : "user_id_first_six"+******+"user_id_last_four" but this doesnt work.
Apologies if I cant be more specific as there are portions that I have left out due to confidentiality issues.
The easiest way to achieve this in Java would be to use JSONObject. In your Request-Handler, add two parameters of Type JSONObject and then merge them:
jsonObj.putAll(jsonObj1)
Thanks all for the guidance. I basically did what Knu8 suggested and extracted the values using Matcher+Regex (<(.*)>)(\W*)(<(.*)>) and converted them to strings and then used StringBuilder to append all the components together.

Rest assured : Illegal character in path

I am using response retrieved from one endpoint as path param in another endpoint.
However, when used in URI, it throws java.net.URISyntaxException: Illegal character in path.
//Post the endpoint
Response resp2 = RestAssured.given().
pathParam("id", build).
log().all().
when().urlEncodingEnabled(false).post("https://abc/{id}");
This is because the value of id used in uri is with double quotes like :-
https://abc/"id".
How can I get rid of these double quotes so as to use the value of id in uri , please advise.
First talk to the developer about this, because the nature of path param (/{id}) is to be replaced by a legitimate value (not enclosed in quotes); something like https://abc/23 or https://abc/param
I would not suggest any work-around for this as this is implemented in a wrong way from REST end point definition. You might go ahead and raise a defect against this.
Taking a shot in the dark here because I feel like the issue could possibly be coming from how you're getting the string from that response. If you're pulling it from a JSON using GSON or similar:
String name = myResponseJsonObject.get("member_name")
System.out.Println(name);
will print
"John"
whereas
String name = myResponseJsonObject.get("member_name").getAsString()
System.out.Println(name);
will give you
John
A small detail but this has tripped me up when using GSON and others when working with JSONs in java.
Thank you John and Mohan for your time , I really appreciate it.
I resolved this issue yesterday evening using Stringof function which removed the double quotes and provided me the String like value.

Passing Jackjson JSON object from JSP to JavaScript function

I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){
alert(h);
}
Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
<input type="button"
name="setFontButton"
value="Set"
class="form_btn_primary"
onclick="test('<%=theJSON%>'); return false;"/>
Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);
Then pass in it
onclick="test('<%=widg%>'); return false;"/>
Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget#ba8af9
I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);
and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this
{
"id":1,
"splits":[
{
"texts":[
{
"value":"Test",
"locationX":3,
"locationY":-153,
"font":{
"type":"Normal",
"size":"Medium",
"bold":false,
"colour":"5a5a5a",
"italics":false
}
}
]
}
]
}
Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>
That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');
Should work fine
I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"
and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'
You can follow the following steps
Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.
this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi

Converting HTTP Response (Java "Properties" stream format) in to NSDictionary

I am working on iphone application which contains HTTP Request and Response.
The format of the response is a key/value format compatible with the Java "Properties" stream format.
I want to store the response into a NSDictionay. Could you suggest me any way to do this?
Thank you.
sangee
Edit:
Thanks guyz for the quick replies!!!
is their any other ways to store them in NSSdictionay?
I just want to store the album name and description in an array like this:
mutablearray = [wrwr, dsf, my album];
could you please let me know if this possible or not?
Thanks again!!!
This is the response i got it for my HTTP request...
GR2PROTO
debug_album= debug_gallery_version= debug_user=admin debug_user_type=Gallery_User debug_user_already_logged_in= server_version=2.12 status=0 status_text=Login successful.
#GR2PROTO debug_album= debug_gallery_version= debug_user=admin debug_user_type=Gallery_User debug_user_already_logged_in=1
album.name.1=wrwr album.title.1=wrwr album.summary.1= album.parent.1=0 album.resize_size.1=640 album.thumb_size.1=100 album.perms.add.1=true album.perms.write.1=true album.perms.del_item.1=true album.perms.del_alb.1=true album.perms.create_sub.1=true album.info.extrafields.1=Description
album.name.2=dsf album.title.2=dsf album.summary.2= album.parent.2=0 album.resize_size.2=640 album.thumb_size.2=100 album.perms.add.2=true album.perms.write.2=true album.perms.del_item.2=true album.perms.del_alb.2=true album.perms.create_sub.2=true album.info.extrafields.2=Description
album.name.3=my album album.title.3=my album album.summary.3= album.parent.3=0 album.resize_size.3=640 album.thumb_size.3=100 album.perms.add.3=true album.perms.write.3=true album.perms.del_item.3=true album.perms.del_alb.3=true album.perms.create_sub.3=true album.info.extrafields.3=Description
If you can, I would recommend serializing the data as JSON (or XML, if you have to) and parsing it using TouchJSON or a similar parser. If you really can't, then you'll have to implement your own parser--take a look at NSScanner.
Look at NSStream and the Stream Programming Guide for Cocoa.
Back in the day when Java was fully integrated into Cocoa, NSStream mapped onto Java streams. It still might. IIRC, (it's been a while) NSStream will return a properly populated NSDictionary from a Java stream.
Edit:
It looks like the text returned is just a space delimited hash which is the Java version of dictionary. It takes the form of key=value space key=value. The only tricky part is that some of the hashes are nested.
The first line for example is nested:
debug_album{
debug_gallery_version{
debug_user=admin
debug_user_type=Gallery_User
debug_user_already_logged_in{
server_version=2.12
status=0
status_text=Login successful.
}
}
}
You need a recursive scanner to parse that. The "key=space" pattern indicates a nested dictionary.

Categories

Resources