<?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>erik dörnenburg &#187; Coding</title>
	<atom:link href="http://erik.doernenburg.com/topics/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://erik.doernenburg.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 24 Aug 2010 02:54:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Call Graph Visualisation with AspectJ and Dot</title>
		<link>http://erik.doernenburg.com/2008/09/call-graph-visualisation-with-aspectj-and-dot/</link>
		<comments>http://erik.doernenburg.com/2008/09/call-graph-visualisation-with-aspectj-and-dot/#comments</comments>
		<pubDate>Sat, 27 Sep 2008 17:26:28 +0000</pubDate>
		<dc:creator>Erik Doernenburg</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Visualisation]]></category>

		<guid isPermaLink="false">http://erik.doernenburg.com/?p=101</guid>
		<description><![CDATA[One of my favourite tools to render graphs is GraphViz Dot and in an earlier entry I described how to use it to visualise Spring contexts. Today I want to showcase a different application.
Call graphs show how methods call each other, which can be useful for a variety of reasons. The example I use here [...]]]></description>
			<content:encoded><![CDATA[<p>One of my favourite tools to render graphs is <a href="http://www.graphviz.org/">GraphViz Dot</a> and in an <a href="http://erik.doernenburg.com/2008/08/springviz/">earlier entry</a> I described how to use it to visualise Spring contexts. Today I want to showcase a different application.</p>
<p>Call graphs show how methods call each other, which can be useful for a variety of reasons. The example I use here is the graph rooted in a unit test suite, and in this case the graph gives an understanding of how localised the unit tests are, how much they are real unit tests or how close they are to mini-integration tests. In an ideal case the test method should call the method under test and nothing else. However, even with mock objects that&#8217;s not always practical. And if, like myself, you fall into the classicist camp of unit testers, as described by Martin Fowler in <a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks aren&#8217;t Stubs</a>, you might actually not be too fussed about a few objects being involved in a single test. In either case, looking at the call graph shows you exactly which methods are covered by which unit tests.</p>
<p>There are several ways to generate calls graphs and I&#8217;m opting for dynamic analysis, which simply records the call graph while the code is being executed. A good theoretical reason is that dynamic analysis can handle polymorphism but a more practical reason is that it&#8217;s actually really easy to do dynamic analysis; provided you use the right tools. The approach I describe in this article uses <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a> to run the unit tests with a simple Java aspect that records the call graph and writes it out into a format that can be rendered more or less directly with Dot. Of course, this technique is not limited to creating graphs for unit test; it only depends on weaving an AspectJ aspect into a Java application.</p>
<p><span id="more-101"></span></p>
<p>Let&#8217;s start with the result. The following diagram shows the call graph for a few simple unit tests in the test suite for the CruiseControl dashboard. The tests methods are in the leftmost column and method invocations occur from left to right. It&#8217;s clearly visible that the tests are quite localised.</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_simple.png"><img src="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_simple-600x250.png" alt="" title="CC Test Suite - Normal Call Graph" width="600" height="250" class="alignnone size-medium wp-image-113" /></a></p>
<p>The next example shows a section that&#8217;s a bit more intertwined. Some tests exercise the same method, some tests call more than one method, and some methods are called indirectly through different paths. All in all pretty reasonable, though.</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_normal.png"><img src="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_normal-600x138.png" alt="" title="CC Test Suite - Normal Call Graph" width="600" height="138" class="alignnone size-medium wp-image-110" /></a></p>
<p>Now, I don&#8217;t want to showcase only the good parts. There are also sections in the graph that show how some of the test and dependencies are, well, a bit messy. In fairness, though, this is partly caused by some domain objets that are used across multiple tests.</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_knot.png"><img src="http://erik.doernenburg.com/wp-content/uploads/2008/09/cc_calls_knot-600x178.png" alt="" title="CC Test Suite - The Knot" width="600" height="178" class="alignnone size-medium wp-image-114" /></a></p>
<p>How hard can it be to create these graphs? Not very, as it turns out.</p>
<p><strong>Step 1</strong> is to create an aspect that intercepts all interesting method calls, which normally means calls to methods that are part of the project. It&#8217;s also possible, though, to include calls to libraries and frameworks. Depending on your experience with AspectJ this is as simple as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.example.callgraph</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect CallInterceptor
<span style="color: #009900;">&#123;</span>
    pointcut allInterestingMethods<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
        <span style="color: #339933;">!</span>within<span style="color: #009900;">&#40;</span>CallInterceptor<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span>within<span style="color: #009900;">&#40;</span>CallLogger<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span>
          execution<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #339933;">*</span> com.<span style="color: #006633;">example</span>..<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>..<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    before<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> allInterestingMethods<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        CallLogger.<span style="color: #006633;">INSTANCE</span>.<span style="color: #006633;">pushMethod</span><span style="color: #009900;">&#40;</span>thisJoinPointStaticPart.<span style="color: #006633;">getSignature</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        CallLogger.<span style="color: #006633;">INSTANCE</span>.<span style="color: #006633;">logCall</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    after<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> allInterestingMethods<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        CallLogger.<span style="color: #006633;">INSTANCE</span>.<span style="color: #006633;">popMethod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The first part of the aspect is the definition of the pointcut: it matches all public methods in &#8220;com.example&#8221; and sub-packages but excludes calls to the two classes that form part of the call graph logger itself.</p>
<p>The <em>before</em> advice, which is run before each method that matches the pointcut, places the signature of the current method on a stack maintained by the graph logger class. With the current method signature as the topmost element and the one that called it as the second from the top, the advice asks the logger to log the corresponding call. The <em>after</em> advice simply pops the topmost call from the stack.</p>
<p>This is almost all the excitement. The implementation of <code>CallLogger</code> deals with maintaining the stack and writing out the call in the format required by Dot. The complete implementation with some comments follows below.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.example.callgraph</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.BufferedWriter</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.FileWriter</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.IOException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Writer</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Stack</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.HashSet</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Set</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.aspectj.lang.Signature</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CallLogger
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> CallLogger INSTANCE <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CallLogger<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>An instance is made available as a public singleton. The main reason for using a singleton, rather than creating an instance in the aspect, is that if coherent logging is required across multiple projects in Eclipse it&#8217;s easiest to add a copy of the aspect to each project and have all aspects use the same logger instance.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">private</span> Stack<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> callStack <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Stack<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> callLog <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Writer</span> writer<span style="color: #339933;">;</span></pre></div></div>

<p>The fields hold the actual stack of method names, a set that contains all calls that have been logged already, and a writer to which the actual output is written. The set is a simple optimisation to prevent the same call from being written over and over again.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">     <span style="color: #000000; font-weight: bold;">public</span> CallLogger<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            writer <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BufferedWriter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">FileWriter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;calls.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">IOException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot open 'calls.txt' for writing.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> pushMethod<span style="color: #009900;">&#40;</span><span style="color: #003399;">Signature</span> s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> type <span style="color: #339933;">=</span> s.<span style="color: #006633;">getDeclaringType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> method <span style="color: #339933;">=</span> type.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span>type.<span style="color: #006633;">lastIndexOf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'.'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;.&quot;</span> <span style="color: #339933;">+</span> s.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        callStack.<span style="color: #006633;">push</span><span style="color: #009900;">&#40;</span>method<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>If anyone knows a better way to turn the AspectJ signature into a pretty string, please leave a comment.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> popMethod<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        callStack.<span style="color: #006633;">pop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> logCall<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>callStack.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000000; font-weight: bold;">return</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> call <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">+</span> top<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> -&gt; <span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">+</span> top<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>callLog.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span>call<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            write<span style="color: #009900;">&#40;</span>call<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            callLog.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>call<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Following a guard statement that protects the code from trying to log a call when only one method is on the stack, the code creates a description of the call in the format required by Dot for a graph edge, ie. the origin node in double quotes, followed by a stylised arrow, followed by the target node, again in double quotes.</p>
<p>If this call is not in the call log, the code writes it to the writer and then stores the call in the log so that it does not get written again.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Signature</span> top<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> callStack.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>callStack.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> write<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> line<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            writer.<span style="color: #006633;">write</span><span style="color: #009900;">&#40;</span>line <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            writer.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Running some code, the unit tests in this example, will now create a file named &#8220;calls.txt&#8221; that contains all calls to methods that match the pointcut description in the aspect. The calls are written in Dot format but to make the output a valid input file for Dot a header and a closing bracket at the end are required.</p>
<p>It would be easy to write the required header when the writer is initialised but realistically it&#8217;s not possible to know when <code>logCall</code> is called for the last time, and thus it&#8217;s not possible to write the closing bracket from the Java code. Therefore&#8230;</p>
<p><strong>Step 2</strong> is a small shell script, or a script in your favourite scripting language, that wraps the required header and footer around the raw graph edges.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #cc0000; font-style: italic;">&lt;&lt;-EOS
strict digraph G {
    graph [ ratio=&quot;auto compressed&quot;,
            rankdir=&quot;LR&quot;,
            ranksep=2,
            remincross=&quot;true&quot;,
            ];
    node  [ shape=box,
            style=filled,
            fillcolor=white,
            fontname=helvetica
            fontsize=10,
            fontcolor=black
            ];
EOS</span>
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">cat</span> calls.txt
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #cc0000; font-style: italic;">&lt;&lt;-EOS
    }
EOS</span></pre></div></div>

<p>I have an admission to make: This script is simplified and would not create the output I&#8217;ve shown further up. With a graph definition like this Dot would not put all unit tests nodes into the leftmost column but instead it would move them just left of the method they call. If, for example, test 1 called method A, which in turn called method B, and test 2 called method B directly, then test 1 would be in the first column, method A and test 2 in the second column and method B in the third column. The following UNIX command line wizardry, when added just below the <code>cat calls.txt</code> line in the script above, solves this problem. The explanation is left as an exercise to the reader&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'{ rank = same; '</span>
<span style="color: #c20cb9; font-weight: bold;">fgrep</span> Test.test calls.txt <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #660033;">-F</span> <span style="color: #ff0000;">&quot; -&gt; &quot;</span> <span style="color: #ff0000;">'{ print $1 }'</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">sort</span> <span style="color: #660033;">-u</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{ printf &quot;%s; &quot;, $1 }'</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'}'</span></pre></div></div>

<p>I hope this article shows how two simple but powerful tools combined make it easy to create a really useful visualisation; and how clever but cryptic UNIX command lines can be.</p>
]]></content:encoded>
			<wfw:commentRss>http://erik.doernenburg.com/2008/09/call-graph-visualisation-with-aspectj-and-dot/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>SpringViz and the 1000ft view</title>
		<link>http://erik.doernenburg.com/2008/08/springviz/</link>
		<comments>http://erik.doernenburg.com/2008/08/springviz/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 02:07:30 +0000</pubDate>
		<dc:creator>Erik Doernenburg</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Visualisation]]></category>

		<guid isPermaLink="false">http://erik.doernenburg.com/?p=47</guid>
		<description><![CDATA[The Spring framework has become ubiquitous in the Java world, and there are a large number of tools supporting developers of Spring-based applications. In this post I describe SpringViz; or, more accurately, my variant of it.
SpringViz helps developers with what is at the heart of a Spring-based application, the container and the contexts files that [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.springframework.org/about">Spring framework</a> has become ubiquitous in the Java world, and there are a large number of tools supporting developers of Spring-based applications. In this post I describe <a href="http://www.samoht.com/wiki/wiki.pl?SpringViz">SpringViz</a>; or, more accurately, my variant of it.</p>
<p>SpringViz helps developers with what is at the heart of a Spring-based application, the container and the contexts files that describe the beans. In larger projects these context files can grow quite a bit. Newer versions of the Spring framework introduced features that help reduce the clutter and there are vast numbers of blog posts voicing different opinions on what should and what shouldn&#8217;t be in a context file but, no matter what, the number of beans in the context files will grow with the size of a project, and at some point it becomes difficult to understand the overall structure. This is no different from trying to maintain an understanding of a large codebase. In fact, I consider the context files to be code rather than configuration.</p>
<p>I&#8217;ve argued before (<a href="http://softarch.97things.oreilly.com/wiki/index.php/Get_the_1000ft_view">here</a> and <a href="http://www.infoq.com/interviews/erik-doernenburg-software-visualization">here</a> for example) that to deal with the complexity and sheer size of software systems we need a 1000ft view. This is a view that uses visualisation techniques to aggregate large amounts of data and multiple metrics into one big picture. SpringViz provides that 1000ft view for Spring context files.</p>
<p><span id="more-47"></span></p>
<p>Let&#8217;s look at an example first. The following diagram shows the context files for the Spring JPetStore example application (click on the image for the full-size version):</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/08/jpetstore_beans.png"><img src="http://erik.doernenburg.com/wp-content/uploads/2008/08/jpetstore_beans_small.png" alt="Diagram showing the context files and beans contained in them for the Spring JPetSore example application" title="JPetStore Beans" width="600" height="424" class="size-full wp-image-81" /></a></p>
<p>I find that this diagram presents the architecture of the application quite nicely. The web controllers are defined in the petstore-servlet context in the top left and many of them have a dependency on the petStore bean, defined in the main application context. The petStore bean in turn has dependencies on all the DAOs, which are defined in the data access context. In that context we can clearly see how the top four DAOs share the same data source while the <em>Order</em> and <em>Sequence</em> DAOs use a different one. In addition to the individual dependencies we also get an impression of the overall architecture: a simple, multi-layered design with a single central choke point that acts as an adaptor between the presentation and data access layers.</p>
<p>From personal experience I can say that the bigger and more complex a system gets, the more valuable these diagrams become. In many cases they not only help share a common understanding of the architecture in the development team but they also help spot inconsistencies in the design and often trigger and support discussions around important restructurings. Ok, this is all I&#8217;m going to say to convince you to try out SpringViz. In the following paragraphs I&#8217;ll explain how to use it on your own projects.</p>
<p><strong>Step 1:</strong> You need a copy of SpringViz. The version I&#8217;m discussing in this article can be downloaded <a href="http://erik.doernenburg.com/wp-content/uploads/2008/08/springviz-20080813.zip">here</a>. When you unzip the archive you should have an Ant build file, a <em>springviz</em> folder with a few files in it and an <em>example</em> folder that contains the context files for JPetStore.</p>
<p><strong>Step 1b:</strong> SpringViz uses <a href="http://www.graphviz.org/">GraphViz Dot</a> to render the diagram. So, if you don&#8217;t have this on your system you need to download and install it. You should also open the build file and change the <em>dot.command</em> property to point to the Dot executable. On the Mac you should really get <a href="http://www.pixelglow.com/graphviz/">Pixelglow&#8217;s version</a> of GraphViz.</p>
<p><strong>Step 2:</strong> You can now run SpringViz by calling Ant with the default target. This will create a <em>target</em> folder, process the context files with the SpringViz XSLT sheet to create an input file for GraphViz Dot, and then invoke Dot to create <em>beans.png</em>, the final diagram.</p>
<p><strong>Step 3:</strong> To integrate SpringViz into your own projects you can simply add the contents of the build file to your build file, place the <em>springviz</em> folder in an appropriate place, and adjust the configuration properties at the top of the build file.</p>
<p>If you are adventurous you can have a look at the Dot documentation and change the XSLT sheet to create slightly different input for Dot. You could colour the beans according to all sorts of criteria or you could change other aspects of their appearance depending on bean attributes.</p>
<p>There are a few limitations that you should be aware of: In its current version the system can&#8217;t deal with multiple beans with the same name defined in different contexts. So, if you have a <em>defaultUrlMapping</em> bean or similar in multiple files and you have dependencies to/from these the resulting diagram will be wrong. In this case it&#8217;s easiest to modify the style sheet to filter out the problematic beans. Another important point is that in its current form the sheet simply tries to use a bean&#8217;s id and name, which usually works out but will cause problems when beans have both, name and id. And lastly, the XSLT processor will need access to the web to fetch the schema files. I guess this can be avoided but so far this hasn&#8217;t been a problem for me.</p>
<p><strong>If you missed the link above you can download the specific version of SpringViz discussed in this article from <a href="http://erik.doernenburg.com/wp-content/uploads/2008/08/springviz-20080813.zip">this site</a>. The latest version of SpringViz as well as more documentation and resources are available on <a href="http://www.samoht.com/wiki/wiki.pl?SpringViz">Mike Thomas&#8217;s site</a></strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://erik.doernenburg.com/2008/08/springviz/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Testing Cocoa Controllers with OCMock</title>
		<link>http://erik.doernenburg.com/2008/07/testing-cocoa-controllers-with-ocmock/</link>
		<comments>http://erik.doernenburg.com/2008/07/testing-cocoa-controllers-with-ocmock/#comments</comments>
		<pubDate>Fri, 04 Jul 2008 04:33:27 +0000</pubDate>
		<dc:creator>Erik Doernenburg</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://erik.doernenburg.com/?p=44</guid>
		<description><![CDATA[For a few releases the Apple development tools have included OCUnit and many developers have now started to write unit tests. There are lots of tutorials that explain how this is done for the straight-forward cases but there&#8217;s one area of testing that has proven difficult on most platforms, and that is testing of the [...]]]></description>
			<content:encoded><![CDATA[<p>For a few releases the Apple development tools have included OCUnit and many developers have now started to write unit tests. There are lots of tutorials that explain how this is done for the straight-forward cases but there&#8217;s one area of testing that has proven difficult on most platforms, and that is testing of the user interface. That said, there are a few things that make this an easier problem to solve with Cocoa and in this post I&#8217;ll explain why.</p>
<p><span id="more-44"></span></p>
<p>Let&#8217;s look at an example. <a href="http://ccmenu.sourceforge.net/">CCMenu</a> is a small application that displays the status of <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a> continuous integration servers. As part of adding a new project to be monitored the user has to enter the URL for the CruiseControl server and a combox provides a history of previously used servers.</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/07/ccmenu_snapshot1.png"><img class="alignnone size-full wp-image-45" title="CCMenu Snapshot 1" src="http://erik.doernenburg.com/wp-content/uploads/2008/07/ccmenu_snapshot1.png" alt="" width="449" height="264" /></a></p>
<p>The same dialog has a matrix of buttons to set the type of the server. Actually, by default CCMenu detects the server type automatically but that&#8217;s beside the point. What we&#8217;re interested in is the piece of functionality that is responsible for selecting the correct server type for the URL chosen by the user. In our case, this would be Cruise Control Dashboard.</p>
<p><a href="http://erik.doernenburg.com/wp-content/uploads/2008/07/ccmenu_snapshot2.png"><img class="alignnone size-full wp-image-46" title="CCMenu Snapshot 2" src="http://erik.doernenburg.com/wp-content/uploads/2008/07/ccmenu_snapshot2.png" alt="" width="449" height="264" /></a></p>
<p>One difference between Cocoa and most other UI frameworks is the fact that the user interface is stored by serialising the objects, rather than generating code. For this reason I&#8217;m happy to not insist on test-first for the actual interface. What I do want to test is the code in the controller classes.</p>
<p>Obviously, I could load the serialised objects, locate the elements involved and then use methods such as performClick: to trigger the actions. Sounds convoluted? Yes, I agree. Luckily there&#8217;s a better way.</p>
<p>This is a case where testing is tricky because the object under test interacts with objects that are difficult to deal with. In such cases dynamic mock objects have proven extremely useful. A good introduction can be found <a href="http://martinfowler.com/articles/mocksArentStubs.html">here</a> and <a href="http://mockobjects.com/">mockobject.com</a> lists papers and implementations. For Objective-C I created <a href="http://www.mulle-kybernetik.com/software/OCMock/">OCMock</a>. Let&#8217;s look at how this helps us testing our controllers.</p>
<p>Here are the relevant parts of the interface declaration of the controller. Given that I&#8217;m doing test-driven development there&#8217;s currently no implementation of the methods. I simply created the interface of the controller based on my needs while designing the dialog.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> CCMPreferencesController <span style="color: #002200;">:</span> CCMWindowController
<span style="color: #002200;">&#123;</span>
    IBOutlet <span style="color: #400080;">NSComboBox</span> <span style="color: #002200;">*</span>serverUrlComboBox;
    IBOutlet <span style="color: #400080;">NSMatrix</span> <span style="color: #002200;">*</span>serverTypeMatrix;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>historyURLSelected<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;</pre></div></div>

<p>In my test I want to use mock objects instead of loading the actual user interface. So, in the test setup, after creating my controller, I create appropriate mock objects and set up the controller to use these.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> CCMPreferencesControllerTest
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUp
<span style="color: #002200;">&#123;</span>
    controller <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCMPreferencesController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
    serverUrlComboBoxMock <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>OCMockObject mockForClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSComboBox</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>controller setValue<span style="color: #002200;">:</span>serverUrlComboBoxMock forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;serverUrlComboBox&quot;</span><span style="color: #002200;">&#93;</span>;
    serverTypeMatrixMock <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>OCMockObject mockForClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMatrix</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>controller setValue<span style="color: #002200;">:</span>serverTypeMatrixMock forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;serverTypeMatrix&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>You notice that I&#8217;m using key-value coding to set the variables (outlets). I&#8217;m doing this because the variables are not public and at the same time I don&#8217;t want to write accessor methods for them.</p>
<p>Now, we can start writing the actual test for the functionality. Have a look at the full test first.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>testSelectsServerTypeWhenHistoryURLIsSelected
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>selectedUrl <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://localhost/cctray.xml&quot;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>serverUrlComboBoxMock stub<span style="color: #002200;">&#93;</span> andReturn<span style="color: #002200;">:</span>selectedUrl<span style="color: #002200;">&#93;</span> stringValue<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>serverTypeMatrixMock expect<span style="color: #002200;">&#93;</span> selectCellWithTag<span style="color: #002200;">:</span>CCMCruiseControlDashboard<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>controller historyURLSelected<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>What&#8217;s going on here? Firstly, I tell the mock object that stands in for the actual combox box that it should stub the stringValue method. This means that when somebody invokes stringValue on this object it will return the string @&#8221;http://localhost/cctray.xml&#8221;. This is all we&#8217;d have done with the real combo box anyway.</p>
<p>Secondly, I tell the mock that stands in for the server type matrix that it should expect that the method selectCellWithTag: is called with CCMCruiseControlDashboard as an argument.</p>
<p>Lastly, I invoke the method I want to test. What happens, once the implementation is complete, is that the code will go the the combo box and ask it for its string value. The first mock will return the stubbed value. Now, the code should do whatever it needs to do to figure out which server type this corresponds to and then set that in the server type matrix by selecting the cell with the appropriate tag, and this is what we&#8217;ve told the second mock to expect.</p>
<p>Wait, you might say, we don&#8217;t have an implementation yet. So, how does this test fail? It doesn&#8217;t yet. We&#8217;ll have to tell the mock objects to verify that everything we told them to expect actually occurred, and a logical place for this is the test tearDown.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tearDown
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>serverUrlComboBoxMock verify<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>serverTypeMatrixMock verify<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>Strictly speaking, we don&#8217;t have to verify the combo box mock because it doesn&#8217;t have any expectations but it&#8217;s good practice to verify all mocks in the tear down, especially if the same mocks are used for multiple tests. By the way, by default the mocks also have fail-fast behaviour; when they receive a method that wasn&#8217;t stubbed or expected, they raise an exception right away. Detecting something that wasn&#8217;t expected can be done right way, detecting that something that was expected didn&#8217;t occur must be trigger by the user.</p>
<p>Now, if we run this test with an empty implementation of historyURLSelected: it will fail when we tell the server type matrix mock to verify because the expected method hasn&#8217;t been called. The error message will look something like this:</p>
<p><code>Unknown.m:0: error: -[CCMPreferencesControllerTest testSelectsServerTypeWhenHistoryURLIsSelected] : OCMockObject[NSMatrix]: expected method was not invoked: selectCellWithTag:0</code></p>
<p>Adding an implementation like the following one adds the right functionality and makes our test pass.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> CCMPreferencesController
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>historyURLSelected<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>serverUrl <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>serverUrlComboBox stringValue<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>serverTypeMatrix selectCellWithTag<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>serverUrl cruiseControlServerType<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>In summary, testing controllers becomes relatively easy when we follow this pattern:</p>
<p>1. Replace all UI elements with mocks; using key-value coding to access the outlets.</p>
<p>2. Set up stubs with return values for UI elements that the controller will query.</p>
<p>3. Set up expectations for UI elements that the controller should manipulate.</p>
<p>4. Invoke the method in the controller.</p>
<p>5. Verify the expectations.</p>
<p>I find tests following this pattern easier to write and understand than tests that load a NIB file and interact with the actual user interface elements.</p>
]]></content:encoded>
			<wfw:commentRss>http://erik.doernenburg.com/2008/07/testing-cocoa-controllers-with-ocmock/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
