<?xml version="1.0" encoding="iso-8859-1"?>

<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:admin="http://webns.net/mvcb/"
  xmlns:cc="http://web.resource.org/cc/"
  xmlns="http://purl.org/rss/1.0/">

<channel rdf:about="http://blogs.codehaus.org/people/jboner//archives/aop.html">
<title>grubbel - aop</title>
<link>http://blogs.codehaus.org/people/jboner//archives/aop.html</link>
<description></description>
<dc:language>en-us</dc:language>
<dc:creator></dc:creator>
<dc:date>2005-10-25T13:22:54+01:00</dc:date>
<admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=2.661" />

<items>
<rdf:Seq><rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001202__introducing_hyperbeans_multidimensional_pojos_.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001165_aop_roadshow_in_japan.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001149_jvm_support_for_aop_part_2.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001134_semantics_for_a_synchronized_block_join_point.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001106_dso_transparent_clustering_enabled_through_aop.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001094_jvm_support_for_aop_technical_session_at_javaone_2005.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001093_nordev_2005_rickard_on_real_world_usecases_for_aop_etc.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/001012_aosd05_has_started.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000912_interception_aop_finally_true_.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000913_aspect_hot_deployment_in_practice_implementing_a_jmx_monitoring_aspect_.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000915_cglib_proxies_are_doing_aspectwerkz.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000914_awproxy_proxy_on_steroids.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000909__spring_and_aspectwerkz_a_happy_marriage_v2.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000870_interviewed_on_javahispanoorg.html" />
<rdf:li rdf:resource="http://blogs.codehaus.org/people/jboner/archives/000826_spring_and_aspectwerkz_a_happy_marriage.html" />
</rdf:Seq>
</items>

</channel>

<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001202__introducing_hyperbeans_multidimensional_pojos_.html">
<title> Introducing HyperBeans – multi-dimensional POJOs </title>
<link>http://blogs.codehaus.org/people/jboner/archives/001202__introducing_hyperbeans_multidimensional_pojos_.html</link>
<description><![CDATA[<h1> Introducing HyperBeans – multi-dimensional POJOs </h1>

<h2> Introduction </h2>

<p>
This article is introducing <i>HyperBeans</i>, a proposal for a framework for <a href="http://domino.watson.ibm.com/library/cyberdig.nsf/0/2a4097e93456d0cf85256ca9006dac29?OpenDocument">Symmetric Aspect-Oriented Software Development</a>  in <b>plain</b> Java (i.e. no extensions to Java is being used). These ideas are based on the work I have done in <i><a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a></i>  and in the <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_2.html">JVM support for AOP</a>  in <i>JRockit</i> and are loosely based on the work on <a href="http://www.cs.virginia.edu/~eos/papers/cs_2004_21.pdf"><i>Classpects</i></a>  by Kevin Sullivan and Hridesh Rajan. 
</p>

<p>
If you don't care about the research and background behind the ideas presented in this article (and want to see some code right away), then you should skip the rest of this section.
</p>

<p>
Aspect-Oriented Software Development (AOSD) in general, tries, among other things, to address the problem defined as <a href="http://www.research.ibm.com/hyperspace/Papers/tr21452.ps">the tyranny of dominant decomposition</a> , in which the prominent concerns, usually the business logic, dominate the class design, especially the inheritance hierarchy (as observed in <a href="http://www-128.ibm.com/developerworks/java/library/j-aopwork4/">this article</a>).  
</p>

<p>
Historically there has been (and still is) two different main philosophies in AOSD, the asymmetric philosophy and the symmetric philosophy.
A detailed discussion about their semantic and philosophical differences is out of the scope for this article (read <a href="http://domino.watson.ibm.com/library/cyberdig.nsf/0/2a4097e93456d0cf85256ca9006dac29?OpenDocument">this article</a>  for a detailed discussion). </p>

<p>
Juri Memmert has written a good <a href="http://www.jpmdesign.net/wordpress/2005/08/04/symmetry-vs-asymmetry/">introductory article</a> on the subject in which he defines the different philosophies like this:
</p>

<blockquote>
<b>The asymmetric philosophy</b>

<p>An asymmetric approach to AOSD relies on the notion that there is a base body of code that is then augmented with aspects. There is a concept ional difference (and an implementation difference) between the base and the aspects so that an aspect can not serve as the base of another composition. Most asymmetric approaches use language extensions to declare aspects as first class entities.
</p>
	 
<b>The symmetric philosophy</b>

<p>A symmetric approach to AOSD is based on the notion that all concerns in a system are created equal and, in the asymmetric terminology, can serve as both aspect and base in different compositions. Most symmetric approaches use programming languages as-is, although there are approaches that rely on language extensions as well.
</p>
</blockquote>

<p>
The leading implementation for asymmetric AOSD is <a href="http://www.eclipse.org/aspectj/"><i>AspectJ</i></a>, while the most well-known symmetric implementation is <a href="http://www.research.ibm.com/hyperspace/HyperJ/HyperJ.htm"><i>Hyper/J</i></a> (now part of the <i>Concern Manipulation Environment</i> (CME) project).
</p> 

<p>  
Asymmetric AOSD has so far been the dominant way of implementing AOSD in Java, and in the enterprise space at large. There has been, and still is, a lot of debate in the research community around whether the symmetric or the asymmetric philosophy is the best way of implementing AOSD and many papers have been written on the subject (see the reference section at the end).
</p>

<p>
When implementing the <i>AspectWerkz</i> AOP framework  (which now has been merged with <i>AspectJ</i>), I have been involved in efforts trying to stretch the boundaries of asymmetric AOSD and even though I believe that the asymmetric approach is the preferable in many cases, it definitely has some shortcomings. For example, asymmetric AOSD addresses the problem of 'the tyranny of dominant decomposition' by allowing us to modularize all concerns, but the dominant concern, using aspects. Since the dominant concern needs to serve as "base", the decision deciding which concern should be seen as the dominant one still needs to be taken, and this is a decision that should not be taken lightly since it is something that is usually very hard to change.
</p>

<p>
When taking a look at how a symmetric approach handles the above given problem, I find the symmetric solution very natural and appealing (at least conceptually). In which, if using <i>Hyper/J</i>'s terminology, a system is seen as a multi-dimensional hyperspace, which is built up using different hyperslices (dimensions). A hyperslice is the abstraction of a concern, which can be built up by many components.  This gives you the possibility of viewing the hyperspace (your system) differently in regards to different hyperslices (concerns); you have the possibility of looking at the system from the point of view (concern) that you currently want. 
</p>

<p>
I do not want to take any position in regards to if symmetric AOSD is a (or will be a) serious contender to asymmetric AOSD. I simply have not used the symmetric approach to solve real world problems enough yet, but I do believe that it is something worth exploring more. So, let's take a look at the proposal.
</p>

<h2> HyperBeans – multi-dimensional POJOs </h2>

<p>
There is no the distinction between classes and aspects, e.g. no need for one concern to serve as "base", all there is is <i>HyperBeans</i>. <i>HyperBeans</i> are regular Plain Old Java Objects (POJOs), they are instantiated with <code>new</code> and you work with them just as with regular classes, no configuration file or similar is needed.
</p>

<p>
Similarly, there is no the distinction between methods and <i>advice</i>, there are just regular methods, which can be invoked explicitly (like regular methods) or implicitly (when a join point is being executed - like a regular <i>advice</i>).
</p>

<h2> Deployment and undeployment </h2>

<p>
<i>HyperBeans</i> are instantiated using the <code>new</code> keyword, which will call the constructor and instantiate the HyperBean just like any other POJO. However, the constructors can also control deployment of the HyperBean. 
</p>

<p>
Deployment of a HyperBean means that its "blessed" methods (<i>advice</i>) are weaved in, while undeployment means that the woven code is removed.   
</p>

<p>
You control deployment of a HyperBean by annotating (one or many of) its constructors with the <code>@Deploy</code> annotation. This example shows how to deploy a HyperBean as a singleton (more on other instantiation models later):
</p>

<pre>
public class POJO {

    @Deploy
    public POJO() {    	
    }

    ... // remaining methods omitted 
}
</pre>

<p>
Since there is no such thing as 'destructors' in Java, we are handling undeployment of HyperBeans by annotating a regular Java method (static or member) with the <code>@Undeploy</code> annotation. This means that when such a method is invoked, the HyperBean will be undeployed. It also give us the possibility of doing additional clean up (closing resources etc.) if necessary:
</p>

<pre>
public class POJO {

    @Undeploy
    public void close() {
        // clean up - close resources etc.
    }

    ... // remaining methods omitted 
}
</pre>

<h2> Instantiation models </h2>

<p>
You can control instantiation model (also called the deployment scope) of the HyperBean by adding a special argument to the constructor. This special argument defines the deployment scope for the HyperBean and needs to be annotated with the <code>@Scope</code> annotation. What this means is that the HyperBean will be deployed with the scope defined by the type of the argument.   
</p>

<p>
For example, adding the argument <code>@Scope Thread scope</code> to a constructor, (which is annotated with the <code>@Deploy</code> annotation), will deploy the HyperBean with the scope of this particular thread. 
</p>

<p>
Here are all the currently supported instantiation models:
<table border="1">
<tr>
	<th>Type annotated with @Scope</th>
	<th>Instantiation model</th>
</tr>
<tr>
	<td><code>No argument with a @Scope annotation</code></td>
	<td>Singleton</td>
</tr>
<tr>
	<td><code>Thread</code></td>
	<td>Per Thread</td>
</tr>
<tr>
	<td><code>Class</code></td>
	<td>Per Type</td>
</tr>
<tr>
	<td><code>Instance</code> (but not of type <code>Class</code> or <code>Thread</code>)</td>
	<td>Per Instance</td>
</tr>
</tr>
</table>
</p>

<p>
Here are some examples:
<pre>
public class POJO {

    /** Singleton deployment */
    @Deploy
    public POJO() {    	
    }

    /** Per Type deployment */
    @Deploy
    public POJO(@Scope Class scope) {    	
    }

    /** Per Instance deployment */
    @Deploy
    public POJO(@Scope SomeType scope) {    	
    }

    /** Per Thread deployment */
    @Deploy
    public POJO(@Scope Thread scope) {    	
    }

    ... // remaining methods omitted 
}
</pre>
</p>

<p>
The current semantics for the <code>@Scope</code> annotation is that it:
<ul>
<li>
Narrows the scope for the matching. For example using the <i>Per Type</i> instantiation model will add an implicit <code>&& within(scope)</code> to the pointcuts defined in the HyperBean (same as in AspectJ).   
</li>
<li>
Controls the life cycle. The HyperBean will have the same life cycle as the instance annotated with the <code>@Scope</code> annotation.
</li>
<li>
Controls state management. Tied to the life cycle.
</li>
</ul>
</p>

<h2> Control flow management - no more cflow </h2>

<p>
There is no more any need for the <i>cflow</i> pointcut (as defined by <i>AspectJ</i>). Instead we suggest a simple programmatic model for control flow management of HyperBean deployment. I believe that the same functionality can be reached by a combination of the <i>Per Thread</i> instantiation model and the deployment/undeployment API. This approach has similarities with the work done in <i><a href="http://caesarj.org/">CaesarJ</a></i> and its concept of a <code>deploy {..}</code> block. Here is an example:
</p>

<p>
You have a HyperBean that can be deployed on a per-thread basis:
<pre>
class POJO {
    @Deploy
    public POJO(@Scope Thread scope) {    	
    }

    @Undeploy
    public void close() {
    }

    ... // remaining methods omitted 
}
</pre>
</p>

<p>
Then you can use the following idiom to achieve fine grained control flow (cflow) management:
<pre>
POJO hyperBean;
try {
    hyperBean = new POJO(Thread.currentThread()); // deploys the HyperBean to the current control flow ONLY
    
    ... // do stuff - the HyperBean is woven into this control flow ONLY

} finally {
    hyperBean.close(); // undeploy the HyperBean from the control flow
}
</pre>
</p>

<p>
If you don't want to have this be tangled with your application logic, you can of course put the block in an <i>advice</i>, (and have its HyperBean be a singleton and instantiated somewhere else):
<pre>
@Around(..)
public Object cflowAdvice(InvocationContext ctx) {
    POJO hyperBean;
    Object result;
    try {
        hyperBean = new POJO(Thread.currentThread()); 
        result = ctx.proceed();
    } finally {
         hyperBean.close(); 
    }
    return result;
}
</pre>

</p>

<h2> Cross-cutting methods - advice </h2>

<p>
So how do we define these "blessed" methods? They are defined using Java 5 annotations, in a similar fashion to <i>AspectWerkz</i>'s and <i>AspectJ 5</i>'s annotation style of development, but mixed with the API defined by the JVM support for AOP in <i>JRockit</i> (as described <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_2.html">in this article</a> ).
</p>

<p>
Let's take a look at an example:
</p>
 
<pre>
public class POJO {
 
    @Before("call(Foo.new(..))")
    public void doSomething() {
        ... // do something before an instance of Foo is created
    }

    ... // remaining methods omitted 
}
</pre>

<p>
This is a regular POJO with one "blessed" method that performs some action before an instance of <code>Foo</code> is created.  There's really nothing special with this class apart from that one of its method is annotated with a special annotation borrowed from the annotation style syntax in <i>AspectJ</i>.  Now let's take a look at a (slightly) more interesting example, one that makes use of contextual information.
</p>

<pre>
public class POJO {
 
    @Before("call(@test.TraceMe * *.*(..))")
    public static void traceBefore(@CalleeMethod Method callee) {
        System.out.println("--> " + callee.toString());
    }
  
    @After("call(@test.TraceMe * *.*(..))")
    public static void traceAfter(@CalleeMethod Method callee) {
        System.out.println("<-- " + callee.toString());
    }

    ... // remaining methods omitted 
}
</pre>

<p>
This is a regular POJO with two different "blessed" methods (that are tracing 
invocations to all methods that are annotated with the <code>@Trace</code> annotation). Contextual information (like caller and callee method, caller and callee instance, parameters, return value etc.) is retrieved using annotated parameters borrowed from the <i>JRockit</i> API for AOP . 
</p>

<p>
Here is a list of the current set of defined annotations and their meaning:
</p>
<p>
<table border="1">
<tr>
	<th>Annotation</th>
	<th>Exposes</th>
</tr>
<tr>
	<td><code>@CalleeMethod</code>
	</td>
	<td>The callee method (method, constructor, static initializer)
	</td>
</tr>
<tr>
	<td><code>@CallerMethod</code>
	</td>
	<td>The caller method (method, constructor, static initializer)
	</td>
</tr>
<tr>
	<td><code>@Callee</code>
	</td>
	<td>The callee instance
	</td>
</tr>
<tr>
	<td><code>@Caller</code>
	</td>
	<td>The caller instance
	</td>
</tr>
<tr>
	<td><code>@Arguments</code>
	</td>
	<td>The invocation arguments (wrapped in an object array)
	</td>
</tr>
<tr>
	<td><code>@Returning</code>
	</td>
	<td>The return value (used in 'after returning advice')
	</td>
</tr>
<tr>
	<td><code>@Throwing</code>
	</td>
	<td>The exception thrown from a method (used in 'after throwing advice')
	</td>
</tr>
</table>
</p>

<p>
These annotated arguments (except caller and callee method) also works as 'filters', the same is true for all unannotated arguments which are treated as the regular arguments to the method (or the field value about to be set etc.). The methods can be either member or static (dependent on if you want to keep state in the instance or not).
</p>

<p>
Since some people might be curious how "around advice" (i.e. 'interception') is handled, below is an example of how to implement the same functionality as in the class above using an "around advice". Here we introduce the <code>InvocationContext</code> abstraction (similar to the <code>ProceedingJoinPoint</code> abstraction in <i>AspectJ</i>), which serves as the context on which we can invoke the <code>proceed()</code> method in order to continue with the execution flow.  
</p>

<pre>
public class POJO {
 
    @Around("call(@test.TraceMe * *.*(..))")
    public Object trace(InvocationContext ctx, 
                        @CalleeMethod Method callee) {
        System.out.println("--> " + callee.toString());
        Object result = ctx.proceed();
        System.out.println("<-- " + callee.toString());
        return result;
    }

    ... // remaining methods omitted 
}
</pre>

<h2> Implementation </h2>

<p>
I have prototyped HyperBeans using the <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_1.html">JVM support for AOP in JRockit</a>. The implementation was actually very simple and shows the power of the JRockit API (the JRockit prototype is <a href="http://forums.bea.com/bea/forum.jspa?forumID=600000004">available now</a> for those who wants to try it out).  
</p>

<p>
I am planning on writing another article in which I go through (and release) the actual implementation. 
</p>

<p>
Stay tuned. 
</p>
]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-10-25T13:22:54+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001165_aop_roadshow_in_japan.html">
<title>AOP Roadshow In Japan</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001165_aop_roadshow_in_japan.html</link>
<description><![CDATA[<p><b>Japan Tour</b></p>

<p>My Japan tour is starting to come to an end. During the past week I have been traveling in Japan, done two general sessions at <a href="http://www.beasys.co.jp/news_events/bea_seminar/td_2005.html">BEA Tech Day 2005</a> conferences (Tokyo and Osaka), plus a press conference and a bunch of BEA internal training sessions.</p>

<p>I had never been to Japan before, but I am very interested in their culture and I love Japanese food, so this trip has in many ways been a very interesting and fun experience. I had some fears that my visit would turn out similar to the movie 'Lost In Translation' by Bill Murray (for those that have seen this movie), but my fears were unfounded. Most people spoke good english and I only met very generous people with a lot of heart. </p>

<p><b>Excitement around AOP</b></p>

<p>There is a lot of excitement and interest around AOP in Japan, both among developers, management and press. They are especially excited about <a href="http://aspectwerkz.codehaus.org/">AspectWerkz </a> (it is actually more popular than <a href="http://www.eclipse.org/aspectj/">AspectJ</a>) and <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_1.html">JRockit support for AOP</a>.</p>

<p> It was fun to learn that they had translated every single article I have written, to Japanese.  On the other hand, the problem having to translate almost every article and book is one of the biggest hurdles on the way to mass adoption of AOP. </p>

<p><b>Press conference</b></p>

<p>The press conference I did was an interesting experience, it was my first real press conference, with interviewers lined up, pounding me with questions. It was a lot of fun. The topic for the interview was <a href="http://dev2dev.bea.com/jrockit/">JRockit </a>and its new AOP support which they seemed very impressed about. </p>

<p>They have already published, two articles based on the press conference:<br />
<a href="http://www.atmarkit.co.jp/news/200508/31/bea.html">http://www.atmarkit.co.jp/news/200508/31/bea.html</a><br />
<a href="http://itpro.nikkeibp.co.jp/free/NC/NEWS/20050830/167117/">http://itpro.nikkeibp.co.jp/free/NC/NEWS/20050830/167117/</a><br />
and from what I understand, two more articles with the published.</p>

<p><b>BEA Tech Day 2005 in Tokyo</b></p>

<p>The general session I did had around 350 attendees and was simultaneously translated. Things worked out pretty well. People seem to like the talk and came up with a bunch of really good questions at the end. What was even more fun was that there were actually other speakers that talked about AspectWerkz/AspectJ in different contexts.  One guy for example, talked about how to implement the transaction and dependency injection parts of the EJB 3 specification using AspectWerkz.  In general, one of the main themes of the conference was AOP. </p>

<p>Afterwards, during the conference party, I was treated almost like a celebrity, with "fans" coming up and wanted to shake hands and have a picture taken with the mysterious AOP guru from the north pole (Sweden). :-) </p>

<p><b>Seasar framework - a Japanese Spring killer?</b></p>

<p>During lunch at the conference I had the pleasure of having interesting discussion with the founder of the dependency injection and component framework <a href="http://www.seasar.org/">Seasar</a>. For those that have never heard about Seasar, Seasar is a project very similar to <a href="http://www.springframework.org/">Spring</a>, which is more popular than Spring here in Japan. It uses plain bytecode manipulation to do the AOP part (and not proxies), and is based on the AOP Alliance interfaces. One cool thing that I found out about the project is that they are not only using but are very excited about Alex's and my project <a href="http://backport175.codehaus.org/">backport175</a> (so much that they actually asked to contribute back some code).  </p>

<p><b>BEA Tech Day 2005 in Osaka - Kyoto sightseeing</b></p>

<p>Today I am off for Osaka for my last talks at the BEA Tech Day 2005 in Osaka tomorrow.  The trip will conclude with one day off,  which I will spend sightseeing in Kyoto. Kyoto is the historical and cultural center in Japan, with many buildings and temples being more than 1000 years old (compared to Tokyo which is only a couple of hundred years old). So that is going to be interesting.</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-08-31T16:43:07+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001149_jvm_support_for_aop_part_2.html">
<title>JVM support for AOP - part 2</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001149_jvm_support_for_aop_part_2.html</link>
<description><![CDATA[<p>The <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_2.html">second part</a> of our article series about <a href="http://commerce.bea.com/products/weblogicjrockit/5.0/jr_50.jsp">JRockit </a>JVM support for AOP is now published.</p>

<p>This article describes in more detail on how the API is used, showing some code samples and ends with a discussion in which we try to explain how we address the questions and issues (around the shortcomings of bytecode manipulation) raised in <a href="http://dev2dev.bea.com/pub/a/2005/08/jvm_aop_1.html">part one</a> in the series.</p>

<p>The prototype will be downloadable soon, stay tuned.<br />
</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-08-08T21:18:32+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001134_semantics_for_a_synchronized_block_join_point.html">
<title>Semantics for a Synchronized Block Join Point</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001134_semantics_for_a_synchronized_block_join_point.html</link>
<description><![CDATA[As I mentioned in my previous blog entry, the <code>synchronized</code> block is currently not a supported join point in AspectJ 5 (or in any other AOP framework):

<blockquote>
Currently you can for example pick out a call to a method that is declared as being synchronized and you can pick out calls to Thread:: notify()/notifyAll()/wait(). Meaning that being able to pick out synchronized blocks are the only missing piece left in order to completely control thread management and locking in Java. The actual bytecode modifications needed to make this work would be fairly simple, but capturing the correct semantics in a good language design would probably be a lot trickier.
</blockquote>

<p>
Well, I'm not a language designer, but I think the problem is interesting so I will spend some time discussing it anyway.

<p>
In bytecode, a synchronized block is represented as a MONITOR ENTRY and a MONITOR EXIT bytecode instruction pair (however these are not required to be paired).  The first natural approach would to let these two bytecode instructions be join points and treat them similar to field access and modification (PUTFIELD and GETFIELD bytecode instructions), meaning simply pick out (and intercept) this single bytecode instruction.  

<p>
Just to clarify what I mean, here is an example of how the syntax for the above given semantics could look in the AspectJ pointcut expression language:
<code language="java">
lock(Type t) && withincode(* Foo.bar(..)) && args(t)

unlock(Type t) && withincode(* Foo.bar(..)) && args(t)
</code>

<p>
Let us take a look at a synchronized block and how it would be affected:
<code language="java">
synchronized(obj) {
    // body
}
</code>

<p>
In bytecode to this is equivalent to (pseudo code):
<code language="java">
MONITOR ENTRY // lock on obj
    // body
MONITOR EXIT
</code>

<p>
If we now add around advices to these join points then we could for example get (pseude code):
<code language="java">
try {
    // a call to the around advice, which calls the lock manager
    aroundAdvice1(obj) --> myLockManager.acquire(obj); 

    // body

} finally {
    aroundAdvice2(obj) --> myLockManager.release(obj);
}
</code>

<p>
This approach would give you the possibility to completely control how locking is done in Java (including the possibility of enhancing or completely screw up the Java Memory Model (JMM)). On the other hand it does not allow you to pick out the actual code block that is synchronized (is this something that we want?) .  Therefore this approach is perhaps not intuitive, since in Java source code, what we see is not lock acquisition and release but a code block that is guaranteed to be synchronized. So now let's try to approach this problem from the perspective of source code.

<p>
Since AspectJ (and AspectWerkz) already has limited support for the synchronized keyword by allowing calls to methods declared as being synchronized to be matched, let us take a look at the semantics for this join point.  

<p>
Here's a simple method that is defined as being synchronized:
<code language="java">
public synchronized void doStuff() { 
    // body
}
</code>

<p>
What this actually means is:
<code language="java">
public void doStuff() { 
    synchronized(this) {
        // body
    }
}
</code>

<p>
The options we have of picking up this synchronized code block (wrapped up in the doStuff() method) is by using a <pre>execution(synchronized void *.doStuff())</pre> or <pre>call(synchronized void *.doStuff())</pre> pointcut.

<p>
Using the execution pointcut, the above method body would be transformed to (pseudo code):
<code language="java">
synchronized(this) {
    // the advice has option of invoking the original body
    myAroundAdvice(this) 
}
</code>

<p>
I.e. only synchronized body is matched and intercepted.

<p>
If we are using the call pointcut, the same code snippet would be transformed to (pseudo code):
<code language="java">
...
// the advice has the option of invoking the original synchronized block
myAroundAdvice(this) 
...
</code>

<p>
I.e. the whole synchronized block, including the locking is matched (and intercepted). (This is conceptionally true, in regards to the locking, which is easy to see if you think of the doStuff() method as being inlined.)

<p>
I will not go into much detail about how these semantic differences should be expressed in the pointcut language here (this post is too long already). But for example, the last discussion would require the possibility of making a distinction between picking out a code block <code>inclusively</code> and <code>exclusively</code> (i.e. picking out the whole code block, or just the body of the code block), which could be expressed something like this:
<code language="java">
// pick out synchronized block including the locking
block-inclusive(synchronized(Type t)) && withincode(* Foo.bar(..)) && args(t)

// pick out only the synchronized block's body, not the locking
block-exclusive(synchronized(Type t)) && withincode(* Foo.bar(..)) && args(t) 
</code>

<p>
(These "block" pointcut descriptors can of course be used in any kind of block, loops, conditional statements etc., if/whenever they are supported in AspectJ.)

<p>
To sum up, the questions are: Do we want the power of intercepting the whole locking mechanism (but not the synchronized body), or is it better to follow the semantics we have for a synchronized method? Which approach addresses the use cases we want?  Is the most intuitive?  Is more orthogonal? 

<p>
Thoughts?  Comments?  Ideas?
<p>





]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-07-18T12:07:24+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001106_dso_transparent_clustering_enabled_through_aop.html">
<title>DSO: transparent clustering enabled through AOP</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001106_dso_transparent_clustering_enabled_through_aop.html</link>
<description><![CDATA[<p><a href="http://www.terracottatech.com/index.html">Terracotta</a> just recently launched a product (DSO) for clustering POJOs in a completely transparent way.  What I find interesting in this product is not mainly in the clustering and caching, but how they make use of AOP and loadtime weaving to make it completely transparent.  </p>

<p>This sounds a lot like techniques that we have been working on in <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> last years, and I was not too surprised, although very happy, to learn that they are actually using AspectWerkz. It is really great to see some of the ideas that Alex and I have been working on being used in new and interesting ways and in real-world applications.</p>

<p>They seem to use techniques that are fairly similar to the <a href="http://docs.codehaus.org/display/AWARE/UnitOfWorkProtocol">Unit of Work aspect library</a> that I wrote for the AWare aspect library. Meaning: record field changes to object graphs within a transaction which can be committed/rolled back./etc. add specific methods that are defined declaratively.</p>

<p>However they have extended to this idea by adding semantics currently not available in AOP.  For example being able to pick out synchronized blocks.  This is a great idea, and when you think of it, it is in a way a hole in the current AOP implementations.  Currently you can for example pick out a call to a method that is declared as being synchronized and you can pick out calls to Thread:: notify()/notifyAll()/wait().  Meaning that being able to pick out synchronized blocks are the only missing piece left in order to completely control thread management and locking in Java. The actual bytecode modifications needed to make this work would be fairly simple, but capturing the correct semantics in a good language design would probably be a lot trickier.</p>

<p>All and all a very interesting product that shows the beauty of AOP and loadtime weaving in action, go and check it out.</p>

<p>/Jonas</p>

<p><br />
</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-06-07T15:34:29+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001094_jvm_support_for_aop_technical_session_at_javaone_2005.html">
<title>JVM support for AOP (technical session at JavaOne 2005)</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001094_jvm_support_for_aop_technical_session_at_javaone_2005.html</link>
<description><![CDATA[<p>If you're interested in knowing more about what the future holds for AOP, then you should come to the technical session TS-7659 (titled "Runtime Aspects With JVM Support") on Tuesday, June 28 at JavaOne 2005.</p>

<p>This will be the first time ever to show an enterprise JVM - BEA JRockit - with native AOP support. Alex Vasseur and myself have been pushing for this idea since the early days of AspectWerkz when we joined the JRockit group, and it's finally taking shape, with now support for AspectJ 5, the de-facto standard for AOP in Java.</p>

<p>Credit should also go to Joakim Dahlstedt, the CTO of JRockit, who has been playing a leading role in the design and implementation.</p>

<p>We will talk about the current problems with bytecode based weaving (multiple agents, double bookkeeping, performance etc.) and then discuss how these problems can be solved through native JVM support. We will show a prototype of our implementation, go through the programming model and run a live demo.</p>

<p>Here is the abstract:</p>

<p>"Aspect Oriented Programming (AOP) is growing in popularity. Adding aspects at runtime, dynamic weaving, can be a very powerful technique for diagnostics, profiling, or debugging of a running system. The concept of adding aspects at runtime (dynamic weaving) is looked upon with skepticism by some. It's also easy for multiple instrumenting agents to cause havoc for each other. We have implemented prototype changes to our Java™ Virtual Machine (JVM™ software), BEA Weblogic JRockit, to support dynamic weaving in the JVM software in a controlled fashion. We also have modified AspectJ 5 to try out this functionality. We believe our changes to the JVM software to support dynamic weaving lessens the skepticism about runtime aspects and allows for multiple instrumenting agents to coexist.<br />
In this session we present the changes we made to the JVM software to support this functionality and the results of this effort. In addition, we compare this approach to current approaches like JVMTI/Hotswap and Project JFluid. Finally, we provide a demonstration of various runtime advice you'll find useful to analyze the behavior of your applications."</p>

<p>Don't miss it, see you there.</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-05-29T20:02:34+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001093_nordev_2005_rickard_on_real_world_usecases_for_aop_etc.html">
<title>Nordev 2005: Rickard on real world use-cases for AOP etc.</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001093_nordev_2005_rickard_on_real_world_usecases_for_aop_etc.html</link>
<description><![CDATA[<p>I just got back from the Nordic Software Developer Summit (Nordev) 2005.  Strange enough, this is the first good developer conference that we have had in Sweden.  </p>

<p>Altogether it was a really good event with two major tracks, one Java and one .Net. The Java track had interesting talks on topics like: AOP :-), agile development, hibernate, spring, manageability of the JRockit JVM etc. (e.g. the usual suspects).</p>

<p>I was glad to see that AOP got a lot of focus with talks from myself and Rickard Oberg and a hands-on workshop (on AspectJ).  Both sessions were packed, and people seemed enthusiastic about it.   </p>

<p>Of all things you can be nervous about, I was nervous about speaking in Swedish (my native language).  I had never spoken about AOP in Swedish so it was interesting and a good exercise :-).  Everything went pretty well except that eclipse died on me when I was starting up the demo (3.1 M6). (The demo was about how to write a unit of work to achieve transparent persistence/replication/transaction management, perhaps something for an upcoming blog post...).</p>

<p>I enjoyed Rickard's talk.  He based the talk on examples from the CMS application and he has built, and it was interesting to see both simple and advanced usage of AOP in the real world application.  He's using a pretty extreme approach to AOP in which every single object is built up a using intertype declarations (introductions/mixins).  I do not think that this model fits every project, and it for sure has drawbacks, but in their CMS application it has given them extremely high reuse and development speed.</p>

<p>He showed examples of client aspects, how objects can render themselves differently based on which intertype declarations it has.  For example, if an object in their GUI (a page, a site, a portlet etc.) has the intertype declaration ACL applied to it then it will give you the possibility to open up a window to manage security for this object. This object can also be given the Tree intertype declaration, which will allow you to browse the object in a tree structure etc.</p>

<p>He also showed examples on how they do client synchronization and cluster wide replication, using the same aspect (which simply records the events triggered and then plays it back).  Another interesting aspect that they have is what he calls partial object versioning, in which intertype declarations can be versioned and different versions can be used (in the same object), depending on how system is configured. </p>

<p>Rickard gave an example of a customer that came in with a new functional requirements very late in the release cycle, requirements that required redesign of some parts of the system, but that he managed to solve in a simple and generic way by applying an aspect.</p>

<p>Then he talked about the need for tools and that most problems that people are complaining about when it comes to AOP are actually not related to AOP, but to the lack of good tools. He showed one interesting tool that they are using on a daily basis, a tool for doing a diff of the system.  This diff showed you which advice and or intertype declarations had been removed or added since the last time the system's state was recorded. For example, after a regular refactoring, the diff should be zero.  This is something that we should add to AJDT.</p>

<p>All and all a good conference, you should try to get there next year.</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-05-20T10:17:39+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/001012_aosd05_has_started.html">
<title>AOSD.05 has started</title>
<link>http://blogs.codehaus.org/people/jboner/archives/001012_aosd05_has_started.html</link>
<description><![CDATA[<p><a href="http://aosd.net/2005/index.php">AOSD 2005</a> has just started. I am excited, and have high expectations since last years conference was a real hit, and this year we have a separate industry track with many interesting talks coming up, f.e. Grady Booch is doing a keynote.  </p>

<p>I will be giving a talk on AspectWerkz 2 and the road to AspectJ 5 at the AOSD 2005 conference hosted at the Intercontinental hotel in Chicago.</p>

<p>If you are in the area, please drop in and say hi.</p>

<p>If you are interested you can read the abstract etc. <a href="http://aosd.net/2005/industry/talk3.php">here</a> </p>

<p>For those who can't make it, I will make the slides available online after the conference.</p>

<p>Hope to see you there...<br />
</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-03-15T21:28:57+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000912_interception_aop_finally_true_.html">
<title>Interception == AOP (finally true ;-)</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000912_interception_aop_finally_true_.html</link>
<description><![CDATA[<p>
One of the new features in the <a href="http://aspectwerkz.codehaus.org/index.html">AspectWerkz 2</a> architecture is that it comes with a full-blown interception framework that allows per instance programmatic deployment with most of  the AOP semantics preserved. You can make use of this using both the regular load-time weaving or the AW Proxy (that I blogged about <a href="http://blogs.codehaus.org/people/jboner/archives/000914_awproxy_proxy_on_steroids.html">here</a>)
</p>

<p>
In short you will get: 
<br/>
Per instance programmatic deployment for <i>before</i>, <i>around</i>, <i>after</i>, <i>after finally</i> and <i>after throwing</i> advice types for <i>call</i>, <i>execution</i>, <i>set</i> and <i>get</i> pointcuts as well as the expressiveness of the AspectWerkz' pointcut pattern language all wrapped up in a very simple and intuitive API.  
</p>

<p>
<pre>
    POJO pojo = new POJO();

    // adds tracing to all methods in the 'pojo' instance
    ((Advisable) pojo).aw$addAdvice(
        "* *.*(..)",
        new BeforeAdvice() {
            public Object invoke(JoinPoint jp) {
                System.out.println("Entering: " + jp.getSignature().toString());
            }
        }
    );
</pre>
</p>

<h3>The Advisable interface</h3>
<p>
From a users perspective pretty much all you need to know about is in the <code>Advisable</code> interface. This interface is added to all the classes that you want to do per instance runtime deployment at. This interface is added to your classes by the framework, but more on that later. 
</p>

<p>
The <code>Advisable</code> interface basically has two methods that are of interest to you:
<ul>
    <li>
    <code>void aw$addAdvice(String memberPattern, Advice advice)</code> - this methods allows you to add an <code>Advice</code> instance to the members specified by the <code>memberPattern</code> argument
    </li>
    <li>
    <code>void aw$removeAdvice(String memberPattern, Class adviceClass)</code> - this methods allows you to remove the last advice (that was added last) of the type specified in the <code>adviceClass</code> argument from from the list of aspects applied to the members specified by the <code>memberPattern</code> argument
    </li>
</ul>
The funny prefix <code>aw$</code> is just to minimize method clashes since these methods are added to your classes on-the-fly.
</p>

<h3>The different Advice interfaces</h3>
<p>
The intercept framework supports all main types of advice defined in AOP today:
<ul>
    <li>
    <code>AroundAdvice</code> - works like a regular interceptor and is invoked "around" or "instead-of" the target method invocation or field access/modification.
    <br/>
    It has one method you need to implement which has the following signature:
    <br/>
    <code>Object invoke(JoinPoint jp)</code>
    </li>

    <br/>
    <li>
    <code>BeforeAdvice</code> - is invoked before the actual member invocation
    <br/>
    It has one method you need to implement which has the following signature:
    <br/>
    <code>Object invoke(JoinPoint jp)</code>
    </li>

    <br/>
    <li>
    <code>AfterAdvice</code> - is invoked after the actual member invocation, is invoked both if the method returns normally or with an exception. E.g. can be seen as being invoked in the <code>finally</code> block.
    <br/>
    jt has one method you need to implement which has the following signature:
    <br/>
    <code>Object invoke(JoinPoint jp)</code>
    </li>

    <br/>
    <li>
    <code>AfterReturning</code> - is invoked after the actual method has returned normally 
    <br/>
    It has one method you need to implement which has the following signature:
    <br/>
    <code>Object invoke(JoinPoint jp, Object returnValue)</code>
    </li>

    <br/>
    <li>
    <code>AfterThrowingAdvice</code> - is invoked after the actual method has returned with an exception 
    <br/>
    It has one method you need to implement which has the following signature:
    <br/>
    <code>Object invoke(JoinPoint jp, Throwable exception)</code>
    </li>
</ul>
As you can see, all of these methods takes a <code>JoinPoint</code> instance as a parameter. This class contains f.e. contextual information bout the join point (member) we are executing before/after/around. Such as caller and callee instances and types, argument values and types etc. You can also see that some of the advice takes an optional parameter which provides direct access to the return value or the exception instance. 
</p>

<h3>Preparing your application</h3>
<p>
To make this work you finally need to tell AspectWerkz which classes you want to make "advisable" and to which extent. This is done in the <code>META-INF/aop.xml</code> deployment descriptor in which you have to make use of the <code>&lt;advisable .../&gt;</code> element. This element has two attributes:
<ul>
    <li>
    <code>expresssion</code> - here you specify the type pattern that picks out the classes that you want to make "advisable" and this is done by defining a <code>within(&lt;TYPE PATTERN&gt;)</code> pointcut expression 
    </li>

    <li>
    <code>pointcut-type</code> - here you defined which pointcut semantics you want the added advice to follow
    <br/>
    Valid types are:
    <ul>
        <li>
        <code>call</code> - the advice added to a method will be invoked on the caller side of the method invocation (if you think client-server then it is executing on the client side)
        </li>
        <li>
        <code>execution</code> - the advice added to a method will be invoked on the execution side of the method invocation
        </li>
        <li>
        <code>set</code> - the advice added to a field will be invoked when a field is modified 
        </li>
        <li>
        <code>get</code> - the advice added to a field will be invoked when a field is accessed
        </li>
        <li>
        <code>all</code> - a combination of all the above pointcut types
        </li>
        Or any combination of these separated by a <i>|</i> character.
    </ul>
    </li>
</ul>
</p>

<p>
Example:
<pre>
    &lt;aspectwerkz&gt;
        &lt;system id="intercept-sample"&gt;
            &lt;advisable expression="within(my.application.domain.*)" pointcut-type="call|set|get"/&gt;
        &lt;/system&gt;
    &lt;/aspectwerkz&gt;
</pre>
</p>

<h3>Bringing it all together</h3>
<p>
So now we have talked about the <code>Advisable</code> interface that we can use to add the advice we want to a specific instance. We have talked about the different <code>Advice</code> interfaces and their differences. Finally we talked about how we tell the AspectWerkz container which classes it should make "advisable" and how it should treat them. Let's now try to bring it all together in a small example.
</p>

<p>
In this example we are taking a regular POJO and we are adding an advice that will be applied to all methods that are annotated with the annotation <code>@OneWay</code> and turn the otherwise synchronous invocations into ansynchronous invocations.  
<pre>
    ...

    POJO pojo = new POJO();

    ((Advisable) pojo).aw$addAdvice(
        "@OneWay * *.*(..)",
        new AroundAdvice() {
            private Executor m_threadPool = Executors.newCachedThreadPool();

            public Object invoke(JoinPoint jp) throws Throwable {
                m_threadPool.execute(
                    new Runnable() {
                        public void run() {
                            try {
                                // proceed with the invocation in a new thread
                                jp.proceed();
                            } catch (Throwable e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                );
                return null;
            }
        }
    );

    ...
</pre>

The <code>META-INF/aop.xml</code> file looks like this:
<pre>
    &lt;aspectwerkz&gt;
        &lt;system id="intercept-sample"&gt;
            &lt;advisable expression="within(sample.intercept.POJO)" pointcut-type="call"/&gt;
        &lt;/system&gt;
    &lt;/aspectwerkz&gt;
</pre>
</p>

<h3>Resources</h3>
<p>
I have not written any specific sample application for this article but if you want you can look at and run the tests in the AspectWerkz distribution. You can download the distribution <a href="http://aspectwerkz.codehaus.org/releases.html">here</a>. The tests are in <code>./src/test/test/intercept/*</code> directory and you can run them (along with all the other tests) by invoking <code>ant test</code> when standing in the AspectWerkz distribution's root dir.
</p>
Enjoy]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2005-01-06T17:10:17+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000913_aspect_hot_deployment_in_practice_implementing_a_jmx_monitoring_aspect_.html">
<title>Aspect hot deployment in practice: Implementing a JMX monitoring aspect </title>
<link>http://blogs.codehaus.org/people/jboner/archives/000913_aspect_hot_deployment_in_practice_implementing_a_jmx_monitoring_aspect_.html</link>
<description><![CDATA[<p>
One of the new features in the <a href="http://aspectwerkz.codehaus.org/index.html">AspectWerkz 2</a> architecture is the ability to deploy and undeploy aspects at runtime, e.g. to do "hot" deployment and undeployment. 
</p>

<p>
The implementation is based on <i>HotSwap</i> class redefinition and handles 'change sets' which ensures that the changes to each single join point is atomic. What this means in practice is that if you for example are deploying an aspect which has one before and one after advice, both advising the <b>same</b> join point (method/field etc.) then either <b>both</b> of them will be added <b>or none</b>.
</p>

<p>
The API exposed to the user is very simple and straight forward to use. Everything is handled by the <code>Deployer</code> class, which provides the following API for runtime deployment and undeployment of aspects:

<pre>
    DeploymentHandle deploy(Class aspect)
    DeploymentHandle deploy(Class aspect, ClassLoader deployLoader)
    DeploymentHandle deploy(Class aspect, DeploymentScope scope)
    DeploymentHandle deploy(Class aspect, DeploymentScope scope, ClassLoader deployLoader)
    DeploymentHandle deploy(Class aspect, String xmlDef)
    DeploymentHandle deploy(Class aspect, String xmlDef, ClassLoader deployLoader)
    DeploymentHandle deploy(Class aspect, String xmlDef, DeploymentScope scope)
    DeploymentHandle deploy(Class aspect, String xmlDef, DeploymentScope scope, ClassLoader deployLoader)
    void undeploy(Class aspect)
    void undeploy(Class aspect, ClassLoader loader)
    void undeploy(DeploymentHandle deploymentHandle)
</pre>

As you can see you can for example choose to deploy an annotation defined aspect, e.g. a regular Java5 class with AspectWerkz defined annotations (or a regular Java 1.3/1.4 class with AspectWerkz defined JavaDoc annotations, compiled with AspectWerkz's JavaDoc annotation compiler): 

<ul>
    <li>
in the context classloader (just specify the aspect class)
    </li>
    <li>
in an arbitrary class loader (this option is most useful for application server vendors that can garantuee that all the dependecies can be resolved) 
    </li>
    <li>
within a specific <code>DeploymentScope</code> (more about this in a minute)  
    </li>
</ul>

You can read more about how you can use the <code>DeploymentHandle</code> (that is returned from each of these methods) <a href="http://aspectwerkz.codehaus.org/dynamic_aop.html">here</a>.
</p>

<p>
You also deploy a class without any annotation definition and pass in the definition in XML format. Here you pass in a string containing the <code>&lt;aspect&gt;...&lt;/aspect&gt;</code> part of the regular <code>aop.xml</code> definition (see the <a href="http://aspectwerkz.codehaus.org/xml_definition.html">online docs</a> for details).
</p>

<h2>Use-case: Implementing a JMX monitoring aspect</h2>
<p>
Now let's take a look at a concrete example on how to hot deploy an aspect that can do some monitoring for us, report that to an JMX MBean and then undeploy it when the monitoring is done. 
</p>

<h3>Writing the aspect</h3>
<p>
So first, here is the (main parts of the) JMX monitoring aspect:
<pre>
    @Aspect
    public class ResponseTimeAspect {

        ... // methods for registering the MBean lazily, member fields etc.

        // the "invocationsToMonitor" pointcut will be defined at deployment time 
        // in the aop.xml file
        @Around("invocationsToMonitor")
        public Object monitor(StaticJoinPoint jp) throws Throwable {
            Signature signature = jp.getSignature();
            long tsStart = System.currentTimeMillis();
            Object result = null;
            try {
                result = jp.proceed();
            } finally {
                // note: this code is using a JMX helper method and  
                // we will have one MBean per jointpoint signature (i.e. method, field, etc.) 
                long tsElapsed = System.currentTimeMillis() - tsStart;
                ObjectInstance mbeanI = registerMBean(signature);
                if (mbeanI != null) {
                    m_mbeanServer.invoke(
                        mbeanI.getObjectName(),
                        "update",
                        new Object[]{new Long(tsElapsed)},
                        new String[]{long.class.getName()}
                    );
                }
            }
            return result;
        }

        public static void enableMonitoring(String pointcut) { ... }

        public static void disableMonitoring() { ... }
    }
</pre>
As you can see, this aspect is defined using Java5 annotations, but if you are using Java 1.3/1.4 you can define the annnotations using JavaDoc (just put the annotation exactly as it is in the JavaDoc for the method/class) and run <code>AnnotationC</code> on the class. Then the rest in this article should stay the same. You can read more about the <code>AnnotationC</code> compiler <a href="http://aspectwerkz.codehaus.org/attribute_definition.html#Aspect_annotation_compilation">here</a>. 
</p>

<h3>Hot deploy and undeploy the aspect</h3>
<p>
As you can see we have added two static methods to the aspect, these will be used to enable and disable the response time aspect. E.g. deploy it and undeploy it.
</p>

<p>
First we have the <code>enableMonitoring</code> method, which enables monitoring in our application, e.g. deploys the monitoring aspect. This method can be invoked at <b>any</b> point in time, all threading issues etc. are handled by the underlying implementation. Here we make use of the XML definition to resolve the annotation definition in the aspects by defining the "abstract pointcut" that we have bound the advice to (the <i>invocationsToMonitor</i> pointcut). 
</p>

<p>
<pre>
    public static void enableMonitoring(String pointcut) {
        String xmlDef = "&lt;aspect&gt;&lt;pointcut name='invocationsToMonitor' expression='" + pointcut + "'/&gt;&lt;/aspect&gt;";
        Deployer.deploy(ResponseTimeAspect.class, xmlDef);
    } 
</pre>
</p>

<p>
Second we have the <code>disableMonitoring</code> method which disables monitoring for us, e.g. undeploys the aspect from <b>all</b> the join points where it had been defined (see the concept of <a href="http://aspectwerkz.codehaus.org/dynamic_aop.html"><code>DeploymentHandle</code></a>s for a more fine grained undeployment API). 
<pre>
    public static void disableMonitoring() {
        Deployer.undeploy(ResponseTimeAspect.class);
    } 
</pre>
</p>

<h3>Use the aspect to monitor JDBC SQL statements</h3>
<p>
This means that in the user code, all we need to do to enable and disabling this aspect is to invoke these two methods. Here we will monitor the executions of all JDBC statements:
<pre>
    public static void trackResponseTimeOfSqlQueries() {
        ResponseTimeAspect.enableMonitoring("call(* java.sql.Statement+.execute*(..))");

        ... // wait a while to do a recording  

        ResponseTimeAspect.disableMonitoring();
    }
</pre>
</p>

<p>
What this pointcut expression (<code>call(* java.sql.Statement+.execute*(..))</code>) actually means is: 
<br/>
<ul>
    <li>
Pick out all method calls (<code>call(..)</code>)
    </li>
    <li>
to alll methods that has a name that starts with <code>execute</code> (<code>execute*</code>) 
    </li>
    <li>
that can have any parameter types (<code>(..)</code>) or return type (<code>*</code>)
    </li>
    <li>
that are in a concrete class that implements the <code>java.sql.Statement</code> interface (<code>java.sql.Statement+</code>) 
    </li>
</ul>
By basing the pointcut expression on an interface we can be igonrant of how the actual JDBC driver is implemented (concrete subclasses etc.).
</p>

<p>
Note: we could in this specific use-case benefit from retrieving and storing the parameter value to the <code>execute*(..)</code> methods, since it is the actual <i>SQL query</i> that we are monitoring the execution time of. This could be done really easy but is out of scope for this article.   
</p>

<p>
So now after doing some monitoring you should be able to easily see the data in any JMX console. For example hook in <i>JConsole</i> which you can read more about in <a href="http://www.onjava.com/pub/a/onjava/2004/09/29/tigerjmx.html">this article</a>.
</p>

<h3>Define a deployment scope</h3>
<p>
Finally, to get this to work in the general case we need to define a <i>deployment scope</i> which defines the set potential join points that we might want to monitor at runtime. 
</p>

<p>
This construct gives you (as a application developer or vendor) control over which join points are exposed to the hot deployment API i.e. helps to prevent usage of the hot deployment facilities in specific areas of the application.   
</p>

<p>
This can be done either in the <code>META-INF/aop.xml</code> file or using annotations in the aspect class. In this case we want to make the aspect generic so we will define it in the external XML definition:
<pre>
    &lt;aspectwerkz&gt;
        &lt;system id="monitoring"&gt;
            &lt;deployment-scope name="response_time" expression="call(* sample.deployment..*.*(..))"/&gt;
        &lt;/system&gt;
    &lt;/aspectwerkz&gt;
</pre>
</p>

<p>
Here we have defined a deployment scope that picks out all method calls in our sample application, which means that we can safely deploy our <code>ResponseTimeAspect</code> at these points. (We could have added something like <code>AND within(package..*)</code> to the expression if we wanted to narrow down the scope.)  
</p>

<p>
In the code above we have an implicit contract that says that we can not define the aspect to be deployed outside a deployment scope. If we do not define a pointcut that is wider than this it is all fine. But we can now use this <i>deployment scope</i> to ensure that we only deploy the aspect at valid points. To do that we need to retrieve a handle to the scope like this (can be done at any point):  
<pre>
    DeploymentScope scope = SystemDefinition.getDefinitionFor(loader, systemId).getDeploymentScope("response_time");
</pre>
</p>

<p>
Now we can use the <code>DeploymentScope</code> handle to make a more explicit deployment (e.g. knowing exactly the points where our aspect will be applied): 
<pre>
    Deployer.deploy(ResponseTimeAspect.class, xmlDef, scope);
</pre>
</p>

<h3>Notes on the impact of the deployment scope preparation</h3>
<p>
The preparation made by the <i>deployment scope</i> construct means in practice that we are simply adding a level of indirection by adding a call to a <code>public static final</code> method that redirects to the target join point (method, field, constructor). This method will be inlined by all modern JVMs. 
</p>

<p>
When we do undeploy of an aspect, if this aspect is the last one that affects the join point, then the class' bytecode will be reverted to the same state it had before any aspect was deployed.     
</p>

<h3>Resources</h3>

<h4>More info about the JMX ResponseTimeAspect</h4>
<p>
The code for the monitoring aspect is based on the implementation of the <code>ResponseTimeAspect</code> in the <a href="http://docs.codehaus.org/display/AWARE">AWare Project</a>. The only difference is that in this example I am defining it using Java5 annotations and I have added the two static methods for doing the deployment and undeployment. You can read more about this aspect <a href="http://docs.codehaus.org/display/AWARE/ResponseTimeAspect">here</a> and the source code for it can be found <a href="https://aspectwerkz-aware.dev.java.net/source/browse/aspectwerkz-aware/components/jmx/main/org/codehaus/aware/jmx/#dirlist">here</a>. 
</p>

<p>
You can also check out the complete AWare project which has some tests for the JMX module. Info about how to check out the sources can be found <a href="https://aspectwerkz-aware.dev.java.net/source/browse/aspectwerkz-aware/">here</a>.
</p>

<h4>More info about the Deployer Module</h4>
<p>
I have not written any specific sample application for this article but if you want you can look at and run the tests for the deployer module in the AspectWerkz distribution. You can download the distribution <a href="http://aspectwerkz.codehaus.org/releases.html">here</a>. The tests are in <code>./src/jdk15/test</code> directory and you can run them by invoking <code>ant test:jdk15</code> when standing in the AspectWerkz distribution's root dir.
</p>

<p>
The <code>aspectwerkz*.jar</code> jars and the dependency jars are in the <code>./lib</code> folder in the AspectWerkz distribution.
</p>

Enjoy.]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-12-15T04:12:02+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000915_cglib_proxies_are_doing_aspectwerkz.html">
<title>CGLIB proxies are doing AspectWerkz</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000915_cglib_proxies_are_doing_aspectwerkz.html</link>
<description><![CDATA[<h3>The idea</h3>
<p>
After implementing the <a href="">AW Proxy</a> extension to <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> I figured, why not hook into the most widely used proxy implementation out there: <a href="http://cglib.sourceforge.net/">cglib</a> and let AspectWerkz weave in the aspects that are around just before the proxy is returned to the user.  
</p>

<h3>The solution</h3>
<p>
So, this is all that this <i>cglib</i> extension does: asks AspectWerkz if it has anything to say about the class that has just been proxied. If so, then let the AspectWerkz weaver do its job, e.g. weave in the aspects that are currently deployed (on the classpath), and when returns the proxy to the user. 
</p>

<p>
If no AspectWerkz aspects are found that has pointcuts that matches the class being proxied then nothing happens.
</p>

<p>
All that was needed to make this work was to add 30 lines of code to <b>one</b> single <i>cglib</i> class. 
</p>

<h3>How do I use it?</h3>
<p>
This means that all you need to do to make <b>any</b> <i>cglib</i> based applications, and there are many: <a href="http://geronimo.apache.org/">Geronimo</a>, <a href="https://dynaop.dev.java.net/">dynaop</a>, <a href="http://www.springframework.org/">Spring AOP</a>, <a href="http://www.hibernate.org/">Hibernate</a> etc., become "aspectwerkz-aware" is to <b>replace one single class</b> in the <code>cglib.jar</code> jar. 
</p>
<p>Or.</p>
<p>
If you can't or don't want to patch the <code>cglib.jar</code> jar, you can just put the class <b>before</b> the jar on the classpath.  

</p>


<h3>What is the impact on my existing code?</h3>
<p>
If no AspectWerkz aspects are found that has pointcuts that matches the class being proxied then nothing happens.
And if AspectWerkz is not available then the whole process is skipped. So basically, there is nothing to loose, it is pay as you go (or should I rather say: gain as you go ;-) ).
</p>

<h3>How do I get it?</h3>
<p>
The single file you need can be found in the AspectWerkz RC2 distribution, which you can find <a href="http://aspectwerkz.codehaus.org/releases.html">here</a>.  
</p>

<p>
The cglib extension is in the <code>./src/cglib-ext</code> dir (in the root of the AspectWerkz distribution). So step into this directory and type <code>ant dist</code> and it will compile the class and put it in a jar that is to be found in the <code>./src/cglib-ext/target</code>. This jar only contains one single class file (which you either put in the <code>cglib.jar</code> jar or make sure that it is before the jar on the classpath). 
</p>

<p>
In the <code>./src/cglib-ext</code> dir you also have a sample that you can run. This sample is just a sample taken from the <i>cglib</i> distribution, but it has a tracing aspect on the classpath, that is weaved into the proxy. You can run this test by invoking <code>ant samples:trace</code>. 
</p>

<p>
Enjoy.
</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-12-13T19:50:08+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000914_awproxy_proxy_on_steroids.html">
<title>AWProxy: Proxy on steroids</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000914_awproxy_proxy_on_steroids.html</link>
<description><![CDATA[<h3>Summary</h3>
<p>
Proxies are an important piece in the J2EE puzzle. Since it offers a non-intrusive an more transparent way of weaving in advice/interceptors. However, non of the current proxy implementations utilizes all the rich semantics of AOP (as defined by AspectJ), the expressiveness of a real pointcut pattern language and has the speed of statically compiled code. 
</p>

<p>
<i>AW Proxy</i> is here to try to narrow this gap. It makes use of the rich semantics for AOP in AspectWerkz and is very high-performant due to the use of static compilation (utilizing the AspectWerkz weaver). All wrapped up a very simple and intuitive API.  
</p>

<h3>The need for proxies</h3>
<p>
The two arguments against load-time weaving that we hear the most are:
<ul>
    <li>
    that it is complex - 
    <br/>
    which is an argument that I don't understand, since all you need to do is to add one single VM option when starting up the VM 
    </li>
    <br/>
    <li>
    that the transparency of proxies is hard to beat - 
    <br/>
    which is an argument that I can fully agree on 
    </li>
</ul>
</p>

<p>
Adding the possibility of using <a href="http://aspectwerkz.codehaus.org/index.html">AspectWerkz</a> together with proxies is something that <a href="http://blogs.codehaus.org/people/avasseur/">Alex</a> and I have been talking about for a long time but never implemented due to lack of time. Well, this weekend I took the time and it was actually more simple than I thought. 
</p>

<p>
After a couple of hours coding (taking the <a href="http://cglib.sourceforge.net/">cglib</a> route with its "class proxy", e.g creating a new class on-the-fly that extends the target class and which methods and constructors delegates to the base class' methods, but with the difference that they don't wrap the arguments but pass them on as they are, which gives a lot better performance), I had a working solution. 
</p>

<h3>Introducing AW Proxy</h3>
<p>
The benefit with using the AspectWerkz Proxies compared to the regular load time weaving is that there are no VM options. You simply create your proxy and before it is returned to you it is weaved with the aspects that happens to be available on the classpath at that time.
</p>

<p>
The API is pretty straight forward. All you need is in the 
<pre>
    org.codehaus.aspectwerkz.proxy.Proxy
</pre> 
class which has the following API:
<pre>
    // Returns a new proxy for the class specified
    public static Object newInstance(Class clazz);

    // Returns a new proxy for the class specified, instantiates it by invoking the constructor 
    // with the argument list specified
    public static Object newInstance(Class clazz, Class[] argumentTypes, Object[] argumentValues);

    // Same as above, but with optional parameters for caching and making the proxy advisable 
    public static Object newInstance(Class clazz, boolean useCache, boolean makeAdvisable);

    // Same as above, but with optional parameters for caching and making the proxy advisable 
    public static Object newInstance(Class clazz, Class[] argumentTypes, Object[] argumentValues, 
                                     boolean useCache, boolean makeAdvisable);
</pre>
</p>

<ul>
    <li>
        <p>
        The <code>makeAdvisable</code> argument decides if the proxy instance should be <i>advisable</i>, e.g. be prepared for runtime programmatic deployment. More on this later in this article. 
        </p>
    </li>
    <li>
        <p>
        The <code>useCache</code> argument decides if the <code>Proxy</code> should try to reuse an already compiled proxy class for the specific target class. 
        </p>
        <p>
        If you set this flag to <code>true</code> then a cached class it is returned (if found) e.g. no new proxy class is compiled. This has both benefits and drawbacks. The benefits being that if there is a new aspect that has been deployed that advises a <b>new</b> join point in the target class then these new join points will not be advised (but already advised join points will be redefined). 
        </p>
        <p>
        However if you set this flag to <code>false</code> then a new proxy class will be compiled for each invocation of the method, which will make the invocation a bit slower but you will get a completely new proxy class that is advised at <b>all</b> matched join points.  
        </p>
    </li>
</ul>

<h3>How to use the API?</h3>
<p>
Here is a little example on how to use the <code>Proxy</code> API:
<pre>
    // creates and instantiates a new proxy for the class Target
    Target target = (Target) Proxy.newInstance(Target.class, false);
</pre> 
</p>

<p>
That's it! 
</p>

<p>
This <code>target</code> instance have now been advised with all the aspects that have been found on the classpath that matches the members of the <code>Target</code> class.  
</p>

<h3>Utilizing programmatic runtime deployment</h3>
<p>
As I said before, when you create your proxy it will get automatically weaved with all the matching aspects that are found (on the classpath). This is most of the time what you want and need, but there might be cases when you want to add a specific feature, at runtime, to a specfific instance only. In these cases you need <i>programmatic runtime per instance deployment</i>.
</p>

<p>
One of the new features in the <a href="http://aspectwerkz.codehaus.org/index.html">AspectWerkz 2</a> architecture is that it comes with a full-blown interception framework that allows per instance programmatic deployment with most of  the AOP semantics preserved.
</p>

<p>
In short you will get: 
<br/>
Per instance programmatic deployment for <i>before</i>, <i>around</i>, <i>after</i>, <i>after finally</i> and <i>after throwing</i> advice types for <i>call</i>, <i>execution</i>, <i>set</i> and <i>get</i> pointcuts as well as the expressiveness of the AspectWerkz' pointcut pattern language all wrapped up in a very simple and intuitive API.  
</p>

<p>
<pre>
    POJO pojo = new POJO();

    // adds tracing to all methods in the 'pojo' instance
    ((Advisable) pojo).aw$addAdvice(
        "* *.*(..)",
        new BeforeAdvice() {
            public Object invoke(JoinPoint jp) {
                System.out.println("Entering: " + jp.getSignature().toString());
            }
        }
    );
</pre>
</p>

<p>
The advice "interceptors" that are supported are:
<ul>
    <li>
    <code>AroundAdvice</code> - works like a regular interceptor and is invoked "around" or "instead-of" the target method invocation or field access/modification.
    </li>
    <li>
    <code>BeforeAdvice</code> - is invoked before the actual member invocation
    </li>
    <li>
    <code>AfterAdvice</code> - is invoked after the actual member invocation, is invoked both if the method returns normally or with an exception. E.g. can be seen as being invoked in the <code>finally</code> block.
    </li>
    <li>
    <code>AfterReturning</code> - is invoked after the actual method has returned normally 
    </li>
    <li>
    <code>AfterThrowingAdvice</code> - is invoked after the actual method has returned with an exception 
    </li>
</ul>

</p>

<p>
Now we can combine use this feature together with the AW Proxies. All proxies that are created implements the <code>Advisable</code> interface which makes it really easy and straightforward to use them together:  
</p>

<h4>Example</h4>
<p>
In this example we create and instantiate a new proxy for the class <code>Target</code>, we set it to become <i>advisable</i> (e.g. it will implement the <code>Advisable</code> interface transparently), and then we add an <i>after returning</i> advice to all methods that returns an instance of <code>java.lang.String</code>.
<pre>

    Advisable target = (Advisable) Proxy.newInstance(Target.class, true, true);
    target.aw$addAdvice(
        "String *.*(..)",
        new AfterReturningAdvice() {
            public void invoke(JoinPoint jp, Object returnValue) {
                // do some stuff     
            }
        }
    );
</pre>
</p>

<h3>Benefits</h3>
<h3>Plain proxies with rich AOP semantics</h3>
<p>
The benefits are, besides a less intrusive and more transparent approach, that you can utilize the rich semantics for AOP (well, not all, see below for limitations) that are supported AspectWerkz. Such as, a rich pointcut expression language, before/after/around advice, deployment modules defined by the <code>META-INF/aop.xml</code> file etc. 
</p>

<h3>Very high-performant</h3>
<p>
You will also get the full performance of the AspectWerkz 2 architecture. 
</p>

<p>
If you are interested details of the benchmark we made (and/or run it yourself) then you can read <a href="http://docs.codehaus.org/display/AW/AOP+Benchmark">this paper</a>. 
</p>

<p>
But in short <i>AW Proxy</i> is roughly:
<ul>
    <li>
    25 times faster than <i>Spring AOP</i> for before and after advice  
    </li>
    <li>
    8 times faster than <i>Spring AOP</i> for around advice  
    </li>
    <li>
    16 times faster than <i>dynaop</i> for before and after advice  
    </li>
    <li>
    5 times faster than <i>dynaop</i> for around advice  
    </li>
    <li>
    4 times faster than straight <i>cglib</i> for before and after advice  
    </li>
    <li>
    1.25 times faster than straight <i>cglib</i> for around advice  
    </li>
</ul>
</p>

<h3>Limitations</h3>
<p>
Since it is a proxy approach it only supports <code>execution</code> pointcuts and can only advise methods and constructors that is non-private and non-final. E.g not <code>call</code>, <code>set</code>, <code>get</code> or <code>handler</code> pointcuts. Advice bound to these pointcut types will simply not affect the class being proxied.
</p>

<h3>Resources</h3>
<p>
This new feature will be available in <i>AspectWerkz 2.0 RC2</i> that will be available soon. Until then you can check out the sources from the <a href="http://aspectwerkz.codehaus.org/cvs.html">CVS</a> and build it yourself (by invoking <code>ant dist</code>).
</p>

<p>
There are some samples in the <code>./src/samples/examples/proxy</code> dir in the distribution. These can be executed by invoking <code>ant samples:proxy</code> from the command line.
</p>

<p>
Enjoy.
</p>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-12-08T05:31:44+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000909__spring_and_aspectwerkz_a_happy_marriage_v2.html">
<title> Spring and AspectWerkz: A Happy Marriage v2</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000909__spring_and_aspectwerkz_a_happy_marriage_v2.html</link>
<description><![CDATA[<p>
The <a href="http://aspectwerkz.codehaus.org/index.html">AspectWerkz 2</a> architecture has been designed to be an <i>Extensible Aspect Container</i>, which can deploy and run arbitrary aspects. You can read more about the details in <a href="http://www.theserverside.com/articles/article.tss?l=AspectWerkzP1">this article</a>.
</p>

<p>
In this article I will show you how you can make use of this container to run <a href="http://www.springframework.org/">Spring AOP</a> aspects more performant plus utilize the annotation-driven AOP in AspectWerkz along with its more expressive pointcut pattern language. 
</p>

<p>
In this article I am using Spring as an example but everything covered here applies to all frameworks that implements the <a href="http://aopalliance.sourceforge.net/">AOP Alliance</a> interfaces (e.g. dynaop, JoyAop, JAC etc.).
</p>

<h3>Write a regular Spring advice</h3>
<p>
First we write a regular spring advice that implements authentication:
<pre>
    public class AuthenticationAdvice implements MethodBeforeAdvice {

        public void before(Method m, Object[] args, Object target) throws Throwable {
            // try to authenticate the user
            // if not authenticated throw a SecurityException  
        }
    } 
</pre>
</p>

<h3>Define the advice using Java 5 annotations</h3>
<p>
In this example we will not define this advice using the slightly verbose Spring config file. But make use of Java 5 annotations. In AspectWerkz you have a set of predefined annotations that we can use, f.e. one for each advice type. The advice we have implemented here is a <i>before advice</i> so we will use the <code>@Before</code> annotation when defining the advice:
<pre>
    public class AuthenticationAdvice implements MethodBeforeAdvice {

        @Before("authenticationPoints")
        public void before(Method m, Object[] args, Object target) {
            // try to authenticate the user
            // if not authenticated throw a SecurityException  
        }
    } 
</pre>
Here we bind the advice to the pointcut named <code>"authenticationPoints"</code>, this pointcut will pick out all the points where we want authentication to take place. However we do not define this pointcut yet. Since we want to make this aspect reusable, then it is better to just compile it, put it in a jar and then at deployment time resolve this definition by defining the pointcut in the external <code>META-INF/aop.xml</code> file. 
</p>

<p>
We can of course choose to not define the pointcut in an external XML file but directly in the <code>Before</code> annotation like this: 
<pre>
    @Before("call(@RestrictedOperation * *.*(..))")
    public void before(Method m, Object[] args, Object target) {
        ... 
    }
</pre>
if we think that that is beneficial. (Then the <code>META-INF/aop.xml</code> only have to define the aspect class name, see below for details). 
</p>

<h3>Define the pointcut in the external aop.xml file</h3>
<p>
Now all we need to do put this advice to work is to write the little <code>META-INF/aop.xml</code> file.
In this case there are two things that we need to define there:
<ul>
    <li>
    we need to tell the AspectWerkz container that it should deploy this Spring advice as a regular AspectWerkz aspect 
    </li>
    <li>
    we need to resolve the definition by defining the "authenticationPoints" pointcut
    </li>
</ul>
Example:
<pre>
    &lt;aspectwerkz&gt;
        &lt;system id="spring-extension-sample"&gt;
            &lt;aspect class="my.application.aspects.AuthenticationAdvice"&gt;
                &lt;pointcut name="authenticationPoints" expression="call(@RestrictedOperation * *.*(..))" /&gt;
            &lt;/aspect&gt;
        &lt;/system&gt;
    &lt;/aspectwerkz&gt;
</pre>
Here we defined the pointcut to pick out all method calls to a method that is marked with the annotation <code>@RestrictedOperation</code>.    
</p>

<p>
Note that we are using a <i>call</i> pointcut here, which means that this advice will execute on the client side and not the server (something that is not possible with regular spring aop which only supports <i>execution</i> pointcuts). This can be beneficial in many situations, it can f.e. can save us a remove call from the client to the server, or take some load off the server if the client is executing in a separate VM, etc.
</p>

<h3>Start up the application</h3>
<p>
The last thing we need to do is to add two VM options:
<ul>
    <li>
    we need to register the <i>Aspect Model</i> implementation for the Spring extension in the AspectWerkz container. This is done like this:
    <br/>  
    <code>-Daspectwerkz.extension.aspectmodels=org.codehaus.aspectwerkz.transform.spring.SpringAspectModel</code>
    </li>
    <li>
    we need to register the AspectWerkz weaver agent:  
    <br/>  
    <code>-javaagent:lib/aspectwerkz-jdk5-RC2.jar</code>
    </li>
</ul>
You also need to put the <code>aspectwerkz-core-RC2.jar</code>, <code>aspectwerkz-RC2.jar</code>, <code>aw-ext-spring-0.1.jar</code> and <code>aw-ext-aopalliance-0.1.jar</code> plus the regular AspectWerkz dependency jars on the classpath. (You find the aspectwerkz jars in the aspectwerkz distribution and the aw-ext-*.jar jars you need to build yourself (see Resources for details).
</p>

<p>
The you can start up the application as usual using <code>java ...</code>.
</p>

<p>
We have been thinking of providing a way of defining the spring aspect model on the application level (per <code>META-INF/aop.xml</code> file) and not only on the VM level (using a VM option). If there is interest in this, please get back to us and we will add support for this.
</p>

<!--p>
This means that we can start up the application like this:
<pre>
    # set AspectWerkz version and libs dependancies
    set VERSION=2.0.RC1
    set DEPS=... // AspectWerkz dependancies - see bin/setEnv for the complete list

    # all AspectWerkz jar, and dependancies
    set AW_PATH=aspectwerkz-core-$VERSION.jar:aspectwerkz-$VERSION.jar:$DEPS

    # -javaagent option
    # adapth the path to aspectwerkz-core-$VERSION.jar as required
    java -javaagent:lib/aspectwerkz-jdk5-$VERSION.jar -cp $AW_PATH:... \
         -Daspectwerkz.extension.aspectmodels=org.codehaus.aspectwerkz.transform.spring.SpringAspectModel \ 
         ... my.application.Main 
</pre>
</p-->

<h3>What about my Spring bean config file, dependency injection etc?</h3>
<p>
Good news is that you can still use your regular Spring bean config file and let Spring do its job, with dependency injection, bean configurations etc.  
</p>

<p>
AspectWerkz has a pluggable factory mechanism for the aspect instantiation and life-cycle management. We have written a factory for the Spring framework that allows you to use Spring to configure your aspects/advice just as usual. Read more about that <a href="http://blogs.codehaus.org/people/jboner/archives/000826_spring_and_aspectwerkz_a_happy_marriage.html">here</a>.
</p>

<h3>Much better performance</h3>
<p>
Apart from allowing defining your aspects using Java5 annotations and using the semantics of the AspectWerkz pointcut language and weaver, you will also get <b>much</b> better performance (ranging between 1300 to 50 percent). I won't go into detail on that here but you can read more about it in <a href="http://docs.codehaus.org/display/AW/AOP+Benchmark">this article</a>. 
</p>

<h3>Drawbacks</h3>
<p>
Everything has tradoffs and there are of course some drawbacks in using the <i>AspectWerkz Extensible Aspect Container</i> as the runtime environment for your Spring aspects/advice: 
<ul>
    <li>
    You will weave the actual target classes - this is a more intrusive way of doing the weaving, which in some cases perhaps is not beneficial
    </li>
    <li>
    You need a couple of extra VM options when you start up your application.
    </li>
    <li>
    You need one extra XML (very tiny) config file - the <code>META-INF/aop.xml</code> file
    </li>
</ul>
</p>

<h3>Resources</h3>
<p>
I have not written any specific sample application for this article but if you want you can look at and run the tests in the AspectWerkz distribution. You can download the distribution <a href="http://aspectwerkz.codehaus.org/releases.html">here</a>. The tests are in <code>./src/compiler-extensions/spring/src/test</code> directory and you can run them by invoking <code>ant test</code> when standing in the <code>./src/compiler-extensions/spring</code> directory. However these tests does not use the Java5 annotation syntax but only the XML definition to define the aspects. But you should be able to modify the tests as you like.
</p>

<p>
The <code>aspectwerkz*.jar</code> jars and the dependency jars are in the <code>./lib</code> folder in the AspectWerkz distribution, but the <code>aw-ext-*.jar</code> jars you need to build yourself. This is done by stepping into the  <code>./src/compiler-extensions/spring</code> directory and type <code>ant dist</code> then the jar will be put into the <code>./src/compiler-extensions/spring/lib</code> directory, use same procedure to build the AOP Alliance extension jar.  
</p>

Enjoy.]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-12-06T13:36:41+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000870_interviewed_on_javahispanoorg.html">
<title>Interviewed on javaHispano.org</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000870_interviewed_on_javahispanoorg.html</link>
<description><![CDATA[<p/>
I gave an interview for the spanish Java community site <a href="http://www.javahispano.org/canyamo.action">javaHispano.org</a>. 
<p/>
Here is the
<a href="http://www.javahispano.org/text.viewer.action?file=jonas_en">english version</a>.
<p/>]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-11-02T08:28:42+01:00</dc:date>
</item>
<item rdf:about="http://blogs.codehaus.org/people/jboner/archives/000826_spring_and_aspectwerkz_a_happy_marriage.html">
<title>Spring and AspectWerkz - A Happy Marriage</title>
<link>http://blogs.codehaus.org/people/jboner/archives/000826_spring_and_aspectwerkz_a_happy_marriage.html</link>
<description><![CDATA[<p/> 
<a href="http://www.springframework.org/">The Spring Framework</a> is a very powerful library for J2EE development. It comes with an AOP implementation (based on proxies) that is in many cases sufficient in terms of what you need to do. However, there are many situations where you need a more full-blown AOP framework (such as <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a>) to do the job. 

<p/> 
On the other hand <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> (even though it has a decent API for configuration and management) could sometimes benefit from more finegrained and expressive configuration and life-cycle management, which is one thing that <a href="http://www.springframework.org/">Spring</a> does very well.

<p/> 
In short, it is sometimes beneficial to use these two frameworks together and I will now show you a first step on how you can make that happen.

<p/> 
<a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> has a very open architecture in regards to
instantiation, configuration and management of the aspects. Here I will show you how you can make use of this to
take control over your aspects using <a href="http://www.springframework.org/">Spring</a>. (The concepts are the same for <a href="http://picocontainer.org/">PicoContainer</a>
, <a href="http://jakarta.apache.org/hivemind/index.html">HiveMind</a> or a home-grown IoC implementation.)

<p/> 
In <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> instantiation, management and configuration of aspects is handled by an "aspect
container" and to make it easier for users to provide their own custom implementation
it provides the abstract
<code>org.codehaus.aspectwerkz.aspect.AbstractAspectContainer</code>
class which handles all the nitty-gritty details. 

<p/> 
All we have to do is to extend the
<code>org.codehaus.aspectwerkz.aspect.AbstractAspectContainer</code> 
class and implement the abstract <code>Object createAspect()</code> method.

<p/> 
So let us do that. Here is the implementation of our <code>SpringAspectContainer</code>:

<pre> 
public class SpringAspectContainer extends AbstractAspectContainer {

    public static final String SPRING_ASPECT_CONTAINER_CONFIG = "spring-bean-config.xml";

    /**
     * The Spring bean factory.
     */
    private XmlBeanFactory m_factory = null;

    /**
     * Creates a new aspect container strategy that uses the Spring framework to manage aspect instantiation and
     * configuaration.
     *
     * @param crossCuttingInfo the cross-cutting info
     */
    public SpringAspectContainer(final CrossCuttingInfo crossCuttingInfo) {
        super(crossCuttingInfo);
    }

    /**
     * Creates a new aspect instance.
     *
     * @return the new aspect instance
     */
    protected Object createAspect() {
        if (m_factory == null) {
            InputStream is = null;
            try {
                is = ClassLoader.getSystemResourceAsStream(SPRING_ASPECT_CONTAINER_CONFIG);
                m_factory = new XmlBeanFactory(is);
            } finally {
                try {
                    is.close();
                } catch (Throwable e) {
                    throw new WrappedRuntimeException(e);
                }
            }
        }

        // here we are letting Spring instantiate the aspect based on its name 
        // (the m_infoPrototype field is the CrossCuttingInfo instance passed to the base class) 
        return m_factory.getBean(m_infoPrototype.getAspectDefinition().getName());
    }
}
</pre> 

<p/> 
This is all that is needed implementation wise. Now we only have to define which
aspects should be managed by our new container and configure the aspect in the
Spring bean config file. 

<p/> 
To tell the <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a> system that we want to deploy a specific aspect in our
custom aspect container we have to specify that in the regular
<code>aop.xml</code> file like this:

<pre> 
&lt;aspect class="some.package.MyAspect" container="some.other.package.SpringAspectContainer"&gt;
    ...
&lt;/aspect&gt;
</pre> 

<p/> 
 For details on the <code>aop.xml</code> file (what it is, how it is used etc.) see the <a href="http://aspectwerkz.codehaus.org/startup_and_runtime_issues.html#Handling_several_Aspects_across_several_deployed_applications">online documentation</a>.

<p/> 
To configure the aspect we just configure it like any other <a href="http://www.springframework.org/">Spring</a> bean class:

<pre> 
&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;

&lt;beans&gt;
    &lt;bean id="some.package.MyAspect"
          class="some.package.MyAspect"
          singleton="false"
          init-method="intialize"&gt;
        &lt;property name="someProperty"&gt;
            ...
        &lt;/property&gt;
        ...
    &lt;/bean&gt;
    ...
&lt;/beans&gt;
</pre> 

<p/> 
For details on how to define your bean classes see the <a href="http://www.springframework.org/documentation.html">Spring documentation</a>. But
here are some explainations:
<ul>
    <li>
     <b>id</b> - specifies the name of the aspect if a custom name is define you that else use the class name of the aspect (which is the default name). Mandatory.
    </li>
    <li>
    <b>class</b> - specifies the class name of the aspect. Mandatory.
    </li>
    <li>
    <b>singleton</b> - specifies if the aspect will be instantiated using the prototype pattern or not. Mandatory.
    </li>
    <li>
    <b>init-method</b> - the init-method is the method that you are using to initialize the aspect. This method will be called when all the properties have been set. Optional.
    </li>
    <li>
    <b>property</b> - the metadata that you want to pass to the aspect (see the Spring documentation for details on how how to define properties). Optional.
    </li>
</ul>

<p/> 
<a href="http://www.springframework.org/">Spring</a> has great support for passing in expressive metadata. It for example allows you
to pass in lists, maps of for example strings, primitives or custom objects, and arrange them pretty much as you like.

<p/> 
Here is a more interesting example on how you can configure an aspect using
Spring's properties. This aspect
implements role-based security and is part of the <a href="http://docs.codehaus.org/display/AWARE">AWare</a>
aspect library:

<pre> 
&lt;bean id="org.codehaus.aware.security.RoleBasedAccessProtocol"
    class="org.codehaus.aware.security.RoleBasedAccessProtocol"
    singleton="false"
    init-method="intialize"&gt;

    &lt;property name="type"&gt;
        &lt;value&gt;JAAS&lt;/value&gt;
    &lt;/property&gt;

    &lt;property name="roles"&gt;
        &lt;list&gt;
            &lt;value&gt;admin&lt;/value&gt;
            &lt;value&gt;jboner&lt;/value&gt;
        &lt;/list&gt;
    &lt;/property&gt;

    &lt;property name="permissions"&gt;
        &lt;list&gt;
            &lt;bean class="org.codehaus.aware.security.Permission"&gt;
                &lt;property name="role"&gt;
                    &lt;value&gt;jboner&lt;/value&gt;
                &lt;/property&gt;
                &lt;property name="className"&gt;
                    &lt;value&gt;org.codehaus.aware.security.SecurityHandlingTest&lt;/value&gt;
                &lt;/property&gt;
                &lt;property name="methodName"&gt;
                    &lt;value&gt;authorizeMe1&lt;/value&gt;
                &lt;/property&gt;
            &lt;/bean&gt;

           &lt;bean class="org.codehaus.aware.security.Permission"&gt;
                &lt;property name="role"&gt;
                    &lt;value&gt;jboner&lt;/value&gt;
                &lt;/property&gt;
                &lt;property name="className"&gt;
                    &lt;value>org.codehaus.aware.security.SecurityHandlingTest&lt;/value&gt;
                &lt;/property&gt;
                &lt;property name="methodName"&gt;
                    &lt;value&gt;authorizeMe2&lt;/value&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
        &lt;/list&gt;
    &lt;/property&gt;

&lt;/bean&gt;
 
</pre> 

<p/> 

You can find the code for the <code>SpringAspectContainer</code> along with many other reusable aspects in the <a href="http://docs.codehaus.org/display/AWARE">AWare</a> library. 
Which is a community-driven OSS library for reusable aspects for <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a>.

<p/> 



































 ]]></description>
<dc:subject>aop</dc:subject>
<dc:creator>jboner</dc:creator>
<dc:date>2004-08-31T20:01:19+01:00</dc:date>
</item>


</rdf:RDF>
