I annotate my spring boot controller some functions with a custom annotation for logging purpose. However, I find the before advice is executed twice for nested methods. Looking for some idea here. Please refer to the code snippets below.
Controller
#RequestMapping(value = "apply")
#OperationMILog
public ApplyHttpResponse apply(#RequestHeader final String custId, #RequestAttribute final String cardNo,
#RequestBody final InstallmentApplyHttpRequest installApplyReq, #PathVariable final String source) {
//test
this.test(); //**line 387**
...
}
....
#OperationMILog
private String test() {
return this.test1(); //**line 593**
}
#OperationMILog
private String test1() {
return "test1";
}
The annotation
#Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Inherited
#Documented
public #interface OperationMILog {
}
The Aspect
#Aspect
public class GenericLoggingAspect {
public static GenericLoggingAspect genericLoggingAspect;
#PostConstruct
public void init() {
genericLoggingAspect = this;
}
#Before("#annotation(com.mycomp.log.OperationMILog)")
public void doBefore(JoinPoint joinPoint) {
System.out.println("Before .........." + joinPoint.getSignature().getName());
}
}
When triggering the apply function in controller, the following logs are printed.
Before ..........apply
Before ..........test
Before ..........test
Before ..........test1
Before ..........test1
Settin break point at doBefore function and Looking into the stack trace in debug mode .
When the first "Before ............ test" is printed,the stack trace looks fine.
GenericLoggingAspect.doBefore(JoinPoint) line: 87
InstallmentController.apply(String, String, InstallmentApplyHttpRequest, String) line: 387
InstallmentController$$FastClassBySpringCGLIB$$55eeb128.invoke(int, Object, Object[]) line: not available
When the second "Before .......... test" is going to show, the stack trace is quite wired as below
GenericLoggingAspect.doBefore(JoinPoint) line: 87
InstallmentController.test() line: 593
InstallmentController.apply(String, String, InstallmentApplyHttpRequest, String) line: 387
InstallmentController$$FastClassBySpringCGLIB$$55eeb128.invoke(int, Object, Object[]) line: not available
I am running out of idea why line 593 triggers the doBefore. The same case applies to the printing of test1.
My project doesn't have any XML configuration, all configurations are done in annotations.
Thanks for showing the log output I asked for in my comment. Now I can tell you what the problem is:
Before ..........call(String com.mycomp.controller.InstallmentController.test())
Before ..........execution(String com.mycomp.controller.InstallmentController.test())
It is obvious that you use AspectJ (probably with LTW), not Spring AOP. Why can I say that? Because Spring AOP only knows execution() joinpoints, not call() ones.
For the reason given above, your pointcut matches twice for each method call: once for the joinpoint where the call is made (caller) and once for the joinpoint where the called method is actually executed (callee). This is why you get both output lines in your log.
So what you actually want to do is to specify in your pointcut what exactly you want to intercept, call or execution. I suggest you add && execution(* *(..)) to the pointcut. Then you get the expected result, similar to what Spring AOP would do even without that addition.
Lesson learned: AspectJ is much more powerful than Spring AOP. You need to learn how to wield such a powerful tool and sometimes limit its power on purpose. :-)
Related
I'm using Spring AOP to intercept a method execution.
I have an interface that looks like the following:
public interface MyAwesomeService {
public Response doThings(int id, #AwesomeAnnotation SomeClass instance);
}
Here is the implementation of the interface:
public class MyAwesomeServiceImpl implements MyAwesomeService {
public Response doThings(int id, SomeClass instance) {
// do something.
}
}
Now i would like any method which has a parameter annotated with #AwesomeAnnotation should be captured by Spring AOP.
So I wrote the following aspect which works.
#Aspect
#Component
public class MyAwesomeAspect {
#Around("myPointcut()")
public Object doAwesomeStuff(final ProceedingJoinPoint proceedingJoinPoint) {
final MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Annotation[][] annotationMatrix = methodSignature.getMethod().getParameterAnnotations();
// annotationMatrix is empty.
}
#Pointcut("execution(public * *(.., #package.AwesomeAnnotation (package.SomeClass), ..))")
public void myPointcut() {}
}
However when I try to find the parameter annotations I don't get any annotations back. As mentioned above, the annotationMatrix is empty.
So here are my questions:
Why is the annotationMatrix empty? Probably because parameter annotations are not inherited from an interface.
Why I'm able to capture the method execution. Since Spring AOP is able match the pointcut, Spring somehow is able to see the method's parameter annotations but when I try to see that using methodSignature.getMethod().getParameterAnnotations() it doesn't work.
I also faced this issue with one of my parameter annotations. I was able to fix the same by making sure that the parameter annotation definition had RetentionPolicy as RUNTIME and Target as PARAMETER
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface Param {
public String name();
}
The answers to your questions:
Parameter annotations are not inherited from interfaces to implementing methods. In fact, annotations are almost never inherited, only from class (not interface!) to subclass if the annotation type itself is annotated by #Inherited, see JDK API documentation.
Update: Because I have answered this question several times before, I have just documented the problem and also a workaround in Emulate annotation inheritance for interfaces and methods with AspectJ.
Because during compile or weave time AspectJ can match your pointcut against the interface method and thus sees the annotation.
You can fix the situation by adding the annotation to the parameter in your interface implementation, e.g. like this:
#Override
public Response doThings(int id, #AwesomeAnnotation SomeClass instance) {
// ...
}
Then with an aspect like this...
#Aspect
#Component
public class MyAwesomeAspect {
#Pointcut("execution(public * *..MyAwesomeService.*(*, #*..AwesomeAnnotation (*), ..)) && args(*, instance, ..)")
static void myPointcut(SomeClass instance) {}
#Around("myPointcut(instance)")
public Object doAwesomeStuff(Object instance, ProceedingJoinPoint proceedingJoinPoint) {
System.out.println(proceedingJoinPoint);
System.out.println(" instance = " + instance);
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Annotation[][] annotationMatrix = methodSignature.getMethod().getParameterAnnotations();
for (Annotation[] annotations : annotationMatrix) {
for (Annotation annotation : annotations) {
System.out.println(" annotation = " + annotation);
}
}
return proceedingJoinPoint.proceed();
}
}
... you get a console log similar to this:
execution(Response de.scrum_master.app.MyAwesomeServiceImpl.doThings(int, SomeClass))
instance = de.scrum_master.app.SomeClass#23fc625e
annotation = #de.scrum_master.app.AwesomeAnnotation()
Tried to find the answer on the Web but failed. Should be simple for pro Spring Devs... so here it comes:
In few words I want to bind the List of interface type: List to the form and get the data back (possibly modified by user via form. The problem is that it doesn't work :(
my code (short version) - command/model class which is passed to the form:
public class RoomsFormSearchResultCommand extends RoomsFormSearchCommand {
#SuppressWarnings("unchecked")
private List<IRoom> roomsList = LazyList.decorate(new ArrayList<Room>(),
FactoryUtils.instantiateFactory(Room.class));
public List<IRoom> getRoomsList() {
return roomsList;
}
public void setRoomsList(final List<IRoom> roomsList) {
this.roomsList = roomsList;
}
(...)
then in the form I use it like that (short version):
<form:form method="post" action="reserve" commandName="roomsResultsCmd">
(...)
<c:forEach var="room" items="${roomsResultsCmd.roomsList}"
varStatus="status">
<tr>
<td><form:input path="roomsList[${status.index}].roomNumber" readonly="true"/>
(...)
The form is displayed fine but after submitting it I get:
2012-01-22 21:31:55 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [wyspa] in context with path [/wyspa] threw exception [Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'roomsList[0]' of bean class [com.wyspa.controller.command.RoomsFormSearchResultCommand]: Illegal attempt to get property 'roomsList' threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property 'roomsList' of bean class [com.wyspa.controller.command.RoomsFormSearchResultCommand]: Could not instantiate property type [com.wyspa.entity.IRoom] to auto-grow nested property path: java.lang.InstantiationException: com.wyspa.entity.IRoom] with root cause
org.springframework.beans.NullValueInNestedPathException: Invalid property 'roomsList' of bean class [com.wyspa.controller.command.RoomsFormSearchResultCommand]: Could not instantiate property type [com.wyspa.entity.IRoom] to auto-grow nested property path: java.lang.InstantiationException: com.wyspa.entity.IRoom
at org.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:633)
at org.springframework.beans.BeanWrapperImpl.growCollectionIfNecessary(BeanWrapperImpl.java:863)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:770)
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:555)
(...)
The deal is then when I change the List to "instances" list everything works fine!
public class RoomsFormSearchResultCommand extends RoomsFormSearchCommand {
#SuppressWarnings("unchecked")
//notice that the List is now List<Room>
private List<Room> roomsList = LazyList.decorate(new ArrayList<Room>(),
FactoryUtils.instantiateFactory(Room.class));
In this case data is passed to the controller in proper way.
Since I am used to devlop on interfaces and I am pretty crazy about it I would REALLY prefer not to translate the List<IRoom> (which comes back from services) to List<Room> which seems to suit Spring. Is it possible to work with List<IRoom> in this case or Spring just doesn't support it?
//Of course Room implements IRoom - but I guess you already got that...
I would be VERY happy for any help/suggestions!
Best Regards,
Nirwan
I have exact the same problem. Changing to following won't fix the problem. It looks spring binding ignores the factory utils and tries to instantiate the null object itself:
#SuppressWarnings("unchecked")
private List<IRoom> roomsList = LazyList.decorate(new ArrayList<IRoom>(),
FactoryUtils.instantiateFactory(Room.class));
The workaround is to set auto grow nested path off in your controller:
#InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.setAutoGrowNestedPaths(false);
super.initBinder(request, binder);
}
The problem is you'll lose the handy nested path like user.account.address.street. You have to make sure none of user, account, addresss is null. It does cause a lot of problems. That's why I came here, see if I can find better solution.
If you don't actually need the list to auto-grow, you can store the form object in the session to avoid the nasty side effects of disabling auto-growing nested paths.
#Controller
#SessionAttributes(types = RoomsFormSearchResultCommand.class)
public final class SearchController {
#InitBinder
protected void initBinder(final WebDataBinder binder) {
binder.setAutoGrowNestedPaths(false);
}
#RequestMapping(method = RequestMethod.GET)
public String showForm(final Model model) {
RoomsFormSearchResultCommand form = ... // create or load form
model.addAttribute(form);
}
#RequestMapping(method = RequestMethod.POST)
public String onSubmitUpdateCart(
#ModelAttribute final RoomsFormSearchResultCommand form,
final BindingResult result,
final SessionStatus status) {
// if result has no errors, just set status to complete
status.setComplete();
}
}
Try the following lines
#SuppressWarnings("unchecked")
private List<IRoom> roomsList = LazyList.decorate(new ArrayList<IRoom>(),
FactoryUtils.instantiateFactory(Room.class));
don't have time to try that myself, but it would make sense.
I am working in J2EE 5 using JPA, I have a working solution but I'm looking to clean up the structure.
I am using EntityListeners on some of the JPA objects I am persisting, the listeners are fairly generic but depend on the beans implementing an interface, this works great if you remember to add the interface.
I have not been able to determine a way to tie the EntityListener and the Interface together so that I would get an exception that lead in the right direction, or even better a compile time error.
#Entity
#EntityListener({CreateByListener.class})
public class Note implements CreatorInterface{
private String message;....
private String creator;
....
}
public interface CreatorInterface{
public void setCreator(String creator);
}
public class CreateByListener {
#PrePersist
public void dataPersist(CreatorInterface data){
SUser user = LoginModule.getUser();
data.setCreator(user.getName());
}
}
This functions exactly the way I want it to, except when a new class is created and it uses the CreateByListener but does not implement the CreatorInterface.
When this happens a class cast exception is thrown somewhere deep from within the JPA engine and only if I happen to remember this symptom can I figure out what went wrong.
I have not been able to figure a way to require the interface or test for the presence of the interface before the listener would be fired.
Any ideas would be appreciated.
#PrePersist
public void dataPersist(Object data){
if (!(data instanceof CreatorInterface)) {
throw new IllegalArgumentException("The class "
+ data.getClass()
+ " should implement CreatorInterface");
}
CreatorInterface creatorInterface = (CreatorInterface) data;
SUser user = LoginModule.getUser();
creatorInterface.setCreator(user.getName());
}
This does basically the same thing as what you're doing, but at least you'll have a more readable error message indicating what's wrong, instead of the ClassCastException.
I just come from my tiny nice JavaSE/Guice world and am currently discovering the path of "carried by the container"-EE6. After having some trouble with Glassfish3.1, I just switched to JBoss and am now facing a problem that shouldnt be one.
As infrastructural assisting class, im trying to create a generic repository/DAO for any kind of entity. In a very simple manner, this might look like this one.
public class Repository<E, K extends Serializable & Comparable<K>> {
private final Instance<EntityManager> entityManagerInstance;
protected final Class<E> getDomainObjectClass() {
return domainObjectClass;
}
private final Class<E> domainObjectClass;
protected final EntityManager getEntityManager() {
return entityManagerInstance.get();
}
#Inject
public Repository(Instance<EntityManager> entityManageryProvider, Provider<E> domainObjectProvider) {
//This is a dirty hack, sadly :(
domainObjectClass = (Class<E>)domainObjectProvider.get().getClass();
this.entityManagerInstance = entityManageryProvider;
}
public final void persist(E domainObject) {
final EntityManager em = getEntityManager();
em.persist(domainObject);
}
public final Collection<E> getAllEntities() {
final EntityManager em = getEntityManager();
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<E> query = cb.createQuery(getDomainObjectClass());
final List<E> result = em.createQuery(query).getResultList();
return Collections.unmodifiableList(result);
}
public final E find(K id) {
Preconditions.checkNotNull(id);
final EntityManager em = getEntityManager();
return em.find(getDomainObjectClass(), id);
}
// [...]
}
Now there may be a bean that does not require entity-dependent query capabilities but just a repository of a certain entity type, like (might be a test case):
public class DomainObjectARepositoryTest{
#Inject
Repository<DomainObjectA, PersistableUUID> domainObjectARepository;
#Test
public void testMitarbeitererstellung() {
for (DomainObjectA a : domainObjectARepository.getAllEntities()) {
// do cool stuff
}
}
}
Unfortunatly Weld does not seem to like this kind of generic injection. At deployment time, I get the following error:
state=Create: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Repository<DomainObjectA , PersistableUUID>] with qualifiers [#Default] at injection point [[field] #Inject sompackage.DomainObjectARepositoryTest.domainObjectARepository]
Am I missing something or did they just forgot to implement generic injects? As far as I understand the generic stuff, it is erasured after compiletime anyway - even this worked so fine in guice3 so far.
Kind regards,
avi
edit: found a comment by garvin king that this behavior is in the spec, but not implemented in weld, (staement was in june 2009)
That's rather a long comment than a complete answer to your question, but might point you in the right direction:
I'm following the discussions in seam-dev & weld-dev since quite some time, and do not remember that anything like this ever popped up. So my guess would be that it hasn't been on the agenda ever since Gavin commented about it.
What you can do relatively easy to verify this assumption:
(a) Obtain a reference to the BeanManager and query it for the relevant bean type (or just for Object to be on the save side), of course you will have to remove #Inject in DomainObjectARepositoryTest in order to get the application started.
(b) Register an extension and listen to ProcessBean to what comes up during the deployment. That would be my suggested way to go, you'll find more information here.
With that outcome you should definitely be able to tell if there are any bean types Repository<E, K extends Serializable & Comparable<K>> hanging around :-)
Would be cool if you'd report back here with the results and also considered filing a Jira issue in the negative case.
I'm looking for a good pattern of providing custom validation of input for Resteasy services.
Let's say I've this service:
#Local
#Path("/example")
public interface IExample {
public Response doSomething ( #QueryParam("arg1") String arg1, #QueryParam("arg2") Integer arg2);
}
which I've implemented:
#Stateless
public class Example implements IExample {
#Override
public Response doSomething ( String arg1, Integer arg2 ) { ... }
}
What's the best practice to validate arg1 and arg2?
My ideas:
Validate inside doSomething(...) method. Drawback: when I add some parameter (ex. arg3) in the future, I could easily forget to validate it.
In custom javax.servlet.Filter. Drawback: I cannot access arg1 and arg2 there as they're not yet parsed by Resteasy framework.
I came up with this concept:
public class ExampleValidator implements IExample {
public static class ValidationError extends RuntimeException { ... }
#Override
public Response doSomething ( String arg1, Integer arg2 ) {
// here do validation. In case of failure, throw ValidationError
return null;
}
}
which can be used as follows:
#Stateless
public class Example implements IExample {
#Override
public Response doSomething ( String arg1, Integer arg2 ) {
try {
(new ExampleValidator()).doSomething(arg1, arg2);
} catch ( ValidationError e ) {
// return Response with 400
}
}
}
In that way, when I change IExample.doSomething method signature, I have to update Validator because of compile time error. In order for Resteasy NOT TO interpret ExampleValidator as a service, I used resteasy.jndi.resources instead of resteasy.scan, but it fails (Example bean is loaded after resteasy attempts to use it on deploy time).
Any ideas - are there any good patterns of validation?
Or is it possible to somehow get my concept to work?
EDIT: Or, which would be the best, there is some Filter counterpart in Resteasy? Some scheme by which my method (Filter) would be called before actual implementation, but with parameters (arg1, arg2) already parsed?
Thanks in advance, sorry for a lengthy post ;)
Kamil
(1) Probably the cleanest approach is to use Java EE 6 Bean Validation framework. This would require writing custom validation interceptor. In this case you would have to change your methods, so instead of
public Response doSomething ( String arg1, Integer arg2 )
you would use domain object as an argument
public Response doSomething ( JAXBElement<MyDomainObject> myOJaxb )
Then you need to trasform your request, so they provide XML or JSON formatted data, which can ba automatically converted to actual object.
(2) Another option is to use normal ServletFilter.
(3) Prepare custom annotations a'la Bean Validation, then you need to plug-in custom annotations processor (look at project Lombok, as an inspiration).
(4) The simplest solution is to use built-in REST validation
#Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")
but this applies to path parameters, not query parameters (I think, but didn't check with JAX-RS spec)
Your choice depends on how much flexibility you have with your interfaces and how many time you have.
If you would come up with a generic, pluggable to Resteasy solution similar to suggested in option (3) and make it open source on GitHub many people would love you :)