codenameone display entire json response message not just a single node - java

I am calling a parcel tracking json service using codenameone java code.
Here is the full json response:
{
"success": true,
"results": {
"tracking_reference": "DY954563460NZ",
"message_id": "682c9b69-7f90-48c6-a36d-3b371e203a96",
"message_datetime": "2016-11-11T08:08:05.0000000Z",
"service": "",
"carrier": ""
}
}
I would like to create a popup that displays the entire response - but all the examples I can see only show how to get the results node.
Here is what I am currently showing:
"results": {
"tracking_reference": "DY954563460NZ",
"message_id": "682c9b69-7f90-48c6-a36d-3b371e203a96",
"message_datetime": "2016-11-11T08:08:05.0000000Z",
"service": "",
"carrier": ""
}
This is because I am using this code to get this specific branch:
Object responseMessage = null;
responseMessage = apiResponse.get("results");
Dialog d = new Dialog("Response");
d.setScrollable(true);
d.show("Response Message", responseMessage.toString(), "OK", null);
According to this website there is a special node called 'root' which should do the trick but it errors out.
https://www.codenameone.com/javadoc/com/codename1/io/JSONParser.html
Any idea how I can display the entire response message?
Thanks

Remove this line:
responseMessage = apiResponse.get("results");

Related

Retrieve Text file content using Bitbucket server rest APIs in Java JsonNode format

I am trying to use the bitbucket server rest API to fetch file content(.json file) from a bitbucket repository in a Java spring boot Application but the response is not as expected.
Content in the file meta.json
{
"key1": "value1",
"key2": "value2"
}
API used
https://bitbucket.domain.com/rest/api/1.0/projects/my-project/repos/my-repo/browse/path/to/meta.json
Java snippet used to get file content
String url = "https://bitbucket.domain.com/rest/api/1.0/projects/my-project/repos/my-repo/browse/path/to/meta.json";
JsonNode bucketData = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class).getBody();
Actual output:
{
"lines": [
{
"text": "{"
},
{
"text": " \"key1\": \"value1\","
},
{
"text": " \"key2\": \"value2\""
},
{
"text": "}"
}
],
"start": 0,
"size": 4,
"isLastPage": true
}
Whereas the output I want is the following
{
"key1": "value1",
"key2": "value2"
}
So I can convert it to JsonNode and use it.
Observation
While hitting the repo url with ?raw param (https://bitbucket.domain.com/projects/my-project/repos/my-repo/browse/path/to/meta.json?raw) I was getting the excepted output in text format, not json format. I also tried using the same url in my spring boot application but that didnt work either.
Any suggestion on how can I get the expected output?
I was able fix this issue, by using Unirest
The following syntax was used
String url = "https://bitbucket.domain.com/rest/api/1.0/projects/my-project/repos/my-repo/browse/path/to/meta.json";
HttpResponse<T> response = Unirest.get(url).headers(headers).asObject(responseClass);
JsonNode bucketData = response.getBody();

How can we set value of context variable of watson assistant using java?

Is it possible to set the value of context variable from java. I have modified the node json and added a action in that action in the result property I want to set data from my local database. So I am getting the action in java code and trying to set the value of result property of action object, below is the code which i am trying but it is not working. can some one suggest a better approach for this.
if(response.getActions()!=null) {
System.out.println("actions : "+response.getActions());
for (int i = 0; i < response.getActions().size(); i++) {
System.out.println(" i : "+response.getActions().get(i).getName());
if(response.getActions().get(i).getName()=="Apply_For_Loan") {
response.getActions().get(i).setResultVariable("123");
}
}
}
For setting value of result_variable in to the context below is my code.
if(response.getActions().get(i).getName().equals("Apply_For_Loan")) {
System.out.println("in action");
Assistant service = new Assistant("2018-12-12");
service.setUsernameAndPassword(userId, password);
service.setEndPoint(endPoint);
String result=response.getActions().get(i).getResultVariable();
Context context = response.getContext();
context.put(result, "123");
MessageOptions msg=new MessageOptions.Builder(watsonId)
.input(new InputData.Builder("Apply For Loan").build())
.context(context)
.build();
response=service.message(msg).execute();
System.out.println("msg : "+response);
}
Below is the response which i am getting after re-executing the assistant call.
{
"output": {
"generic": [
{
"response_type": "text",
"text": "Hello RSR, you loan application of 5420 is created. Please note the Loan Number for future use "
}
],
"text": [
"Hello RSR, you loan application of 5420 is created. Please note the Loan Number for future use "
],
"nodes_visited": [
"node_1_1544613102320",
"node_1_1544613102320"
],
"log_messages": []
},
"input": {
"text": "Apply For Loan"
},
"intents": [
{
"intent": "ApplyForLoan",
"confidence": 1.0
}
],
"entities": [],
"context": {
"number": 9.971070056E9,
"$Loan_Number": "123",
"system": {
"initialized": true,
"dialog_stack": [
{
"dialog_node": "node_1_1544613102320"
}
],
"dialog_turn_counter": 3.0,
"dialog_request_counter": 3.0,
"_node_output_map": {
"node_1_1544613102320": {
"0": [
0.0
]
}
},
"branch_exited": true,
"branch_exited_reason": "completed"
},
"Mail_Id": "Email_Id",
"conversation_id": "b59c7a02-2cc6-4149-ae29-602796ab22e1",
"person": "RSR",
"rupees": 5420.0
},
"actions": [
{
"name": "Apply_For_Loan",
"type": "client",
"parameters": {
"pername": "RSR",
"loanamount": 5420.0
},
"result_variable": "$Loan_Number"
}
]
}
In above response $Loan_Number is the result variable which i have updated from java code and the same result_variable i am using in the output text to return the $Loan_Number, but in output text it is still coming blank and in actions also it is still coming blank?
The simple answer to your question is no, you can't set anything in the JSON Model using setResultVariable. It should work like this:
1) Define an action on your Dialognode
The result_variable defines the <result_variable_name>, e.g. where the result of that action should be stored in the conversation context. If you execute some server side action, you read the result from the specified context location. In this example, the location is context.result_of_action, the context might be omitted. More details are here.
2) Process the action in Java Client
DialogNodeAction action = response.getActions().get(0);
final String result_variable = action.getResultVariable();
The result_variable is like a key. You obtain the value from your DB and add it to the context:
Context context = response.getContext();
context.put(result_variable, "value from DB");
new MessageOptions.Builder("Your ID")
.input(new InputData.Builder("Your response").build())
.context(context) // setting context
.build();
Finally the Watson Assistant Dialog (or some other App) can get the result from the Client:
"context": {
"result_of_action": "value from DB",
The Objects you read using the Java API are being parsed from JSON using Gson and need to be re-parsed back to JSON when construction a new API Call.
Edit after question update
In your example:
"actions": [
{
"name": "Apply_For_Loan",
"type": "client",
"parameters": {
"pername": "RSR",
"loanamount": 5420.0
},
"result_variable": "$Loan_Number"
}
the key result_variable tells other modules in your app where to find the result of your action. So $Loan_Number should not be the value but the key to the value in the session context (a kind of method contract).
Let's say you set the value to context.my_result, then your Watson Assistant should be able to access the "123" from DB in the next dialog node under "context.my_result".

Get data from outside the root level of response

I'm still kind of new to REST and haven't been able to figure this one out.
I have a response like this one:
{
"StatusCode": 200,
"Result": {
"CustomerStuff": {
"Name": "John",
"State": "Oregon",
"GetEmail": false
},
"eText": "Will only get paper mail. "
}
}
I would normally save the response body as a string and then use a JsonPath to get what I need.
String responseBody = given().body().when().etc...;
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result.CustomerStuff");
Then get what I need:
String name = jsonPath.get("name");
I can't figure out how to get the, "eText" value. It's not in the same segment of the response.
Any suggestions?
You should use
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result")
And then call jsonPath.get("eText") in order to get the value you want.
You can still access CustomerStuff with jsonPath.get("CustomerStuff")

Gerrit rest api returns empty JSONArray to java environment, but returns non empty to the browser

I faced following problem:
I wanna get list of changes from gerrit repository using this api function https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
When I sent GET request in browser I got response
[
{
"id": "business~develop~I65d58a2345346cb35a0ecbb63d6ed896c7",
"project": "business",
"branch": "develop",
"hashtags": [],
"change_id": "I65d58a2a045645636cb35a0ecbb63d6ed896c7",
"subject": "Leader property deleted from organizational unit classes. Org unit\u0027s employees cascad type removed. Employee\u0027s roles amount limited by 1 in orgUnit.xsd. Employees identifiers changed in orgUnit.xml. Updated domain model. DataUploadRestService created. Emp",
"status": "NEW",
"created": "2015-05-12 14:31:48.226000000",
"updated": "2015-07-07 07:34:35.195000000",
"mergeable": true,
"insertions": 3100,
"deletions": 1358,
"_number": 589,
"owner": {
"_account_id": 1003473
}
}
]
But when I send GET request using RestEasy or other way to send request using Java code:
try {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client
.target("https://gml-jbpm.gomel.iba.by/gerrit/changes/");
String response = target.request().get(String.class);
final JSONArray array = new JSONArray(response);
System.out.println("RestEasy response: " + array);
} catch (final Exception e) {
e.printStackTrace();
}
I get empty response:
[]
How to solve this problem? Why I get empty JSONArray?

AngularJS: passing complex json data using $http.post

I'm having trouble passing a complex json object in angularjs with $http.post. I'm keep getting a 400 bad request error sent back from the server saying the request was syntactically incorrect. I believe it has something to do with the array since it passes fine when i don't include it.
json i'm passing.
{
customer: {
firstName: "John",
lastName: "Doe",
street: "1234 South Dr",
city: "Detroit",
state: "MI",
zip: "12345",
phone: "123-321-1234",
email: "EMAIL#GMAIL.COM"
},
order: {
orderDate: "06-16-2015",
registerNum: "1",
transactionNum: "7820",
deliveryStatusID: 1,
notes: "Hold order until July",
items: [
{skuID: "1234568",
skuDescription: "Order item 1",
qty: "4",
itemStatusID: 1,
itemStatusDescription: "Backorder"
},
{skuID: "7387491",
skuDescription: "Order item 2",
qty: "1",
itemStatusID: 1,
itemStatusDescription: "Flagged"
}
]
}
}
angular service function
this.addOrder = function(new_order) {
return $http.post(base + "/add", new_order);
};
Spring MVC controller method
#RequestMapping(value="/add", method=RequestMethod.POST)
public void addOrder(#RequestBody CustomerOrder customerOrder) {
System.out.println("----CUSTOMER-INFO----");
System.out.println(customerOrder.getCustomer().getFirstName());
System.out.println(customerOrder.getCustomer().getLastName());
System.out.println("");
System.out.println("----ORDER-INFO----");
System.out.println(customerOrder.getOrder().getOrderID());
System.out.println(customerOrder.getOrder().getOrderDate());
}
The problem only seems to occur when I pass the items array in the json. I've passed the same json object without the items array and it works fine. The format of the json is being sent in the same format that gets returned whenever I GET an order with my angularjs service method so I'm really not sure as to where I'm going wrong with this.
If I need to provide more code please let me know. I appreciate any effort in helping me out.
Thank you.
Jason
Well after struggling to find my error in this problem, I finally found a solution. I thought I'd share how I debugged and fix this problem in case someone else is in a similar situation as I was.
After trying every possible way of sending my data in angular to the server and continually getting the same HTTP 400 error, I decided to send the json as a string and accept the json as a string in my spring mvc controller like this.
angular service method:
this.addOrder = function(new_order) {
return $http.post(base + "/add", angular.toJson(new_order));
};
spring controller
#RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(#RequestBody String json) {
}
From here I simply took the json passed in and used the Jackson ObjectMapper to convert the json string to my POJO like this.
mapping json string to pojo
#RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(#RequestBody String json) {
ObjectMapper mapper = new ObjectMapper();
try {
CustomerOrder order = mapper.readValue(json, CustomerOrder.class);
System.out.println(order.getCustomer().getFirstName() + " " + order.getCustomer().getLastName());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
After doing this and running my code, I would get an UnrecognizedPropertyException on a field in my Items class when trying to bind the items json to the List in my Order class. It was just a simple mispelling on the json side and I completely missed it. After correcting this, jackson mapped everything correctly and I no longer get this HTTP 400 Error The request was syntactically incorrect.
Another thing to note is that if you pass your object as a string in angular using the JSON.stringify you may encounter this same exception on hashKey field in the JSON object. The hashKeys are used by angular to monitor changes. I believe you can use a jackson annotation to ignore unknown fields or you can simply use angular.toJson instead which will remove all the hasKey/values for you which is what I did.
Just formatted the Json in a better way. Try this if it helps. Also, post the java classes if possible:
{
"customer": {
"firstName": "John",
"lastName": "Doe",
"street": "1234 South Dr",
"city": "Detroit",
"state": "MI",
"zip": "12345",
"phone": "123-321-1234",
"email": "EMAIL#GMAIL.COM"
},
"order": {
"orderDate": "06-16-2015",
"registerNum": "1",
"transactionNum": "7820",
"deliveryStatusID": 1,
"notes": "Hold order until July",
"items": [
{
"skuID": "1234568",
"skuDescription": "Order item 1",
"qty": "4",
"itemStatusID": 1,
"itemStatusDescription": "Backorder"
},
{
"skuID": "7387491",
"skuDescription": "Order item 2",
"qty": "1",
"itemStatusID": 1,
"itemStatusDescription": "Flagged"
}
]
}
}

Categories

Resources