I have a Spring application with a JPA Repository. Now I'd like to add some validations. I found several solutions but none works perfect and I don't know which methode should be used in which case:
1.) Im using validation annotations (e.g. #NotNull) in my model object. But this generates a not usefull rest error response like ""Internal Server Error","message":"Could not commit JPA transaction; "
2.) I'm using the 'Validator' interface for custom validations but I get the spring "compiler" error "Validator has incorrect spelling"
3.) Some tutorials use 'ConstraintValidator' interface
4.) Some tutorials write custom rest methods for validations.
When should I use which and how can I solve my problems?
This is how you can manage it and easy is:
Define all your custom message in /messages/messages.properties under resources folder.
so if you error property is: error.user.name = User name can not be null.
then call your specific property in your pojo for that property.
#NotNull(message = "error.user.name")
Related
I am creating an controller where there is certain attributes in json which is an doing in postman a POST request like this if all attributes are posted then its fine
if one then is missing then it would look like this
i want this response when some attribute is missing how to implement this
This is normally implemented in two steps:
Implement a validation mechanism for the method that handles the incoming request. Normally you would throw an exception here if the input is incorrect, in your example a missing JSON key.
Implement a global error handler that will process the exception from point 1 and format the response as JSON.
For point 1 the usual choice is the Java Bean Validation framework because it's integrated with Spring Boot and allows to define validation constraints with annotations like #NotEmpty. You can take a look at this example.
For point 2 the usual choice is #RestControllerAdvice or #ControllerAdvice. You would have to understand your service web server setup to implement it properly e.g. it might behave differently if you use Spring WebFlux.
I'm using spring integration to store data in a mongo database. I'm using the java classes (MongoDbStoringMessageHandler), not the xml configuration and I can't find the way to get the results when adding some data in the database...
Is it possible ? How ?
The MongoDbStoringMessageHandler is a one-way component and it doesn't return anything.
Consider to use a MongoDbOutboundGateway instead with the CollectionCallback injected where you can perform an updateMany() and get UpdateResult as a reply from this gateway.
See more info in the Reference Manual: https://docs.spring.io/spring-integration/reference/html/mongodb.html#mongodb-outbound-gateway
UPDATE
but I don't know what parameter to put for the function to insert the Message payload.... Since there is no reference of the message in the ServiceActivator
Oh! I see. That a bug. We can't get access to the message from that context. Please, raise a JIRA on the matter: https://jira.spring.io/projects/INT/
Meanwhile as a workaround I suggest you ti write a custom POJO with injected MongoOperations and ther you can build any possible logic against a requestMessage.
The JIRA is here: https://jira.spring.io/browse/INT-4570
Consider a Person entity with a property name that is annotated as #NotNull. Then a simple PersonRepository and this repo exposed with Spring Data Rest.
When I POST to create a new Person, if the name property is null a ValidationException occurs as expected. But what I actually get on the client is an Internal Server Error (500) and the message is a TransactionSystemException that happened much later in the exception chain.
What I'd expect to get is a Bad Request (400) with the actual ValidationException and all it's useful information so the client can know what's wrong with the posted data.
There seems to be a way to attach custom validators with SDR as explained here. But the thing is, this is not a custom validator, it's a standard bean validation that happens when the repository is asked to save data. So I'm not really sure how those two come together.
So questions:
What are my options to let the client know what's wrong with the submitted data when using SDR?. Things like what fields are invalid and what's the error for each field would be awesome.
Are there any examples about this anywhere?
Thanks a lot.
What you need is a proper ExceptionHandler, it will handle back end exceptions and send meaningful rich messages (json/xml) to the front end client.
Take a look a this git repository
Given below is the scenario in which I am facing difficulty, I am using Restful based webservice in spring MVC where I am ineracting with JSON.
I have a class :
RegexObject and another class RegexObjectDME extends RegexObject.
RegexObject is in one common project, which is being used as it is in webservice consumer and RegexObjectDME in webservice provider.
Now, There is another bean in the same common project, Say HDTaskInfoBean ,
There are two child beans extending HDTaskInfoBean as
HDTaskInfoBeanClient extends HDTaskInfoBean<RegexObject>
and
HDTaskInfoBeanAgent extends HDTaskInfoBean<RegexObjectDME> .
The RegexObjectDME and RegexObject have same properties except a few methods.
HDTaskInfoBeanClient and HDTaskInfoBeanAgent too have same properties and there is generic setter getters for regexObject and regexObjectDME. The T type property name is regexArray.
HDTaskInfoBeanClient is used while making request and HDTaskInfoBeanAgent is used on webservice side.
I am getting the following exception:
Syntactical Error.
Another Scenario I used string as requestbody and tried to unmarshall it into Java Object using Gson() , It gave error:
Request processing failed; nested exception is java.lang.UnsupportedOperationException: Expecting parameterized type, got class com.*.
Are you missing the use of TypeToken idiom?
Please help, I want to use **HDTaskInfoBeanClient ** in Request and HDTaskInfoBeanAgent on webservice provider side. If there is any alternative to it, Kindly suggest.
Thanks in advance :)
I am not sure that why did this weird behavior was shown by default message converter which Comes with Spring Framework.
I found that one of the very good message converter from JSON to Object and back is GSON(A utility by Google) .
One reliable approach to handle such a problem is write your own Custom Message Converter by overriding a class and Using GSON in that. Here is the link for such a solution. I hope it helps you as a solution and would be more reliable.
Regards,
Rahul
I am trying to add some metric gathering to a Spring MVC app. Lets say I have a controller whose mapping is:
/User/{username}/Foobar
I want to gather metrics on all controller mapping invocations with the path. Right now I can create a handler/interceptor and look at the requests but that will give me:
/User/Charlie/Foobar
Which is not what I want. I want the controller mapping itself to log. and I don't want to have to add something to every controller. I'd also rather not use AOP if I can help it.
It turns out that Spring hangs the best matching controller pattern on the request itself. You can get this from within a handlerinterceptor like this:
(String)request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)
I can think of two choices:
It seems to me the results of the matching are obtained in the class org.springframework.web.servlet.handler.AbstractUrlHandlerMapping, which logs the patterns obtained (see line 266). I'd try enabling logging for that class and see if the output is helpful for your purposes.
(Complicated)
Extending org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping to override the lookupHandler method inherited from AbstractUrlHandlerMapping and logging/registering what you need. Accoding to this class documentation, you can register a different one so that the DispatcherServlet uses your version.
In Spring 3.2.x DefaultAnnotationHandlerMapping is deprecated so, a different class would have to be used.