Bean validation: method constraints and groups - bean-validation

I use Java EE7 with Bean validations.
I have session bean with a method, where I have defined validation constraints.
public void doTest(#NotNull #Valid Media param1) {
// do something
}
Class Mediahas defined some constraint with groups. Is it possible to validate call of method doTestonly for specific groups?

I found solution with standard annotations. It uses #ConvertGroup.
Working example is:
public void doTest(
#NotNull #Valid
#ConvertGroup(from = Default.class, to = TestGroup.class)
Media param1) {
// do something
}
TestGroup is defined on some constraints inside Media class.

The standard java #Valid annotation can not validate groups. But spring has #Validated that can do. Have a look on this answer.
How to specify validation group for #Valid?.

Related

How to create custom nested validator with JSR 303?

I am using Hibernate Validator - 5.2.2 (JSR 303).
I am doing a cross field validation, so I need to create a custom validator.
However I have no idea how to do the custom conditional nested validation.
example:
#ValidChildrenIfEnabled
public class MainDto {
public boolean isEnabled;
public List<Child> children;
}
public class Child {
#NotBlank
public String name;
#Range(min = 1, max = 3)
public int age;
}
If I don't need conditional validation, I would put
#Valid on top of "children".
#Valid
public List<Child> children;
Note: I know how to create a custom validator, I just don't know how to create a custom validator that do nested validation that take advantage of existing built-in validator. Thanks!
EDIT:
My payload actually has one more payload, let's say SuperDto.
public class SuperDto {
#Valid
public List<MainDto> mainDtos;
}
And I do validation like this:
validator.validate(superDto);
Interesting use case. Unfortunately, I don't think you can do what you want to do as you can't trigger a validation from isValid().
Supposing that you have other constraints you want to validate in every cases, I think the best workaround is probably to use groups. And to use different groups depending of if isEnabled is true or not.
Anyway, you would have to special case how this bean is validated.

Pass object between two Around functions - AOP

I am doing Auditing for my Controller, Service and Dao layer. I have three Around aspect functions for Controller, Service and Dao respectively. I use a custom annotation which if present on the Controller method will invoke an Around aspect function. Inside the annotation I set a property which I wish to pass from the Controller Around function to the Service around function inside the Aspect class.
public #interface Audit{
String getType();
}
I will set the value of this getType from an interface.
#Around("execution(* com.abc.controller..*.*(..)) && #annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit){
//read value from getType property of Audit annotation and pass it to service around function
}
#Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp){
// receive the getType property from Audit annotation and execute business logic
}
How can I pass an object between two Around functions?
Aspects are, by default, singleton objects. However, there are different instantiation models, which could be useful in use cases like yours. Using a percflow(pointcut) instantiation model, you could store the value of the annotation in your controller around advice and retrieve it in your service around advice. The following is just an example on how it would look like:
#Aspect("percflow(controllerPointcut())")
public class Aspect39653654 {
private Audit currentAuditValue;
#Pointcut("execution(* com.abc.controller..*.*(..))")
private void controllerPointcut() {}
#Around("controllerPointcut() && #annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
Audit previousAuditValue = this.currentAuditValue;
this.currentAuditValue = audit;
try {
return pjp.proceed();
} finally {
this.currentAuditValue = previousAuditValue;
}
}
#Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("current audit value=" + currentAuditValue);
return pjp.proceed();
}
}

How to target specific handlers with a #ControllerAdvice #ModelAttribute?

I'd like to display a warning message on specific pages 5 minutes prior to a system shutdown. Rather than add it manually to each these pages I created a #ControllerAdvice class with a #ModelAttribute method that adds the message to the Model parameter, but from what I understand reading the documentation and SO and some initial testing this model attribute will be added to every method with a #RequestMapping.
I realize I could refactor my code so that the targeted methods are all in one controller and limit the #ControllerAdvice to that one controller, but I would end up with a collection of otherwise non-related methods in that controller which muddies up the overall structure of my controllers.
So, is there a way to indicate which specific methods in multiple controllers the #ModelAttribute is applied to? Would a custom annotation be a solution (not sure how that would work)? I'd like to do this via annotations if possible.
Edit:
The #ControllerAdvice code is pretty basic:
#ControllerAdvice
public class GlobalModelController {
private final Logger logger = LoggerFactory.getLogger(getClass());
#Autowired
private MaintenanceInterceptor maintInterceptor;
#ModelAttribute()
public void globalAttributes(Model model, Locale locale) {
if (maintInterceptor.isMaintenanceWindowSet() && !maintInterceptor.isMaintenanceInEffect()) {
String msg = maintInterceptor.getImminentMaint(locale);
model.addAttribute("warningMaint", msg);
logger.debug("maint msg= " + msg);
}
}
}
A controller advice can be limited to certain controllers (not methods) by using one of the values of the #ControllerAdvice annotation, e.g.
#ControllerAdvice(assignableTypes = {MyController1.class, MyController2.class})
If you need to do it on a method level I suggest to take a look at Interceptors.
Thanks to #zeroflagL for pointing me to the interceptor solution. I ditched the #ControllerAdvice approach and ended up with this:
Custom annotation:
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Qualifier
public #interface MaintAware {
String name() default "MaintAware";
}
Interceptor:
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
MaintAware maintAware = method.getAnnotation(MaintAware.class);
if (maintAware != null) {
Locale locale = request.getLocale();
if (isMaintenanceWindowSet() && !isMaintenanceInEffect()) {
String msg = getImminentMaint(locale);
if (!msg.isEmpty())
modelAndView.addObject("warningMaint", msg);
}
}
super.postHandle(request, response, handler, modelAndView);
}
Now I can annotate the specific methods that require the maintenance notification. Easy peasy. :)

Using Spring AOP 3.1.0 to set service instance using method argument

Hi i am new to Annotation and Spring AOP. below is what i am trying to achieve
public interface Service {
public void process(String ServiceName, Bean bean);
}
public class ServiceImpl1 implements Service{
public void process(String ServiceName, Bean bean) {
/// do something here
}
}
public class ServiceImpl2 implements Service{
public void process(String ServiceName, Bean bean) {
/// do something here
}
}
from other class i would be calling something like
...
public void doSomething(String serviceName, Bean bean){
service.process("ServiceImpl1", bean);
}
...
I can achieve the same by using AroundAdvice and Before advice and intercepting my doSomething method and then instantiate the service object after reading the serviceName.
I there is a better approach for this?
I just need a direction and then i will figure this out.
Thanks
Well, I am guessing what you want to do is have a Before advice that takes the passed in service name, creates an object of appropriate class, then calls the appropriate method on that newly created object. It seems like, to me, you are really looking for more of a Factory pattern, but trying to use AOP to accomplish it.
If you took the Factory pattern, you would create a class called ServiceFactory, which takes some parameters and returns the correct Service implementation for those parameters. You calling code would simply use the Factory to get the right Service at runtime.
Another approach, if you want to stick with more of a DI pattern, might be to create a wrapper class that serves as the "conductor". This might have a Map of service names to Service implementation. You could then inject this wrapper into your code, and even inject the Map into the wrapper. Your calling code would call methods on the wrapper, which would locate the correct, singleton implementation and aggrigate the call to it.
I just feel that using AOP for this is asking for trouble.
You can inject the service impl class using the spring #Autowire annotation. Since u have 2 implementation classes, you can use qualifier to specify which impl needs to b injected.

NVelocity extension method ASP.NET webform

I was wondering if it's possible to use an extension method with asp.net webforms and nvelocity. I would like to set some defaults if the string value is null or empty.
Example of .vm file:
Example of my email body...
Billable Status: $billableStatus.Evaluate()
rest of my email body...
Attempted extension method:
public static class Helper
{
public static string Evaluate(this string value)
{
if (String.IsNullOrEmpty(value))
return "Not Provided";
else
return value;
}
}
Or is there an alternative to what I'm tryting to accomplish?
I don't think NVelocity can resolve extension methods with C#/VB.NET syntax sugar. What I do is register an instance of a helper in the velocity context:
var context = VelocityContext();
context.Put("helper", new Helper());
context.Put("billableStatus", "something");
...
and then in your template:
$helper.Evaluate($billableStatus)
You have to make your helper non-static for this to work, of course.
I came across something similar in past and I was looking for something more sophisticated and with more control. I found that NVelocity does provide a way to intercept the method and property calls but for that you will have to implement certain things. In order to make your custom interceptor you will need to implement NVelocity.IDuck. For example
public class MyClass : NVelocity.IDuck
{
public object GetInvoke(string propName)
{
....
}
public object Invoke(string method, params object[] args)
{
....
}
public void SetInvoke(string propName, object value)
{
....
}
}
Now any instance of MyClass will intercept and pass the method and property calls to our these three function implementation and give us a chance to resolve and return the output. You may notice from these three function signatures that in order to implement them we may need some reflection where we can locate respective methods on available extension types and execute them. If needed you can read following blog post for more details about going this way. NVelocity and extension methods

Resources