Micronaut POJO deserialisation error message when the format is invalid or type throws error - deserialization

When providing the incorrect format of a field for a request to my application if the type throws an error then the error message returned by micronaut is vague.
E.G two scenarios
public class fakeClass {
#NotNull
private String fakeName;
}
if my request is {"fakeName": ""}
then the response, correctly, would be something like
{
"violations": [
{
"field": "create.fakeClass.fakeName",
"message": "must not be blank"
}
],
"type": "https://zalando.github.io/problem/constraint-violation",
"title": "Constraint Violation",
"status": 400 }
But lets say my class looks like this:
public class fakeClass {
#Format("yyyy-MM-dd")
private LocalDate exampeDate;
}
With an invalid date or incorrect format of {"exampleDate": 202222--01-01} or {"exampleDate": 2022/01/01}
Then the error message is
{
"type": "about:blank",
"parameters": {
"path": "/project"
},
"status": 400,
"detail": "Required argument [fakeClass fakeClass] not specified"
}
Is there a simple way to provide more information to the error message to make it clear why the request failed for an invalid format or type like #NotNull or #NotBlank?

The problem here is not Micronaut but your payloads. The examples you mentioned are invalid JSON documents.
For example this on here is invalid, since the value is not a number nor a string.
{
"exampleDate": 202222--01-01
}
this would be the a valid variant
{
"exampleDate": "202222--01-01"
}
Make sure you send the date as a String. In your case this is expected to be valid.
{
"exampleDate": "2022-11-01"
}
In general it is recommended to send date using the ISO-8601 format, which you did (yyyy-MM-dd). Furthermore I recommend to apply a global configuration rather than using on each POJO a #Format("yyyy-MM-dd") annotation.
jackson:
dateFormat: yyyyMMdd
timeZone: UTC
serializationInclusion: NON_NULL
serialization:
writeDatesAsTimestamps: false

#Format("yyyy-MM-dd") is a formatter not a Constraint.
You can use #Pattern(<regex>). There is also date specific ones like #Past, #PastOrPresent, #Futureand #FutureOrPresent.

Related

Problem when the entity value attribute contain special character

I have tied to insert in OCB an entity with a password attribute codified:
{
"id": "prueba-tipo-string2",
"type": "StringParser",
"dateObserved": {
"type": "DateTime",
"value": "2020-08-13T08:56:56.00Z"
},
"password": {
"type": "text",
"value": "U2FsdGVkX10bFP8Rj7xLAQDFwMBphXpK/+leH3mlpQ="
}
}
OCB always response to me with the following error:
"found a forbidden character in the value of an attribute"
In Postman
{
"error": "BadRequest",
"description": "Invalid characters in attribute value"
}
Orion restricts the usage of some characters due to security reasons (script injections attack in some circumstances), see this piece of documentation. In particular, the = you have in the password attribute value.
You can avoid this, for instance, by encoding the password in base 64, or using URL encoding before storing it in Orion.
Another alternative using TextUnrestricted in attribute type. This special attribute type does not check if the attribute value contains a forbidden character. However, it could have security implications, use it at your own risk!

Generate current date in stubbed's json file

To stub http response I use WireMock.
So here my stubbed response as json file.
Location: /wiremock/__files/myproject/stub.resp.json
Content of stub.resp.json
{
"requestId": "903004f5-7033-4aa8-a605-a10d4ff19241",
"Code": 0,
"Text": "Success",
"data": {
"request_id": "a12c6161-463b-e911-85dc-c81f66ca042a",
"paid_currency_code": "USD",
"transfer_amount": 1.0,
"transfer_currency_code": "USD",
"paid_amount": 1.0,
"exchange_rate": 1.0,
"referenceNumber": "123456",
"receiverName": "Bruce Lee",
"receiveDate": "2019-02-28T12:48:00"
}
}
Nice. It's work fine.
But I have one question. As you can see the field receiveDate is hardcoded date-time (always 2019-02-28T12:48:00). But I need every time when return this stub response, in the field receiveDate to generate current date.
How I can do this?
And I need to generate current date in format "yyyy-MM-ddTHH:mm:ss"
You should be able to put something like this into your JSON response body:
"receiveDate": "{{now format='yyyy-MM-dd HH:mm:ssZ'}}"
For referecence: http://wiremock.org/docs/response-templating/, specifically the section under the heading: "Date and time helpers".

API Mapping Templates with Serverless

When using http-event with serverless-framework multiple response status are created by default.
In case of error a Lambda returns an error message stringified in the errorMessage property, so you need a mapping template such as
$input.path('$.errorMessage')
for any status code you want to use. F.e.:
"response": {
"statusCodes": {
"200": {
"pattern": ""
},
"500": {
"pattern": ".*\"success\":false.*",
"template": "$input.path('$.errorMessage')"
}
}
}
But the serverless-framework does not create one by default, thus rendering the default status codes useless. If I would create a mapping template myself, the default response status would be overwritten by my custom ones.
What is the correct way of mapping with the default status codes created by the serverless-framework#1.27.3?

Nested Rest resource throws constraint violation in Jhipster

I have a nested resource like this:
#GetMapping("/tour-requests/{tourRequestId}/tour-request-messages")
#Secured({AuthoritiesConstants.ADMIN})
public ResponseEntity<List<TourRequestMessageDTO>> getTourRequestMessagesForTourRequest(
#PathVariable("tourRequestId") long tourRequestId,
TourRequestMessageCriteria criteria) {
...
}
When I call this resource, for example with GET api/tour-requests/1301/tour-request-messages I get unexpected error:
{
"type": "https://zalando.github.io/problem/constraint-violation",
"title": "Constraint Violation",
"status": 400,
"path": "/api/tour-requests/1301/tour-request-messages",
"violations": [
{
"field": "tourRequestId",
"message": "Failed to convert property value of type 'java.lang.String' to required type 'io.github.jhipster.service.filter.LongFilter' for property 'tourRequestId'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'io.github.jhipster.service.filter.LongFilter' for property 'tourRequestId': no matching editors or conversion strategy found"
}
],
"message": "error.validation"
}
I tried to debug this, it seems that the exception is happening before the method is called-
The problem is that the search criteria has hijacked the path parameter tourRequestId, as it happen to be also a possible search parameter of the generated QueryService.
That it is why it tried to convert the tourRequestId parameter to LongFilter.
Renaming the path variable to ìd` did also not helped, but after renaming it to something different, the problem disappeared.
I've also hit this problem, but my choice was to remove the field from child's pt.up.hs.project.service.dto.ChildCriteria. When the resource is always nested, it just does not make sense to allow querying by the field which is also specified in the path.

Can't post node that requires a pre assigned value with services api

I have setup a content type with a subject field that has pre assigned values in a dropdown field.
I am using the services api to post new content from a polymer app.
When I POST to the api I send the field structure and value in json but get and error.
"406 (Not Acceptable : An illegal choice has been detected. Please contact the site administrator.)"
Even though the object I am sending matches one of the required values in the field.
Do I need to prefix the value with something? I assume I'm posting to the right place to get that response but don't know why it would accept anything other than the string value.
Here is what I sent to the api which is picked up by my Charles proxy.
{
"node": {
"type": "case",
"title": "my case",
"language": "und",
"field_subject": {
"und": {
"0": {
"value": "subject1"
}
}
},
"body": {
"und": {
"0": {
"value": "my details of subject"
}
}
}
}
}
And here is an example of what I have setup in my Drupal field
subject1| first
subject2| second
subject3| third
subject4| forth
For anyone else with the same problem, this subject is poorly documented, but the answer is simple, my subject did not need the value key despite devel suggesting thats how it would be formatted.
"field_subject": {
"und": [
"subject1"
]
}
I could also shorten my code with "und" being an array.