JsonPath Query for Rest Assured - java

API URL : https://davids-restaurant.herokuapp.com/menu_items.json?category=C
I'm trying to retrieve name property of ID 913 from the above rest API
Please find my code below
String URL = "https://davids-restaurant.herokuapp.com/menu_items.json?category=C";
Response res = RestAssured.get(URL);
JsonPath jsonPathEvaluator = res.jsonPath();
System.out.println(jsonPathEvaluator.get("$..menu_items[?(#id == 913)].description"));
Error Message
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 40.
$..menu_items[?(#id == 913)].description
^
I tried this which works but I donot want to query with index but I want to query with ID
System.out.println(jsonPathEvaluator.get("menu_items[1].description"));

You can use Groovy filters to get the result. Have a look at this code.
io.restassured.response Response;
// response= Get the API response
List<String> namesList = from(response.asString()).getList("menu_items.findAll { it.id == 913 }.name");
Here I have created a list but you can find single item by using 'item.find'.

Related

How add special characters in WebTarget.queryParam name in client JavaEE 7

I try make request using client library javax.ws.rs
I'm trying to add a parameter name containing characters [ and ] to query parameters, for encdoded special characters i am used URLEncoder.encode(). But after the request, the response contains data without this parameter, the server ignored this request parameter. I made a request on the command line using "curl" on purpose with an error in this parameter and got the same result as from the request in the application. The error is clearly in the encoded parameter name, but I don’t understand how to correctly add parameters containing special characters.
The Code:
WebTarget webTarget = new Client().target(uri);
String key = "filters[Time].Start";
key = URLEncoder.encode(key,StandardCharsets.UTF_8.toString());
String value = "2022-08-27+17:00:00";
value = URLEncoder.encode(value,StandardCharsets.UTF_8.toString());
System.out.println(key + " " + value);
webTarget = webTarget.queryParam("per_page","10");
webTarget = webTarget.queryParam(key,value);
webTarget = webTarget.queryParam("order_by","time");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
Result sout : filters%5BTime%5D.Start 2022-08-27%2B17%3A00%3A00
By advise #cyberbrain, i did checked my request in server by help 'tcpdump' utilite with key '-A'.
I did request by curl and after by my java application and compare data.
In my case problems was in value parametrs, my value equels "2022-08-27+17:00:00". After add in queryparametr this symbol '+' encoded to code '%2B' and this don't like my server. I just replaced symbol '+' to symbol space (code %20) in value ("2022-08-27 17:00:00"). After that i geted correct data from my server

list of ids - ALM API Automation

i am doing api automation of hp-alm using rest assured n java.For test cases with multiple runs, im getting the below response in xml format.I want to know the list of id attributes with its values.
enter image description here
RequestSpecification httpRequest10 = RestAssured.given().cookies(loginCookies).cookies(sessionCookies).queryParam("query", "{cycle-id["+cycleId+"];test-id["+testCaseId+"]}");
Response testRunId = httpRequest10.request(Method.GET,"/qcbin/rest/domains/"+domain+"/projects/"+project+"/runs");
String testRunIdResponseBody = testRunId.getBody().asString();
//logger.info("testRunId Response Body is => " + testRunIdResponseBody);//test run details in xml format
statusCode = testRunId.getStatusCode();
//logger.info("The testRunId status code recieved: " + statusCode);
String stepID= testRunId.xmlPath().from(testRunIdResponseBody).get("**.find {it.#Name == 'id'}.Value");
List<String> runIds = testRunId.xmlPath().from(testRunIdResponseBody).getList("**.find {it.#Name == 'id'}.Value");
logger.info("stepID"+stepID);
Using the above code im able to the first id but not list of ids
I suppose **.find should be replaced with **.findAll:
List<String> runIds = testRunId.xmlPath().from(testRunIdResponseBody).getList("**.findAll {it.#Name == 'id'}.Value");

Solr Nextcursor mark returning error Unable to parse 'cursorMark' after totem

On my code I am trying to search for page and getting result I have included cursor mark as * when I get the return next cursor mark as "AoE/SkhJVkVfRFNDNjAwNDlfVklTVEFfVklTVEFQX1RaX0RCOi8vSGl2ZSBNZXRhc3RvcmUvZHNjNjAwNDlfdmlzdGFfdmlzdGFwX3R6X2RiL2Fucl9sb2dvbl9sb2cvbG9nX3RpbWVzdGFtcA== where it's throwing error:
Unable to parse 'cursorMark' after totem: value must either be '*' or the 'nextCursorMark' returned by a previous search
I need to encode the nextCursorMark here is my code below:
do {
String response = RestClient.doGet(url, userName, password, offSetTemp, pageSize, cursorMark);
System.out.println("res:----"+response);
jsonObject = ProfileDataExportUtil.getJson(response);
JsonArray profilingInfo = null;
if (jsonObject.has("items")) {
profilingInfo = jsonObject.get("items").getAsJsonArray();
}
if (profilingInfo == null) continue;
moreResultsExists = profilingInfo.size() >= 1;
ProfileDataExporter.writeProfileInformation(bWriter, profilingInfo);
if (!jsonObject.has("nextCursorMark")) continue;
cursorMark = jsonObject.get("nextCursorMark").toString();
} while (moreResultsExists);
I have tried using tostring which throws an error.
My URL is encoded and when I use
cursorMark = jsonObject.get("nextCursorMark").getAsString();
I get "string out of bound exception" error.
Can anyone tell me how encode the nextCursorMark?
I have faced similar issue. It was due to nextCursor String encoding. You should encode this string also before appending in the final URL. A sample example is given below
from urllib.parse import quote_plus
...
cursorMark = quote_plus(response['nextCursorMark'])
...

Using Arraylist in Mule to query Salesforce

We are trying to query Salesforce with an ArrayList in the where statement.
Below is is the error we ran into when we tried using the ArrayList in the where clause.
Query we used against Salesforce:
Select Id,Billing_Number__c from Call_Log__c where Id in #[flowVars.successlist]
successlist contains the values ['a1o90000001msXwAAI', 'a1o90000001msXxAAI'].
Error Message:
Message: Failed to invoke query. Message payload is of type: ArrayList
How do I resolve this error?
Unfortunately, you can't use ArrayLists as parameters in Salesforce (or Database) queries. You'll have to create the query dynamically with a script component.
Try this:
<scripting:script engine="Groovy">
<![CDATA[def sb = new StringBuilder()
sb.append('Select Id,Billing_Number__c from Call_Log__c')
if (flowVars.successlist != null && !flowVars.successlist.empty) {
sb.append(' where Id in (\'')
for (i in 0 .. flowVars.size()) {
if (i > 0) sb.append('\',\'')
sb.append(flowVars.successlist[i])
}
sb.append('\')')
}
flowVars.query = sb.toString()]]>
</scripting:script>
<sfdc:query query="#[flowVars.query]" doc:name="Salesforce - Query"/>
If you were using a Database, you would have to set the query type as dynamic:
<db:select doc:name="Database">
<db:dynamic-query><![CDATA[#[flowVars.query]]]></db:dynamic-query>
</db:select>
We have used a Java function string.join to convert the list as shown below:
SELECT id FROM User where Id in (#["'" + String.join("','", flowVars.fvCreatedbyIdList) + "'"])

Bing Search API error using odata4j

I am trying to run Bing search API. I used odata4j and tried the code provided here:
How to use Bing search api in Java
ODataConsumer c = ODataConsumers
.newBuilder("https://api.datamarket.azure.com/Bing/Search")
.setClientBehaviors(OClientBehaviors.basicAuth("accountKey", "{your account key here}"))
.build();
OQueryRequest<OEntity> oRequest = c.getEntities("Web")
.custom("Query", "stackoverflow bing api");
Enumerable<OEntity> entities = oRequest.execute();
After I registered in the bing service, I obtained the key and placed it inside the double quotation in the above code. I got the following error:
Exception in thread "main" java.lang.RuntimeException: Expected status OK, found Bad Request. Server response:
Parameter: Query is not of type String
at org.odata4j.jersey.consumer.ODataJerseyClient.doRequest(ODataJerseyClient.java:165)
at org.odata4j.consumer.AbstractODataClient.getEntities(AbstractODataClient.java:69)
at org.odata4j.consumer.ConsumerQueryEntitiesRequest.doRequest(ConsumerQueryEntitiesRequest.java:59)
at org.odata4j.consumer.ConsumerQueryEntitiesRequest.getEntries(ConsumerQueryEntitiesRequest.java:50)
at org.odata4j.consumer.ConsumerQueryEntitiesRequest.execute(ConsumerQueryEntitiesRequest.java:40)
at BingAPI.main(BingAPI.java:20)
Caused by: org.odata4j.exceptions.UnsupportedMediaTypeException: Unknown content type text/plain;charset=utf-8
at org.odata4j.format.FormatParserFactory.getParser(FormatParserFactory.java:78)
at org.odata4j.jersey.consumer.ODataJerseyClient.doRequest(ODataJerseyClient.java:161)
... 5 more
I could not figure out the problem.
All what you need is to set your query like that %27stackoverflow bing api%27
Here is my source code:
ODataConsumer consumer = ODataConsumers
.newBuilder("https://api.datamarket.azure.com/Bing/Search/v1/")
.setClientBehaviors(
OClientBehaviors.basicAuth("accountKey",
"{My Account ID}"))
.build();
System.out.println(consumer.getServiceRootUri() + consumer.toString());
OQueryRequest<OEntity> oQueryRequest = consumer.getEntities("Web")
.custom("Query", "%27stackoverflow%27");
System.out.println("oRequest : " + oQueryRequest);
Enumerable<OEntity> entities = oQueryRequest.execute();
System.out.println(entities.elementAt(0));
You can further try different queries with different filters by keep adding name-value pairs by using .custom("Type of parameter","parameter") of the oQueryrequest object.Say you want to search for indian food but you want only small square images.
ODataConsumer consumer = ODataConsumers
.newBuilder("https://api.datamarket.azure.com/Bing/Search/v1/")
.setClientBehaviors(
OClientBehaviors.basicAuth("accountKey",
"YOUR ACCOUNT KEY"))
.build();
System.out.println(consumer.getServiceRootUri() + consumer.toString());
OQueryRequest<OEntity> oQueryRequest = consumer.getEntities("Image")
.custom("Query", "%27indian food%27");
oQueryRequest.custom("Adult", "%27Moderate%27");
oQueryRequest.custom("ImageFilters", "%27Size:Small+Aspect:Square%27");
System.out.println("oRequest : " + oQueryRequest);
Enumerable<OEntity> entities = oQueryRequest.execute();
int count = 0;
Iterator<OEntity> iter = entities.iterator();
System.out.println(iter.next());

Categories