Retrieve specific data from REST Json response based on condition - java

I looked at all related posts but I couldn't find what I am looking for.
Verified the query syntax by using https://codebeautify.org/jsonpath-tester and https://jsonpath.com/. In below code, I get correct response if I print just id. I am looking for title, based on specific userID and id.
Getting "Invalid JSON expression" as o/p. Can anyone pls help here!
public void restPost2(){
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts";
RequestSpecification req = RestAssured.given().log().all();
String res1 = req.given().when().get().then().extract().asString();
JsonPath js = new JsonPath(res1);
System.out.println("list of Ids : " + js.get("id"));
System.out.println("specific title : " + js.get("(?(#.userId == '3') && (#.id == '23')).title"));
}

Following changes will solve your issue.
Use JsonPath.read to set json string to be queries
Syntax of jsonPath queries need to be corrected.
suggest you to refer jsonPath documentation again.
Please find a working example
json = <data fetched for the api>
Object x = JsonPath.read(json,"$..id");
Object y = JsonPath.read(json,"$[?(#.userId == 3 && #.id == 23)]");

Related

Create Release Notes using JIRA Rest API in HTML format in groovy

I am working on a script where I need to create the release notes using JIRA REST API in HTML format for any project.The below four field should come in that release notes.
Issue Key Module Summary Release Note
I am trying the below code but it is giving me only the issue Key field but need all other fields as well and in html file.Could you please suggest me on this?
Issue:1
Initially it was giving me the output in below format:
NTTB-2141
NTTB-2144
NTTB-2140
But now it is giving me the output json fromat way.
Code which I am trying from the groovy console:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
final String USAGE =
"Usage: -Djira.username=xxx -Djira.password=xxx -Djira.fixVersion=1.0"
String jiraUsername = 'ABCDEF'
String jiraPassword = '********'
String jiraFixVersion = '3.8.101'
println "Getting issues..."
if (!jiraUsername?.trim()) {
fail("Empty property: jira.username " + USAGE)
}
if (!jiraPassword?.trim()) {
fail("Empty property: jira.password " + USAGE)
}
if (!jiraFixVersion?.trim()) {
fail("Empty property: jira.fixVersion " + USAGE)
}
final String JIRA_SEARCH_URL = "https://jira.test.com/rest/api/latest/"
// see JIRA docs about search:
// https://docs.atlassian.com/jira/REST/latest/#idp1389824
String JQL = "project = NCCB"
JQL += " AND issuetype in standardIssueTypes()"
JQL += " AND status in (Resolved, Closed)"
JQL += " AND fixVersion = \"${jiraFixVersion}\""
def jira = new RESTClient(JIRA_SEARCH_URL)
def query = [:]
query['os_username'] = jiraUsername
query['os_password'] = jiraPassword
query['jql'] = JQL
query['startAt'] = 0
query['maxResults'] = 1000
try {
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
assert (resp.data instanceof net.sf.json.JSON)
resp.data.issues.each { issue ->
println issue.key
}
println "Total issues: " + resp.data.total
} catch (groovyx.net.http.HttpResponseException e) {
if (e.response.status == 400) {
// HTTP 400: Bad Request, JIRA JQL error
fail("JIRA query failed: ${e.response.data}", e)
} else {
fail("Failure HTTP status ${e.response.status}", e)
}
}
I suspect the code is right, except for that assertion:
assert (resp.data instanceof net.sf.json.JSON)
I get a groovy.json.internal.LazyMap (maybe you have changed versions of Groovy or Jira or something).
As a result, the assertion fails and Groovy tries to be helpful by giving you a comparison... but it shows you the toString() of the result, which is a huge mess of maps.
If you remove that assertion, it works for me, and I suspect it will work for you too.
Edit: huh... you cannot literally take "all" data and print to html. You will have to select the properties you need, and those depend on your Jira configuration. Here is an example with only 2 properties that should be universal:
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
def output = new File('issues.html')
output << "<html><body><ul>"
resp.data.issues.each { issue ->
def url = "https://yourjirainstance/browse/${issue.key}"
output << "<li>${issue.key}: ${issue.fields.summary}</li>"
}
output << "</ul></body></html>"
println "Exported ${resp.data.total} issues to ${output.name}"
See here details about what the service will give you.
If you just want an HTML dump, maybe the REST API is not what you want: you can also ask Jira to export results of JQL as a printable output (that will actually be html).

Invalid statement. Please check aliases, field identifiers, projections and query conditions

I'm using Dynamicloud and something is wrong in my code.
This is my code:
DynamicProvider<ContactForm> provider = new DynamicProviderImpl<ContactForm>(new RecordCredential(csk, aci));
contactFormModel.setBoundClass(ContactForm.class);
Query<ContactForm> query = provider.createQuery(contactFormModel);
try {
RecordResults<ContactForm> list = query.add(Conditions.like("contact.namef", "ProBusiness%")).list();
System.out.println("list = " + list.getFastReturnedSize());
if (list.getFastReturnedSize() > 0) {
System.out.println("Contact Name = " + list.getRecords().get(0).getName());
System.out.println("Contact Comments = " + list.getRecords().get(0).getComments());
}
} catch (DynamicloudProviderException e) {
e.printStackTrace();
}
This code throws the following Exception:
org.dynamicloud.exception.DynamicloudProviderException: Invalid statement. Please check aliases, field identifiers, projections and query conditions.
What's wrong?
Thanks!
Hi
The problems is the contact word right before namef in your like condition.
Dynamicloud API provides a method to set the alias of a model. For example, the aliases are used in situations where you need to execute JOINS
The problem is solved by calling the method setAlias from the query object query.setAlias("contact")
query.setAlias("contact");
Dynamicloud resources about Query class
Hope this helps

Retrieving a reply to a comment from facebook erro (java)

I am trying to grab reply to certain comment from facebook using the help from the comment library of restfb and the function getcomments().
After executing my code, it returns me a null rather than a reply to the comment.
Below is my snapshot of my code.
Connection<Comment> allComments = fbClient.fetchConnection(myArr1.get(xy)+"/comments", Comment.class);
for(List<Comment> postcomments : allComments){
for (Comment comment : postcomments){
String commentTemp = comment.getId() +" "+ comment.getFrom().getId() +" "+ comment.getCreatedTime() +" "+ comment.getMessage() +" "+ comment.getLikeCount() +" "+ comment.getComments()+" "+myArr1.get(xy);
}
}
All the function returns me the correct value except for the comment.getcomments()
You should use the fetchConnection on the comment-id/comments. This is perhaps a bit expensive, but so you can fetch really all replies.
Hi I am using restfb and found similar problem; the issue is that the connection.getData() returns only the first page of data. I used the iterator and was able to get all the comments.
Please note you would have to do the same thing even for replies of comments; you will need to create a separate connection using comment id, instead of post id and then iterate out the comments in the same way shown below.
Connection<Comment> commentsConnection= fbClient.fetchConnection(post.getId()+"/comments",com.restfb.types.Comment.class);
if(commentsConnection!=null)
{
Iterator<List<Comment>> commentsIterator=commentsConnection.iterator();
while(commentsIterator.hasNext())
{
List<Comment> comments= commentsIterator.next();
for(Comment comment:comments)
{
String message=comment.getMessage();
}
}
}

Filter users except SubscriptionAdmin in Java

I am trying to apply certain business rules for all users, except Subscription Administrators in Java. When i set the filter as below,
user.setQueryFilter(new QueryFilter("SubscriptionAdmin", "=", "false"));
I get an error like this
Could not parse: Attribute "SubscriptionAdmin" on type User is not allowed in query expressions.
How do i achieve this? Any help is appreciated.
Per WS API documentation, SubscriptionAdmin field on a User object cannot be used in queries. You may iterate over users and use an if statement with a condition:
if (userQueryObject.get("SubscriptionAdmin").getAsBoolean() == false){
//your code here;
}
SubscriptionAdmin field must be included in the fetch. Here is a code fragment where the condition is evaluated:
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName", "SubscriptionAdmin"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "someuser#co.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
System.out.println(userRef);
if (userQueryObject.get("SubscriptionAdmin").getAsBoolean() == false){
System.out.println(userQueryObject.get("SubscriptionAdmin"));
}

Obtain a share UpdateKey from LinkedIn using LinkedIn J and getNetworkUpdates() with Coldfusion

Using the "Network Updates API" example at the following link I am able to post network updates with no problem using client.postNetworkUpdate(updateText).
http://code.google.com/p/linkedin-j/wiki/GettingStarted
So posting works great.. However posting an update does not return an "UpdateKey" which is used to retrieve stats for post itself such as comments, likes, etc. Without the UpdateKey I cannot retrieve stats. So what I would like to do is post, then retrieve the last post using the getNetworkUpdates() function, and in that retrieval will be the UpdateKey that I need to use later to retrieve stats. Here's a sample script in Java on how to get network updates, but I need to do this in Coldfusion instead of Java.
Network network = client.getNetworkUpdates(EnumSet.of(NetworkUpdateType.STATUS_UPDATE));
System.out.println("Total updates fetched:" + network.getUpdates().getTotal());
for (Update update : network.getUpdates().getUpdateList()) {
System.out.println("-------------------------------");
System.out.println(update.getUpdateKey() + ":" + update.getUpdateContent().getPerson().getFirstName() + " " + update.getUpdateContent().getPerson().getLastName() + "->" + update.getUpdateContent().getPerson().getCurrentStatus());
if (update.getUpdateComments() != null) {
System.out.println("Total comments fetched:" + update.getUpdateComments().getTotal());
for (UpdateComment comment : update.getUpdateComments().getUpdateCommentList()) {
System.out.println(comment.getPerson().getFirstName() + " " + comment.getPerson().getLastName() + "->" + comment.getComment());
}
}
}
Anyone have any thoughts on how to accomplish this using Coldfusion?
Thanks
I have not used that api, but I am guessing you could use the first two lines to grab the number of updates. Then use the overloaded client.getNetworkUpdates(start, end) method to retrieve the last update and obtain its key.
Totally untested, but something along these lines:
<cfscript>
...
// not sure about accessing the STATUS_UPDATE enum. One of these should work:
// method 1
STATUS_UPDATE = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType$STATUS_UPDATE");
// method 2
NetworkUpdateType = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType");
STATUS_UPDATE = NetworkUpdateType.valueOf("STATUS_UPDATE");
enumSet = createObject("java", "java.util.EnumSet");
network = yourClientObject.getNetworkUpdates(enumSet.of(STATUS_UPDATE));
numOfUpdates = network.getUpdates().getTotal();
// Add error handling in case numOfUpdates = 0
result = yourClientObject.getNetworkUpdates(numOfUpdates, numOfUpdates);
lastUpdate = result.getUpdates().getUpdateList().get(0);
key = lastUpdate.getUpdateKey();
</cfscript>
You can also use socialauth library to retrieve updates and post status on linkedin.
http://code.google.com/p/socialauth

Categories

Resources