Intercept method declaration - java

I have the following method:
#OnEvent
public void onEvent(Event event) {
}
Now, I am puzzled whether AspectJ can intercept the method "declaration", i.e. neither its call nor its execution, in order to provide functionality somewhere else.
The objective is to "take" that method and register it as a handler of events into the OSGi service registry:
public void start(BundleContext bc) {
bc.registerService(EventHandler.class, new EventHandler() {
#Override
public void handleEvent(Event event) {
// TODO get a "reference" of the onEvent(...) method and call it here
onEventJoinPoint.proceed(event);
}
}, null);
}

No, this is conceptually impossible in AspectJ and probably also in any other AOP framework. But you have several alternatives:
How about putting marker annotations in all places where the aspect should kick in? There you could parametrise the annotation so as to mention which method to call.
Or if you really want to have it all in one place and avoid config files, use a configuration class similar to Spring. The class or one of its methods which you call when booting up your component, would carry all config annotations which would thus be interceptable by AspectJ.
You could also keep the annotation where it is and call the annotated method once after loading the class, intercept the method execution and take note of the method from an aspect, then re-use this information later.
There are other, similar options. But in each case, please note that
class loading / initialisation order is important,
if you just have a method and class name, you will need reflection in order to call it, unless the method is either static or the class is a singleton and the method does not rely on any object state, i.e. an instance can easily be obtained and the method be called as often as needed. Then you could maybe even tweak the solution into calling proceed() multiple times.
If you have follow-up questions which are too complex for simple comments, please update the main question and notify me. I cannot be any more concrete now because I do not know enough about your use case. Thus, I am not providing any sample code (yet).

Related

Spring #Transactional annotation is not working in the provider class which is a subclass of AbstractUserDetailsAuthenticationProvider [duplicate]

I want to know what actually happens when you annotate a method with #Transactional?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
I heard that Spring creates a proxy class? Can someone explain this in more depth. What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class
I also read in Spring docs that:
Note: Since this mechanism is based on proxies, only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with #Transactional!
Source: http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
Why only external method calls will be under Transaction and not the self-invocation methods?
This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare #Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with #Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the this reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in this forum post in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called me. Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. me.someMethod().) The forum post explains in more detail.
Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.
When Spring loads your bean definitions, and has been configured to look for #Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with #Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client executes Proxy.method().
The client calls a method on the target from his perspective, and is silently intercepted by the proxy
If a before aspect is defined, the proxy will execute it
Then, the actual method (target) is executed
After-returning and after-throwing are optional aspects that are
executed after the method returns and/or if the method throws an
exception
After that, the proxy executes the after aspect (if defined)
Finally the proxy returns to the calling client
(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: https://www.noelvaes.eu)
The simplest answer is:
On whichever method you declare #Transactional the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then all commits are with in this transaction boundary.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.
Transaction :
entity1.save
entity2.save
entity3.save
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
All existing answers are correct, but I feel cannot give this complex topic justice.
For a comprehensive, practical explanation you might want to have a look at this Spring #Transactional In-Depth guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.
It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.
For example, you have a class that looks like this
#Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
and you have an aspect, that looks like this:
#Component
#Aspect
public class CrossCuttingConcern {
#Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
When you execute it like this:
#Service
public class CoreBusinessKickOff {
#Autowired
CoreBusinessSubordinate subordinate;
// getter/setters
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
}
Results of calling kickOff above given code above.
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
but when you change your code to
#Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
//subordinate.doSomethingSmall(4);
}
You see, the method internally calls another method so it won't be intercepted and the output would look like this:
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
You can by-pass this by doing that
public void doSomethingBig() {
System.out.println("I did something small");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
Code snippets taken from:
https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/
The page doesn't exist anymore.

Can I use annotation to call method after the annotated one?

I am wondering if I can use custom annotation to call some method right after annotated one. For example I have a class that holds some settings that can also notify objects that something has changed (for example user changed something in settings panel). Not all listeners are interested in all types of events, so MyEvent is enum. Now I have structure like this:
class Settings
{
private ArrayList<Listeners> listeners;
private void notifyListeners(MyEvent e)
{
// notify all listeners that something was changed
}
public void setSomeOption(int value)
{
// validate parameter, store it etc.
notifyListeners(MyEvent.SOME_INTEGER_SETTING_CHANGED);
}
}
Of course listening object has to check type of event and ignore it or perform some action, but it is not the case here.
I am interested if I can achieve this with annotations, like this
#NotifyAnnotation(MyEvent.SOME_INTEGER_SETTING_CHANGED)
public void setSomeOption(int value)
{
// validate parameter, store it etc.
// NO NEED TO CALL NOTIFY HERE - WILL BE HANDLED BY ANNOTATION
}
In JUnit for example, we have #Before or #After annotations, and I am wondering if JUnit has own annotations parser that handles method annotated this way, or this kind of behavior can be done simpler, since annotations can be #Retention(value=RUNTIME).
I know that in this example it might look over-complicated and calling notifyListeners() is much simper, but I wan't to know if annotation can be used the way I described, and if yes, can i get some tips? I don't expect ready solution, just a hint if this is possible and what should I take in consideration.
yes, you can do it but you have to use a framework or write one by yourself. you can use for example spring aspects and #After advice (or any other proxy mechanism). you can also use full aspectj for this. another option is to write it by yourself using reflection api. in last case you will need some kind of inversion of control - some mechanism that will launch your method and then the other method
In annotations you need a class that checks for it. they don't work on themselves.
The way systems check for them are with reflection.
Annotation<NotifyAnnotation> a = method.getAnnotation();
And explicitly call their methods
a.notifyListeners(a.evt);
I can't see any advantage with your case. but I see full of disadvantages. They should not be used in actual coding, just for test systems or similar scenarios, where an external system has control on your class.
It could be do that using bytecode manipulation (JAssist, Asm, Java Rocks ...). All the classes would be instantiated thru a Factory that would identify annotated methods and would inject in the first line of this method a call to the method specified in its annotation.

Difference between call and execution pointcuts in PHP?

In AOP in Java (AspectJ) when we talk about method pointcuts, we can differentiate them into two different sets: method call pointcuts and method execution pointcuts.
Basing on these resources here on SO:
execution Vs. call Join point
Difference between call and execution in AOP
And some AspectJ background, we can tell that basically the differences between the two can be expressed as the following:
Given these classes:
class CallerObject {
//...
public void someMethod() {
CompiletimeTypeObject target = new RuntimeTypeObject();
target.someMethodOfTarget();
}
//...
}
class RuntimeTypeObject extends CompileTypeObject {
#Override
public void someMethodOfTarget() {
super.someMethodOfTarget();
//...some other stuff
}
}
class CompiletimeTypeObject {
public void someMethodOfTarget() {
//...some stuff
}
}
A method call pointcut refers to the call of a method from a caller object which calls the method of a target object (the one which actually implements the method being called). In the example above, the caller is CallerObject, the target is RuntimeTypeObject. Also, a method call pointcut refers to the compile time type of the object, i.e. "CompiletimeTypeObject" in the example above;
So a method call pointcut like this:
pointcut methodCallPointcut():
call(void com.example.CompiletimeTypeObject.someMethodOfTarget())
Will match the target.someMethodOfTarget(); join point inside the CallerObject.someMethod() method as the compile type of the RuntimeTypeObject is CompiletimeTypeObject, but this method call pointcut:
pointcut methodCallPointcut():
call(void com.example.RuntimeTypeObject.someMethodOfTarget())
Will not match, as the compile time type of the object (CompiletimeTypeObject) is not a RuntimeTypeObject or a subtype of it (it is the opposite).
A method execution pointcut refers to the execution of a method (i.e. after the method has been called or right before the method call returns). It doesn't give information about the caller and more important it refers to the runtime type of the object and not to the compile time type.
So, both these method execution pointcuts will match the target.someMethodOfTarget(); execution join point:
pointcut methodCallPointcut():
execution(void com.example.CompiletimeTypeObject.someMethodOfTarget())
pointcut methodCallPointcut():
execution(void com.example.RuntimeTypeObject.someMethodOfTarget())
As the matching is based on the runtime type of the object which is RuntimeTypeObject for both and RuntimeTypeObject is both CompiletimeTypeObject (first pointcut) and a RuntimeTypeObject (second pointcut).
Now, as PHP doesn't provide compile time types for objects (unless type-hinting is used to somehow emulate this behaviour), does it make sense to differentiate method call and method execution pointcuts in a PHP AOP implementation? How then will the pointcuts differ from each other?
Thanks for the attention!
EDIT: #kriegaex has pointed out another interesting aspect between call and method execution pointcuts in AspectJ.
Thank you for the great and concise example. I have tried to make an example myself too and here is what I understood:
In case A (I use a 3rd party library), I actually can't intercept the execution of a library method because the library itself was already compiled into bytecode and any aspect concerning that library was already woven into that bytecode too (I would need to weave the sources in order to do so).
So I can only intercept the method calls to the library methods, but again I can only intercept the calls to library methods in my code and not the calls to library methods from within the library itself because of the same principle (the calls to library methods from within the library itself are also already compiled).
The same applies for System classes (same principle) as is said here (even if the reference refers to JBoss):
https://docs.jboss.org/jbossaop/docs/2.0.0.GA/docs/aspect-framework/reference/en/html/pointcuts.html
System classes cannot be used within execution expressions because it
is impossible to instrument them.
In case B (I provide a library for other users), if I actually need to intercept the usage of a method of my library either in the library itself or in the future user code which will use that method, then I need to use an execution pointcut as the aspect weaver will compile both the method execution and call pointcuts that concern my library and not the user code which will use my library methods (simply because the user code doesn't exist yet when I am writing the library), therefore using an execution pointcut will ensure that the weaving will occur inside the method execution (for a clear and intuitive example, look at the #kriegaex pseudo-code below) and not wherever the method is called within my library (i.e. at the caller side).
So I can intercept the usage (more precisely, execution) of my library method both when the method is used within my library and in the user's code.
If I had used a method call pointcut in this case, I would have intercepted only the calls made from within my library, and not the calls made in the user's code.
Anyway, still think if these considerations make sense and can be applied in the PHP world, what do you think guys?
Disclaimer: I do not speak PHP, not even a little. So my answer is rather general in nature than specific to PHP.
AFAIK, PHP is an interpreted rather than a compiled language. So the difference is not compile time vs. runtime type, but semantically rather declared vs. actual type. I imagine that a PHP-based AOP framework would not "compile" anything but rather preprocess source code, injecting extra (aspect) source code into the original files. Probably it would still be possible to differentiate declared from actual types somehow.
But there is another important factor which is also relevant to the difference between call vs execution joinpoints: The place in which the code is woven. Imagine situations in which you use libraries or provide them by yourself. The question for each given situation is which parts of the source code is under the user's control when applying aspect weaving.
Case A: You use a 3rd party library: Let us assume you cannot (or do not want to) weave aspects into the library. Then you cannot use execution for intercepting library methods, but still use call pointcuts because the calling code is under your control.
Case B: You provide a library to other users: Let us assume your library should use aspects, but the library's user does not know anything about it. Then execution pointcuts will always work because the advices are already woven into your library's methods, no matter if they are called from outside or from the library itself. But call would only work for internal calls because no aspect code was woven into the user's calling code.
Only if you control the calling as well as the called (executed) code it does not make so much difference whether you use call or execution. But wait a minute, it still makes a difference: execution is just woven in one place while call it woven into potentially many places, so the amount of code generated is smaller for execution.
Update:
Here is some pseudo code, as requested:
Let us assume we have a class MyClass which is to be aspect-enhanced (via source code insertion):
class MyClass {
method foo() {
print("foo");
bar();
}
method bar() {
print("bar");
zot();
}
method zot() {
print("zot");
}
static method main() {
new McClass().foo();
}
}
Now if we apply a CallAspect like this using call()
aspect CallAspect {
before() : call(* *(..)) {
print("before " + thisJoinPoint);
}
}
upon our code, it would look like this after source code weaving:
class MyClass {
method foo() {
print("foo");
print("before call(MyClass.bar())");
bar();
}
method bar() {
print("bar");
print("before call(MyClass.zot())");
zot();
}
method zot() {
print("zot");
}
static method main() {
print("before call(MyClass.foo())");
new McClass().foo();
}
}
Alternatively, if we apply an ExecutionAspect like this using execution()
aspect ExecutionAspect {
before() : execution(* *(..)) {
print("before " + thisJoinPoint);
}
}
upon our code, it would look like this after source code weaving:
class MyClass {
method foo() {
print("before execution(MyClass.foo())");
print("foo");
bar();
}
method bar() {
print("before execution(MyClass.bar())");
print("bar");
zot();
}
method zot() {
print("before execution(MyClass.zot())");
print("zot");
}
static method main() {
print("before execution(MyClass.main())");
new McClass().foo();
}
}
Can you see the difference now? Pay attention to where the code is woven into and what the print statements say.
PHP is dynamic language, so it's quite hard to implement call joinpoints because there are many languages features like call_user_func_array(), $func = 'var_dump'; $func($func);
#kriegaex wrote a good answer with main differences between call and execution types of joinpoints. Applying to the PHP, only possible joinpoint for now is an execution joinpoint, because it's much easier to hook execution of method|function by wrapping a class with decorator or by providing PHP extension for that.
Actually, Go! AOP framework provides only execution joinpoint, as well, as FLOW3 framework and others.

How can one add breakpoints or custom code to an interface method implemented by many subclasses?

I am working on source that has a lot of subclasses (call them A and B) implementing a common interface Visitor, with a method visitProgram. Is there any way to break when any of the subclasses hits this method (i.e. A.visitProgram or B.visitProgram)? Alternate language solutions would be fine, but I cannot rewrite the existing source.
Since you're debugging I assume you can add some new code and build the whole thing.
That said, you can use Aspect Oriented Programming (AOP) to get a pointcut that captures the execution of visitProgram, and in theory you can put your breakpoint in the pointcut. You can think of AOP as a technique to cut laterally through your program (as opposed to OOP which builds "vertical" structure).
In this instance, you want to perform something just before each time visitProgram (of any instantiation of your Visitor interface) is run. This is a lateral cut, so AOP should fit your need.
Basically, you'll have a function in which you can set a breakpoint such that any time visitProgram gets called your program will halt just before it executes.
I'd recommend using Spring AOP, it's pretty straight forward, just follow the manual for setup instructions. Your pointcut should look like this:
#Aspect
public class BeforeVisitProgram {
#Before("visitProgram()")
public void doStuff() {
// break in here
}
}
Use an abstract class between the calling code and your implementations, such as:
interface DoesStuff {
void doStuff();
}
abstract class AbstractDoesStuff implements DoesStuff {
void doStuff() {
doStuffToo(); // debug point
}
abstract void doStuffToo();
}
It does mean though that all your implementation must be subclasses of the abstract class, so this approach might not suit every situation.

How to control object's lifecycle with Guice

I have Guice-injected objects which have two lifecycle methods bind() and unbind(). The method bind() is called automatically after the object is instantiated by Guice using following annotated method:
#Inject
final void autoBind() {
bind();
}
What I want to do is to call the method unbind() on the old (current) object before a new instance of the object is created by Guice. How do I do that?
Thanks in advance!
First of all, I would not advise that you just annotate arbitrary methods with #Inject. Keep it to constructors, and occasionally for optional injection and/or field injection.
What you are trying to do does sound a bit weird, and I'm not sure it's exactly what you want. Can you please provide more background on what you're trying to do because maybe a different approach is better. There are definitely some concerns here with thread safety and how you manage references.
Based on what you described, an approach like what #meverett mentioned would probably work. If the objects you have are Foos, it would look something like this.
// Later on be sure to bind(Foo.class).toProvider(FooProvider.class);
final class FooProvider implements Provider<Foo> {
private final Provider<Foo> unboundFooProvider;
private Foo currentInstance;
#Inject FooProvider(#Unbound Provider<Foo> unboundFooProvider) {
this.unboundFooProvider = unboundFooProvider;
}
#Override public Foo get() {
if (currentInstance != null) {
currentInstance.unbind();
}
currentInstance = unboundFooProvider.get();
currentInstance.bind();
return currentInstance;
}
}
NOTE that your #Unbound Foo provider would generate Foos without invoking any special methods. The regular FooProvider keeps track of state and deciding when to bind() and unbind() the instances. Please be careful with how you manage multiple instances and use them with multiple threads.
Also, just to be clear: I'm using #Unbound since the methods you want to invoke are called bind() and unbind(). I'm not using "bound" in the Guice sense.
Also note... off the top of my head I'm pretty sure Providers are treated as singletons, so maintaining state like this will work. If it didn't, you could obviously just create a level of indirection with some kind of singleton factory (but that shouldn't be necessary).
Previous responses address other concerns nicely, so to just answer the question:
Netflix introduced governator in github in 2012 to "enhance Google Guice to provide ... lifecycle management". It provides annotations (#PreConfiguration, #PostConstruct, #PreDestroy, and others), classpath scanning & auto binding, and other features. Bootstrapping is straight forward.
I suppose you could have a provider that keeps a reference to the current object. When you call get on the provider it would unbind the last object, construct the new one and save the reference to it.
though I'm not really sure why you would want to do something like this since other objects can in theory still be referencing it

Categories