API xml response looping and extract all the element values - Groovy - java

Below is the snapshot of my API XML response
<Plaintiff>
<PlaintiffName>SEB B.A.
</PlaintiffName>
<PlaintiffName>SEB??
</PlaintiffName>
</Plaintiff>
I want to extract all the PlaintiffName under the Plaintiff node.
Code:
String caseResponseText = response.getResponseText()
def xmlResult = new XmlSlurper().parseText(caseResponseText)
def plaintiff = xmlResult.Case.Plaintiff.PlaintiffName[0].text()
The above one i got the result of first plaintiff name / second plaintiff name. But how should i looping thru this node and get all the palintiff value dynamically?
Because response may have only one plaintiff or more than one, so I need to parse dynamically and get all the values thru looping

Simply loop over the nodes:
def plaintiffs = xmlResult.Case.Plaintiff.PlaintiffName
for (plaintiff in plaintiffs) {
// do something with plaintiff
}

Related

How to pass query parameter or form parameter having array items so that all options should get pass

I have a request which have multiple form parameters. One of the form parameters is in below format:
"DistributionChoices": ["ABC.com", "JPQ.com", "N\A"]
When I am doing post request with queryParams and passing:
queryParam.put("DistributionChoices", Arrays.asList("ABC.com", "JPQ.com", "N\A"));
or
formParam("DistributionChoices", Arrays.asList("ABC.com", "JPQ.com", "N\A"));
Then it is selecting only the first value, i.e. ABC.com
The field is a multichoice which accepts all values.
How can I pass all values in this parameter?
Note: In Postman, it works fine if I pass it like this:
"DistributionChoices": ["ABC.com", "JPQ.com", "N\A"]
Language: Java
Framework: RestAssured along with TestNG
Code:
List<String> items = Arrays.asList("ABC.com", "JPQ.com", "N\A");
RestAssured.base = "baseURI";
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("apiKey","apiKeyValue");
queryParams.put("name","nameValue");
queryParams.put("description","descriptionValue");
queryParams.put("distrbutionChoice",items); // Here is the issue
RestAssured.given().params(queryParams);
Response response = request.when().post();
Output: This takes the first value from the item list.
It is not clear what is exactly the format which it needs to be sent as,
but a quick guess would be: DistributionChoices=["ABC.com", "JPQ.com", "N\A"].
So, in order to parse the list to this format do the following:
var value = "[\"" + String.join("\", \"", Arrays.asList("ABC.com", "JPQ.com", "N\\A")) + "\"]";
queryParam.put("DistributionChoices", value)
This is simply adding a comma between every word in this list, and wrapping these in brackets. (JSON format)

Update field of a document inside an array of arrays in mongodb

I have a Document that has an array field called listsOfItems. Its contents are Documents and they all contain another array field called setOfItems, which is composed of Document.
So the structure is like listsOfItems(Array of Documents) > setOfItems(Array of Documents) > Items(Documents)
Each Document in listsOfItems has a listId field which is used to uniquely identify it's contents.
Each Document in setOfItems has a itemId field which is used to uniquely identify it's contents.
I want to change the value of a field inside a Document of setOfItems given the listId and itemId.
Currently, I'm trying to do it like this:
final var filter = Filters.and(Filters.eq("accessDetail.email", email),
Filters.eq("listsOfItems.listId", listId),
Filters.eq("listsOfItems.$.setOfItems.itemId", itemId));
final var updateQuery = Updates.set("listsOfItems.$.setOfItems.obtained", BsonBoolean.TRUE);
usersCollection.findOneAndUpdate(filter, updateQuery)
The query doesn't match any Document
I cannot access the elements in the setOfItems by directly accessing them by index because they are ordered by other indexes and not according to their itemId field.
What is the right query for performing the update given the condition?
EDIT1
I have replaced my filter to:
final var filter = Filters.and(Filters.eq("accessDetail.email", email),
Filters.elemMatch("listsOfItems",
Filters.eq("listId", listId)),
Filters.elemMatch("listsOfItems.setOfItems",
Filters.eq("itemId", itemId)));
Now I get the error message: 'Cannot create field 'obtained' with the correct sub-document that it should make changes in.
The issue boils down to the updateQuery.
To do this, you need to make use of arrayFilters.
Document filter = new Document("base-doc-field","<value>");//query for base doc
//fields if any
Document updateDoc = new Document("$inc",
new Document("listOfItems.$[elem].setOfItems.$[elem1].fieldName","value to
update"));
//prepare array filters.
List<Bson> arrayFilters = new ArrayList<>();
arrayFilters.add(new Document("elem.listId","<list_id>"));
arrayFilters.add(new Document("elem1.itemId","<item_id>"));
//prepare update options, and set these array filters to update options.
UpdateOptions options = new UpdateOptions().
arrayFilters(filterArr).bypassDocumentValidation(true);
//execute update method.
collection.updateOne(filter,updateDoc,options);
Visit https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-nested-arrays-in-conjunction-with

how can i sort data on a particular column in Couchbase?

hi i am new to couchbase. I have a view like below:
function (doc, meta) {
if(doc.docType == "DeviceData")
emit([doc.group, doc.time], [doc.node, doc.node_gps_lat, doc.node_gps_long]);
}
So i want have to get the result which is sorted by doc.node value. I searched the documentation but couldnot find the proper solution.
Please need help on this.
Couchbase sorting results by key. So in your example results will be sorted firstly by doc.group and then by doc.time. If you want to sort results by doc.node, you should include that field in key or sort result on client/app side.
If you're quering your view with some time range (you have startkey and endkey that differs by doc.time param like in your previous question) ordering by doc.node is only possible on client/app side. If you want to sort on couchbase side - try to change your data model.
Here is a doc that explains ordering in couchbase. And here is doc with explanation how couchbase sorts view results.
I think I'm adding to what m03geek said above in that in order to sort by a particular column (value in CB), you need to pass that value back as the key(s). I'm building a Django app using CB and I wanted to sort by create date so I created the following view map function.
function (doc, meta) {
if (doc.type && doc.type == "snapshot" && doc.published == "yes" && doc.section == "sports") {
var arrDate = doc.create_date.split("-");
var newDate = new Date(arrDate[2], arrDate[0], arrDate[1]);
var numTime = newDate.getTime();
doc.time = numTime;
emit(doc.time, null);
}
}
In the map function above, I turn the string create date into a numerical time and then emit that as the key which sorts the results by create date.

Neo4j - get all nodes belonging to an index using Java API

Say that I have an index named "user". How do I get all the nodes belonging to that index using Neo4j-Java Api?
I tried the code below
val nodeIndex = getNodeIndex("article").get
val nodes = nodeIndex.getGraphDatabase().getAllNodes()
But, I got all the nodes present in the db. How do I solve this?
You should use "get" or "query" on the nodeIndex, like:
IndexHits<Node> allArticles = nodeIndex.query( "*:*" );
... do stuff ...
allArticles.close();
or
Node myArticle = nodeIndex.get( "name", "MyArticle" ).getSingle();
What you did above was to regardless of the index, get the graph database and return all nodes.

How to add all row elements in database to JSON object

I'm trying to retrieve all elements in database and display in webpage.But with my code it able to retrieve only one row element. Problem is, it retrieves all element but it adds the last row element to the object. I think all elements retrieved first are overwritten Because of that it displays last row element. Can anyone tell me how add all row elements to the JSON object. Please help me.
code :
while(rs.next()){
ImageFile.setName(rs.getString("imagename").trim());
ImageFile.setDisc(rs.getString("imagedisc").trim());
ImageFile.setImageid(rs.getInt("imageid"));
ImageFile.setalbumid(rs.getInt("albumid"));
byte imageData[] = rs.getBytes("imagethumb");
String encoded = DatatypeConverter.printBase64Binary(imageData);
ImageFile.setThumb(encoded);
byte image1Data[] = rs.getBytes("imagethumb");
String encoded1 = DatatypeConverter.printBase64Binary(image1Data);
ImageFile.setFull(encoded1);
}
The complete source code is in this question
Please help me........Thanks....
Use a list Collection to keep all the row-values of db, like - List<ImageFileInfo> which denotes List containing of ImageFileInfo Objects . And then serialize the list to json String.
List<ImageFileInfo> imageFileList = new ArrayList<ImageFileInfo>();
while(rs.next()){
ImageFileInfo info = new ImageFileInfo();
info..setName(rs.getString("imagename").trim());
...
imageFileList.add(info);
}
Json serialization -
Type typeOfList= new TypeToken<List<ImageFileInfo>>(){}.getType();
String s = gson.toJson(imageFileList , typeOfList);

Categories

Resources