<?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; Magnus Robertsson</title>
	<atom:link href="http://blog.jayway.com/author/magnusrobertsson/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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>6</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>Java ME Testing Done Right</title>
		<link>http://blog.jayway.com/2007/02/01/java-me-testing-done-right/</link>
		<comments>http://blog.jayway.com/2007/02/01/java-me-testing-done-right/#comments</comments>
		<pubDate>Thu, 01 Feb 2007 14:55:35 +0000</pubDate>
		<dc:creator>Magnus Robertsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[mockme]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3513</guid>
		<description><![CDATA[Is there a right or wrong way to unit test applications? We believe so. Especially when it comes to testing Java ME applications. Down-scaled copies of our faithful testing frameworks are popping up everywhere in the Java ME community. But has anyone dared to ask the question: Why? The Problem Java Micro Edition (Java ME) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Is there a right or wrong way to unit test applications? We believe so. Especially when it comes to testing Java ME applications. Down-scaled copies of our faithful testing frameworks are popping up everywhere in the Java ME community. But has anyone dared to ask the question: Why? </strong></p>
<h2>The Problem</h2>
<p>Java Micro Edition (Java ME) is the most ubiquitous application platform for mobile devices. However, testing Java ME applications is not a simple task. The constraints on the Virtual Machine (VM), the limited resources and the not-always-so-well-designed APIs are all contributors to this statement. The limited environment has ”forced” application developers to write their code as compact as possible. On many an occasion this has led to an unsound application design that isn’t test friendly. In a test friendly design, the collaborators of an object can easily be stubbed. Such a design is often called a testable design. There are architectural patterns such as dependency injection that can be used to achieve a testable design. Even though this is mostly used in enterprise applications, it can be used with most modern programming languages and environments.<br />
The ability to stub collaborating objects is great when testing code. We can create<br />
fake or ”mock” instances of our collaborating objects and set up an expected behav-<br />
ior for them. By doing this, we can isolate the code being exercised and verify that<br />
the behavior of the collaborating objects was met, i.e. verify that the code under test<br />
actually did what we intended it to do. This is known as unit testing based on mock<br />
objects. Those who are inexperienced with this kind of testing can ﬁ nd some good<br />
articles on the subject in the References section located at the end of this article.<br />
In the Java SE world, there are excellent tools like JUnit and EasyMock for creat-<br />
ing unit tests based on mock objects. Since Java ME doesn’t support reﬂ ection, we<br />
have lighter versions of JUnit, such as J2MEUnit, JMUnit and Mobile JUnit. As the<br />
Connected Limited Device Conﬁ guration (CLDC) VM doesn’t support dynamic<br />
object creation, we can’t use EasyMock and have to write the mock objects our-<br />
selves.<br />
Even if you have a testable design, there are more issues that make unit testing dif-<br />
ﬁ cult in Java ME: </p>
<ul>
<li> Creating mock objects is tedious and error prone. There are tools that can help<br />
you generate code for your mock objects, but you have to regenerate these if you<br />
change your objects, otherwise you may encounter version conﬂ icts. This is why<br />
dynamic frameworks like EasyMock have gained such popularity.
<li> Running unit tests on the target platform takes time. Even if it only takes a minute<br />
to install and run some tests, it may be enough to make you not want to run the<br />
tests every time you change your code. Running JUnit tests in Eclipse takes a cou-<br />
ple of seconds. Furthermore, the limited environment puts a constraint on how<br />
many tests you can run on your Java ME device. This forces you to split your test<br />
cases between several test suites, creating even longer turn-around times.
<li> Automation of tests is difﬁ cult. You’ll need a physical device attached to your<br />
build server to run your tests.
<li> The test suite setup is done manually with Java ME unit testing frameworks. Each<br />
time you add or remove a test, you have to update your test suite setup. This takes<br />
unnecessary time and is error prone.
</ul>
<p>These issues lead the Java ME developers to the darker side of testing: integration<br />
unit testing. Integration unit testing means that you don’t fully isolate your unit un-<br />
der test, but rather let it talk to real instances of all or some of its collaborators. There<br />
are however some problems with integration unit testing: It catches errors too late in<br />
the development process, it’s complex to set up, and it often causes seemingly end-<br />
less problems when trying to manage the test data. Unit tests based on mock objects,<br />
on the other hand, require a minimum of test data, they are written together with<br />
your production code, and they verify that your code actually does what you want it<br />
to do. Java SE has elegant solutions to all of the above issues. Why not use them? </p>
<h2>Introducing MockME </h2>
<p>For Java ME developers, there is an underlying assumption that unit tests need to be<br />
run on the target device. This is not true. Consider a Java EE project: An enterprise<br />
application may be targeted to run on an application server on other hardware and<br />
JVM vendor from our development environment. The unit tests are still run in<br />
the development environment. How does it work? The ability to ”write once, run<br />
everywhere” is one of the greatest strengths of Java. However, any experienced Java<br />
developer knows that this is not completely true. There can be some compatibility<br />
issues (e.g. threading), but for unit tests this will not be a problem. We’re only testing<br />
a small unit in a controlled setup.<br />
Given that the above statement is true, we could run our tests in a Java SE en-<br />
vironment and utilize all its excellent tools! This is the basic idea behind MockME;<br />
to write unit tests for Java ME applications and run them in Java SE. So how does<br />
it work? MockME contains empty objects for CLDC, Mobile Information Device<br />
Proﬁ le (MIDP), and other JSRs designed to run in Java SE. Then we use EasyMock<br />
to create mock objects dynamically from MockME. Now, some might ask: ”Why<br />
not create the mock objects from the classes in a wireless toolkit (WTK)”? Unfor-<br />
tunately, these toolkits contain native methods that can’t be mocked. Even if it was<br />
possible, EasyMock can’t mock static methods, such as RecordStore.openRecordS<br />
tore(String,boolean). MockME solves this by delegating static method invocations<br />
to a static delegate instance with a special method name. Let’s have a look at the<br />
inner workings:</p>
<h3>RecordStore.java</h3>
<pre>
public class RecordStore {
  // Used to delegate static method invocations
  private static RecordStore _delegate;
  // Used to set static delegate, i.e. a mock object
  public static void setStaticInstance(RecordStore delegate) {
    _delegate = delegate;
  }
  // The static method delegates to a non-static equivalent
  public static RecordStore openRecordStore(String recordStoreName,
                                            boolean createIfNecessary)
      throws RecordStoreException,
             RecordStoreFullException,
             RecordStoreNotFoundException {
    return _delegate.static_openRecordStore(recordStoreName, createIfNeces-
sary);
  }
    // This method represent the static method and can be mocked!
    protected RecordStore static_openRecordStore(String recordStoreName,
                                                 boolean createIfNecessary)
          throws RecordStoreException,
                 RecordStoreFullException,
                 RecordStoreNotFoundException {
        return null;
    }
    // ...
}</pre>
<p>By creating a mock object and setting the static instance, we fake the static method<br />
invocations. No real magic here, but it’s important to make the development of Java<br />
ME unit tests much simpler. </p>
<h2>MockME In Action</h2>
<p>OK, after motivating MockME, let’s look at a small example: </p>
<h3>MessageDao.java</h3>
<pre>public class MessageDao {
  private static ﬁ nal String RECORD_STORE_NAME = ”MessageDao”;
  public void addMessage(Message message) throws RecordStoreException {
    RecordStore recordStore = null;
    try {
      // This static method invocation is normally hard to mock
      recordStore = RecordStore.openRecordStore(RECORD_STORE_NAME, true);
      byte[] bytes = encodeMessage(message);
      if (message.getId() == -1) {
        message.getId() = recordStore.addRecord(bytes, 0, bytes.length);
      } else {
        recordStore.setRecord(message.getId(), bytes, 0, bytes.length);
      }
    } ﬁ nally {
      if (recordStore != null) {
        recordStore.closeRecordStore();
      }
    }
  }
  private byte[] encodeMessage(Message message) {
    // Convert message to bytecode
    byte[] bytes = ...;
    // Not important for the example and therefore omitted
    return bytes;
  }
}
</pre>
<p>The class above is an example of a simple Data Access Object (DAO). It allows us<br />
to store and access messages from a record store. Now, we’d like to create a unit test<br />
for the addMessage() method. It’s especially important to make sure that we always<br />
close the record store after use. This should be done even if we get a RecordStore-<br />
FullException. Let’s create test methods for both cases: </p>
<h3>MessageDaoTest.java</h3>
<pre>public class MessageDaoTest extends TestCase {
  private MessageDao messageDao;        // Object under test
  private RecordStore recordStoreMock;  // Mock object
  // Called by JUnit to initialize the test
  public void setUp() {
    // Create mock object for RecordStore and use the special method
    // provided by MockME to set the static instance
    recordStoreMock = createMock(RecordStore.class);
    RecordStore.setStaticInstance(recordStoreMock);
    // Create object under test
    messageDao = new MessageDao();
  }
  // Called by JUnit to clean up after each test run
  public void tearDown() {
    messageDao = null;
    recordStoreMock = null;
  }
  public void testAddMessage() throws Exception {
    // Set up expected behaviour
    byte[] expectEncMess = ”\u0004from\u0004text”.getBytes();
    expect(RecordStore.openRecordStore(”MessageDao”, true))
      .andReturn(recordStoreMock);
    expect(recordStoreMock.addRecord(aryEq(expectEncMess), eq(0), eq(10)))
      .andReturn(42);
    recordStoreMock.closeRecordStore();
    // Put the mock object in test state
    recordStoreMock.replay();
    // Executing the code we want to test
    Message message = new Message(”from”, ”text”);
    messageDao.addMessage(message);
    // Verify the behaviour
    recordStoreMock.verify(); 

    assertEquals(”Wrong message ID”, 42, message.getId());
  }
  public void testRecordStoreFull() throws Exception {
    // Set up expected behaviour
    expect(RecordStore.openRecordStore(”MessageDao”, true))
      .andReturn(recordStoreMock);
    expect(recordStoreMock.addRecord(eq(42), (byte[]) anyObject(),
                                     eq(0), eq(10)))
      .andThrow(new RecordStoreFullException());
    recordStoreMock.closeRecordStore(); 

    // Put the mock object in test state
    recordStoreMock.replay();
    // Executing the code we want to test
    try {
      Message message = new Message(”from”, ”text”);
      messageDao.addMessage(message);
      fail(”Expected exception”);
    } catch (RecordStoreFullException e) {
      assert(true); // Ok, expected
    }
    // Verify the behaviour
    recordStoreMock.verify();
  }
}
</pre>
<p>Lets look at the <strong>setUp()</strong> method. First we use EasyMock to create a mocked<br />
RecordStore object dynamically, that the MessageDao is going to write its data to.<br />
Then we invoke <strong>RecordStore.setStaticInstance()</strong> to mock all static methods<br />
in RecordStore. Static method invocations will be delegated to <strong>static_&lt;method<br />
name&gt;()</strong> equivalents.<br />
Next is the test method <strong>testAddMessage()</strong>. The method starts preparing the en-<br />
coded message and continues by setting up the expected behavior of the mock<br />
object. You do this in EasyMock by invoking methods directly on the mock object.<br />
In a sense, EasyMock ”records” these expected method invocations so it can com-<br />
pare, or replay, the expectations with the actual invocations later, when the method<br />
under test is called. If a method has a return value, you need to use a (statically<br />
imported) <strong>expect()</strong> method. By using the <strong>andReturn()</strong> method, we can return a<br />
mocked value.<br />
Before executing the code we want to test, we invoke<strong> replay()</strong> to stop the mock<br />
object from recording and set it to the replay state. All recorded method invocations<br />
will be veriﬁ ed from now on. After executing the code under test, we verify the<br />
behavior by calling <strong>verify()</strong> on all mock objects. Finally, we use a standard JUnit<br />
<strong>assert()</strong> method to assert the message ID. That’s it! The next test method uses<br />
the same principle, except that we let EasyMock throw an exception during <strong>ad-<br />
dRecord()</strong> to test that we really close the record store even if we get an exception. A<br />
test that could be quite difﬁ cult if running in a Java ME environment. This is one ex-<br />
ample of how to use MockME and EasyMock for unit testing Java ME applications.<br />
Once you get the hang of it, it’s easy to unit test your Java ME code in Java SE. </p>
<h3>Eyes On The Prize </h3>
<p>We’ve now seen how MockME has given us the opportunity to use Java SE tools,<br />
such as EasyMock, for Java ME unit tests. But there is so much more, for example<br />
code coverage. A code coverage tool is used to detect what parts of your code are<br />
executed. This is a great tool for motivating developers to write test code. A code<br />
coverage report indicates the percentage of your code that was tested (covered),<br />
normally indicated with a green bar of variable length. It’s highly motivating, and<br />
fun, to see how the green bar grows. Remember that it is not the number of test cas-<br />
es that is important, but what parts of your code are executed by your test cases.<br />
You are not limited to the above mentioned tools. You could use any Java SE unit<br />
testing tool or testing library. For example, there are libraries that simplify testing of<br />
multi-threaded classes, comparing XML documents, and so on. This would not be<br />
possible, or at least it would be very hard, if you were to use one of the traditional<br />
Java ME testing frameworks. </p>
<h3>Conclusion </h3>
<p>In this article we have shown how to write true unit tests for Java ME applications.<br />
Running the tests in a Java SE environment gives us a lot of advantages and is pos-<br />
sible thanks to MockME. So, should we throw away all our Mobile JUnit test code?<br />
No. It’s important to distinguish between unit tests and integration unit tests. We<br />
have stressed the use of true unit tests in Java ME, something rarely seen in Java<br />
ME projects. There is always a need to test parts of your application on the target<br />
platform, but in combination with true unit tests, the integration unit tests will be<br />
fewer and more focused on integration issues. </p>
<p><em>Magnus Robertsson and Johan Karlsson </em></p>
<h2>References</h2>
<p><a href="http://www.martinfowler.com/articles/injection.html ">Dependency Injection</a><br />
<a href="http://www.connextra.com/aboutUs/mockobjects.pdf">Mock Objects</a><br />
<a href="http://www.mockme.org/">MockME</a><br />
<a href="http://www.junit.org/">JUnit</a><br />
<a href="http://www.easymock.org/">EasyMock</a><br />
<a href="http://j2meunit.sourceforge.net/ ">J2MEUnit</a><br />
<a href="http://sourceforge.net/projects/jmunit/ ">JMUnit</a><br />
<a href="http://developer.sonyericsson.com/site/global/docstools/java/p_java.jsp">Mobile JUnit</a></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/02/01/java-me-testing-done-right/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

