Default globalErrors in Spring - java

I want to know if there are any default globalErrors in Spring framework. I need to create my own custom validator by implementing org.springframework.validation.Validator interface. And there I add a globalError by errors.reject().
In controller class I have to catch this custom validation error If it's occurred. My plan is to catch it by using getGlobalErrors method. But if there any default globalErrors in spring, they will be also caught by getGlobalErrors method.
So I really need to know if there are any default globalErrors in Spring framework.

Well, actually I think there is just one type of errors - when object or some of its fields cannot be mapped to Java object.
For example - when you are trying to set null value from your front-end for LocalDateTime - it's gonna give you an error.
I really believe there are no other errors you can have.

getGlobalErrors method is there in the Spring. Here is the URL -
https://docs.spring.io/autorepo/docs/spring-framework/3.2.8.RELEASE/javadoc-api/org/springframework/validation/AbstractBindingResult.html#getGlobalErrors()

Related

How to force developers to write CustomAnnotation before each api Springboot

How can we force developer to write Developed Custom-annotation on rest api
Example :
We Developed annotation Called : ValidatePermission
what we need to do , displaying runtime error for developer that he missing annotation #ValidatePermission on API , when he tried to write new api
#ValidatePermission
#GetMapping("/details")
#PreAuthorize("hasAuthority('902')")
public ResponseEntity<CustDtlsInqDto> getCustomerDetails(#CurrentUser UserPrincipal currentUser,
#RequestParam(name = "poiNumber", required = false) String poiNumber,
#RequestParam(name = "cif", required = false) String cif) {
return ResponseEntity.ok(customerService.getCustomerDetailsByPoiOrCif(currentUser.getId(), poiNumber, cif));
}
Annotations usage cannot be forced in any way before or on compilation (at least I am not aware of any technique, feel free to correct me).
The only way to go is to perform a check-up during the unit testing phase. Simply write an unit test that scans through the REST API definition beans and its public methods (or annotated) to check up using teh Reflection API whether an annotation from a particular category (implementation details up to you) is present within the formal parameters of methods.
Gits Github: Find all annotated classes in a package using Spring
Baeldung: A Guide to the Reflections Library
Something looks to me weird in this approach.
So you say:
...displaying runtime error for developer that he missing annotation #ValidatePermission on API
Based on this phrase, let me suggest an alternative:
So the developer that runs the project locally (during the debugging session or maybe tests) should see an error if he/she didn't put the annotation on the methods of rest controller, right?
If so, Why don't you need the developers to put this annotation?
The main idea of my suggestion is: Why not letting spring to do it for you automatically?
You could implement some kind of aspect or if you don't want to use a spring aop and prefer 'raw plain spring', BeanPostProcessor, that would 'wrap' all the methods of class annotated with RestContoller (by creating a run-time proxy) and before running a controller method will executed the logic that was supposed to be supported by the annotation?
In the case of Web MVC, another approach is to implement an interceptor that will be invoked automatically by spring mvc engine and you'll be able to execute any custom logic you want there, you'll also be able to inject other beans (like auxiliary services) into the interceptor.
Read this article in case you're not familiar with these interceptors, you'll need preHandle methods as far as I understand.

Spring MVC Validation error

I have a Spring controller that accepts one of my business objects as an argument, that spring is automatically building from form data. One of the attributes of the object is an enum that comes from a select dropdown in the form. I am also using the #Valid notation to do validation on the object, using an implementation of the Spring Validator interface.
In testing, I manually added a selection to the dropdown (using the browser inspector) that is not valid, since it can't be converted to an enum. I would have thought that Spring would just leave the enum attribute as null, and the validator would catch the error, but I actually get a runtime error:
javax.el.ELException: Cannot convert CC of type class java.lang.String to class com.app.enums.States
Any ideas on how to handle this?
We need more details on what you want to happen when this occurs. You could tell Spring how to convert that String into an instance of States by using a Converter (see this page for details).

Spring and JSR303

I need to validate an XML coming from a vendor and saving it as XML type in oracle....
Now i need a process to trigger a validation engine... which is going to validate it and save the value in indicator as 'YES' or 'NO' example if the address in XML doesn't exist in our dB make the address indicator as 'NO' [which we correct in another process...]
I already used JSR303 in Spring 303, which is very effective and easy to use....but it uses a form backing object and #valid.....
Can I use it here in my design...
Or let me put it this way -
Is it possible for Spring's JSR-303 implementation to validate object fields that are not from form input?
I know its a very vague question...so please let me know if I need to explain more
Most of the work for object's validation performed by JSR-303 provider (hibernate-validator in most cases). Spring's role in this process is minimal -- it just parses user's data, binds it to the object and passes this object to validator. Also, during application startup, Spring creates Validator instance.
So, you can interfere in this proccess: create object, which will be validated, manually, get Validator instance and pass object to him. As result you will get a Set of ConstraintViolation which represents errors of each fields.
In this scheme main problem is that JSR-303 validator works with object, while you operates with XML document. You may deserialize XML document to object, validate it and, if it doesn't have errors, serialize it back to XML and writes to DB.
I recommend to read the following part of Hibernate Validator manual: 2.2. Validating constraints It describe Validator interface and a few useful methods: validate(), validateProperty() and validateValue().
One benefit from Spring here is that you won't need to create Validator by yourself with Validation.buildDefaultValidatorFactory().getValidator(): just #Autowire it as all other Spring beans:
#Autowired
private Validator validator;

How to handle in spring validation of json request / bean if the json cannot be converted to the bean?

I have classic Spring MVC application.
I want to validate a Form using a corresponding Java Bean, annotated with JSR-303 validation annotation.
The form data is sent by an ajax call using JSON. This Json is converted to the target Java Bean with Jackson - automatically by spring:
#RequestMapping(value = ControllerConstants.CALCULATION_MAPPING_SUBMIT_FORM,method = RequestMethod.POST)
public String submitForm(#Valid #RequestBody MyFormBean bean, final BindingResult result) {
...
}
Problem is for example if I have an Integer field in my bean but, in JSON the values is not a number. In this case it cannot create the target bean, that cannot be validated. This situation cannot be solved with custom property editors, since there is no way to convert a a text that not represents an Integer to Integer.
It seems that this is solved in Grails, we get errors from validator (errors is domain object) which has to be created during the data binding. So I assume spring supports this, thus Grails just uses Spring's support)
So how to elegantly solve this situation to handle this "validation" error?
UPDATE
Actually I figured out, that is this is supported by spring if we use simple form submit. The problem is with integration of Jackson deserialized. It does not fills errors. Still how to solve this?
I see two options...
Have client side validation that would not allow the form to be submitted if the there are formatting issues.
On the server side you will have to have a mechanism of handling the exception that would catch it and report the problem back to client.
Hope that helps.
EDIT:
Well not having client side validations may not be a good user experience. Users do not want to be reminded about validation errors after they have made a server round trip. However, if this is still a constraint have a look at following url and it gives elegant way of handling such issues and reporting informative error messages.
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

Spring-MVC: Calling a Validator, not from within a Controller

I would like to call a Validator on some object, but not from within a Controller, and then get the Error object.
Could you provide a code sample for this?
Spring's docs show how to use Validator without a Controller in sight:
http://static.springsource.org/spring/docs/2.0.x/reference/validation.html
Been possible since the beginning. It's commonly used in Controllers and the web tier, but that's not required. There's no dependency on the web tier in the validator framework.

Categories

Resources