<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; aop</title>
	<atom:link href="http://blog.jayway.com/tag/aop/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Intercepting Scala trait constructors</title>
		<link>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/</link>
		<comments>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 21:40:01 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5430</guid>
		<description><![CDATA[Today I was writing an AspectJ aspect for a Scala trait and was wondering why my constructor pointcut definition didn't work. Having a closer look at the Scala byte code together with my colleague Johan solved the puzzle. Here is what I did (using AspectJ 1.6.8 and Scala 2.8.Beta1): To start with here's a simplified [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was writing an AspectJ aspect for a Scala trait and was wondering why my constructor pointcut definition didn't work. Having a closer look at the Scala byte code together with my colleague Johan solved the puzzle. Here is what I did (using AspectJ 1.6.8 and Scala 2.8.Beta1):</p>
<p>To start with here's a simplified version of the trait that I wanted to intercept:</p>
<pre class="brush:scala">
trait MyTrait {
    var someStuff = "someStuff"
    def someMethod() : String = {
        "do something"
    }
}

class SomeClass extends MyTrait
</pre>
<p>As I wanted to intercept the constructor and some method calls I defined my aspect like this:</p>
<pre class="brush:java">

public aspect MyAspect {

	public pointcut newInstance() : execution(MyTrait+.new(..));

	public pointcut someInvocation() : execution(String MyTrait+.someMethod(..));

	after() : newInstance() {
	    System.out.println("after MyTrait constructor invocation");
	}

	after() : someInvocation() {
	    System.out.println("after someMethod invocation");
	}
}
</pre>
<p>Runnning the code I got quite puzzled that the method invocation pointcut worked fine, but not the constructor pointcut. After consulting the AspectJ reference and convincing myself that the pointcut definition was ok, I had a closer look at the byte code. As we don't have traits in Java the byte code for my trait becomes equivalent to the following pseudo-javacode:</p>
<pre class="brush:java">
public interface MyTrait extends scala.ScalaObject{
    public String someMethod();
}

public abstract class MyTrait$class extends java.lang.Object{
    public static String someMethod(MyTrait myTrait) {
      // invoke someMethod
    }
    public static void $init$(MyTrait myTrait) {
      // some init stuff
    }
}
</pre>
<p>So in bytecode I've got an interface and a class with some static method calls. The stuff that goes in the constructor of my trait is done in the <code>$init$</code> method of the <code>MyTrait$class</code> class. And that's the reason why my pointcut won't work. So actually I have to intercept the <code>$init$</code> method of the <code>MyTrait$class</code> to get what i want:</p>
<pre class="brush:java">
public pointcut newInstance() : execution(void MyTrait$class.$init$(..));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Architectural Enforcement with Aid of AspectJ</title>
		<link>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/</link>
		<comments>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 17:50:57 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4991</guid>
		<description><![CDATA[After working some time within the software industry, you get a feeling for good software architecture. Or, to be more honest, you get a creeping feeling when the architecture is really bad. That is when the code is tangled like a Gordian knot. After some futile refactoring attempts, you consult the software architect at your [...]]]></description>
			<content:encoded><![CDATA[<p>After working some time within the software industry, you get a feeling for good software architecture. Or, to be more honest, you get a creeping feeling when the architecture is really bad. That is when the code is tangled like a Gordian knot. After some futile refactoring attempts, you consult the software architect at your company and you will be given a design document stating the architectural principles that should be obeyed during software development. It is a nifty piece of paper and you can tell by looking at it that someone has spent a lot of time working out how the software should be structured. The bad news is that it has little resemblance of the current state of the code base. </p>
<h2>Recipe</h2>
<p>So how can you shape up the code? Yet better, how can you prevent that the code turns into spaghetti in the first place? One way of looking at architectural requirements is that they are crosscutting concerns that are scattered throughout the software. As such, they can be implemented and enforced by using AOP, <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">aspect-oriented programming</a>. The recipe is pretty straight forward:</p>
<ol>
<li>Implement a pointcut that finds the violations of your architecture.</li>
<li>Implement an advice that notifies you about the violations.</li>
<li>Wrap the pointcut and the advice into an aspect.</li>
<li>Refactor your code and exercise your aspect until all architectural violations have been removed.</li>
</ol>
<h2>Example</h2>
<p>This recipe of using aspects as a way of enforcing architectural rules can be applied in any kind of project, for example to enforce the MVC pattern, to separate one domain from another in a DDD project and so on. In this particular example, the application is based on a three layer architecture. The top layer being the GUI layer, the middle layer is the service layer and then there is the DAO layer in the bottom. Each layer has a separate package, as stated below:</p>
<table width="90%">
<colgroup>
<col width="2*"/>
</colgroup>
<colgroup>
<col width="1*"/>
</colgroup>
<tbody>
<tr>
<td>
<h4>SomeGui.java</h4>
<pre class="brush:java">
package com.jayway.application.gui;

/** Simplistic GUI */
public interface SomeGui {

    /** Renders the GUI */
    void render();
}
</pre>
<h4>SomeService.java</h4>
<pre class="brush:java">
package com.jayway.application.service;

/** Simplistic Service */
public interface SomeService {

    /** Executes some service */
    void service();
}
</pre>
<h4>SomeDao.java</h4>
<pre class="brush:java">
package com.jayway.application.dao;

/** Simplistic DAO */
public interface SomeDao {

    /**
     * Finds something in the DAO
     * @return some data
     */
    public Object find();
}
</pre>
</td>
<td>
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/architectural-enforcement.png" alt="Architectural Enforcement" class="alignright size-full wp-image-5041" />
</td>
</tr>
</tbody>
</table>
<h3>Architectural Rules</h3>
<p>Four architectural rules have been defined:</p>
<ol>
<li>The GUI layer must not access the DAO layer</li>
<li>The Service layer must not access the GUI layer</li>
<li>The DAO layer must not access the Service layer</li>
<li>The DAO layer must not access the GUI layer</li>
</ol>
<p>These rules are the candidates for defining the pointcuts that should be implemented. An example of code that would violate the first rule is:</p>
<h4>BadGuiImpl.java</h4>
<pre class="brush:java">
/**
 * Bad GUI implementation that violates the architectural rule
 * because it calls a method in the DAO layer
 */
public class BadGuiImpl implements SomeGui {

    private SomeService someService;
    private SomeDao someDao;

    @Override
    public void render() {
        // it is ok to use the service...
        someService.service();

        // ...but it is not ok to call the DAO directly
        someDao.find();    

        // more rendering
    }
}
</pre>
<p>Using <a href="http://eclipse.org/aspectj/">AspectJ</a>, two pointcuts have been implemented to trap the violation. Additionally, AspectJ also provides the <code>@DeclareError</code> annotation that can be used for the advice implementation. Finally, an aspect that comprises the pointcuts and the advice has been created:</p>
<h4> ArchitecturalEnforcement.java</h4>
<pre class="brush:java">
/**
 * The aspect that is responsible for architecture enforcement:
 * The GUI layer must not access the DAO layer.
 */
@Aspect
public class ArchitecturalEnforcement {

    /** Pointcut for finding join points inside the GUI layer */
    @Pointcut("within(*..*gui..*)")
    public void withinGui() {}

    /** Pointcut for finding method calls to the DAO layer */
    @Pointcut("call(* *..*.dao..*(..))")
    public void callDao(){}

    /** Advice that defines an error when a GUI method calls a method in the DAO layer */
    @DeclareError("withinGui() && callDao()")
    private static final String GUI_MUST_NOT_USE_DAO = "GUI must not access DAO";
}
</pre>
<h3>Exercise the Aspect</h3>
<p>How should you use your aspects to enforce the architecture? Since we now have the tools to automate the architectural review, you should use them frequently. AspectJ has support for compile time weaving which means that the advices can be woven into their corresponding join points during source code compilation. The <a href="http://mojo.codehaus.org/aspectj-maven-plugin/">aspectj-maven-plugin</a> can do it for you:</p>
<h4>pom.xml</h4>
<pre class="brush:xml">
&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
        &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;
        &lt;version&gt;1.6.7&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
    ...
&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
            &lt;artifactId&gt;aspectj-maven-plugin&lt;/artifactId&gt;
            &lt;version&gt;1.3&lt;/version&gt;
            &lt;configuration&gt;
                &lt;complianceLevel&gt;1.6&lt;/complianceLevel&gt;
            &lt;/configuration&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;compile&lt;/goal&gt;   &lt;!-- Weaves the main classes --&gt;
                        &lt;goal&gt;test-compile&lt;/goal&gt;   &lt;!-- Weaves the test classes --&gt;
                    &lt;/goals&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<h3>Result</h3>
<p>If you have put everything together correctly, you will find that you will get a compile time error when you attempt to execute <code>mvn compile</code>:</p>
<pre class="brush:shell">
[[INFO] [aspectj:compile {execution: default}]
[ERROR] "GUI must not access DAO"
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Compiler errors:
error at someDao.find();
^^^^^^^^^^^^^^
/home/mattias/architectural-enforcement/src/main/java/com/jayway/application/gui/BadGuiImpl.java:20:0::0 "GUI must not access DAO"
	see also: /home/mattias/architectural-enforcement/src/main/java/com/jayway/application/aspects/ArchitecturalEnforcement.java:1::0
</pre>
<p>You can also see the error in your Eclipse IDE if you are using the <a href="http://www.eclipse.org/ajdt/">AJDT - AspectJ Development Tools</a> plugin:<br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/eclipse-screenshot.png" alt="Eclipse Screenshot" class="alignright size-full wp-image-5357" /></p>
<p>Notably, the implementation above was just one of the stated rules. The implementation of all four rules together with some examples that break them and the Maven pom file are available for <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/architectural-enforcement.zip">download</a> for your convenience.</p>
<h2>Considerations</h2>
<p>There are some things that you may want to consider before introducing aspects as a tool for automated architectural enforcement:</p>
<ul>
<li>
<h3>Error or Warning</h3>
<p> A compile time error is a powerful tool that prevents the developer to commit any code that does not conform to the architectural rules (presumed, of course, that the code is actually compiled before being checked in). A less brutal way of introducing aspects as a part of architectural review is to use the <code>@DeclareWarning</code> annotation rather than the <code>@DeclareError</code> that was used in the example. Consequently, any architectural offenders will be punished with a compiler warning rather than a compiler error.</li>
<li>
<h3>Performance</h3>
<p> The compile time will increase when you add more architectural rules that should be obeyed, that is when you add more pointcuts. Likewise, the compile time will also increase when your code base grows, because of the increasing number of join points in the code. By limiting the <code>aspectj-maven-plugin</code> to certain maven profiles, the developers only have to verify that their particular module conforms to the rules. Alternatively, all modules can be verified by the integration server during nightly builds. The drawback is that the advantage of having the architecture enforced <i>before</i> the code is committed to the version control system will be lost.
</li>
<li>
<h3>Limitation</h3>
<p> The aspect above can only trap architectural violations when a method is being <i>called</i>. Regrettably, any <i>unused declaration</i> that would violate the architecture will pass unnoticed:</p>
<h4>AnotherBadGuiImpl.java</h4>
<pre class="brush:java">
package com.jayway.application.gui;

import com.jayway.application.dao.SomeDao;

/**
 * Another bad GUI implementation that violates the architectural rule
 * because it has references to the DAO layer.
 * However, these errors will remain undetected by AspectJ.
 */
public class AnotherBadGuiImpl implements SomeGui {

    /** Unused DAO reference */
    private SomeDao someDao;

    /**
     * Setter method that for some obscure reason adds a DAO to the GUI
     * @param someDao A DAO reference that is not found by the pointcut
     */
    public void setDao(SomeDao someDao) {
        this.someDao = someDao;
    }

    @Override
    public void render() {
        // valid gui rendering that does not use the dao reference
    }
}
</pre>
<p>One solution is to create another pointcut, such as <code>@Pointcut("set(*..*.*dao*..* *)")</code>, that traps the assignment of the <code>someDao</code> member variable.
</li>
</ul>
<h2>Wrap Up</h2>
<p>Education of the developers and repeated manual code reviews have been the traditional ways of improving software architecture. Unfortunately, it is not good enough. It is always a good idea to have skilled employees, but even experts do make mistakes. After all, people that manually review code are only humans, which implies that the reviews are resource demanding, yet error prone. With the powerful tools of today's IDEs it is very easy to do refactoring hastily and soon the code starts to degrade. With a proper implementation, AspectJ offers one way to automate architectural enforcement, hereby preventing architectural drift.</p>
<h2>Edit</h2>
<p>2010-04-16: Added screenshot of AJDT plugin and an example of how the "set" pointcut can be used.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Spring and load-time weaving of Neo4j-based domain objects</title>
		<link>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/</link>
		<comments>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/#comments</comments>
		<pubDate>Tue, 26 May 2009 07:51:25 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1773</guid>
		<description><![CDATA[What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as Neo4j Nodes. I was playing around with creating a Twitter clone, in my opinion the [...]]]></description>
			<content:encoded><![CDATA[<p>What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as <a href="http://www.neo4j.org">Neo4j</a> Nodes. </p>
<p>I was playing around with creating a Twitter clone, in my opinion the "Hello World" of graph databases, and I started out with the following simple service.</p>
<p>Spring configurating:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;beans</span> ... <span style="font-weight: bold; color: black;">&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:annotation-config</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.api.core.EmbeddedNeo&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;value<span style="font-weight: bold; color: black;">&gt;</span></span></span>var/neo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/value<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.util.index.NeoIndexService&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;twitterService&quot;</span>
		<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.twitter.neo.NeoBasedTweetService&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- Transactions --&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tx:annotation-driven</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        ...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/beans<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The service:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span>neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setKvitt</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		userNode.<span style="color: #006600;">createRelationshipTo</span><span style="color: #66cc66;">&#40;</span>tweetNode, KvittRelationships.<span style="color: #006600;">KVITTRAT</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This doesn't feel very DDD. I would really want to do the User to be responsible for creating the Tweet. Like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> userNode.<span style="color: #006600;">createTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The TweetNode and UserNode would look like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing Tweet-stuff</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//Here comes a problem! I need a new Node</span>
		<span style="color: #808080; font-style: italic;">//from the NeoService to create the TweetNode</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>NodeDelegate, extended by both User- and TweetNode implements the Neo4j interface <code>Node</code> and delegates all the method calls to the underlying node ( for more on this, see my <a href="http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/">previous post</a>) :</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>As you see I have a problem here. In the first version my NeoService is injected into NeoBasedTweetService and used when I create the new TweetNode. In the re-made, more DDD-style example I create the new TweetNode in the UserNode, where I don't have access to my NeoService. How do we solve this?</p>
<p>One alternative that I instinctively dislike is to inject the NeoService into the UserNode. The reason for me disliking this is that my UserNode IS a Node, and it feels very tangled if a Node holds a reference to its container. But I came to think of another solution thanks to a talk I did a while back together with Henrik Reinhold on what was new in Spring 2.5. </p>
<p>In Spring 2.5 load-time weaving (LTW) capabillites was introduced, and with LTW you can manipulate objects in load-time, as opposed to runtime weaving that is proxy based. This, combine it with @Configurable and @Autowired, proves to be <em>very</em> helpful when the Spring context is not in charge of creating the objects in question, as in the example above...</p>
<p>To enable LTW we add one tag in the Spring configuration:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:load-time-weaver</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;</pre>
<p>After that we have to inform the Spring container of how we want thing done. To do we edit the TweetNode and NodeDelegate like this:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">//Annotate the class with @Configurable so that Spring can find it.</span>
@Configurable
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a default constructor both in the TweetNode</span>
	<span style="color: #808080; font-style: italic;">//and the NodeDelegate, it is new:able without a Node.</span>
	<span style="color: #000000; font-weight: bold;">public</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a setter for the underlaying Node and annotate it with @Autowired.</span>
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">setNode</span><span style="color: #66cc66;">&#40;</span>nodeDelegate<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Tweet-methods as before</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>delegate == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			delegate = nodeDelegate;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now Spring only has to be able to create Nodes. To do that we create a simple NodeFactory, like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeFactory <span style="color: #000000; font-weight: bold;">implements</span> FactoryBean<span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> NeoService neo = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNeo<span style="color: #66cc66;">&#40;</span>NeoService neo<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">neo</span> = neo;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> getObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> Node.<span style="color: #000000; font-weight: bold;">class</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> isSingleton<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">false</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>... and add it to the configuration, like this:</p>
<pre class="xml">&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;node&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.neo.utils.NodeFactory&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The result of this is that Spring now has a NodeFactory that returns a new node for every request, I have annotated the TweetNode so that Spring knows of it (@Configurable) and what to do with it (@Autowired on setNode) and I've enabled load-time weaving in order to get the a new Node woven into a TweetNode every time a new instance of it is created in the code.</p>
<p>In UserNode I really don't have to make any changes. "setNode(Node)" will get a new Node after the instantiation of a TweetNode, even if the constructor that takes a Node is called. For clarity I still changed the UserNode as follows:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//This TweetNode will get a Node set by Spring</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The problem I had when trying to make the UserNode responsible for creating its TweetNode's was that I needed to inject something that could create Nodes into the UserNodes. By using load-time weaving and instructing Spring of how to wire a TweetNode I don't have to pass my NeoService around to all the UserNodes created in my code. Instead I can rely on Spring to inject what is needed, when it's needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Transparent bind of JavaFX and POJOs</title>
		<link>http://blog.jayway.com/2009/05/12/transparent-bind-of-javafx-and-pojos/</link>
		<comments>http://blog.jayway.com/2009/05/12/transparent-bind-of-javafx-and-pojos/#comments</comments>
		<pubDate>Tue, 12 May 2009 12:24:06 +0000</pubDate>
		<dc:creator>Magnus Robertsson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[javafx]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1517</guid>
		<description><![CDATA[When I started coding JavaFX I quickly found that the great bind mechanism doesn't work together very well with my legacy Java code. In fact, it doesn't work at all. In my case I wanted to reuse my domain objects and just add a fancy user interface on top of it. This happen to be [...]]]></description>
			<content:encoded><![CDATA[<p>When I started coding JavaFX I quickly found that the great <a href="http://openjfx.java.sun.com/current-build/doc/reference/Binding.html">bind mechanism</a> doesn't work together very well with my legacy Java code. In fact, it doesn't work at all. In my case I wanted to reuse my domain objects and just add a fancy user interface on top of it. This happen to be harder that I anticipated. Very annoying. Since bind is a new feature in JavaFX and all primitive types have been replaced with special object equivalents they can't interoperate with the Java primitive types. (This is another reasons why primitive types should have been objects in Java from the start.)</p>
<p>After searching on Google I found that there are two solutions for the problem which both includes an adapter class:</p>
<ul>
<li>Polling - The adapter class polls for changes in the POJO. While this solution is transparent to our POJOs it does not keep the state synchronised and is not very resource efficient.</li>
<li>Observer-pattern - The adapter class listens for changes in the POJO. This implies that we add listener mechanism to our POJOs and thus not very transparent.
</li>
</ul>
<p>Michael Heinrichs at Sun have a <a href="http://blogs.sun.com/michaelheinrichs/entry/binding_java_objects_in_javafx">great post</a> about it. The problem is that none of these solutions are really adequate.</p>
<h3>The best of both worlds</h3>
<p>Since I didn't want to change my POJOs or coding adapters I had to come up with a new strategy. We've seen how listener mechanisms can be added using AOP. Great! By adding an aspect we can mixin the functionality we need for JavaFX to be able to bind to my POJOs. Furthermore we can generate the adapters. We only need to decide what fields we need to bind to in our POJOs. These will serve as our pointcuts. The default strategy would be to select all JavaBean properties. What a great day for coding a tool coding! The result is an easy to use tool that I hosted on Google Code:</p>
<p>http://code.google.com/p/javafxbinder/</p>
<p>For example if I have a POJO like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">javafxbinder</span>.<span style="color: #006600;">example</span>.<span style="color: #006600;">domain</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> name;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">int</span> age;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Person<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> getName<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> name;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Name was set: &quot;</span> + name<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">name</span> = name;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">int</span> getAge<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> age;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAge<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> age<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">age</span> = age;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Using JavaFX binder I can run the following command to generate some JavaFX code:</p>
<pre>javafxbinder.sh -classpath ./target/classes -includes se.jayway.javafxbinder.example.domain.* -out ./output</pre>
<p>And here is what gets generated:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">javafxbinder</span>.<span style="color: #006600;">example</span>.<span style="color: #006600;">domain</span>;
&nbsp;
<span style="color: #a1a100;">import se.jayway.javafxbinder.example.domain.Person;</span>
<span style="color: #a1a100;">import se.jayway.javafxbinder.infrastructure.Bean;</span>
<span style="color: #a1a100;">import java.beans.PropertyChangeEvent;</span>
<span style="color: #a1a100;">import java.beans.PropertyChangeListener;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JfxPerson <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3APropertyChangeListener+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">PropertyChangeListener</span></a> <span style="color: #66cc66;">&#123;</span>
    public-init var pojo : Person on replace oldValue <span style="color: #66cc66;">&#123;</span>
        var oldBean : Bean = oldValue as Bean;
        oldBean.<span style="color: #006600;">removePropertyChangeListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        var newBean : Bean = pojo as Bean;
        newBean.<span style="color: #006600;">addPropertyChangeListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> var age : <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> = pojo.<span style="color: #006600;">getAge</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> on replace <span style="color: #66cc66;">&#123;</span>
        pojo.<span style="color: #006600;">setAge</span><span style="color: #66cc66;">&#40;</span>age<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>;
    <span style="color: #000000; font-weight: bold;">public</span> var name : <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> = pojo.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> on replace <span style="color: #66cc66;">&#123;</span>
        pojo.<span style="color: #006600;">setName</span><span style="color: #66cc66;">&#40;</span>name<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>;
&nbsp;
    override <span style="color: #000000; font-weight: bold;">public</span> function propertyChange<span style="color: #66cc66;">&#40;</span>event : <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3APropertyChangeEvent+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">PropertyChangeEvent</span></a><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    	<span style="color: #808080; font-style: italic;">// Make sure that we're updating in the right thread</span>
        FX.<span style="color: #006600;">deferAction</span><span style="color: #66cc66;">&#40;</span>function<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            var bean : Bean = pojo as Bean;
            bean.<span style="color: #006600;">removePropertyChangeListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event.<span style="color: #006600;">getPropertyName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;age&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                age = event.<span style="color: #006600;">getNewValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> as <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a>;
            <span style="color: #66cc66;">&#125;</span>
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event.<span style="color: #006600;">getPropertyName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;name&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                name = event.<span style="color: #006600;">getNewValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> as <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a>;
            <span style="color: #66cc66;">&#125;</span>
            bean.<span style="color: #006600;">addPropertyChangeListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>To enable the listener functionality in my POJO I need to define an aspect:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">javafxbinder</span>.<span style="color: #006600;">example</span>.<span style="color: #006600;">domain</span>;
&nbsp;
<span style="color: #a1a100;">import se.jayway.javafxbinder.infrastructure.Bean;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect MyJavaBeans <span style="color: #66cc66;">&#123;</span>
    declare parents: <span style="color: #66cc66;">&#40;</span>se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">javafxbinder</span>.<span style="color: #006600;">example</span>.<span style="color: #006600;">domain</span>.<span style="color: #006600;">Person</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">implements</span> Bean;
<span style="color: #66cc66;">&#125;</span></pre>
<h3>Conclusion</h3>
<p>Using AOP and a simple code generator is a good solution to the annoying JavaFX bind to Java problem. We use this tool for one of our clients and it works really good. However, my hope goes to someone at Sun/Oracle to integrate a similar functionality in the JavaFX compiler itself... Transparency looks good both in GUIs and in software design!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/12/transparent-bind-of-javafx-and-pojos/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Proxy Based AOP for Cocoa Touch</title>
		<link>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/</link>
		<comments>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 14:46:33 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1041</guid>
		<description><![CDATA[UITabBarController is generally used as is, no subclassing required. It creates a UITabBar and manages a list of UIViewControllers, keeping track of the tab in focus, UI creation and everything nice. UITabBarController has a delegate, the UITabBarControllerDelegate protocol. Unfortunately this is not a superset of the UITabBarDelegate protocol, and UITabBarController already implements the UITabBarDelegate protocol [...]]]></description>
			<content:encoded><![CDATA[<p><code>UITabBarController</code> is generally used as is, no subclassing required. It creates a <code>UITabBar</code> and manages a list of <code>UIViewControllers</code>, keeping track of the tab in focus, UI creation and everything nice. <code>UITabBarController</code> has a delegate, the <code>UITabBarControllerDelegate</code> protocol. Unfortunately this is not a superset of the <code>UITabBarDelegate</code> protocol, and <code>UITabBarController</code> already implements the <code>UITabBarDelegate</code> protocol itself. So how can I hook into and respond to delegate calls from the managed <code>UITabBar</code>?</p>
<p>Simply replacing the original delegate will break the default functionality. We need to somehow insert our own code to execute before the original delegates call. Or in AOP speak; a before advice.</p>
<h3>The Wanted Solution</h3>
<p>What we want is a proxy that can forward invocations both to our own delegate, and to the original delegate. The interface for said class looks looks like this:</p>
<pre class="objc"><span style="color: #0000ff;">@protocol</span> CWDelegateOverrideProxyDelegate
@required
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>shouldCallOriginalImplementationForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWDelegateOverrideProxy : <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSProxy.html"><span style="color: #0000ff;">NSProxy</span></a> <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
  id&lt;NSObject&gt; _originalDelegate;
  id&lt;NSObject&gt; _overrideingDelegate;
  id&lt;CWDelegateOverrideProxyDelegate&gt; _delegate;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; originalDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; overridingDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, assign<span style="color: #002200;">&#41;</span> id&lt;CWDelegateOverrideProxyDelegate&gt; delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And then we could use this class to replace an existing delegate with a short piece fo code like this:</p>
<pre class="objc">UITabBar* tabBar = <span style="color: #002200;">&#40;</span>UITabBar*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>self.tabBarController.view
    viewWithKindOfClass:<span style="color: #002200;">&#91;</span>UITabBar <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
CWDelegateOverrideProxy* proxy = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CWDelegateOverrideProxy alloc<span style="color: #002200;">&#93;</span>
    initWithOriginalDelegate:tabBar.delegate overridingDelegate:self<span style="color: #002200;">&#93;</span>;
tabBar.delegate = <span style="color: #002200;">&#40;</span>id&lt;UITabBarDelegate&gt;<span style="color: #002200;">&#41;</span>proxy;</pre>
<p>See <a href="http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/">my previous post</a> for the implementation of <code>viewWithKindOfClass:</code>.</p>
<p>Easy enough to use, only thing left is to implement <code>CWDelegateOverrideProxy</code>.</p>
<h3>Enter <code>NSProxy</code></h3>
<p>Java only have one root class; <code>java.lang.Object</code>. Objective-C can have many, and Cocoa defines two; <code>NSObject</code> and <code>NSProxy</code>. Both of them conforms to the protocol <code>NSObject</code>, wich can be confusing. What we need to know is that class names, and protocol names have two different name spaces in Objective-C. Imagine it as if you could have a class and an interface with the same name in Java; in Objective-C you can. <code>NSObject</code> class is the root class for all concrete classes, and <code>NSProxy</code> class is the root class for proxies, both implements <code>NSObject</code> protocol allowing them to be interchangeable.</p>
<p>Without much ado, here is the base implementation for the initializer:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWDelegateOverrideProxy.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWDelegateOverrideProxy
&nbsp;
@synthesize originalDelegate = _originalDelegate;
@synthesize overridingDelegate = _overridingDelegate;
@synthesize delegate = _delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
<span style="color: #002200;">&#123;</span>
  _originalDelegate = <span style="color: #002200;">&#91;</span>originalDelegate retain<span style="color: #002200;">&#93;</span>;
  _overridingDelegate = <span style="color: #002200;">&#91;</span>overridingDelegate retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code goes here!</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Introspection</h3>
<p>In Objective-C, just as in Java, an instance can be queried for its class, and conformance to protocols (interface in Java speak). But as a bonus an instance can also be queried for specific methods per instance.</p>
<p>Our <code>CWDelegateOverrideProxy</code> class inherits from <code>NSProxy</code>. And it makes a simple assumption; if the original delegate, or the overriding delegate is capable of something, then so it is. So if queried for type of class, protocol conformance, or implemented methods, then we reply with whatever our managed delegates replies.</p>
<p>The <code>NSObject</code> protocol defines methods, equivalent of the <code>java.lang.reflect</code> package, that allows us to implement this as such:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Testing Object Behavior, and Conformance</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>isKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>conformsToProtocol:<span style="color: #002200;">&#40;</span>Protocol *<span style="color: #002200;">&#41;</span>aProtocol;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>respondsToSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Invocation Forwarding</h3>
<p>The <code>NSObject</code> protocol also defines methods for functionality equivalent of <code>java.lang.reflect.InvocationHandler</code> and hooks to act as a <code>java.lang.reflect.Proxy</code>. The details are different as Objective-C do not enforce calls to only known methods at compile time, which means that at run-time unimplemented methods can be called.</p>
<p>When an unimplemented method is called the run-time will call <code>methodSignatureForSelector:</code>, that can return a <code>NSMethodSignature</code> instance, sort of the equivalent of a <code>java.lang.reflect.Method</code>. The run-time will then use the information from the <code>NSMethodSignature</code> instance to create a correct <code>NSInvocation</code> (other half of a <code>java.lang.reflect.Method</code>) instance, and set the correct arguments. This NSInvocation instance is then used as argument to call <code>forwardInvocation:</code>.</p>
<p>And thus our implementation is completed with:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Handling Proxy Methods</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMethodSignature.html"><span style="color: #0000ff;">NSMethodSignature</span></a>*<span style="color: #002200;">&#41;</span>methodSignatureForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.originalDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>super methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>forwardInvocation:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSInvocation.html"><span style="color: #0000ff;">NSInvocation</span></a>*<span style="color: #002200;">&#41;</span>anInvocation;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">BOOL</span> shouldCallOriginal = YES;
  <span style="color: #0000ff;">SEL</span> aSelector = <span style="color: #002200;">&#91;</span>anInvocation selector<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.overridingDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self.delegate != <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      shouldCallOriginal = <span style="color: #002200;">&#91;</span>self.delegate shouldCallOriginalImplementationForSelector:aSelector<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>shouldCallOriginal &amp;&amp; <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.originalDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre>
<p>And that rounds up how to implement a class that handles proxy based AOP, in order to introduce a before advice for delegate methods. For a more complex code base you can look at <a href="http://sourceforge.net/projects/hessiankit/">HessianKit</a>, a framework that uses proxies, invocation forwarding and dynamic class creation in order to use a web service as distributed objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Aspect Oriented Programming In Java ME</title>
		<link>http://blog.jayway.com/2008/02/01/aspect-oriented-programming-in-java-me/</link>
		<comments>http://blog.jayway.com/2008/02/01/aspect-oriented-programming-in-java-me/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 10:37:07 +0000</pubDate>
		<dc:creator>Magnus Robertsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[innovation]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3354</guid>
		<description><![CDATA[Do you want to structure your Java ME applications better? Aspect Oriented Programming is a cool technology that can modularize your applications and separate the verbose infrastructure code from the application logic. The only catch is that it doesn’t exist for Java ME. Or does it? Introduction Aspect Oriented Programming (AOP) is gaining popularity within [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Do you want to structure your Java ME applications better? Aspect Oriented Programming is a cool technology that can modularize your applications and separate the verbose infrastructure code from the application logic. The only catch is that it doesn’t exist for Java ME. Or does it? </strong></p>
<h2>Introduction</h2>
<p>Aspect Oriented Programming (AOP) is gaining popularity within the Java SE/EE communities. There are many advantages of AOP especially as it provides a clear separation of concerns. The code becomes much more modular than with<br />
traditional object technology. It’s not the intent of the article to explain all AOP<br />
concepts and if you’re new to AOP you can find a couple of introduction sites in the<br />
references section. Instead we will show how AOP can be used in CLDC enabled<br />
devices such as mobile phones.<br />
In Java ME applications there haven’t been much use of AOP. In fact, there<br />
haven’t been any AOP frameworks available at all! Until now that is. AspectME<br />
is a new open source project that delivers an AOP framework mainly targeted at<br />
CLDC devices. Maybe most importantly, AspectME adds a reflection API. Reflec-<br />
tion makes it possible to invoke methods and access fields dynamically. Advanced<br />
frameworks use reflection to enable non-intrusive and modular mechanisms. Reflec-<br />
tion is needed in AOP frameworks since we need information about where in the<br />
code the aspect is executing. </p>
<h2>What’s in the box?</h2>
<p>AspectME consists of a runtime jar file that needs to be packaged together with<br />
your Java ME application. Then we have an aspect weaver that is used to weave the<br />
aspects into the compiled classfiles. During the weaving process necessary reflection<br />
information is also added. What aspects to apply and extra reflection information is<br />
controlled by a configuration file. And that’s all. To conclude, to use AspectME you’ll<br />
need the following: </p>
<p>1. Add aspectmeruntime.jar to your Java ME project.<br />
2. Write a configuration file that defines your aspects.<br />
3. Run the aspect weaver after you’ve compiled your source code. </p>
<p>The assembly and deployment of your application is the same as before. AspectME<br />
doesn’t change or remove debugging information so you can debug your application<br />
as usual. Now, lets look at a small example. </p>
<h2>Logging example</h2>
<p>The first example is the classic logging example where we want to write enter/exit<br />
outputs to the console around certain methods. Consider the following code: </p>
<pre>public class Foo {
  public int bar(String s) {
    return Integer.intValue(s);
  }
}
</pre>
<p>It would be easy to add System.out statements when we enter and exit the method.<br />
However, it would clutter the code, especially if we want to print out if we exit from<br />
an exception:</p>
<pre>public class Foo {
  public int bar(String s) {
    System.out.println(”Enter bar()”);
    try {
      int rv = Integer.intValue(s);
      System.out.println(”Exit bar()”);
      return rv;
    } catch (Exception e) {
      System.out.println(”Exit bar() from exception ” + e);
      throw new RuntimeException(e.getMessage());
    }
  }
}
</pre>
<p>Instead we can use AspectME and write an advice that can be used to weave logging<br />
functionality into the code:</p>
<pre>
import org.aspectme.api.MethodInterceptor;
import org.aspectme.api.MethodInvocation;  

public class LoggingAdvice implements MethodInterceptor {
  public Object invoke(MethodInvocation mi) {
    // Create a pretty string
    String methodSignature = mi.getMethod().getName() + ”()”;  

    System.out.println(”Enter ” + methodSignature);  

    // Continue the method invocation
    Object rv = mi.proceed();  

    System.out.println(”Exit ” + methodSignature);
    return rv;
  }
} </pre>
<p>Now we need to define the pointcut where we want to apply the advice. In this case<br />
it’s only one joinpoint, the bar() method, but we could apply the advice to many<br />
joinpoints, e.g. all public methods in a package. AspectME uses the AspectJ pointcut<br />
language because it’s powerful and de-facto standard within the AOP community.<br />
We do this in a XML file: </p>
<pre> &lt;?xml version=”1.0”?&gt;
&lt;aspectme&gt;
  &lt;pointcut id=”barMethod” expression=”execution(* org.aspectme.example.Foo.
bar())” /&gt;     

  &lt;advice id=”log” class=”org.aspectme.example.aspects.LoggingAdvice” /&gt;  

  &lt;aspect advice-ref=”log” type=”around” pointcut-ref=”barMethod” /&gt;
&lt;/aspectme&gt;
</pre>
<p>Note that combining the parameters from the aspect definition actually describes<br />
in “plain english” what the aspect does, “log around barMethod”. Now we’re ready<br />
to weave everything together into the final executable. We do this with the weave<br />
command from a shell: </p>
<pre>weave -in classes -f aspectme.xml -out weaved_classes</pre>
<p>The weave command will analyze all classes from the classes folder and weave in the<br />
advices according to the definition in the aspectme.xml file. All modified classes will<br />
be written to the weaved_classes folder.<br />
But hey, didn’t we want to write to the console if we leave the method from an<br />
exception? With AOP this becomes a breeze: </p>
<pre>public class LoggingAdvice implements MethodInterceptor {
  public Object invoke(MethodInvocation mi) {
    // Create a pretty string
    String methodSignature = mi.getMethod().getName() + ”()”;  

    System.out.println(”Enter ” + methodSignature);  

    // Continue the method invocation
    try {
      Object rv = mi.proceed();  

      System.out.println(”Exit ” + methodSignature);
      return rv;
    } catch (Exception e) {
      System.out.println(”Exit ” + methodSignature + ” with exception ” + e);
      throw e;
    }
  }
} </pre>
<p>Note that we have totally separated the concern of logging in our example. We can<br />
easily change the logging mechanism by editing a single file, even though it’s applied<br />
in hundreds of joinpoints. </p>
<h2>Persistence example </h2>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/02/Picture-74.png" alt="Figure 1" title="Figure 1" width="303" height="154" class="alignnone size-full wp-image-3371" /></p>
<p>The previous example was simple but showed the basics of AspectME. Now lets<br />
concentrate on a more interesting example. Imagine we have an application that will<br />
manage contact information. If designed properly we would have a domain model<br />
consisting of two classes, ContactList and Contact. The ContactList contains zero or<br />
more Contact objects.<br />
The MIDlet would create the ContactList at startup and pass the model to the views.<br />
The views would use the ContactList to add and remove Contact elements. In tradition-<br />
al application design we would add a ContactListDAO that manages the persistence mechanism. The DAO object would be used from the controller whenever a contact is added or removed. Nice design? Not really since the DAO clutters the code and adds unnecessary infrastructure code into our application.<br />
Using the AOP approach we would intercept the execution at certain joinpoints<br />
as shown in the picture. We start by writing a persistence advice: </p>
<pre>public class PersistenceAdvice implements MethodInterceptor,
                                          ConstructorInterceptor {  

  /**
   * Stores the target object after invocation.
   * @param invocation The joinpoint of the method invocation.
   * @return The return value from the method invocation.
   */
  public Object invoke(MethodInvocation invocation) throws Throwable {
    // Run the target method
    Object result = invocation.proceed();  

    // Store the object
    store(invocation.getThis());  

    // Return the result
    return result;
  }  

  /**
   * Loads an object from the record store instead of creating it.
   * @param invocation The joinpoint of the constructor call.
   * @return The created object.
   */
  public Object construct(ConstructorInvocation invocation) throws Throwable
{
    Object obj = load();
    // If this is the first time we load the object we’ll get a null object.
    // In that case we need to create the object, i.e. proceed with the
    // normal execution.
    if (obj == null) {
      obj = invocation.proceed();
    }
    return obj;
  }  

  private void store(Object obj) throws IOException {
    // Store the passed object into the record store by serializing it
    // to the record store
  }  

  private Object load() throws IOException {
    Object obj = null;
    // Load the specified object from the record store
    return obj;
  }
}
</pre>
<p>The advice implements both the MethodInterceptor and ConstructorInterceptor.<br />
The MethodInterceptor is used to intercept methods that changes the object and<br />
store them in the record store. In our case the ContactList. The ConstructorIn-<br />
terceptor is used to intercept the creation of ContactList objects, so rather than<br />
creating them it will load them from the record store. This means that anywhere in<br />
the code we execute “new ContactList()” we would load the object and return the<br />
loaded object instead of creating it.<br />
The serialization of objects can be made using the reflection API in AspectME.<br />
An ObjectOutputStream reads the field values from the written object and primi-<br />
tive fields are written to the DataOutputStream. Objects are written recursively.<br />
Counterwise we have an ObjectInputStream that reads objects by writing the field<br />
values by reading them from a DataInputStream. The result is very similar to Java<br />
SE serialization mechanism as shown in the code example below. </p>
<pre>public Object storeAndLoad(Object obj) {
  // Write object to byte array
  ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
  ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
  objOut.writeObject(obj);
  objOut.close();
  byteOut.close();
  byte[] bytes = byteOut.toByteArray();  

  // Read object from the byte array
  ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
  ObjectInputStream objIn = new ObjectInputStream(byteIn);
  return objIn.readObject();
}
</pre>
<p>If you’re interested in the implementation of the classes you can find them in the<br />
code examples on the AspectME home page (see References).<br />
All that’s left is to define our aspects in an aspectme.xml file: </p>
<pre>&lt;?xml version=”1.0”?&gt;
&lt;aspectme&gt;
   &lt;pointcut id=”addRemoveMethods”
             expression=”execution(*
*..domain.ContactList.addContact(..)) ||
                         execution(*
*..domain.ContactList.removeContact(..))” /&gt;
   &lt;pointcut id=”newContactList”
expression=”call(*..domain.ContactList.new())” /&gt;
   &lt;advice id=”persist”
class=”org.aspectme.example.aspects.PersistenceAdvice” /&gt;
   &lt;aspect advice-ref=”persist” type=”around”
pointcut-ref=”addRemoveMethods” /&gt;
   &lt;aspect advice-ref=”persist” type=”around”
pointcut-ref=”newContactList” /&gt;
   &lt;!-- This will add reflection information for all objects
in the specified package. --&gt;
   &lt;reflect include=”org.aspectme.example.contact.domain.*” /&gt;
&lt;/aspectme&gt;
</pre>
<p>After the weaving process our application will store the ContactList object into the<br />
record store whenever a contact is added or removed. When the application is run<br />
again the ContactList object is loaded from the record store. The application can<br />
still run without the persistence aspect but all contact information will be lost when<br />
the application closes. A good example of how crosscutting concerns creates total<br />
transparency of an application mechanism. </p>
<h2>Summary </h2>
<p>AspectME is a promising AOP framework that can be used to take advantage of<br />
AOP in CLDC enabled devices. The reflection capabilities add new dimensions to<br />
CLDC applications such as object serialization. We have seen how advices can be<br />
built and reused over many applications since it crosscuts the concern of persist-<br />
ence. The performance impact is acceptable when dealing with large concerns such<br />
as persistence. The bytecode footprint increases a couple of KB but that is a small<br />
price to pay for the increased modularity. Often the footprint becomes smaller as we<br />
gather all copy’n’paste like infrastructure code into small advices. </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/02/01/aspect-oriented-programming-in-java-me/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Mock using AspectJ</title>
		<link>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/</link>
		<comments>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/#comments</comments>
		<pubDate>Fri, 16 Feb 2007 09:00:08 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=284</guid>
		<description><![CDATA[After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way.]]></description>
			<content:encoded><![CDATA[<p>After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way. For example how would we mock the following class?</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StupidSingleton <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> doStatic<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AUnsupportedOperationException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">UnsupportedOperationException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;method not implemented yet...&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #993333;">void</span> sayHello<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Hello&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">void</span> nativeMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>We would like to write something like this:</p>
<pre class="java">&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testMocking<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mock<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		expect<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;17&quot;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		replay<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;17&quot;</span>, StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verify<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>After playing around with <a href="http://www.eclipse.org/aspectj/">AspectJ</a> I discovered that this is actually possible! Two things are needed:<br />
* An aspect that allows us to catch calls to static methods!<br />
* An implementation of the mock, replay, verify for classes</p>
<p>This turns out to be really easy! The following aspect catches ALL calls to ALL static methods. Might be a bit aggressive, but it works! If you want you can implement your own aspect with a more specialized pointcut.</p>
<pre class="java">&nbsp;
@Aspect
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAll <span style="color: #000000; font-weight: bold;">extends</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	@Pointcut<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;call(static * *(..))&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> anyStaticOperation<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Around<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;anyStaticOperation()&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">aroundStaticMethods</span><span style="color: #66cc66;">&#40;</span>jp<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The mock, replay, verify methods turns out to be trivial:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMock <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">static</span> Map&lt;Class, MockInvocationHandler&gt; mocks = <span style="color: #000000; font-weight: bold;">new</span> HashMap&lt;Class, MockInvocationHandler&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> mock<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		MockInvocationHandler h = <span style="color: #000000; font-weight: bold;">new</span> MockInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MocksControl<span style="color: #66cc66;">&#41;</span> EasyMock.<span style="color: #006600;">createControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		mocks.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>type, h<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> replay<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> verify<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Finally, the base class for the aspect that does the actual work is also quite simple:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">Class</span> type = jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringType</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInvocationHandler+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InvocationHandler</span></a> h = getInvocationHandler<span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>h == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> jp.<span style="color: #006600;">proceed</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
		MethodSignature methodSignature = <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MethodSignature<span style="color: #66cc66;">&#41;</span>jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> h.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>type, methodSignature.<span style="color: #006600;">getMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, jp.<span style="color: #006600;">getArgs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> MockInvocationHandler getInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #66cc66;">&#40;</span>StaticMock.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> StaticMock.<span style="color: #006600;">mocks</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>h3. Notes</p>
<p>Things to note and think about:<br />
* Static methods and native methods can be mocked! By using the "call" pointcut we change all code that tries to call the native methods and not the native method itself.<br />
* AspectJ is required to make this work. I have been using <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a><br />
* It should be possible to replace the Aspect with "plain" byte code manipulation and "just" reload the class. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Indented Tracing Using AspectJ</title>
		<link>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/</link>
		<comments>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/#comments</comments>
		<pubDate>Fri, 15 Dec 2006 15:36:14 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tracing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=188</guid>
		<description><![CDATA[Given inspiration from the book "AspectJ In Action", I wrote a little aspect that provides indented tracing of method executions. This means that the aspect keeps track of the current indentation level in a call flow, giving an output like the following: Entering [org.springframework.ldap.LdapTemplateListTest.] Exiting [org.springframework.ldap.LdapTemplateListTest.] Entering [org.springframework.ldap.LdapTemplateListTest.setUp] Entering [org.springframework.ldap.LdapTemplate.] Entering [org.springframework.ldap.DefaultNamingExceptionTranslator.] Exiting [org.springframework.ldap.DefaultNamingExceptionTranslator.] Exiting [...]]]></description>
			<content:encoded><![CDATA[<p>Given inspiration from the book "AspectJ In Action", I wrote a little aspect that provides indented tracing of method executions. This means that the aspect keeps track of the current indentation level in a call flow<span id="more-188"></span>, giving an output like the following:</p>
<pre>Entering [org.springframework.ldap.LdapTemplateListTest.]
Exiting [org.springframework.ldap.LdapTemplateListTest.]
Entering [org.springframework.ldap.LdapTemplateListTest.setUp]
  Entering [org.springframework.ldap.LdapTemplate.]
    Entering [org.springframework.ldap.DefaultNamingExceptionTranslator.]
    Exiting [org.springframework.ldap.DefaultNamingExceptionTranslator.]
  Exiting [org.springframework.ldap.LdapTemplate.]
  Entering [org.springframework.ldap.LdapTemplate.setExceptionTranslator]
  Exiting [org.springframework.ldap.LdapTemplate.setExceptionTranslator]
Exiting [org.springframework.ldap.LdapTemplateListTest.setUp]
Entering [org.springframework.ldap.LdapTemplateListTest.testList_Name]
  Entering [org.springframework.ldap.LdapTemplateListTest.expectGetReadOnlyContext]
  ...</pre>
<p>The part that keeps track of the indentation level was written as a reusable aspect:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.apache.commons.logging.Log;</span>
<span style="color: #a1a100;">import org.apache.commons.logging.LogFactory;</span>
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Abstract logging aspect for producing indented logging. Override the
 * &lt;code&gt;loggingOperations&lt;/code&gt; pointcut in order to provide the joinpoints
 * where you would like the logging to be applied. Also override the methods
 * &lt;code&gt;beforeLog&lt;/code&gt; and &lt;code&gt;afterLog&lt;/code&gt; to provide the actual
 * logging statements. The current indentation string will be provided to these
 * methods, along with an instance of &lt;code&gt;JoinPoint&lt;/code&gt;.
 *
 * @author Ulrik Sandberg
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> aspect IndentedLogging <span style="color: #66cc66;">&#123;</span>
    Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;trace&quot;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * The current number of indentation levels.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">int</span> indentationlevel = <span style="color: #cc66cc;">0</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide pointcut to log.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide the actual logging statement for when the logged
     * method is entered.
     *
     * @param indent
     *            The string of spaces that provides the current indentation.
     * @param joinPoint
     *            Information about the current joinpoint.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide the actual logging statement for when the logged
     * method is exited.
     *
     * @param indent
     *            The string of spaces that provides the current indentation.
     * @param joinPoint
     *            Information about the current joinpoint.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> around<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>: loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a> sb = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>log.<span style="color: #006600;">isInfoEnabled</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            indentationlevel++;
            <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>, spaces = indentationlevel * <span style="color: #cc66cc;">2</span>; i &amp;lt; spaces; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot; &quot;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
            beforeLog<span style="color: #66cc66;">&#40;</span>sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, thisJoinPoint<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> result;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
            result = proceed<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>log.<span style="color: #006600;">isInfoEnabled</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                afterLog<span style="color: #66cc66;">&#40;</span>sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, thisJoinPoint<span style="color: #66cc66;">&#41;</span>;
                indentationlevel--;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> result;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Since the reusable aspect does all the grunt work, the actual tracing aspect becomes rather small:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        <span style="color: #66cc66;">&#40;</span>execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> || execution<span style="color: #66cc66;">&#40;</span>*.<span style="color: #000000; font-weight: bold;">new</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Entering [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Exiting [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Now, let's say we don't want to trace each and every method and constructor execution, but rather a small subset, like for example only the normal methods (no constructors) in any subclass of <code>NameClassPairCallbackHandler</code>. We'll remove the execution of <code>new</code> from the pointcut and add the handler subclass condition:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// just plain methods</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; within<span style="color: #66cc66;">&#40;</span>org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">NameClassPairCallbackHandler</span>+<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// added</span>
    ...</pre>
<p>The output becomes:</p>
<pre>Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair]
  Entering [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair]
  Exiting [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair]
Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList]</pre>
<p>You might argue that it would be good to see the arguments to each call. That could easily be done by using <code>JoinPoint.getArgs()</code> in the tracing aspect. It would look like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        <span style="color: #66cc66;">&#40;</span>execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; within<span style="color: #66cc66;">&#40;</span>*..<span style="color: #006600;">NameClassPairCallbackHandler</span>+<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Entering [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
                + createParameterMessage<span style="color: #66cc66;">&#40;</span>indent, joinPoint<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Exiting [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
                + createParameterMessage<span style="color: #66cc66;">&#40;</span>indent, joinPoint<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> createParameterMessage<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a> sb = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;(&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> args = joinPoint.<span style="color: #006600;">getArgs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>args.<span style="color: #006600;">length</span> &amp;gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>    &quot;</span> + indent<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; args.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>i != args.<span style="color: #006600;">length</span> - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">','</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
        sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>And the output would be this:</p>
<pre>Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair(
    o=example.com: com.example.SomeClass)]
  Entering [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair(
      o=example.com: com.example.SomeClass)]
  Exiting [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair(
      o=example.com: com.example.SomeClass)]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair(
    o=example.com: com.example.SomeClass)]
Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList()]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList()]</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
