conditional validation for multiple registrations - java

I have 2 fields that are being passed in request body. I have a conditional validation for if value1="OK" then value2 must be "PASSED" or raise a validationerror. It's working fine for single instance but in my json body I can pass multiple registration requests at once, like the Json request body shown below.
[
{
"Value1": "OK",
"Value2": "NOTPASSED"
},
{
"Value1": "OK",
"Value2": "PASSED"
}
]
How can I process second record, though validation for first record failed?
EDIT: Looking at the comments I thought to simplify the question even more:
these are the fields from request body:
#NotEmpty
private String value1;
#NotEmpty
private String value2;
I can pass multiple registrations in my json body as shown above.
let's say I passed a body like this:
[
{
"Value1": "",
"Value2": "NOTPASSED"
},
{
"Value1": "OK",
"Value2": "PASSED"
}
]
Since we have NotEmpty validation for value1, it will throw a validation error but second record with value1 as "OK" and value2 as "PASSED" doesn't have any validation errors. So I need a functionality to be able to process the second record while throwing error for the first record.

take that list of object and loop then after make a if else condition
and validate ..
list.forEach(object->{
if(object.getValue1()=="OK")
if(object.getValue2()=="PASSED")
//do ur logic because if pointer come here means it's valid
else
//do ur logic if not valid like raise a validation-error
//my suggestion is store invalid instances here and through in single
//shot
});

Request body is an array having multiple instances of
{
"Value1": "OK",
"Value2": "NOTPASSED"
}
You can loop through the array and validate each instance something like
List<VallidationError> validationErrorList = new ArrayList<>();
for(RequestElement element: requestBody) {// RequestElement is the class for each instance in the request body
if(element.getValue1().equals("OK") && !element.geValue2().equals("PASSED")) {
validationErrorList.add(new ValidationError());// Add validation error to a list of validation errors
} else {
processElement(element);// Process the record here
}
}

As you said it can be Empty String sometimes then instead of using #NotEmpty you should use #NotNull.
I guess it should solve your problem as on an empty string for value1 it will not throw validation.

Related

Matching JSON request body based on JSON Path with logical operators in WireMock

In WireMock I am trying to match the request based on the JSON body with path matchers as shown below. But it seems that the logical operators are not supported inside matchesJsonPath expression.
Is this understanding correct? What could be a possible alternative solution?
...
"request": {
"url": "/mock/score",
"method": "PUT",
"bodyPatterns": [
{
"matchesJsonPath": "$[?(#.code == '123')]"
},
{
"matchesJsonPath": "$[?(#.amnt < '200000')]"
}
]
}
...
Your assumption is incorrect. You can use operators inside of the JSONPath filters. You might be running into issues because the value being checked on amnt is a string. The following should work.
...
{
"matchesJsonPath": "$[?(#.amnt < 20000)]"
}
...
This of course, requires that the value being passed in the body is a number type and not a string itself.
{
"amnt": 20000 // correct format
"amnt": "20000" // incorrect format
}
If your amnt value is a string, you may have to write a custom matcher that can parse the body and convert the string value into a number (or the java data type equivalent)

Rest response being captured as a map instead of custom object

I am getting the following from a rest call.
[
{
"IMAGE": "",
"DESCRIPTION": "",
"HEADER": ""
}
]
I am using these values to construct another response to the calling client.
In that response, I want it to be in lower case as follows.
[
{
"image": "",
"description": "",
"header": ""
}
]
This is what I am doing currently to convert.
// a large json response received from the rest call.
Benefit benefits = // rest call
//this is above block of response where the keys are upper case currently.
benefits.get(FURTHER_DATA); // type is Object
// casting to my custom object.
List<FurtherData> data = (List<FurtherData>) benefits.get(FURTHER_DATA);
Works fine but the key is still upper case.
When I see it in debug format, I am expecting it to be a list of my FurtherData object.
Instead it is actually showing up as a LinkedHashMap. How? Am so confused. Please help. Thanks.
This is the custom FurtherData object. Another weird thing going on here. I can comment out all the fields here. Still works. Again... how?
#Getter
#Setter
public class FurtherData {
#JsonProperty("IMAGE")
private String image;
#JsonProperty("DESCRIPTION")
private String description;
#JsonProperty("HEADER")
private String header;
}
P.S: To note, this is not myself missing out some additional logic elsewhere.
>It's all happening in following line. If I comment it out, the response doesn't have the above block of data as expected.
List<FurtherData> data = (List<FurtherData>) benefits.get(FURTHER_DATA);
This is Benefit object.
// other fields
private List<FurtherInfo> furtherInfo;

How to sum value of two values of a json array in java spring boot?

My Api response(for the url http://localhost:8080/findTotSum/12-01-2020/12-02-2020) in JSON format is this
[
{
"id": 121982,
"expdate": null,
"exptype": null,
"expamt": 1000
},
{
"id": 121984,
"expdate": null,
"exptype": null,
"expamt": 54
}
]
I want to sum both the expamt and should get the result as 1054 and should give the response with summed up amount alone if possible
At first you should update API for /findTotSum endpoint according to your buisness logic. If you want to get the sum of several values you should choose correct return type.
Second, you need to implement a service for such operations, in this case for sum operation, and use it controller class.
The response can be changed for something like that:
Class newResponseWithSum {
private List<SomeEntity> list;
private int sum;
}

Pass object inside existing model object, where the new object parameters are not defined and may change

Problem: I have a request body where I have a predefined POJO class, inside this class I need to add another object as parameter. This new object at a given time may have random properties/attributes/params. How can I achieve this?
{
"id": "{{id}}",
"enableTouchId": true,
"idleLogoutMinutes": 10,
"platformSpecificPreferences": {
"ios": {
"terms": "1234",
"privacy": "12345"
},
"web": {
"terms" : "abc"
},
"android": {
"newProperty" : "newValue"
}
}
}
So the new object I am trying to add is platformSpecificPreferences, which when hit using rest calls might or might not have all the properties shown here, which is why I cannot use redefined POJO class for platformSpecificPreferences and create its object.
Solution I tried:
I thought of using JsonObject inside request body, which makes
#JsonProperty("platformSpecificPreferences")
private JsonObject platformSpecificPreferences;
but the problem is, I am not able to hit the api as it doesnt accept this parameter and gives 404.
Thanks in advance.
You can use, kind must a predefined pojo for platformSpecificPreferences but in the pojo you need to ignore values that are not given in the rest call!
You can do this with a json annotation:#JsonIgnoreProperties(ignoreUnknown = true) in the Pojo above the class.

Check for extra fields

I'm using Jersey with javax.ws.rs.*.
I have the following function:
#PUT
public R modify(#PathParam("id") int id, R in) throws Exception {
...
}
Where R (Resource) is a JSON object containing the fields to be updated. Example:
{
"name": "Building",
"address": "Street number",
"address2": "Lower floor"
}
The update process is working, but as an extra measure for our website developers which are using this API I want the method to throw an exception when a field is sent which isn't allowed. Example:
{
"name": "Qcast HQ",
"illegalField" : "someValue"
}
Because the input gets treated as a Resource object I am not sure whether the method can check for illegal fields. Maybe there is an annotation or something I can use to check for this?

Categories