Saturday, March 10, 2007
Terracotta' Jonas & Eugene on AOP at AOSD 2007
Jonas and Eugene from Terracotta - the Naturally Clustered Java provider and maker of OpenTerracotta - have published a very interesting paper on industry use of AOP and point out some limitations present in current AOP frameworks: "Clustering the Java Virtual Machine using Aspect-Oriented Programming".
Excerpt:
"application startup time with AspectJ load-time weaving [which I partly authored] was ... slower and memory overhead was ... bigger ... when comparing with similar transformations done with either the Terracotta runtime or the AspectWerkz AOP engine [which I authored with my friend and former coworker Jonas]."
This comes to no surprise to me as AspectJ is born for build time weaving and Eclipse integration and AspectWerkz was born for load time and runtime weaving. As author of both (as we joint forces from AspectWerkz to AspectJ back mhh.. 2 years ago) I was unable to get the best of both world in one engine as we initially focussed on features integration - such as thru the @AspectJ style that is annotation-defined and driven AOP. Since that time my open source bandwith has been drawned due to work engagements. That is unfortunate as I believe there are no technical reasons for this multi-weaving-optimized engine to not happen. Fortunately AspectJ is strong on runtime performance which is something you really have to consider as well.
Their paper is available online on AOSD 2007
Thursday, December 29, 2005
Microsoft goes AOP?
While AOP has reached a decent maturity level in the Java platform, thanks to several iniatives from different players with different priorities and goals (IBM, BEA, JBoss, Spring, and individuals like Bob Lee to name a few), Microsoft seems to be willing to move beyond that.
Last year at AOSD they were hosting a session on Phoenix, an interesting building block in the .Net CLR labs to help enable AOP frameworks. The community in .Net around AOP is fairly active as well, and Microsoft did awarded some of the projects, like Alan Cyment' SetPoint hosted on CodeHaus, the home of AspectWerkz.
Recently (Nov. 2005) Microsoft has set up a research event to emulate discussions around the best way to have good AOP solutions in the .Net platform. Several key .Net AOP project leads and folks from the AOP research academia were invited for a full day event at Redmond.
As far as I know Sun never set up such an event to try to understand AOP from its roots, and most of the discussion on the field has been driven by individual to individual networking and the AOSD annual conference.
I am eager to see where .Net ends up in that field in 2 years from now. There are certainly interesting architectures and concepts that we have implemented in Java based AOP that could be ported rightaway to .Net, though .Net luminaries have certainly several new ideas that 'd be worth exploring from Java luminaries point of view - and possibly standardizing on - obviously outside the JCP - unless Sun suddenly cares more about AOP.
Thursday, October 20, 2005
JRockit powered AOP prototype available
It's there !
I am very pleased to announce the prototype version of JRockit that includes our AOP API is available. It will drive you far far away from current bytecode instrumentation techniques to a world of plain Java API, complete runtime control for hot deployment and undeployment, agnostic from the programming model you like for your aspects.
If you are involved in the AOP field, bytecode instrumentation field, APM field, and did not heard from us recently, please drop me an email and I 'll consider your participation in evaluating this technology to help us drive it to reality.
You can read the official announcement and some background information in our BEA dev2dev dedicated forum.
Monday, October 10, 2005
Synchronized block join points (v2)
Back in July Jonas suggested some semantics for a synchronized block join point. The discussion was interesting but I am wondering if we actually came up with the right question.
What if we simply think in terms of "is this type listening to locking events ?" instead of trying to come up with a pointcut expression that defines the semantics of a synchronized block - as done in Jonas discusion?
Lets draft some code:
Consider the program:
class Bar {
synchronized void foo() {
..
}
static synchronized void statfoo() {
..
}
void stuff() {
..
synchronized(bar) {
..
}
}
}
So the deal is to listen to lock events - mainly:
- waiting the lock
- just acquired the lock
- just released the lock (or perhaps about to release it - but this does not matter much for this discussion)
I argue that instead of defining semantics, the issue should be narrowed to a type pattern ie something as simple as Bar (or more fancy variations based on type hierarchy or annotation - you bet it).
Given that we can define this interface:
interface Lockable {
void waiting();
void acquired();
void released();
}
As a user you can then implement this interface on your own types, use some sort of AOP or proxy to have it introduced where you want, etc.
So what should happen to make that work?
First based on the type pattern, we simply introduce Lockable to Bar. This can be done manually, by the mean of AOP if f.e. I was writing @Distributed class Bar { .. } and so on - depends on the use case.
Second the interface must then be implemented by Bar.
The user can provide one if implemented manually, or the system (AOP f.e.) can provide an empty one ie something like (depends on the AOP system but you get the idea)
@Introduce("Bar")
class LockableNOOP implements Lockable {
void waiting() {}
void acquired() {}
void released() {}
}
Last we need to transform the program so that the synchronized block or the Bar' synchronized method are triggering event to that.
This is not that hard since we just need to look at the type hierarchy for non static synchronized method and given that an instance synchronized method can be rewritten (by the system) as a synchronized(this) block we end up to something like that:
Replace all synchronized blocks like that:
Given
synchronized(stuff) {
..
}
to
if (stuff instanceof Lockable) {
Lockable lockable = (Lockable)stuff;
lockable.waiting();
synchronized(stuff) {
lockable.acquired();
..// unchanged body
}
lockable.released();
} else {
synchronized(stuff) {
..// unchanged body
}
}
Fairly easy.
So far, nothing will happen, as we have a LockableNOOP implementation, unless the user (you) explicitly provided some implementation.
Last part: configure the system so that it advises Lockable' methods, so that you can add your behavior there (f.e. distribute lock, or trace them for some application performance system). There, usual AOP stuff can be used.
You can now access the enclosing static join point information if you need - which gives you if you really need it, the rich semantics Jonas was looking for:
call(Lockable.waiting()) && withincode(....) && target(t) && cflow(...) .....
// t is the locked object
There are two interesting things to solve now:
- What if I want to kick out the synchronized() block ?(f.e. for distributed lock). I think a small variation of Lockable can solve that - f.e. boolean shouldUseJavaLocks(), and a tiny change for the transformed program.
- What about the static synchronized statfoo() {..} in Bar? For that one, the transformation would have to be a bit more compex so that we f.e. lock on an introduced static field. That said, the Lockable interface is not handy anymore. Any suggestion for that one? Should we define three methods like static void lockable_waiting() that ones would implement or introduce to adress this use case?
On a more high level perspective, this send us back to a recurrent set of problems in the AOP / bytecode transformation space:
- to achieve API transparency, we have a very intrusive transformation engine (though the one described here can be quite fast)
- by changing the bytecode we break the visibility another system may require to work properly (as f.e. we add if blocks, change synchronized method into synchronized blocks etc).
There is thus a set of open questions:
- So should that belongs to the JVM directly, and in which form?
(as f.e. JVMTI already provides monitor entry / exit events, that should be fairly easy). - Should those 3 Lockable' methods (or 6 if we include the static versions) belong to java.lang.Object direclty?
- Would an hybrid system that changes the synchronize blocks using bytecode transformation but then relies on JVM level support for AOP such as we do in JRockit be enough to listen for lock events?
- Is the cost of the introduced instanceof acceptable?
Happy thinking!
Wednesday, September 28, 2005
How will nextgen AOP looks like?
This last days I have been thinking some about how next gen AOP implementations may look like in say 4 years from now in the Java landscape.
As you may known, 5 years ago AspectJ was not based on bytecode manipulation but was based on source code transformation.
As of today, full blown AOP like AspectJ and JBoss AOP are usually build on top of really heavy bytecode manipulation, while more lightweight approach like Spring AOP are build on top of proxy (which under the hood can use bytecode generation technology ie JDK or CGlib proxy).
In the next few days we will start spreading the prototype implementation of AOP support in JRockit JVM which allows to implement all of the AOP interceptions features without even touching the bytecode but with a more abstracted subscription based API. If you missed the dev2dev series you can read more about it there.
This technology is definitely a breakthrough in the field, but does not address the introduction/mixin features ie capability to add method / field / annotation / change the object hierarchy of the object model in a crosscutting manner.
This means that f.e. to implement AspectJ as it is on top of the new JVM based technology we need to wether
- remove the feature from AspectJ - this is dumb as introduction are an important part of AOP
- do that in the VM - well, perhaps but unlikely from my perspective as it would mean changing the Java language itself else ones would not be able to call the introduced members from regular code
- use an hybrid bytecode / VM based AOP approach - why not but it looks a lot like going back to the old bytecode based implementation complexity
- do it in another way!
My thoughts on that is that we will likely do it in another way - and perhaps going back to source code transformation. This year Sun' folks presented the Jackpot project at JavaOne - which is sort of a rule driven source transformation engine. If that ones goes mainstream somewhere with Java 7, ones will have a fairly great technology set to rethink the way we implement AOP in Java, mixing nextgen APT (that will expose the full AST), Jackpot and JVM weaving.
Wednesday, August 10, 2005
AOP weavers - are we doing it wrong?
These last days I have been prototyping around an interesting idea.
As you know we have been working on an API to add JVM support for AOP in JRockit. The prototype will be available any time soon.
The nice thing about it is that you don't manipulate the bytecode anymore and that you are using only well known java.lang.reflect.* API to tell the JVM if your pointcut is matching or not. This is somehow similar to what ones can do with Spring AOP - as this one is proxy based (see f.e. MethodMatcher API in Spring).
The immediate benefit of it is that first there is no need to have another in-memory representation of classes beeing weaved (before they get loaded) that is backed by some expensive (both memory and CPU) bytecode analysis.
This advantage is detailled in our JVM support for AOP part1 article.
As a consequence it is really easy to query the method annotation, generics properties, and such - something that is extremely complex to achieve with acceptable overhead in regular bytecode based weaver such as AspectJ or AspectWerkz (actually more complex than changing some bytecode instruction).
So what is that idea I had ?
Having AOP support in JRockit is nice, but it will take some time before that gets mainstream (with eventually a JSR etc). In this transition period, there must be a way to implement a better bytecode based weaver that will perform way better than current weavers (both AspectJ and AspectWerkz), that will be easier to implement, and whose only requirement is Java 5 (well off course, it won't be as good as JRockit JVM support for AOP - so it is still a transition technology).
I have thus been sketching on an hybrid system that makes extensive use of the hotswap API, and whose actual weaver relies only on pointcut matching backed by the java.lang.reflect.* API ie does not build any kind of equivalent structure backed by bytecode analysis.
As such the memory overhead is zero, and the CPU overhead is way less than current AspectJ and AspectWerkz.
The overall idea is quite simple and consists in 2 phases:
Phase 1
A first weaver is changing the bytecode in some stable way - such that all classes are transformed (lets say prepared) the same way - while not introducing any dependancies on any kind of AOP, and while not adding any kind of performance overhead (ie no changes in the execution flow such as introduced by wrappers method and such usually used when implementing instrumentation needed for around advice).
All classes thus get loaded as expected with a very limited time overhead and no memory overhead at all (thanks to the excellent ASM performance).
Phase 2
Then when an actual class gets loaded (as per regular application behavior) I get a small callback invoked when this class has just been loaded and just before anything else happens (ie the class static initializer invoked by the JVM). Current load time weavers do things "just before the class gets loaded" and as such cannot access the java.lang.reflect representation of what they weave.
This callback can then perform the actual weaving by relying entirely on the java.lang.reflect.* API to match the pointcuts. It then constructs the instrumented version of the class and hotswap it thanks to the Java 5 API. The JVM eats this one and goes on.
The first prepare phase is needed as the hotswap API does forbids change in the schema (ie cannot add or remove methods or fields).
A nice extra side effect is that at any point in time any class can be exposed to the AOP layer thru a simple API. This can be handy for some cases where there are some circular references in the dependancies (f.e. the instrumentation needs the java.lang.reflect.Method class to match against the pointcuts so if I want to add aspects to the Method class, I cannot do it until I have a representation of this class ie there 's no way to have it working by simply invoking the callback from the prepared Method class itself).
This might seems like gory details, especially when compared to what we do in the JRockit JVM support for AOP, but I am sure there are some concepts worth digging there - as memory usage and weaving overhead as been reported more than once as a major problem (see f.e. use case with AspectJ reported by Ron Bodkin where the system takes 4 minutes to start instead of less than a minute without any weaver here)
This makes it also very easy to add aspects even to java.* classes (though it's not generally a good idea unless you know what you are doing).
This sample is an actual code snip of the actual AOP transformation (part of phase 2). As you can see it relies on the java.lang.reflect API.
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (!filter(access, name)) {//fast filter for f.e. clinit method as we look for method execution join points
// see if we get a match for this join point
// only java.lang.reflect.* API is used here
Member method = ReflectQuery.getMethod(m_klass, name, desc);
Class thisClass = m_klass;
Class targetClass = null;
Member withinCode = null;
//do matching
if (match(method, thisClass, targetClass, withinCode)) {
//change the bytecode but don't change the schema for hotswap purpose
} else {
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
}
Finally I must say this idea is not 100% new as I wrote a paper on it for AOSD 2004 (read my paper here). At that time though I was not doing the pointcut matching based on the java.lang.reflect API - as the purpose was to enable dynamic AOP in AspectWerkz 1.0) ie I was not solving the problem of the memory and CPU overhead of the actual weaver.
What do you think? Are those ideas worth digging more?
Tuesday, August 2, 2005
JVM support for AOP in BEA JRockit
We have plublished a follow-up to our JavaOne 2005 session that describes with some more details the JVM support for AOP that is beeing designed within the BEA JRockit JVM.
This first article introduces the problems that usually happen with current weavers (in the Java land) and briefly described the proposed solution.
The next part to appear in the following weeks will give more details and code samples.
Read the article
JRockit JVM Support For AOP, Part 1 by Jonas Bonér and Alexandre Vasseur, Joakim Dahlstedt -- AOP is all the rage, but how do you implement it? In this article, Jonas, Alexandre, and Joakim show that the current approaches to implementing AOP suffer from many problems, making scalability an issue. Moreover, they indicate that the traditional approach to aspect weaving duplicates efforts that the JVM already performs. |
We are currently working on making the prototype implementation available for further evaluation.
If you could not attend JavaOne 2005, the slides are available from the JavaOne web site, and they are also available here
The full webcast of the JavaOne session is also available on dev2dev.
Monday, August 1, 2005
AspectJ 5 load time weaving with Java 1.3 using ... AspectWerkz
**** Introduction
As development of AspectJ 5 and the merger with AspectWerkz making good progress, several users have started to wonder how the load time weaving under Java 1.3 / 1.4 VM be enabled.
Despite the name, AspectJ 5 is not at all tied to Java 5. I have already explained in this post how to write plain Java aspects using JavaDoc annotation and Backport175.
In this post I 'll explain how to enable load time weaving for Java 1.3/1.4 for AspectJ... by using AspectWerkz ! ie that AspectJ will sit on top of the very low level layer of AspectWerkz.
**** Some background
In AspectWerkz we enable load time weaving to happen thru a wide range of options that user can choose:
- Java 5 agent
- JRockit specific integration with JRockit agent
- bootclasspath family
- hotswap family
I have integrated the most important ones in the AspectJ 5 code base already - ie the first two - but some of them won't be integrated - hence this post.
When running Java 5 or JRockit (java 1.3 / 1.4 / 1.5) you don't need to read further and can stick to what's provided out of the box in AspectJ 5. Else... continue reading.
The AspectWerkz low level layer named aspectwerkz-core is actually a generic load time weaving layer. It comes with one interface that one has to implement - very similar to the JSR-163 instrumentation agent: the org.codehaus.aspectwerkz.hook.ClassPreProcessor.
This core layer comes with a set of tools that allows to turn this one on into the environment. The most easiest to use is what we called the "prepared bootclasspath" where you basically run a little script that will patch the java.lang.ClassLoader to hook in the agent, and will give you back a jar. This jar file can then be used first in the classpath when you start your JVM so that the agent gets called.
You can read more about all the options in the AspectWerkz doc here.
**** Running AspectJ by using AspectWerkz for load time weaving
I describe here the implementation of the agent, but you can use directly the one I ship with this post if you are not interested in the details. You can assume this one is LGPL, as AspectWerkz is.
The implementation of the ClassPreProcessor to use AspectJ on top of AspectWerkz core is straightforward and looks like that:
package org.aspectj.ext.ltw13;
public class ClassPreProcessorAdapter implements
// implements the AspectWerkz core interface
org.codehaus.aspectwerkz.hook.ClassPreProcessor {
/**
* Concrete preprocessor we delegate to
* This one sits in org.aspectj.weaver.loadtime.*
*/
private static ClassPreProcessor s_preProcessor;
static {
try {
s_preProcessor = new Aj();
s_preProcessor.initialize();
} catch (Exception e) {
throw new ExceptionInInitializerError("could not initialize preprocessor due to: " + e.toString());
}
}
public void initialize() {
;
}
public byte[] preProcess(String className, byte[] bytes, ClassLoader classLoader) {
// skip bootCL
if (classLoader == null) {
return bytes;
}
// skip AJ weaver well know stuff to avoid circularity
if (className != null) {
String slashed = className.replace('.', '/');
if (slashed.startsWith("org/aspectj/weaver/")
|| slashed.startsWith("org/aspectj/bridge/")
|| slashed.startsWith("org/aspectj/util/")
|| slashed.startsWith("org/aspectj/apache/bcel")
|| slashed.startsWith("org/aspectj/lang/")
) {
//System.out.println("SKIP " + className);
return bytes;
}
}
// do the weaving using AspectJ weaver
return s_preProcessor.preProcess(className, bytes, classLoader);
}
}
By using the AspectWerkz Plug utility we generate our load time weaving enabled java.lang.ClassLoader in awaj-boot.jar (see AspectWerkz doc for other options, that might be more license friendly if you care). This can be done thru Ant:
The last step consists in starting the JVM with this one, passing in a specific option to say what is the ClassPreProcessor implementation we want to use (the default one beeing AspectWerkz).
Starting a sample with Ant will thus looks like this - the important details are int he jvmarg option
.....
**** Sample project
I am attaching the complete source code, along with a sample Aspect in a zip.
This sample further use Backport175 so that the project is 100% Java 1.3 - without any of the AspectJ specific extra keyword to defines aspects that would disturb your regular javac compiler.
Off course, this load time weaving can be used for any kind of aspects, so adapt it for using AJC if you have some .aj files to compile.
Note: this zip does not include AspectWerkz jars, Backport175 jars, and AspectJ jars needed. You will have to get those and fix the Ant build.xml for your environment. See the build.xml file in the zip. (the sample is also refering to AspectWerkz 2.1RC1 - so change it to AspectWerkz 2.0 / sorry about those minor details).
It may also happen that you will need a SAX XML parser has Java 1.3 does not ships one. You may read more about that in the AspectWerkz FAQ for example
here (read "Does AspectWerkz support Java 1.3?"). This is not contained in the sample project neither.
Get AspectJ load time weaving on Java 1.3 enabled by AspectWerkz !
You will need AspectWerkz 2.0 for it. Get it there.
To run the sample, you will also need AspectJ and Backport and the Backport175 AspectJ extension. See build.xml on how to get those.
Wednesday, July 13, 2005
Opt-out AOP: good or evil ?
There is an interesting option in AspectJ that is named -Xreweavable.
When turned on using any kind of compilation/weaving mode (compiling with ajc, within Eclipse AJDT, doing bynary weaving, or using loadtime weaving), each weaved class keeps track of
- the aspects that are affecting it
- its state before the weaving happened (ie its bytecode without aspects)
This option is very handy when you plan to weave more than once your application (because f.e. this is a library that you distribute), and when you want to make sure everyone will be able to add some more aspects in there.
Actually, discussions are taking place if this should be the default.
An interesting consequence is that it is fairly easy to implement an opt-out AOP engine that simply restores the state prior to weaving, and thus kicks out all the aspects from the application !
There are of course realistic use-cases for it :
- sanity check if production is very scared about use of AspectJ, knowing that the developpers team is using it for their own needs (declare error / warning f.e. and tracing in QA stage etc)
- obtain some more info about which aspect is in, and is affecting the application, to increase the trust everyone gets in using the technology
- introspect some third parties libraries and see if they actually use aspects
- add some more reporting features on the go, to be able to have at any time the list of aspects that are in the system f.e. thru some sort of web console
- enforcing that some key section of the system are not allowed to be advised by anything, or only by some sort of well know and certified aspect(s)
A small amout of code is required for it, the trick is mainly to add another Java 5 agent or loadtime weaver that will check for this reweavable state and do the reporting.
This is actually very easy to do when using f.e. AspectWerkz-core as the backend to hook this one in and have it work as well on Java 1.3, and using ASM for the bytecode details.
Here is a sample output (I am using AspectJ loadtime weaving to do the weaving first, but that could be done using post compilation with AJC, or compilation from within Eclispe AJDT etc)
// in this sample, start the app with AspectJ loadtime weaving (could have been compiled with ajc instead)
// and pipe with the UndoAspectJ opt-out engine using the AspectWerkz core
// as a backend
#java -javaagent:aspectjweaver.jar -Daj5.def=test/aop.xml
-javaagent:aspectwerkz-jdk5-2.0.jar
-Daspectwerkz.classloader.preprocessor=
org.aspectj.ext.undoaspectj.ClassPreProcessor
test.undoaspectj.Sample
weaveinfo Type 'test.undoaspectj.Sample' (Sample.java:28) advised by
around advice from 'test.undoaspectj.Sample$TestAspect' (Sample.java)
// here is the opt-out message
UndoAspectJ - test/undoaspectj/Sample was affected by
test.undoaspectj.Sample$TestAspect
// execution without any aspect takes place:
Sample.target
// without the opt-out we would see the aspect executing:
weaveinfo Type 'test.undoaspectj.Sample' (Sample.java:28) advised by
around advice from 'test.undoaspectj.Sample$TestAspect' (Sample.java)
// execution with aspect takes place:
Sample$TestAspect.around
Sample.target
Though the first idea is quite odd and counter productive, this illustrates that ones could easily implement a security layer on top of AspectJ without even going deep in the AspectJ code base, to enforce security constraints about the use of AOP in the system and in the deployments at large.
So is opt-out AOP good or evil ?
Tuesday, July 5, 2005
@AspectJ in AJDT - a world premiere !
I am happy to announce that the @AspectJ support within Eclipse AJDT will appear in the next build snapshots, ie very soon !
That is an important step that brings to the AspectWerkz and AspectJ merger all its meaning, by providing a plain Java syntax (based on annotations) to write AspectJ aspects (aka @AspectJ) while still providing excellent support for it in Eclipse AJDT plugin - just as it exists for the well know AspectJ style (code style).
In the list of things to already expect, that will officially ship as of AspectJ 1.5 M3 in the following days:
- error checking for pointcuts (even though those looks like strings within an annotation)
- warnings when @AspectJ annotations are misused (f.e. used in a class that is not annotated with an @Aspect annotation etc)
- advised by view
- advises view and cross-reference view
- and off course AJC integration (ie weaving happens behind the scene as compilation is done)
As a world premiere, here is a snapshot of an @AspectJ aspect in AJDT !
For those of you using AspectWerkz, you may wish to give it a try very soon, as it is already much better that the Eclipse plugin I had written for AspectWerkz, and as it will help you to get started with the @AspectJ syntax in your favorite IDE.
Start your download engines to get the next build snapshots and the upcoming AspectJ 1.5 M3 with your fresh Eclipse 3.1 final !
(Many thanks to Andrew and Mik for answering my questions to get that bits working)
Thursday, June 23, 2005
AspectJ, @Aspect and Java 1.3
Following the Backport175 release that Jonas and I have done some days ago, and since AspectJ 1.5 upcoming M3 and especially the @Aspect style is starting to take shape after some month of hard work on my side, I think it is a good timing to also explain that this @Aspect sytle, despite its name tied to these Java 5 annotations, is not at all tied to Java 5, and will bring the plain Java aspect concept to all of you using Java 1.3 and 1.4 (from the real world).
The @Aspect style is also referred as @AJ, or annotation style, or this way to write aspect with annotation that we came up with thru AspectWerkz.
It mainly means that AspectJ allows you to write an aspects using wether the well known code style or the AspectWerkz like annotation style.
// code style
public aspect SomeAspect {
void before() : execution(* Foo.bar()) {
// do some stuff
// use thisJoinPoint etc
}
}
// annotation style, here with Java 5
@Aspect
public class SomeAspect {
@Before("execution(* Foo.bar())")
void before(JoinPoint thisJoinPoint) {
// do some stuff
// use thisJoinPoint etc
}
}
And since Backport175 brings annotations to Java 1.3 while preserving the bytecode format that the Java 5 specification describes, it seamlessly allows you to use the very same AspectJ version to write @Aspect on Java 1.3 as well (but please don't call it the doclet style!)
// annotation style, backported to Java 1.3 or 1.4
/**
* @Aspect
*/
public class SomeAspect {
/**
* @Before("execution(* Foo.bar())")
*/
void before(JoinPoint thisJoinPoint) {
// do some stuff
// use thisJoinPoint etc
}
}
For the Java 1.3 to work, you just need an single little jar that contains the AspectJ defined annotations (like
@interface Aspect) backported to Java 1.3 in the form of regular interfaces (ie interface Aspect) and then make sure you have those classes first when doing the weaving.Aside, since AJC (the AspectJ compiler) is not yet integrated in the doclet parsing pipeline, you need to follow a binary weaving strategy ie:
- develop the aspect and the application with Java 1.3 (remember it's plain Java so you can use IntelliJ if you want)
- compile the sources with regular javac
- post-compile with Backport175 to handle the annotations
- binary weave with AJC
- run
That sounds a bit cumbersome but some simple Ant script is of great help. Aside Backport175 comes with plugins for Eclipse and IntelliJ so you end up with just the binary weaving step - that is rather common.
I have made this little AspectJ extension available here (that can be used with Java 1.3)
You can also grab the source code for it, that includes a small demo here.
Just set
aj.root in the build.properties to the folder that contains aspectjrt.jar and aspectjtools.jar from a recent nightly build (will work for M3, does not for M2, so use a recent one!).Then run
ant clean test.Check the
build.xml file to understand how the different build steps are performed.In the IDE it will also popup pretty well. See for example the little green
@ signs in the margin in this IntelliJ screenshot.So now we have AspectJ @Aspect straight in IntelliJ.
Off course, you'd better use Eclipse AJDT to benefit from the rich user experience that it provides when dealing with software modularity thru AOP and AspectJ.
Using Backport175 also allows to use custom annotations in the pointcuts under Java 1.3 to define stronger contract between the aspect and the application, as Adrian describes here as the Holy Trinity (when you further add dependency injection)
(the demo don't include that but I let you try it).
In a follow-up post I will also explain how the new AspectJ enhanced load time weaving ala AspectWerkz can work with Java 1.3 and 1.4 as well - since it has been a recurrent question.
Wednesday, June 22, 2005
JavaOne 2005 - AOP, distributed Java, and more
I thought it would be interesting to post what kind of session and BOF I am planning to attend during JavaOne 2005 next week.
There are indeed interesting trends going on, and needless to say I don't really want to hear that the EJB (3) XML deployment descriptors are back or that kind of things. Instead, AOP, Annotations and distributed architectures will get my interest.
BOF-9888, Chasing 9s: Modeling and Measuring Availability of J2EE™ Applications (Sun, monday 7h30 PM)
TS-7659, Runtime Aspects With JVM™ Support (BEA JRockit off course, Tuesday 11h AM - don't miss it ! and meet us at the BEA and Eclipse booth)
TS-7695, The Spring Framework: Introduction to Lightweight J2EE™ Architecture (Interface21, Tuesday 11h AM)
TS-7212, Clustering, Consistency, and Caching: An Implementor's View of JSR 107 [JCache] (BEA, Tuesday 01h30 PM)
TS-7159, Java™ Platform Clustering: Present and Future (Sun, Tuesday 2h45 PM) (don't miss it, it is a sneak from Sun research labs, about transparent clustering)
BOF-9385, Apt Usage of APT: When and How to Use the Annotation Processing Tool (Chariot Solutions, Tuesday 7h30 PM) (I know they will give a quote to AspectJ)
BOF-9161, Exploring Annotation-Based Programming Through the APT and Mirror APIs (BEA/Sun, Tuesday 9h30 PM) (ha ! Annotations that drove AspectWerkz for a while)
BOF-9441, Practical Application of Aspects in Everyday Development (ALTERthought, Tuesday 10h30 PM) (AOP from the users - an evidence of adoption phases as regards AOP)
TS-5471, Jini™ and JavaSpaces™ Technologies on Wall Street (JPMorgan, GigaSpaces,others, Wednesday 11h AM)
TS-7429, Speculative Locking: Breaking the Scale Barrier (Azul, Wednesday 4h PM)
TS-7410, Network Attached Processing: Tapping 384-Way SMP, 256GB Java™ Technology Compute Bricks (Azul, Thursday 1h15 PM)
TS-7339, Data Grids for J2EE™ Platform Cluster Deployments (GemStone, Thursday 3h45 PM)
See you there !
Tuesday, June 7, 2005
JRockit AOP and AspectJ 5 and JavaOne 2005
JavaOne 2005 will be a good opportunity for you to have an update on the
AOP field. Last year we presented AspectWerkz plain Java AOP and its
J2EE integration facilities. This year, several sessions will include
AOP related sections and give testimony of interesting use cases, and
as Jonas recently announce we will for the first time present
the JRockit JVM support for AOP.
Make sure you attend this technical session on Tuesday June 28 (TS-7659, "Runtime Aspects With JVM Support") and have a
sight at what's next in the AOP galaxy. If you can't make it, visit us
at the BEA booth where we will be eager to show you the JRockit JVM
AOP support thru live demos.
You can also visit us at the Eclipse booth where we will show latest
AspectJ 5 and AJDT versions. This includes plain Java AOP and
load-time weaving ala AspectWerkz that I have been working on for some
month since we merged with AspectJ, and many new things regarding Java
5 support in AspectJ 5 (annotation matching, generics etc)
Meet you there !
Thursday, April 14, 2005
EJB 3 and AOP: the EJB interceptor dilemna
In this post I present an implementation a subset of the EJB 3 specification (JSR-220) : the EJB interceptors. As of today no EJB 3 preview brings an implementation that seamlessly integrates with AOP, despite the concept similarities.
The proposed implementation is fully runnable out of any container, and introduce a specific extension to allow use of pointcut in EJB interceptors, thanks to AspectWerkz extensible AOP container.
Wants to know more about EJB 3 interceptors, and how they are closed to AOP or different from AOP ? Read more.
Should we consider EJB interceptor as AOP ?
As you may know, the EJB 3 specification (JSR-220) defines
Interceptors for EJBs (stateless, statefull and message-driven). If it might be a good idea to spread an answer
for the need of addressing cross-cutting concerns in J2EE and EJBs in particular, it might be a bad idea to do it for
those of us (more and more numerous) familiar with AOP implementations like AspectJ and
AspectWerkz, especially because huge limitations of what the specification
allows us to do with those interceptors - at first sight and excluding any vendor specific extension.
The most anti-AOP concept in the specification is that the EJB that wants interceptor have to declare it explicitly
using a @javax.ejb.Interceptor or @javax.ejb.Interceptors class level annotation - which breaks the obliviousness of
aspects. That in favor of making things explicit, which might be good for J2EE users.
Further on, the EJB bean itself can have a method that intercept its own business method ie the bean is the
aspect (that sounds like marketing isn'it ?). Well. That's a specification and is interesting in the sense that it
democratize a technology.
So what can we do to democratize AOP as part of the EJB 3 specification ?
@javax.ejb.Stateless
@javax.ejb.Interceptor("test.ejb3.MyInterceptor")
public class MyEJBIsTheAspect {
// business method
public int businessSum(int i, int j) {
return i + j;
}
// interceptor method within the bean (the bean is the aspect)
@javax.ejb.AroundInvoke
public Object interceptMySelf(InvocationContext ctx) throws Exception {
System.out.println("--> MyEJBIsTheAspect.interceptMySelf");
System.out.println(" method: " + ctx.getMethod());
for (int i = 0; i < ctx.getParameters().length; i++) {
Object o = ctx.getParameters()[i];
System.out.println(" args["+i+"]: " + o);
}
return ctx.proceed();
}
}
State of the art (not that much..) in JBoss and Oracle AS EJB 3 preview
After having a look at JBoss EJB 3 and
href="http://www.oracle.com/technology/tech/java/ejb30.html">OracleAS EJB 3 previews, I was even more disapointed.
Both of them are using a reflective based approach to invoke the interceptors. This means that
the performance of the interceptor will be bad, and that a
href="http://www.aip.org/history/heisenberg/p08.htm">Heisenberg effect will be inevitable and actually fairly big
(no wonder that ones will use interceptor to gather performance metrics and thus as soon as you observe the bean, you
are observing a different things than what actually happens).
Ones may say this is a microscopic view. It is. But when thinking about EJB 2 stories in the past a sound idea would be
to make sure we don't waste resources where we can avoid it. And thinking about JBoss history around AOP, that's rather
suprising that the EJB 3 interceptors are not cleanly integrated in their AOP framework. I personnaly consider that we
have enough technology around to make it far better, and far more consistent with AOP. Given the impact that AOP will
continue to have, ones would better figuring out how to do that now with EJB 3 - assuming that EJB 3 succeeds.
AspectWerkz extensible container value proposal to EJB 3 interceptors
I decided to give it a try with the AspectWerkz extensible container. As Jonas Bonér described it in a
href="http://www.theserverside.com/articles/article.tss?l=AspectWerkzP1">TSS article, AspectWerkz can be considered
as a generic AOP runtime platform, in which ones can hook in any kind of AOP/AOP like programming model. AspectWerkz
aspects are one, AspectJ aspects are another, and we have implementations for Spring AOP and AOP Alliance aspects. An
AspectModel answers three essential properties: what is the life cycle of the aspect, how to invoke
it and how the programming model exposes the closure with wich the user proceed.
It happens that the EJB 3 interceptor can be seen as a very simple AOP programming model in two ways:
- ones can define interceptor class. An interceptor (advice) is thus a @javax.ejb.AroundInvoke annotated method with a
specific signature (no interface, no mandatory method name) within a class - the interceptor class (aspect). - ones can define a @javax.ejb.AroundInvoke annotated method (advice) in the EJB itself (aspect): the bean is the
aspect ! - the closure is defined with the interface javax.ejb.InvocationContext
public interface javax.ejb.InvocationContext {
public Object getBean();
public Method getMethod();
public Object[] getParameters();
public void setParameters(Object[]);
public Context getEJBContext();
public java.util.Map getContextData();
public Object proceed() throws Exception;
}
The value proposal I am bringing here with the AspectWerkz extensible container is the following:
- no reflection at all. See performance figure f.e at our
href="http://docs.codehaus.org/display/AW/AOP+Benchmark">benchmark site - seamless integration of the interceptors with the aspects. They are made "aspect" thanks to AspectWerkz and the
other aspect model (AspectWerkz aspect, AspectJ aspect, whatever aspect model registered in the runtime) coexists
nicely - easy points for vendor specific extension:
- real pointcut to narrow the matching of an interceptor method to a very precise set of bean methods
- life cycle control for the interceptor class
- supporting cflow(), args() and alike AOP semantics
- introducing high performant hot deployment and undeployment of EJB interceptors
- "out of container" runtime available
- rich integration patterns: application preparation (like ejbc / appc for faster deployment) or seamless
deployment
AspectWerkz extensible container details
To better understand how things will looks like, you need some background in AspectWerkz:
The first key part is "org.codehaus.aspectwerkz.transform.inlining.spi.AspectModel". We will provide two
implementations of it. One for interceptor class (the interceptor class is the aspect), and one for bean as
interceptor (the bean is the aspect).
The second key part is in integrating the EJB interceptor closure "InvocationContext" that defines the "proceed()"
method with the more general idea of "Joinpoint.proceed()" of the runtime. In short, this means that the interceptor
will be entirely part of the aspect chain, and if there is a transaction aspect to handle EJB transaction boundaries,
they will share the very same chain - as ones expects - thus making it easy for the implementation to organize
precedence rules (as define in section 3.5.1 of JSR 220 for example).
As we already wrote this transaction aspect for EJB 3 in a previous
href="http://www.theserverside.com/articles/article.tss?l=AspectWerkzP2">AspectWerkz TSS tutorial, that's rather a
simple idea and basic requirement.
The runtime will take care of aggregating the models depending on which aspect apply to which join point, each aspect
having its specific AspectModel and each AspectModel implementation being responsible for generating what it needs:
// a closure to deal with the join points
// ie models org.codehaus.aspectwerkz.joinpoint.JoinPoint interface
// to fit with the transaction aspect, or any other aspect
// and javax.ejb.InvocationContext to fit EJB3 interceptors
class jitEJB3Closure implements JoinPoint, InvocationContex
{
// the closure hosts state, optimization makes it more complex than that
// the target of the join point ie the intercepted ejb
// which is also third aspect: remember the bean is the aspect !
private MyEJBIsTheAspect target;
// first aspect in the chain, statically compiled
private TXAspect aspect_0;
// second aspect: the interceptor class
private MyInterceptor aspect_1;
// details skipped that makes those fields initalized as they should.
// as defined in javax.ejb.InvocationContext
public Method getMethod() {...}
// as defined in JoinPoint
public Class getTargetClass {...}
// other methods as per each aspect model affecting the join point
...
// generic proceed() method as defined in JoinPoint and InvocationContext
public Object proceed() throws Throwable
{
// sort of a loop to proceed with the advice chain
// case first round: TX aspect
// TX aspect
// as defined in the "AspectWerkzAspectModel implements AspectModel"
aspect_0.manageTX(this)
// "this" is considered as the JoinPoint instance
...
// case second round: interceptor class
// as defined in the yet to be written
// "EJBInterceptorModel implements AspectModel"
aspect_1.someNameOfYourChoice(this)
// "this" is considered as the InvocationContext instance
...
// case third round: the bean is the aspect
// as defined in the yet to be written
// "EJBIsTheAspectModel implements AspectModel"
target.interceptMyself(this)
// "this" is considered as the InvocationContext instance
...
}
}
That may sound a bit of gory details, but that's actually simple once you get the idea of this closure acting for
multiple AspectModel in mind. The code is actually 15O lines for the interceptor class model (EJBInterceptorModel)
and 25 lines for the bean is the aspect model (EJBIsTheAspectModel) thanks to some inheritance. It mainly deals with
- generating the InvocationContext methods (like getMethod(), getParameters())
- dealing with the EJB 3 aspect life cycle ie
push the EJB instance on stack for the EJBIsTheAspectModel- create an interceptor class instance, bookeep it and push it on stack for the EJBInterceptorModel (as the spec
does not specifies the life cycle, I will use a singleton model).
What about the deployment ?
I presented the runtime, but there is an interesting topic as well: the deployment. AspectWerkz pioneered the aop.xml to
define which
aspects are affecting the system. Obviously, we don't want that for EJB interceptor. We need to use the AspectWerkz API
to register what we need in the system. The interesting concept here is that we will transform what the EJB
specification defines thanks to annotation (@javax.ejb.Interceptor, @javax.ejb.Interceptors, @javax.ejb.AroundInvoke) in
real AOP pointcut that the AOP container understand.
That is where a vendor may easily hook in an extension (ie introduce a new annotation for example) to refine the
interceptor class life cycle, or to introduce a pointcut.
I am defining a class that will expose an API that will hide the AOP registration from the user or from the other parts
of our spec. implementation.
public class EJBInterceptorDeployer {
public static void deploy(String ejbClassName, ClassLoader loader) {
// step 1 - interceptor class
// read the ejbClass @Interceptor and @Interceptors class level annotation
// for each interceptor class name found as value of those annotation
// get the @AroundInvoke method information
// deploy an aspect
// using the EJBInterceptorModel
// to the pointcut : "execution(!@javax.ejb.AroundInvoke !static * " + ejbClassName + ".*(..))"
//
// step 2 - @AroundInvoke method of the bean itself
// find the @AroundInvoke method if any
// deploy an aspect
// using the EJBIsTheAspectModel
// to the same pointcut
}
// method making use of AspectWerkz aspect deployment API
}
The thing to note about the deployer is that it is not using reflection. It is f.e. using our
href="http://backport175.codehaus.org/">BackPort175 implementation to read the EJB annotations from the bytecode. If
we were not doing so, we would trigger the EJB class loading while our system is not yet defined,
and the weaver would not be able to do the job when using load-time weaving approaches.
What about running the system ?
In the sample application, I am deploying the EJB using the EJBInterceptorDeployer presented in the previous section.
In a full blown container I would hook the call to it when the application or EJB deployer would register the EJB in the
system.
The nice thing is that I can run my EJB and still have the interceptors when running as a standalone application by
using AspectWerkz load time weaving, and a simple static block to declare which class is an EJB.
The sample application can be run with (for ones familiar with AspectWerkz, there is no aop.xml..)
java -javaagent:lib\aspectwerkz-jdk5-2.0.jar test.ejb3.Sample
public class Sample {
static {
EJBInterceptorDeployer.deploy("test.ejb3.MyEJBIsTheAspect", Sample.class.getClassLoader());
}
public static void main(String args[]) throws Throwable {
// some one would do a lookup or inject for that when in the container
MyEJBIsTheAspect myEjb = new MyEJBIsTheAspect();
System.out.println("Calling the EJB");
int i = myEjb.businessSum(1, 2);
System.out.println("got : " + i);
}
}
AW EJB3 - Deploying test.ejb3.MyInterceptor for test.ejb3.MyEJBIsTheAspect
AW EJB3 - Deploying test.ejb3.MyEJBIsTheAspect for test.ejb3.MyEJBIsTheAspect
Calling the EJB
--> MyInterceptor.interceptStandalone
method: public int test.ejb3.MyEJBIsTheAspect.businessSum(int,int)
args[0]: 1
args[1]: 2
--> MyEJBIsTheAspect.interceptMySelf
method: public int test.ejb3.MyEJBIsTheAspect.businessSum(int,int)
args[0]: 1
args[1]: 2
got : 3
Conclusion
Though at first glance I found the interceptor part of the EJB 3 specification fairly odd, and was a bit sad that some
important AOP concepts like precedence and aspect life cycle, as well as expressiveness of the pointcut language are
completely sacrified, I must admit that it might help ones familiarize with AOP concepts.
It took 1h to implement the EJB 3 interceptor spec and have it perfectly integrated with AOP - unlike so far exposed EJB
3 previews by JBoss and Oracle (though those are actual preview, while this article is more a technology focus and
positionning).
It took 15 minutes more to implement a pointcut extension thru a new @org.codehaus.aspectwerkz.ejb3.AroundInvokeAOP
annotation, that allows me to reuse the expressiveness of the pointcuts ie a vendor extension:
public class MyInterceptor {
@AroundInvoke
@AroundInvokeAOP("execution(* *.businessSum(..))")
public Object interceptStandalone(InvocationContext ctx) throws Exception {
System.out.println("--> MyInterceptor.interceptStandalone");
System.out.println(" method: " + ctx.getMethod());
for (int i = 0; i < ctx.getParameters().length; i++) {
Object o = ctx.getParameters()[i];
System.out.println(" args["+i+"]: " + o);
}
return ctx.proceed();
}
}
Some more time would allow me to have further features, like f.e. supporting cflow and args pointcut, so that an
interceptor may look like an advice as it looks like in AspectWerkz aspects, with static access to intercepted method
arguments etc (ie no boxing in an Object[] array).
A next iteration would be to integrate with the AspectWerkz hot deployment feature, and this would bring in hot
deployment of EJB interceptors at no cost - while still having everything statically compiled for the runtime to perform
at its best.
This implementation may seems at first glance full of details, and perhaps like a hammer to address a simple part of the
spec. I don't think so. I think it address the very crucial point that so far everyone has skept - including
JBoss folks (that have a foot in the AOP trench): it integrates seamlessly with the aspects and AOP concepts, and
actually allow advanced user to apply more advanced AOP concepts as well ie bridging the gap between a commercial
concept and needs (EJB interception) and a sound concept backed by years of research (AOP and cross-cutting).
So which vendor will be the first to have its EJB play well with AOP : like applying an interceptor thru a real
pointcut, defining programmatic precedence etc, dealing with cflow and hotdeployment of interceptors, and all that with
an implementation that can scale ?
Want the source code ?
This one is part of AspectWerkz CVS.
It can be browsed from
href="http://cvs.aspectwerkz.codehaus.org/viewrep/aspectwerkz/aspectwerkz4/src/compiler-extensions/ejb3">here.
Side note: my feedback on the specication:
There are some odd things in the 3.5 section of the JSR-220 that I have spot:
- (sect. 3.5.1) an interceptor class or EJB can only have one single @AroundInvoke method (advice) in it, and its
signature is (sect. 3.5.4) "@AroundInvoke Object someNameOfYourChoice(InvocationContext ctx) throws Exception". Why
limitating that to having one single method in the interceptor class or EJB (sect. 3.5.1). My guess is that it is tied
to the fact that precedence between advice would then be harder to define in the spec without new semantics.
Then one might wonder why an interceptor is not defined as an interface with one single method "intercept(...)"
that the EJB could implement as well. Having this interface would suppress the need for @AroundInvoke which sounds like
an annotation overuse (unless it is a door open for vendor extension as I will do below..). I'll be interested in EG
feedback on that topic, especially in regards of the first limitation.
- interceptor components life cycle is unspecified but stateless. That sounds like a very important and powerfull
concept of AOP (especially AspectJ) that has been left aside. It is probably an interesting door to provide vendor
specific extension ie thread safe interceptor, per bean class interceptor, per bean instance interceptor, per
application interceptor etc (but then interceptor component may not be stateless anymore.)
- (3.5) an interceptor intercepts all business method (or MessageListener methods for MDB). This means that every
interceptor will be poluted with a code snip like "if (invocationContext.getMethod().getName().equals("doSomething"))
..." ie ones will have to write sort of a pointcut in a very loosy way while AOP allow us to write that in a neat way
(and further, a way that tools can easy understand to spot which method is intercepted by what).
- javax.ejb.InvocationContext is tied to EJB. What will happen when interceptors will end up somewhere else ?
Fortunately, the implementation exposed in this article addresses those issues nicely from a vendor specific extension
perspective.
Note: These are my own thoughts and not of my employer ..
Monday, January 24, 2005
Spring pointcut on steroids
Three months ago when we wrote the AWBench AOP benchmark suite, I had to hack some little Spring AOP aspect and pointcuts.
If you are familiar with Spring and know about AOP (AspectJ, AspectWerkz, JBoss etc), you know that Spring pointcuts are rather ... well sadly un-intuitives.
They might be for new users, but not anymore when you have very basic AOP knowlegde, and you are more and more !
I could not resist and integrating Spring with AspectWerkz pointcut (yes, once again for the third time, after the Spring container Jonas did and the extensible container we shipped.)
A Spring pointcut before the wedding with AspectWerkz - almost impossible to combine with other patterns unless you have your "Mastering Spring XML" in the pocket...
<bean id="theMethodExecutionGetTargetAndArgsAroundAdvisor1"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theMethodExecutionGetTargetAndArgsAroundAdvice"/>
</property>
<property name="pattern">
<value>.*aroundStackedWithArgAndTarget.*</value>
</property>
</bean>
Spring pointcut as a real pointcut thanks to the wedding with AspectWerkzPointcutAdvisor
<bean id="theMethodExecutionAfterThrowingAdvisor"
class="awbench.spring.AspectWerkzPointcutAdvisor">
<property name="advice">
<ref local="theMethodExecutionAfterThrowingAdvice"/>
</property>
<property name="expression">
<value>execution(* *..*.afterThrowingRTE(..))</value>
</property>
</bean>
Such a basic code source is there and should perhaps be reviewed by Spring guys for some of the API details.
The great news is that this will be part of a next release of Spring, and details will be handled by the AspectJ 5 engine instead. That was about time ;-)
Wednesday, January 19, 2005
AspectJ and AspectWerkz to Join Forces
Today we have finally announced that we are joining AspectJ to work on AspectJ 5.
We will focus on what has been the success of AspectWerkz
- plain Java AOP, relying on an annotation defined aspect style
- load time weaving, and integration in J2EE environment
The new team is backed by both IBM and BEA and the new project will be delivered in the coming months. One of the priority is to make sure that a smooth migration path exists from AspectWerkz to AspectJ 5.
That' s a great day for AspectWerkz and AspectWerkz users.
Read more about it
Wednesday, December 22, 2004
YAPB AOP 1.2.3.4 released
I am pleased to announce the first release of YAPB AOP.
For those who don't like this April Fool like YAPB AOP, please read this post on The Server Side - read
Note: YAPBAOP is a real project with real source code and runnable demo !
Features
YAPB AOP 1.2.3.4 is Yet Another Proxy Based AOP for Java.
It is
- proxy-based (AspectWerkz proxy)
- pure java, no language extensions, no external tools needed
- simple and intuitive
- direct, programmatic configuration and un-configuration
- j2ee friendly, no need to mess with class loading
- supports AOP Alliance API for MethodInterception
- JDK 1.5.0 annotations support to match on annotation
- per instance programmatic interception
- full speed
Sample code
here is how YAPB AOP 1.2.3.4 use is simple:
// no aspect
System.out.println(" ( no aspect )");
YapbaopDemo me0 = new YapbaopDemo();
me0.method();
System.out.println(" ( bind a new aspect )");
Yapbaop.Handle handle = Yapbaop.bindAspect(DemoAspect.class, "* yapbaop.demo.YapbaopDemo.*(..)");
YapbaopDemo me1 = (YapbaopDemo) Proxy.newInstance(YapbaopDemo.class);
me1.method();
handle.unbind();
// get a new one but not using the proxy cache then..
System.out.println(" ( unbind it and get a new proxy YapbaopDemo-2)");
YapbaopDemo me2 = (YapbaopDemo) Proxy.newInstance(YapbaopDemo.class, false, false/*not advisable*/);
me1.method();// still has advice
me2.method();// no advice
Extra features
It was very boring to do and does not bring any value to the table, so please, stop inventing (is is the right word ?) YAPB AOP clones based on your favorite bytecode library / proxy library.
It took 40min to hack (time for a train trip, YAPB AOP are that easy today).
If you want to do something usefull, write an email to your favorite AOP framework representative (AspectJ, AspectWerkz, JBoss AOP, Spring AOP, dynAOP, joyAOP [RIP ?], jeetAOP [RIP ?], YAPB AOP [RIP]) and wonder how to
- write some usefull reusable aspect
- write some good article
- provide a new feature, a performance improvement, a bug report or fix
- go an apply to speak about it to the next conference you can find
- imagine new things !
Download Now !
- Get it there (3 Mo jar since YAPBAOP is actually 1 class of 200 lines messed with a lot of dependancies so that you think it is a killing framework)
- Run the demo with:
java -cp yapbaop-1.2.3.4.jar yapbaop.demo.YapbaopDemo
Access the source code
The framework - here
The demo to play with - here
The AOP alliance aspect for the demo - here
Write your own !
Ever wanted to be an Open Source star [*] ? Write your own. Enroll now !
[*] A wrong assumption seems to be that to be an Open Source star, ones have to write at least one YABP AOP. If you only contribute to the next big thing, you ll never be a star, so you 'd better start your own YA RIP framework instead of working with others - that's what mankind is about according to this wrong assumption.
Here are some ideas :
- change the Yapbaop.bindAspect to support binding to a java.lang.reflect.Method
- do the same with an array of java.lang.reflect.Method
- do the same with 1+ Method Annotation(s)
- add some filtering based on 1+ Class Annotation(s)
If you have read till there
Thanks to read this post.
If you dig YAPB AOP architecture, you will find that it is based on
- AspectWerkz proxy
- AspectWerkz extensible AOP container to support AOP Alliance aspect
- AspectWerkz runtime as regards binding of aspects
Quite interesting actuallly isn'it ?
Monday, December 13, 2004
AspectWerkz AOP Eclipse Plugin
Well, we for long have said that plain Java AOP and annotation defined aspects don't needs fancy GUI support, but I have to admit, this makes everyones life easier.
So I am pleased to announce the availability of the AspectWerkz Eclipse Plugin based on the 2.x releases.
Get it now, see the doc and the screenshots !
The plugin contains two almost disjunct features:
- an embedded compiler (a builder in the Eclipse plugin world) for our Java 1.4 strongly typed annotations. Just write the annotations as you would do with Java 5 but in JavaDoc (arrays, nested annotations etc are supported), and write one interface per annotation (where you would write an @interface with Java 5), and the plugin will do the trick when Eclipse will compile your code.
The annotations are then accessible at runtime (using AspectWerkz Annotations API)and you can use them in your pointcuts (nothing new there). - a glue layer that shows the cross cutting view that is add little markers in the gutter to remind you that this piece of code at that line (join point) is advised by this and that before advice in this and that aspect.
(Each feature is a builder so you can deactivate them on a a per project basis if you don't like them / use them.)
Aside since your app will gets weaved, you can just click run and the aspects are in - nothing more to do.
If you need to expose your dependencies jar files to the weaver, use the dedicated AspectWerkz launch configuration that will configure load time weaving for you.
Feedback welcome.
Any volunteer for further evolution ?
The plugin ships for Eclipse 3 and Java 1.4. More to come on Java 5 later.
Alex
Oh forgot to say before others make a story about that: yes we are the last one to write an Eclipse plugin, way (decades?) after AspectJ and some month after JBoss.
Wednesday, September 22, 2004
JAOO 2004 AOP coverage - day 1 and 2
I am back from the JAOO conference that is happening this week in Aarhus, a city in the west part of the Denmark.
Jonas and I had the opportunity to speak there, and since I feel that there is only a little coverage of it in the blog
community, I have decided to take care of that DK duty.
This post won't give you the right view on this conference, since I attented to my own fields related session aka AOP related, but anyway, you will have a minimum.
The conference
The conference is this year largely sponsored by Microsoft, among others of the .Net or Java ground. Great guys are speaking there, like Rod Johnson (Spring / Interface21 - you know him), Rickard Oberg (former JBoss ejb guy, closed source AOP/CMS lead at Senselogic) , Martin Fowler, Arno Schmidmeier (early AspectJ user, AOSD consultant), Peter Von der Ahé (javac Sun guy), Jonas Bonér and myself to name a few and a bunch of .Net guys.
Though the conference location was a bit far from the airport, the accomodation was good, lunches were fine, with DK stuff but not too much for a FR guy, and the monday night social party was pretty good.
Day 1 - Keynote by Microsoft
I have attended the monday keynote given by a Microsoft guy. It was a good insight to see what MS is attempting to achieve, thinking ahead the C# things while people are just excited about the upcoming release of a new Visual C# things.
it was interesting to hear about how clever is Microsoft when it leads to the latest Java 5 Tiger new features, which are some sort of compiler trick for most of them.
In .Net, when you have an int, this one is an object, and there is boxing / unboxing features somehow, but the int himself is reflectively accessible. In the Java world we have blessed (or cursed as Jonas said...) primitive types (int ...) and boxed types (Integer etc), and Tiger provides boxing and unboxing but thru a compiler trick - that is the bytecode will make use of yourInteger.intValue() and Integer.valueOf(yourint) under the hood.
Microsoft gave a bunch of other samples, and admitted that it was somehow easier to start a good language desgin from scratch that sketching on an existing one.
Day 1 - Sessions
I did not attended more on monday morning since I had to prepare some for our own session and I hope to see someone providing feedback on it since it is not fair to write it myself but still...
Annotation driven AOP with AspectWerkz
Jonas and I were giving a talk in the J2SE track on Annotation and AOP.
We started with an AOP crash course just to get everyone on the train.
Then we explained how Tiger annotations are used in AspectWerkz to have annotation defined aspects (something that JBoss has recently lazily followed).
Annotations are also used in AspectWerkz as a matching mechanism, and we went thru a sample where it is perfectely safe to refactor your methods without taking care about the underlying AOP without any whatever IDE plugings.
You can check our slides there, but for the impatient, here is how our strongly typed matching aspect looks like for annotation driven AOP. As you can see, there is no string based, wildcard based magic there.
// Annotation driven AOP
// Sample of strongly typed matching
// in AspectWerkz AOP with annotations
@Service
public class Math {
@Async
public Result complexComputation(Arguments args) {
...// this may take a while - we should do it in another thread
}
}
public class AsyncAspect {
@Around
@Within(Service.class)
@Execution(Async.class)
Object doAsynchronously(JoinPoint joinpoint) {
...
}
}
The session went fine, and the room was pretty much full, with around 400 attendees and after the session we met and chatted some with Rickard Oberg.
After that we had a sort of J2SE panel, which turned out to be a BOF since the JAOO crew had not provided us with a moderator. It ended up in discussing some details and pitfalls in the new Tiger features, like generics and static import.
Night 1 - All conferences are about social events
In the afternoon we met Arno Schmidmeier, an early AspectJ user (meaning late 90's), who is now doing AOSD consulting in Germany (give him a call if you need some AspectJ on-site knowledge), and we then head up to the social event / party with Rod Johnson. Time to share a bunch of beers paid by JAOO sponsors (Microsoft, Borland, Quest, and then I don't really remember) while discussing ideas about Proxy based AOP as in Spring, Geronimo integration, Spring AOP container for AspectWerkz, and some other things.
Day 2 - Sessions
On day 2 I had to leave early and get back at work so I could only make it for Arno and Rickard'sessions and missed Rod' session unfortunately.
AOP - let the code looks like the design
Arno Schmidmeier gave a talk in the Domain Driven Development track, where the main point was to explain how AOP could allow you to let the code looks like the design.
He went thru some use-cases he had seen during his consultancy jobs, and the most interesting part of the session was when he explained how an expression for a domain requirements like "for every successfull bank account operation the accont balance must be checked after the operation and in case of failure, an error should be triggered by the system and the system notified that it should rollabck etc." could be mapped to an AspectJ after returning aspect and thus making his points that AOP enables you to have the code look like the design while avoiding code tangling issues.
Attendees raised questions about code readability, modelling issues and similarities to a predicate language approach. I would have liked to see a running samples in AJDT and alike, and be able to navigate thru the aspects, and may be emphasis more on the domain level pointcuts idea.
Rickard experiences on AOP
I attended Rickard talk about experiences on AOP.
Rickard ellaborated a talk around many of the complex use-case he has for AOP in his company (Senselogic) CMS platform. He started with some classis technical domain concerns, and then jumped on his idea of interface driven system, where an object is actually decomposed in an assembly of entities, each one having a defined stack of advices attached to it.
This approach, which seems quite close to quantum AOP concepts, opens for a bunch of interesting things when it comes to GUI update propagation and server to server replication of sub-graph of persistable objects as well as undo/redo management which again should propagate...
Rickard introduced the idea of a "property=development|production|whatever" pointcut element, that allows for sort of global on/off on the pointcuts. Something you can achieve with a "if" pointcut in AspectJ - although he probably did implemented it at weave time and not at runtime unlike the AspectJ "if".
Rickard then explored the advantages and drawbacks of his "home made" AOP framework, and explained the idea of the abstract schema, where the aspect is abstract and then implements interface of classes where it is actually weaved to, providing sort of natural syntax for accessing the advice target instance methods from within the advice body.
He then went thru a small demo wich showed a nice swinguish things, and then went thru some ajdoc equivalent, where generated javadoc for a class/member is exposing which advices are bounded to it and thru which pointcut.
The next session was Rod Johnson session on Spring and Spring AOP. Unfortunately Jonas and I had to leave since mh, we are pretty busy these days.
Wrap up
Those 2 days were a good investement. I enjoyed the talk we gave there, and it was nice to meet and discuss more with people like Rod, Arno and Rickard.
JAOO has probably a lot more to offer, even if you are on the .net side or on both side (ThoughtWorks had a booth there by the way).
I had some time to think about Rickard abstract schema and experiment some more on Tiger annotations - something I will try to blog about soon.
Get to see the schedule and the JAOO slides there.
Below are some picts of Jonas, Arno, Rickard.
Jonas speaking
Arno session
Rickard explaining his Abstract Schema
Sunday, September 19, 2004
Annotation-driven AOP in Java at JAOO
Jonas and I are going to speak at JAOO about Annotation driven AOP in Java (Tiger / J2SE 5).
The session will cover aspects defined as annotated java classes, as well as matching on annotations and defining strongly typed pointcut thru annotations.
This is a great opportunity to speak there, especially since those ideas have been implemented since the early time of AspectWerkz. Something that some of the other AOP framework are now following.