Iterate over Laravel validation errors object in java - java

I have an android app that uses laravel as backend. I validate user inputs in laravel using Validator facades.
$validator = Validator::make($inputs, $rules);
if ($validator->fails()) {
return response(['errors' => $validator->errors()], 401);
}
The response is an json object that could have different elements.
{
"errors": {
"username": [
"The username has already been taken.",
"The username format is invalid."
],
"email": [
"The email has already been taken."
]
}
}
or
{
"errors": {
"password": [
"The password must have at least 8 characters."
]
}
}
I get the JSONObject in the android app using java.
JSONObject errors = jsonObject.getJSONObject("errors");
My question is that how can I iterate over the errors object to show the errors?

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();

LinkedIn UGC Post Method

I am trying to post a text on LinkedIn using UGC through Postman.
Here is my request body:
{
"author": "urn:li:person:{uid of my account}",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": "Hello World! This is my first Share on LinkedIn!"
},
"shareMediaCategory": "NONE"
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
Note: uid of my account is fetched through - https://api.linkedin.com/v2/me
The response I am getting is:
{
"message": "ERROR :: /author :: \"urn:li:person:oQRNppEnm\" does not match urn:li:company:\\d+|urn:li:member:\\d+\n",
"status": 422
}
Can anyone please help out here?
I had such a mistake. I used wrong value from https://api.linkedin.com/v2/me request answer. You need to add id in your request query if you haven't already,
for example
https://api.linkedin.com/v2/me?projection=(id,localizedFirstName,localizedLastName)
also you need to use value from id field of JSON answer:
{"id\":\"XyyyyXXXXX\"}
It will be some kind of value with numbers and letters, not just numbers.

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".

How I can deserialize a json object without a name and dynamic?

I have this JSON:
{
"username": [
"A user with that username already exists."
],
"ruc": [
"user with this ruc already exists."
],
"code": [
"user with this code already exists."
],
"document_number": [
"user with this document number already exists."
]
}
The name of the properties will be dynamic and the length of the JSON too.
I'm using GSON tool and I create a POJO but without a name, I cant reference to this, that's, why I received that myError instance, is null.
This is my POJO
public class MyError {
public Map<String, Object> message = new HashMap<>();
}
And this is my GSON code
myError = new Gson().fromJson(response.errorBody().string(), MyError.class);
And I want to show a message for every item like this:
for (String key : myError.message.keySet()) {
Utils.showToast(getBaseContext(), "Message: " + myError.message.get(key) + " Field: " + key);
}
You can try to use this:
Map myError = new Gson().fromJson(s, Map.class);
Or if you want to use your class json should look like:
{
"message": {
"username": [
"A user with that username already exists."
],
"ruc": [
"user with this ruc already exists."
],
"code": [
"user with this code already exists."
],
"document_number": [
"user with this document number already exists."
]
}
}
Consider using Gson and java native JsonParser.

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?

Categories

Resources