how to insert an array to JSONArray with rest assured - java

I want to insert the array with Rest Assured.
tokenUUIDs - is an array ( A variable that I defined in a previous step).
When I run the code - tokenUUIDs received a correct value But ArraytokenUUIDs have not received something good. He received : [[Ljava.lang.String;#6fc0bbc6]
This is my Method:
public static void releaseTokens(String[] tokenUUIDs )
{
try{
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject releaseTokens = new JSONObject();
releaseTokens.put("partnerCode", commonOps.partnerCode);
releaseTokens.put("apiAccessToken",commonOps.openAccessToken);
releaseTokens.put("sessionUUID",SessionUUID);
releaseTokens.put("taskUUID","TaskUUID");
JSONArray ArraytokenUUIDs = new JSONArray();
ArraytokenUUIDs.add(tokenUUIDs);
releaseTokens.put("tokenUUIDs", ArraytokenUUIDs);
request.body(releaseTokens.toJSONString());
Response response = request.post((getData("APIenv") + "/api/sessions/releaseTokens.php"));
int code = response.getStatusCode();
Assert.assertEquals(code, 200);
System.out.println("Status code for releaseTokens.php is" +code );
ResponseBody bodyreleaseTokens = response.getBody();
System.out.println("Body bodyreleaseTokens.php " + bodyreleaseTokens.asString() );
String statusbodyreleaseTokens = bodyreleaseTokens.asString();
String status = response.getBody().jsonPath().getString("status");
Assert.assertEquals(status, "OK");
test.log(LogStatus.PASS, "bodyreleaseTokens is done" );
}
catch (Exception e)
{
test.log(LogStatus.FAIL, "bodyreleaseTokens is not done");
test.log(LogStatus.FAIL, e.getMessage());
fail ("bodyreleaseTokens is not done");
}

Try to add every token individually
for (String s : tokenUUIDs){
ArraytokenUUIDs.add(s);
}

Change
ArraytokenUUIDs.add(tokenUUIDs);
to
for (String tokenUUID : tokenUUIDs) {
ArraytokenUUIDs.add(tokenUUID);
}
Also consider that variables in java are named with lowercase first letter as a standard to avoid confusion with classes.

Related

I want to make a request using OkHttpClient and I want to change the URL if the response is not successful

So I am requesting an API call to search records by phone number. If the response is unsuccessful, I want to change the URL to search the record by name. In order to send the request and obtain the response we have a try catch clause. My only thought would be to repeat the request and response using a new URL inside the original catch clause . Can anyone inform me how I should go about changing the URL and making a new request if the original request catches an exception. Here is my snippet of code that requests to search by phone number. And the stackstrace which is evident because the request fails.
OkHttpClient client = new OkHttpClient().newBuilder().build();
String phone = DNC_List[i].getNumber();
Request request = new Request.Builder().url("https://www.zohoapis.com/crm/v2/Leads/search?phone=" + phone)
.method("GET", null).addHeader("Authorization", "Zoho-oauthtoken 1000.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxx")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie",
"1a9a93sda653=12a340a9c5d3e8sfd2161d0b; crmcsr=43sdv9-07ads5-4549-a166-0aad54gw6b; _zcsr_tmp=435e5334fa5-4549-a1667s889s8cf6b; JSESSIONID=54FF23B98378EBB45E4FA411823B5E61")
.build();
System.out.println("request = " + request);
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println(i + "PrettyJson = " + prettyJsonString + "\n______________end of string________");
JSONArray jsonArray = (JSONArray) json.get("data");
JSONObject data0 = (JSONObject) jsonArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
String id2 = data0.getString("id");
DNC_ID[i] = id2;
System.out.println("DNC_ID[" + i + "]= " + DNC_ID[i]);
} catch (Exception e) {
// Need to search leads by name if phone number does not work
// How to change the URL to search by name
System.out.println("Entered catch clause: index = " + i);
e.printStackTrace();
}
Output for the failed code:
request = Request{method=GET, url=https://www.zohoapis.com/crm/v2/Leads/search?phone=1234567890, tags={}}
Entered catch clause: index = 0
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.App.main(App.java:103)
Your code is failing to parse some JSON it doesn't appear like it's necessarily because the search returned zero results. If that were true it would return an empty array. Double check your JSON shapes and make sure they match what the API returns.
Also, it appears like you are mixing and matching two different JSON libraries. The built in Android objects such as JSONObject and Google's GSON pick one and stick with one don't mix and match them.
To aid in debugging this use OkHttps built in logging system and experiment with setting different logger levels.
Also to help debug you can set up OkHttp debug logging with an interceptor.
Logger logger = LoggerFactory.getLogger(HttpUtil.class);
HttpLoggingInterceptor logging =
new HttpLoggingInterceptor((msg) -> {
logger.debug(msg);
});
logging.setLevel(Level.BODY);
client.addNetworkInterceptor(logging);

Convert string of valid JSON to JSON object in Java, so I can index into it

I have this string:
[{"row 0":[{},{},{},{},{},{},{},{}]},{"row 1":[{},{},{},{},{},{},{},{}]},{"row 2":[{},{},{},{},{},{},{},{}]},{"row 3":[{},{},{},{},{},{},{},{}]},{"row 4":[{"column 0":"WhitePawn"},{},{},{},{},{},{},{}]},{"row 5":[{},{},{},{},{},{},{},{}]},{"row 6":[{},{},{},{},{},{},{},{}]},{"row 7":[{},{},{},{},{},{},{},{}]}]
^ it's currently a String, let's call it string.
I'm trying to convert it into JSON like so:
new JSONObject(string);
but it isn't working. How to do this in Java?
Code looks like so:
private void parseMessageRedrawBoard(String message) {
Log.d("0000: ", message);
String trimmed = message.substring(message.indexOf("["));
Log.d("1111: ", trimmed);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(trimmed);
Log.d("maybe worked...", "~");
} catch (Exception e) {
Log.d("dammit: ", e.getMessage());
}
}
You are trimming the string and turning it into an invalid JSON.
Your JSON starts with a "[" that indicates it is an array. If it starts with "{" you can assume that is an object.
So, as your JSON is an array, you can parse this exact content you mentioned with:
JSONArray jsonArray = new JSONArray(string);
And access the elements like in a List:
jsonArray.get(0);

How can I get specific object from methods response JSON

I want to call another method if the condition is satisfied with the response of first method. But the response is in JSON and has many objects. I want to check if "RESPCODE" is "01" and if it is call a method.
Method:
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
if(inResponse.toString().equals("01")) {
CheckoutProcess();
} else {
Toast.makeText(getApplicationContext(), "Transaction Failed ", Toast.LENGTH_LONG).show();
Log.d("LOG", "Payment Transaction : " + inResponse);
}
}
Response:
TXNAMOUNT = 1000.00
PAYMENTMODE = PPI
CURRENCY = INR
TXNDATE = 2018-04-17 18:56:08.0
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Success
GATEWAYNAME = WALLET
BANKTXNID =
BANKNAME = WALLET
org.json library should be enough if it is only one or two properties you are interested in.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
int respcode = jsonObj.getInt("RESPCODE");
You can see a complete example here:
How to parse JSON in Java

Parse Json In Java How to read Inner Value

Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);

Add More than 200 Test Cases to Test Set Using Java Rally Rest API

Using Following Code I am able to add test cases in to newly created test set in RALLY.
But it add only first 200 test cases from the Test case list.
private static String createTestSet(RallyRestApi restApi, String TSName, String points)throws IOException, URISyntaxException {
QueryRequest testcases = new QueryRequest("Test Case");
testcases.setFetch(new Fetch("FormattedID", "Name", "Owner","Test Folder"));
// All Test cases
testcases.setQueryFilter(new QueryFilter("TestFolder.Name", "=","testFolder").and(new QueryFilter("Method", "=", "Manual")));
testcases.setOrder("FormattedID ASC");
QueryResponse queryResponse = restApi.query(testcases);
JsonArray testCaseList = new JsonArray();
if (queryResponse.wasSuccessful()) {
System.out.println(String.format("\nTotal results: %d", queryResponse.getTotalResultCount()));
testCaseList=queryResponse.getResults().getAsJsonArray();
}else{
for (String err : queryResponse.getErrors()) {
System.err.println("\t" + err);
}
}
String ref = "null";
System.out.println("Creating TestSet: "+TSName);
try {
if(!testCaseList.isJsonNull()){
restApi.setApplicationName("PSN");
JsonObject newTS = new JsonObject();
newTS.addProperty("Name", TSName);
newTS.addProperty("PlanEstimate", points);
newTS.addProperty("Project", Project_ID);
newTS.addProperty("Release", Release_ID);
newTS.addProperty("Iteration", Iteration_ID);
newTS.add("TestCases", testCaseList);
CreateRequest createRequest = new CreateRequest("testset",newTS);
CreateResponse createResponse = restApi.create(createRequest);
ref = createResponse.getObject().get("_ref").getAsString();
}
} catch (Exception e) {
//System.out.println("Exception Caught: " + e.getMessage());
}
return ref;
}
Although the Total Result count of Test case query filter is greater than 200, Test Set is getting created with only 200 Test case in it.
#Brian's comment above is correct. By default RallyRestApi.query() will only return one page of data (with the default page size being 200). QueryResponse.getTotalResultCount() will return the total number of records that matched on the server. In order to get more than one page of data simply use QueryRequest.setLimit() first to set an upper bound on the number of results you'd like returned.

Categories