We all know, that Spring MVC integrate well with Hibernate Validator and JSR-303 in general. But Hibernate Validator, as someone said, is something for Bean Validation only, which means that more complex validations should be pushed to the data layer. Examples of such validations: business key uniqueness, intra-records dependence (which is usually something pointing at DB design problems, but we all live in an imperfect world). Even simple validations like string field length may be driven by some DB value, which makes Hibernate Validator unusable.
So my question is, is there something Spring or Hibernate or JSR offers to perform such complex validations? Is there some established pattern or technology piece to perform such a validation in a standard Controller-Service-Repository setup based on Spring and Hibernate?
UPDATE: Let me be more specific. For example, there's a form which sends an AJAX save request to the controller's save method. If some validation error occurs -- either simple or "complex" -- we should get back to the browser with some json indicating a problematic field and associated error. For simple errors I can extract the field (if any) and error message from BindingResult. What infrastructure (maybe specific, not ad-hoc exceptions?) would you propose for "complex" errors? Using exception handler doesn't seem like a good idea to me, because separating single process of validation between save method and #ExceptionHandler makes things intricate. Currently I use some ad-hoc exception (like, ValidationException):
public #ResponseBody Result save(#Valid Entity entity, BindingResult errors) {
Result r = new Result();
if (errors.hasErrors()) {
r.setStatus(Result.VALIDATION_ERROR);
// ...
} else {
try {
dao.save(entity);
r.setStatus(Result.SUCCESS);
} except (ValidationException e) {
r.setStatus(Result.VALIDATION_ERROR);
r.setText(e.getMessage());
}
}
return r;
}
Can you offer some more optimal approach?
Yes, there is the good old established Java pattern of Exception throwing.
Spring MVC integrates it pretty well (for code examples, you can directly skip to the second part of my answer).
What you call "complex validations" are in fact exceptions : business key unicity error, low layer or DB errors, etc.
Reminder : what is validation in Spring MVC ?
Validation should happen on the presentation layer. It is basically about validating submitted form fields.
We could classify them into two kinds :
1) Light validation (with JSR-303/Hibernate validation) : checking that a submitted field has a given #Size/#Length, that it is #NotNull or #NotEmpty/#NotBlank, checking that it has an #Email format, etc.
2) Heavy validation, or complex validation are more about particular cases of field validations, such as cross-field validation :
Example 1 : The form has fieldA, fieldB and fieldC. Individually, each field can be empty, but at least one of them must not be empty.
Example 2 : if userAge field has a value under 18, responsibleUser field must not be null and responsibleUser's age must be over 21.
These validations can be implemented with Spring Validator implementations, or custom annotations/constraints.
Now I understand that with all these validation facilites, plus the fact that Spring is not intrusive at all and lets you do anything you want (for better or for worse), one can be tempted to use the "validation hammer" for anything vaguely related to error handling.
And it would work : with validation only, you check every possible problem in your validators/annotations (and hardly throw any exception in lower layers). It is bad, because you pray that you thought about all the cases. You don't leverage Java exceptions that would allow you to simplify your logic and reduce the chance of making a mistake by forgetting to check that something had an error.
So in the Spring MVC world, one should not mistake validation (that is to say, UI validation) for lower layer exceptions, such has Service exceptions or DB exceptions (key unicity, etc.).
How to handle exceptions in Spring MVC in a handy way ?
Some people think "Oh god, so in my controller I would have to check all possible checked exceptions one by one, and think about a message error for each of them ? NO WAY !". I am one of those people. :-)
For most of the cases, just use some generic checked exception class that all your exceptions would extend. Then simply handle it in your Spring MVC controller with #ExceptionHandler and a generic error message.
Code example :
public class MyAppTechnicalException extends Exception { ... }
and
#Controller
public class MyController {
...
#RequestMapping(...)
public void createMyObject(...) throws MyAppTechnicalException {
...
someServiceThanCanThrowMyAppTechnicalException.create(...);
...
}
...
#ExceptionHandler(MyAppTechnicalException.class)
public String handleMyAppTechnicalException(MyAppTechnicalException e, Model model) {
// Compute your generic error message/code with e.
// Or just use a generic error/code, in which case you can remove e from the parameters
String genericErrorMessage = "Some technical exception has occured blah blah blah" ;
// There are many other ways to pass an error to the view, but you get the idea
model.addAttribute("myErrors", genericErrorMessage);
return "myView";
}
}
Simple, quick, easy and clean !
For those times when you need to display error messages for some specific exceptions, or when you cannot have a generic top-level exception because of a poorly designed legacy system you cannot modify, just add other #ExceptionHandlers.
Another trick : for less cluttered code, you can process multiple exceptions with
#ExceptionHandler({MyException1.class, MyException2.class, ...})
public String yourMethod(Exception e, Model model) {
...
}
Bottom line : when to use validation ? when to use exceptions ?
Errors from the UI = validation = validation facilities (JSR-303 annotations, custom annotations, Spring validator)
Errors from lower layers = exceptions
When I say "Errors from the UI", I mean "the user entered something wrong in his form".
References :
Passing errors back to the view from the service layer
Very informative blog post about bean validation
Related
I have a webapp (Play framework 2.x, Java) that receives JSON payloads as input.
I have input payloads in different shapes like:
{
files: [{id: 1,name: null}}
requiredAttribute: null,
}
I want to output errors in this form, similar to the input:
{
files: [{name: "name can't be null"}}
requiredAttribute: "requiredAttribute can't be null",
}
I'd like to know how I can output errors in this form with Java without too much pain.
I know I'll loose the ability to output multiple errors per field and I'm fine with that.
I'm ok using any external library as long as it's easy to declare the constraints on the fields, so using something like Java validation and validation constraints annotations would be nice. But I wasn't able to find any support for this kind of stuff so far. Any idea how it could be done with Play or Java validation or Jackson?
Using bean validation, you can achieve this by calling validate() yourself and processing a collection of Set<ConstraintViolation<T>>.
You first need to get a Validator object. There may be ways to do this better, but one way is to use the factory (used this in the past, it worked with a Hibernate validator dependency on the class path):
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Then use the validator to retrieve a set of constraint violations (Assuming a generic type T for a bean class with the relevant constraint annotations):
Set<ConstraintViolation<T>> constraintViolations = validator.validate(myBean);
Map<String, String> fieldErrors = new HashMap<>();
for (ConstraintViolation<T> violation : constraintViolations) {
String message = violation.getMessage();
String field = violation.getPropertyPath().toString();
fieldErrors.put(field, message);
}
Note that for nested bean classes, you'll get a dot-separated "path" for field names.
I need your help!
In my web project (it based on Spring MVC) i'm using exceptions to indicate that some validation is failed, but i'm not sure that doing the right way.
For example i have such service:
#Service
#Transactional
public class UserService {
#Autowired
private UserRepository userRepository;
public User createUser(UserDTO userDTO) throws IllegalArgumentExceptio {
validateUserEmail(userDTO);
return userRepository.save(new User(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getPassword()));
}
private void validateUserEmail(UserDTO userDTO) throws IllegalArgumentException {
String emailPattern = "^[a-z0-9-\\+]+(\\.[a-z0-9-]+)*#"
+ "[a-z0-9-]+(\\.[a-z0-9]+)*(\\.[a-z]{2,})$";
if (userDTO() == null) {
throw new IllegalArgumentException(INVALID_EMAIL_NULL.getMessage());
} else if (userDTO().length() > 25) {
throw new IllegalArgumentException(INVALID_EMAIL_LENGTH.getMessage());
} else if (!userDTO().matches(emailPattern)) {
throw new IllegalArgumentException(INVALID_EMAIL_FORMAT.getMessage());
}
}
}
I've read this one article. Also i know that there is another one approach is to use Hibernate Validator.
So, the main question is: which one approach is the best practice and why?
Throw an exception during validation as i do.
Use something like notification pattern.
Use Hibernate Validator.
Clearly, using the Hibernate Validator for Bean Validations, which is the readily available library is the best approach as we don't need to rewrite huge code for min length/max length, etc.. validations explicitly.
Also, if you rewrite the logic for minlength/maxlength validations ourself, you need to do the extensive testing to ensure that the written code is correct, which is must.
The thumb rule, if some trusted code is already available, do not try to reinvent/rewrite again, rather just make use of it, which is called DRY (Don't Repeat Yourself) principle, very important in any programming
That's a very bad idea. One of issues with your solution that comes to my mind is like: How you are going to notify a user if your email validation fails? I would go for custom validation annotation. If validation of email fails, you simply return false. With that approach, you can also easy notify user if email validation fails because simply, BindingResult will contain errors. Also, another benefit is localization of error message. So yeah, Hibernate validatior is way to go.
i.e. In he following query method in a spring repository neither a nor b are required from an HTTP request. Is it possible to enforce the presence of these parameters at the repository level?
I would like to be explicit with the API I expose to the client. Right now no params, a, b, a&b are all accepted by the exposed endpoint. However I only want to expose a&b.
List<Thing> findByBAndC(#Param(value="a") Long a,#Param(value="b") Long b);
Don't know of any Spring Data way to do it, but spontanously I can think of some ways...
You could use a custom #Query where only if both are present ( "is not null" ) something would be returned, if that's enough
You could also (ab)use security with #PreAuthorize to check if both parameters are not null, but that sounds smelly.
Probably the most easy (and least smelly) way I can think of is to write your own Aspect that wraps around the method and throws an exception of both parameters are not present... For example, create your own custom annotation, put it before your method and then write an aspect, something like (not tested):
#Around("#annotation(com.example.AllParametersRequired.class)")
public Object throwExceptionOnMissingParameters(ProceedingJoinPoint pjp) throws Throwable {
int nullCount = Arrays.stream(pjp.getArgs()).filter( o -> o == null).count();
if (nullCount > 0) throw new RuntimeException("Null is not allowed.);
return pjp.proceed();
}
You will probably have to experiment there a little bit, to see which pointcut is the best for your case, but I don't see why you shouldn't be able to wrap an aspect around Spring Data's repository methods. Anyway, here's a link to the Spring AOP documentation, which will probably be helpful if you want to go that way: Link
I'd like to have a method in my Repository that returns a single value.
Like this:
TrainingMode findByTrainingNameAndNameEng( String trainingName, String nameEng );
http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/
Spring Data Docs describe that in this case the method can return null if no entity is found.
I'd like to throw an exception with generic message like No TrainingMode found by %trainingName% and %nameEng% or smth like that.
I can use Optional<TrainingMode> as a return value and then use orElseThrow
Optional<TrainingMode> findByTrainingNameAndNameEng( String trainingName, String nameEng );
repository.findByTrainingNameAndNameEng(name, nameEng).orElseThrow(() -> new RuntimeException(...));
But I should call this method each time when this method is called. It's not clear - DRY priciple is broken.
How to get nonnull single value with orElseThrow using Spring Data?
The DRY principle would be violated if you duplicate null handling throughout the application logic where it is being invoked. If DRY principle is the thing you are worried the most then i can think of:
You can make a "Service" class which would delegate calls to annotated repository and handle null response logic to it, and use that service class instead of calling repositories directly. Drawback would be introducing another layer to your application (which would decouple repositories from your app logic).
There is possibility of adding custom behavior to your data repositories which is described in "3.6.1. Adding custom behavior to single repositories" section of documentation. Sorry for not posting the snippet.
The issue I personally have with second approach is that it pollutes app with interfaces, enforces you to follow a certain naming patterns (never liked 'Impl' suffixes), and might make migrating code a bit more time consuming (when app becomes big it becomes harder to track which interface is responsible for which custom behavior and then people just simply start creating their own behavior which turns out to be duplicate of another).
I found a solution.
First, Spring Data processes getByName and findByName equally. And we can use it: in my case find* can return null (or returns not null Optional, as you wish) and get* should return only value: if null is returned then exception is thrown.
I decided to use AOP for this case.
Here's the aspect:
#Aspect
#Component
public class GetFromRepositoryAspect {
#Around("execution(public !void org.springframework.data.repository.Repository+.get*(..))")
public Object aroundDaoMethod( ProceedingJoinPoint joinpoint ) throws Throwable {
Object result = joinpoint.proceed();
if (null == result) {
throw new FormattedException( "No entity found with arhs %s",
Arrays.toString( joinpoint.getArgs() ) );
}
return result;
}
}
That's all.
You can achieve this by using the Spring nullability annotations. If the method return type is just some Entity and it's not a wrapper type, such as Optional<T>, then org.springframework.dao.EmptyResultDataAccessException will be thrown in case of no results.
Read more about Null Handling of Repository Methods.
We use a standard SEAM setup here ... complete with the validation system that uses hibernate.
Basically what happens is a user enters a value into an html input and seam validates the value they entered using the hibernate validation.
Works fine for the most part except here's my problem: We need to record the results of validation on each field and I can't figure out a good way to do it ... ideally it would be done through communicating with the seam/hibernate validation system and just recording the validation results but as far as I can tell there isn't a way to do this?
Has anyone done anything like this in the past? There are a couple nasty work arounds but I'd prefer to do it cleanly.
Just a quick overview of the process that we have happening right now for context:
1) user enters field value
2) onblur value is set with ajax (a4j:support) at this point the validators fire and the div is re-rendered, if any validation errors occured they're now visible on the page
What I'd like to have happen at step2 is a 'ValidationListener' or something similar is called which would allow us to record the results of the validation.
Thanks if anyone is able to help :o
You should be able to do it by creating a Bean that has a method observing the org.jboss.seam.validationFailed event. That method can then do whatever logging you want.
#Name("validationObserver")
public class ValidationObserver() {
#Observer("org.jboss.seam.validationFailed")
public void validationFailed() {
//Do stuff
}
}
The validationFailed event doesn't pass any parameters so you'll have to interrogate the FacesMessages or possibly the Hibernate Validation framework itself if you want to record what the error was.
I you are only using Hibernate for validation, you can use the Hibernate ClassValidator in the validationFailed() method, as recommended by Damo.
Example:
public <T> InvalidValue[] validateWithHibernate(T object) {
ClassValidator<T> validator = new ClassValidator(object.getClass());
InvalidValue[] invalidValues = validator.getInvalidValues(object);
return invalidValues;
}