How to refactor validators - java

I was thinking about a good implementation for validators. My service method starts like this:
if(badSituation()){
return Response.status(400).entity("bad situtaion").build();
}
if(badSituation2()){
return Response.status(400).entity("bad situtaion2").build();
}
...
if(badSituationN()){
return Response.status(400).entity("bad situtaionN").build();
}
Since validators multiply really fast I have decided to refactor them to some design pattern. I was thinking about Chain of Responsibility or Composite, however I had a problem with practical realization. Can someone suggest how this code should be refactored?

You can use the Cor Pattern for the validation "Behavior" : Each of your validators would implement a base ChainedValidator interface (some of the behavior can be moved to a parent abstract class as it is the same for all chain members):
public class MyFirstValidator implements ChainedValidator{
//This CoR implementation has also a 'Composite' background
ChainedValidator nextValidator;
#Override
private void doValidate(Request request) throws ValidationException
{
if(badSituation){
//throw validation exception
}
}
#Override
public void doChainValidate(Request request) throws ValidationException
{//This method can be moved to a parent abstract class
doValidate(request);
if(nextValidator!=null){
nextValidator.doChainValidate(request);
}
}
private void attachValidator(ChainedValidator newValidator) throws ValidationException
{//same as previous method
if(nextValidator!=null){
nextValidator.attachValidator(request);
}else{
nextValidator=newValidator;
}
}
//setters & other methods
}
On your Controllers/Web tier Service classes, you can inject the first ChainedValidator of the validation chain and call doChainValidate :
public class WebTierService{
ChainedValidator validator;
public Response serviceMethod(Request request){
try{
//...
validator.doChainValidate(request);
//...
}catch(ValidationException e){
return Response.status(400).entity(e.getMessage()).build();
}
}
}
As you can see, the logic is 'fluid' (No if else check depending on type of validation error) and adding a new validator is relatively simple (validator.attachValidator()) which makes the logic extensible and clean.

Related

what is the proper design for calling controller methods?

I have a controller that calls several methods of an external SOAP api and returns some data, for example
public class ExternalApplicationController {
#Autowired
private ExternalApplicationSoapService soapService;
public FirstResponse getFirst() {
return soapService.getFirst()
}
public SecondResponse getSecond() {
return soapService.getSecond()
}
public ThirdResponse getThird() {
return soapService.getThird()
}
...
}
Everything was clear before the client asked to process exceptions on each method call. Now any method of my controller can get SOAPFaultException, so i need to modify each method with a try / catch block like this:
...
public FirstResponse getFirst() {
try {
return soapService.getFirst()
catch (SOAPFaultException ex){
// do something similar for all methods
}
}
....
I guess i should use a generified utility class that handles the common logic, but i suppose that design principles would be broken in that way... There shouldn't be anything between controller and service by MVC...
Also it's not very natural to make a service that should call soapService because all his methods would duplicate logic... And I don't want to write try / catch at each controller method, because it's a clear code duplicate..
Is there any suitable pattern for this?

How can I abort saving an entity within a method annotated with onBeforeSave of a class that extends AbstractRepositoryEventListener?

I am extending AbstractRepositoryEventListener in order to create a md5 hash of an photo and save it with the object.
I'd like to abort saving the photo altogether in the event of an exception.
#Component
public class MyHandler extends AbstractRepositoryEventListener<Photo> {
#Autowired
PhotoService photoService;
#Override
public void onBeforeSave(Photo photo) {
File originalPhoto = new File(foto.getUriOriginal());
try {
String hash = photoService.getHash(originalPhoto);
photo.setHash(hash);
} catch ( IOException | NoSuchAlgorithmException e ) {
e.printStackTrace();
}
}
}
You may throw an instance of RuntimeException. It will get Spring to rollback.
There are other more comprehensive ways, details of which you can find here.
If someone ever have this same problem, here's a better approach.
The goal here is basically to validate an entity.
Spring already provides a ValidatingRepositoryEventListener that uses validators to achieve this goal. Not only will the saving be "aborted", but also the error message will be provided to the client.
It is important to notice that automatic discovery of validators seem to have a bug with a workaround described here.
It is also possible to create custom validation annotations, as described in the link below, resulting in a more reusable code.
In this particular instance, the Validator would look something like this:
#Component("beforeSavePhotoValidator")
public class PhotoValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return Photo.class.equals(clazz);
}
#Override
public void validate(Object obj, Errors errors) {
if (customValidationIsInvalid(obj)){
errors.rejectValue(
"<invalidFieldName>",
"<errorMessageCode>"
);
}
}
}
Observe that:
customValidationIsInvalid, invalidFieldName and errorMessageCode should be appropriately implemented
the errorMessageCode must be set in the ValidationMessages.properties file
the workaround must be implemented, or the validator manually registered

Validation Library Design Pattern selection

I am writing a library which is used for validating some specific objects.
I implemented it like strategy pattern.
What is the best pattern for implementing a validation library ?
Some of my code is shown below.
//INTERFACE
public interface IValidator {
public boolean validate(Object o) throws ValidationException;
}
//VALIDATOR OBJECT
public class Validator {
private IValidator validator;
public Validator(IValidator validator)
{
this.validator=validator;
}
public boolean validate(Object o) throws ValidationException
{
return this.validator.validate(o);
}
}
//EMAIL VALIDATOR
public class EmailValidator implements IValidator{
#Override
public boolean validate(Object o) throws ValidationException {
//VALIDATE E MAIL HERE
return false;
}
}
//TEST RUN
Validator validator = new Validator(new EmailValidator());
validator.validate("some email");
I guess the answer to this question is mainly subjective so I can only give my own opinion:
I myself use the strategy pattern as well for such tasks because that is what it is meant for. You use a specific validation strategy depending on the input of the function so the strategy pattern is alright, I think.
Read the first part of the Wiki article about the strategy pattern Strategy Pattern. Their main example is also about validation.
I would enhance your code as below:
//INTERFACE
public interface IValidator<T> {
void validate(T arg) throws ValidationException;
}
//EMAIL VALIDATOR
public class EmailValidator implements IValidator<Email email>{
#Override
public void validate(Email email) throws ValidationException {
//VALIDATE E MAIL HERE, throw exception, if needed
}
}
// Usage
EmailValidator validator = new EmailValidator();
validator.validate(); // Catch ValidatorException here to transform into business exception and appropriate error handling
Few points:
Here java Type Eraser can help implement IValidator interface with any custom implementation.
Validation logic is outside POJO, POJO is pure POJO :)

Spring MVC: bind an exception handler to particular method

Good day!
I have a #Controller. Some of its methods throw the same exception, but I want to handle this exceptions in different way.
Is there a way how to bind an #ExceptionHandler to a particular method?
You need to use AOP tools like CDI Interceptor or AspectJ to achieve this cross-cutting concerns. A Concern is a term that refers to a part of the system divided on the basis of the functionality.
Basically this type of feature is used to handle logging, security and also handling the errors... which are not part of your business logic...
Like if you want to change the logger for application from log4j to sl4j then you need to go through each and every classes where you have used log4j and change it. But if you have used AOP tools then you only need to go the interceptor class and change the implementation. Something like plug and play and very powerful tool.
Here is a code snippet using JavaEE CDI Interceptor
/*
Creating the interceptor binding
*/
#InterceptorBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface BindException {
}
After we have define interceptor binding we need to define interceptor binding implementation
/*
Creating the interceptor implementation
*/
#Interceptor
#BindException
public class ExceptionCDIInterceptor {
#AroundInvoke
public Object methodInterceptor(InvocationContext ctx) throws Exception {
System.out.println("Invoked method " + ctx.getMethod().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// code for Exception handler
}
}
}
Now we only need to apply interceptor to our method
/*
Some Service class where you want to implement the interceptor
*/
#ApplicationScoped
public class Service {
// adding annotation to thisMethodIsBound method to intercept
#BindException
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionCDIInterceptor
}
}
You can achieve same feature using AspectJ also.
/*
Creating the Aspect implementation
*/
#Aspect
public class ExceptionAspectInterceptor {
#Around("execution(* com.package.name.SomeService.thisMethodIsBound.*(..))")
public Object methodInterceptor(ProceedingJoinPoint ctx) throws Throwable {
System.out.println("Invoked method " + ctx.getSignature().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// codes for Exception handler
}
}
}
Now we only need to enable the AspectJ to our application config
/*
Enable the AspectJ in your application
*/
#Configuration
#EnableAspectJAutoProxy
public class AppConfig {
#Bean
public SomeService SomeService() {
return new SomeService();
}
}
/*
Some Service class where you want to implement the Aspect
*/
package com.package.name;
public class SomeService {
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionAspectInterceptor
}
}
I have code example in my git repo https://github.com/prameshbhattarai/javaee-exceptionBinding by using CDI interceptor.
Just as an option (obviously, it's not ideal): you can wrap the exception into a custom exception in one of your methods and then catch it in an #ExceptionHandler
void boo() throws WrappingException {
try {
} catch (TargetException e) {
throw new WrappingException(e);
}
}
then
#ExceptionHandler(WrappingException.class)
public void handleWrappingException() {
// handle
}
#ExceptionHandler(TargetException.class)
public void handleTargetException() {
// handle
}
Could you please explain why do you need this? I'm asking out of curiosity, because I've never felt like this is required and here is why:
Exception usually represents a very specific "mistake" - something that went wrong in a very specific way.
Basically, exception represents a mistake, not a flow...
There are two "degrees of freedom" that spring can support out of the box:
Exception parameters. Maybe stuff like error code, which can be declared as a data field of exception itself.
Exception inheritance. Example:
If you have in your system a UserDoesNotExistException and you want to be more specific in a case of say, the system that manages the users that are retired in some flows, you can always create a more specific exception:
class UserRetiredException extends UserDoesNotExistException {...}
Obviously, spring can support both the cases: In ExceptionMapper you have the access to the exception anyway so you can do something like:
handleException(SomeExceptionWithErrorCode ex) {
if(ex.getErrorCode() == "A") {
// do this
}
else if(ex.getErrroCode() == "B") {
// do that
}
}
In the second case you just have different exception mappers for the different types of exceptions.
You can also consider #ControllerAdvice annotation to reuse code or something.
I don't think you can specify a specific #ExceptionHandler for a method, but you can bind an #ExceptionHandler method to a specific Exception.
So if you want to handle all DataIntegrityViolationException one way and all other Exceptions in another you should be able to achieve that with something like this:
#ExceptionHandler(DataIntegrityViolationException.class)
public void handleIntegrityViolation() {
// do stuff for integrity violation here
}
#ExceptionHandler(Exception.class)
public void handleEverythingElse() {
// do stuff for everything else here
}
You can derive sub-exceptions from the common exception thrown by other methods according to how you want to handle them.
Say you have declared the parent exception as ParentException. Derive sub classes like ChildAException extends ParentException, ChildBException extends ParentException etc.
Define a #ControllerAdvice class that catches the ParentException and define the specific behaviors in delegate methods.
#ControllerAdvice
public class ParentExceptionHandler {
#ExceptionHandler(ParentException.class)
public ResponseEntity<Object> handleParentException(ParentException pe) {
if (pe instanceof ChildAException) {
return handleChildAException((ChildAException) pe);
} else if (...) {
...
} else {
// handle parent exception
}
}
private ResponseEntity<Object> handleChildAException(ChildAException cae) {
// handle child A exception
}
}
I just got the same issue like you. So I checked the spring source code for this situation. It seems that spring will search in the #Controller class for any method that is annotated with #ExceptionHandler first, if nothing matched then it will continue to search for all class that is annotated with #ControllerAdvice. So you can just use the strategy below:
MyController with a #ExceptionHandler method:
#RestController
public class MyController {
#RequestMapping("/foo")
public String foo() {
throw new IllegalArgumentException();
}
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Specific handler", HttpStatus.BAD_REQUEST);
}
}
AnotherController without any method annotated with #ExceptionHandler:
#RestController
public class AnotherController {
#RequestMapping("/bar")
public String bar() {
throw new IllegalArgumentException();
}
}
A global #ControllerAdvice class:
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Global handler", HttpStatus.BAD_REQUEST);
}
}
Then if you visiting http://ip:port/foo, you will get 400 status code with Specific handler, and 400 status code with Global handler when you visit http://ip:port/bar.
I agree that the inability to map a specific #ExceptionHandler to handle only one specific method in the #RestController should be a very desirable feature.
I tried try{}catch(Exception ex){} and catch no exception. But
exception handler handles it nicely.
Since we are talking about hibernate exceptions, these exceptions are usually thrown at the commit phase of transaction. The problem here is that seems like you have transaction opened right in your controller which is considered as a bad practice.
What you should do is - open transaction in the application layer.
Controller just maps xml/json to incomming RequestDto object.
And then you call the Service to handle the business logic.
The Service(or its method) should be annotated by #Transactional.
#RestController
public class MyController {
#Autowired // but better to use constructor injection
private MyService myService;
public ResponseDto doSomething(RequestDto request) {
try {
myService.doSomething(request);
} catch (DataIntegrityViolationException ex) {
// process exception
}
}
}
#Transactional
class MyService {
public void doSomething() {
// do your processing which uses jpa/hibernate under the hood
}
}
Once you done that, the try catch will start behaving as expected on controller level.
However, I would even go further as DatabaseExeption shouldn't really go that far to controller. The alternative would be to use manual transaction inside of a service and do a try catch there.
Then in the Service layer transform database exception in a more generic exception with all necessary information for controllers to process.
And then you should catch that more generic exception (MyDatabaseAccessException) in the controller and transform as you wish for the sake of a presentation layer.
===
The #ControllerAdvice suggested here is good for a global exception handling across controllers.
The #ExceptionHandler is not suitable for each method unless you wnat to have controller per method. And even after that it can clash with global #ControllerAdvice.
I am not sure why spring doesn't allow #ExceptionHandler at a method level, it would simplify a lot of cases like yours.
My solution is to annotate a method with a marker:
#ExceptionHandler(SomeException.class)
public ResponseEntity<String> handleSomeException(SomeException e, HandlerMethod handlerMethod) {
var marker = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getMethod(), MarkerAnnotation.class);
if (marker != null) return something();
else return somethingElse();
}

Is this a good pattern for annotation processing?

I've got a fairly standard Spring webapp, and I have a number of custom annotations that I would like to use to denote the requirements and constraints applied to a given web-service method. For instance, I might apply an #RequiresLogin annotation to any method that requires a valid user session, and #RequiresParameters(paramNames = {"name", "email"}) on a method that requires that "name" and "email" be set, and so on.
In support of this I implemented an ad-hoc utility for validating a method's annotated constraints at runtime, which basically followed a pattern of:
Map<Class<? extends Annotation>, Annotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
if (annotations.containsKey(AnnotationType1.class)) {
AnnotationType1 annotation = (AnnotationType1)annotations.get(AnnotationType1.class);
//do validation appropriate to 'AnnotationType1'
}
if (annotations.containsKey(AnnotationType2.class)) {
AnnotationType2 annotation = (AnnotationType2)annotations.get(AnnotationType2.class);
//do validation appropriate to 'AnnotationType2'
}
//...
This works fine, but has become a bit unwieldy as I have added additional annotations. I'd like to replace it with something a bit more maintainable. Ideally I'd like to be able to do:
List<ValidatableAnnotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
for (ValidatableAnnotation annotation : annotations) {
annotation.validate(request);
}
But I'm pretty sure that is not possible since annotations themselves cannot contain executable code and since the compiler will not let me extend java.lang.annotation.Annotation (not that I'd know how to go about allowing executable code to be contained in an annotation even if the compiler let me try).
What annotations can contain, however, is a nested inner class, and that inner class can do anything that a normal Java class can do. So what I've come up with based upon that and in the interest of keeping my validation code as closely associated with the annotation being validated as possible is:
public interface AnnotationProcessor {
public boolean processRequest(Annotation theAnnotation, HttpServletRequest request);
}
And then the annotations can be implemented like:
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
public #interface RequiresLogin {
public static class Processor implements AnnotationProcessor {
#Override
public boolean processRequest(Annotation theAnnotation, HttpServletRequest request) {
if (! (theAnnotation instanceof RequiresLogin)) {
//someone made an invalid call, just return true
return true;
}
return request.getSession().getAttribute(Constants.SESSION_USER_KEY) != null;
}
}
}
Which keeps the validation logic nice and tightly coupled with the annotation that is being validated. Then all my ad-hoc validation code can be replaced with:
List<Annotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
for (Annotation annotation : annotations) {
processAnnotation(annotation, request);
}
private static boolean processAnnotation(Annotation annotation, HttpServletRequest request) {
AnnotationProcessor processor = null;
for (Class<?> processorClass : annotation.annotationType().getDeclaredClasses()) {
if (AnnotationProcessor.class.isAssignableFrom(processorClass)) {
try {
processor = (AnnotationProcessor)processorClass.newInstance();
break;
}
catch (Exception ignored) {
//couldn't create it, but maybe there is another inner
//class that also implements the required interface that
//we can construct, so keep going
}
}
}
if (processor != null) {
return processor.processRequest(annotation, request);
}
//couldn't get a a processor and thus can't process the
//annotation, perhaps this annotation does not support
//validation, return true
return true;
}
Which leaves no more ad-hoc code that needs to be revised every time I add a new annotation type. I just implement the validator as part of the annotation, and I'm done.
Does this seem like a reasonable pattern to use? If not then what might work better?
You may want to investigate AOP. You can advise methods that expose certain annotations and perform pre/post processing accordingly.
I would just like to add that while AOP would be a good solution, the Spring framework already provides this functionality by way of the #Secured annotation.
#Secured("ROLE_USER")
public void foo() {
}
Spring also supports JSR-303 validation with the #Valid annotation. So for these use cases at least, it seems you are re-inventing the wheel.
IMHO one could think about the Visitor pattern in combination with a factory. The factory will return a wrapper object that knows the exact annotation type and which the visitor will be able...
class MyVisitor {
public void visit(VisitableAnnotationType1 at) {
//something AnnotationType1 specific
}
public void visit(VisitableAnnotationType2 at) {
//something AnnotationType2 specific
}
... // put methods for further annotation types here
}
class VisitableFactory {
public abstract class VisitableAnnotation {
public abstract void accept(MyVisitor visitor);
}
class VisitableAnnotationType1 implements VisitableAnnotation {
public void accept(MyVisitor visitor) {
visitor.visit(this);
}
}
public static VisitableAnnotation getVisitable(Annotation a) {
if(AnnotationType1.class.isAssignableFrom(a.getClass()) {
//explicitely cast to the respective AnnotationType
return new VisitableAnnotationType1((AnnotationType1)a);
} else if (AnnotationType2.class.isAssignableFrom(a.getClass()) {
//explicitely cast to the respective AnnotationType
return new VisitableAnnotationType1((AnnotationType1)a);
}
}
}
As we cannot extend Annotation, we need those wrapper classes in the factory. You could also pass the original annotation which is then contained in that wrapper class.
What you have to do: For each new AnnotationType add a new "wrapper" class to the factory, extend the factory's
getVisitable()
method accordingly and also add an according method to the Visitor:
public void doSomething(VisitableAnnotationTypeXYZ at) {
//something AnnotationTypeXYZ specific
}
now the generic validation (or whatever) code looks like:
List<ValidatableAnnotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
MyVisitor visitor = new MyVisitor();
for (ValidatableAnnotation annotation : annotations) {
VisitableFactory.getVisitable(annotation).accept(visitor);
}
The visiting works by the indirection that the visited object calls the visitor with itself as the argument and thus the correct visit method will be invoked.
Hope that helps ;-)
Code is not tested, though...

Categories

Resources