<?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>Palantir Technologies &#187; tips and tricks</title>
	<atom:link href="http://blog.palantirtech.com/category/tips-and-tricks/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.palantirtech.com</link>
	<description>Articles from the Engineering Group at Palantir Technologies</description>
	<lastBuildDate>Fri, 23 Jul 2010 23:33:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fun with jMock</title>
		<link>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/</link>
		<comments>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 21:15:08 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[development process]]></category>
		<category><![CDATA[javatech]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=1274</guid>
		<description><![CDATA[
Here at Palantir, a lot of our automatic tests are full-chain tests. A backend server is fired up, client code runs against it, and everything runs much like a production environment. This makes intuitive sense because it’s a faithful approximation of how the system will run in the field.
However, there are some disadvantages to this:

Full-pass [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; width: 175px;'><a href='http://www.jmock.org/'><img src='http://www.jmock.org/logo.png' style='background-color: #000066; padding: 10px'/></a></div>
<p>Here at Palantir, a lot of our automatic tests are full-chain tests. A backend server is fired up, client code runs against it, and everything runs much like a production environment. This makes intuitive sense because it’s a faithful approximation of how the system will run in the field.</p>
<p>However, there are some disadvantages to this:</p>
<ul>
<li>Full-pass tests don’t always localize the problem. Tests on a client class might fail even if it was the service that behaved incorrectly.
</li>
<li>These full-pass tests are relatively slow. Client code is running against an actual remote service. If a client is being tested, the server code still has to do work — sometimes a lot of work — even if that isn’t the focus of the test.</li>
<li>The constraints of the test are loose. Full-chain tests can mostly only see whether the operation finished correctly. It’s much harder to figure out whether the operation was done efficiently and without making unnecessary service calls.</li>
<li>They’re very little setup flexibility. If you want an RPC to return a specific value, you have little choice but to have your test get the service into a state where it can return that value. This is easy in some cases, but prohibitively difficult in others.</li>
<li>Client tests are forced to share any non-determinism leaked from the service. For example, under real conditions, a request to call A might respond before call B, and sometimes the other way around. This can result in flaky tests or tests that don’t always simulate the conditions you want to exercise.</li>
</ul>
<p>What’s to be done? Fortunately, there’s an option that handles these cases elegantly. We also test with <a href="http://www.jmock.org/">jMock</a>, a library that dynamically generates mock objects from arbitrary interfaces. These mock objects can be configured to check that particular methods are called with particular inputs a particular number of times, and then give prescribed responses.</p>
<p>Hit the link to see a concrete example of jMock in action.<br />
<span id="more-1274"></span></p>
<h2>jMock in action</h2>
<p>Let&#8217;s say I want to test my object viewer page in Palantir Web, but I don’t want to fire up a dispatch server at all. First, I create my mock service object.</p>
<pre class="brush: java;">
Mockery context = new Mockery();
final PalantirService service = context.mock(PalantirService.class);
</pre>
<p>Then, I set the expectations of my mock object. In this case, I want to tell my mock object to expect a call to PalantirService.getObject() and PalantirService.getDataSources(). getObject() will return a specific object. Any call made to the service apart from these will make the test fail.</p>
<pre class="brush: java;">
context.checking(new Expectations() {{
        oneOf(service).getObject(realm.getId(), myObject.getId());
        will(returnValue(myObject));
        oneOf(service).getDataSources(myObject.getDataSources());
}});
</pre>
<p>Now, I create the object I want to test and inject the service.</p>
<pre class="brush: java;">
ObjectViewController controller = new ObjectViewController();
controller.setService(service);
</pre>
<p>And then we fire away.</p>
<pre class="brush: java;">
ModelMap model = new ModelMap();
controller.doGet(myObject.getId(), model);
</pre>
<p>Now that the controller (the class we’re exercising) has gone off and populated the model, we check to see that the model is populated correctly. Just like we would in any other test.</p>
<pre class="brush: java;">
assertEquals(myObject.getName(), model.get(&quot;objectName&quot;));
assertEquals(myObject, model.get(&quot;object&quot;));
</pre>
<p>But in addition, we also assert that the expectations specified above were satisfied.</p>
<pre class="brush: java;">
context.assertIsSatisfied();
</pre>
<p>Not only can we be sure that the right calls were made with the right parameters, but we can also be sure that no calls besides the expected calls were made. So the next time you want more speed or control over your tests, take a look at jMock or another framework like it. It’s a powerful tool in the effort to test your best!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaInvoke allows you to spawn additional Java VMs during testing</title>
		<link>http://blog.palantirtech.com/2009/07/28/javainvoke/</link>
		<comments>http://blog.palantirtech.com/2009/07/28/javainvoke/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 22:00:30 +0000</pubDate>
		<dc:creator>Ari</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[enterprise software]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=209</guid>
		<description><![CDATA[
Here at Palantir we use test-driven development (or TDD for short).  Integrated tools like Eclipse and JUnit simplify writing and running unit tests.  However, once you need to test a broader swath of functionality, it&#8217;s time to write functional, integration, and system tests.  While technically not &#8216;unit testing&#8217;, the testing framework that [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; text-align: right; width: 298px'><img src="/wp-content/uploads/2009/07/junit.png" alt="junit success" width="288" height="194" /></div>
<p>Here at Palantir we use <a href="http://en.wikipedia.org/wiki/Test-driven_development">test-driven development (or TDD for short)</a>.  Integrated tools like <a href="http://www.eclipse.org/">Eclipse </a>and <a href="http://junit.org/">JUnit</a> simplify <a href="http://open.ncsu.edu/se/tutorials/junit/">writing and running unit tests</a>.  However, once you need to test a broader swath of functionality, it&#8217;s time to write <a href="http://www.ibm.com/developerworks/library/j-test.html#h1">functional</a>, <a href='http://en.wikipedia.org/wiki/Integration_testing'>integration</a>, and <a href='http://en.wikipedia.org/wiki/System_testing'>system</a> tests.  While technically not &#8216;unit testing&#8217;, the testing framework that JUnit provides is basically the same infrastructure that you want to leverage for writing these more involved types of testing.</p>
<p>When you&#8217;re developing enterprise software, functional testing often means getting your clients to talk to your servers.  For the main <a href="http://www.palantirtech.com/government">Palantir Government</a> product, we integrate the process of bringing the server up and down with the Ant scripts that run our automated unit tests: our testing tasks bring up the server, <a href="http://ant.apache.org/manual/OptionalTasks/junit.html">run the test suite</a>, and then kill the server. This works great and produces nice results.</p>
<p>When I started working on our authentication server, the pattern that we had used before didn&#8217;t work for me.  While the Palantir Government tests ran with a single, static configuration file, I needed to run the authentication server with multiple configurations in the course of running through the all the different functional tests.  I determined that I needed a way to programmatically bring the server up and down for testing. In JUnit parlance, I needed a way to programmatically launch the server component as part of my setup() function for my unit tests and stop it in my teardown().</p>
<p>With my itch-to-scratch firmly in hand (or some other mixed metaphor), I set out to figure out how to invoke new Java processes from inside a unit test.  The solution I came up with (with source code and examples) after the jump.<br />
<span id="more-209"></span></p>
<h2>The Six Ingredients</h2>
<p>So there are six ingredients that go into spawning a new VM:</p>
<ul>
<li>The classpath to use for the new VM</li>
<li>The name of the class to run</li>
<li>The directory to be used as the current directory for the process</li>
<li>The command line arguments to pass to the process</li>
<li>The set of Java system properties to use for this process</li>
<li>The environment to pass to the process</li>
</ul>
<p>Let&#8217;s look at each item individually.</p>
<h3>Classpath</h3>
<p>The classpath will tell the spawned VM where to load classes from.  In JavaInvoke, we use the existing classpath (from the spawning VM) as a starting point and then prepend any new entries to allow overriding the classpath for the spawned VM.</p>
<p>This takes a lot of the tedium out of having to figuring out what to put in the classpath.  Most likely, you want something similar to what you already have, if not completely identical.</p>
<p>We get the classpath from <code>System.getProperty("java.class.path")</code> and can add new entries by prepending the new entry, using the value of  <code>File.pathSeparatorChar</code> as the entry delimiter.  Using <code>File.pathSeparatorChar</code> makes the code cross-platform friendly (since the path separator is &#8216;;&#8217; on Windows and &#8216;:&#8217; on Unix (Linux, Solaris, OS/X, etc.).</p>
<p>Caveat: if you change the working directory and your original classpath was constructed using relative paths, you&#8217;ll probably have trouble getting anything to run (since your classpath will no longer point to right locations).</p>
<h3>Class name</h3>
<p>Pretty simple: what do you want to run in the spawned VM?  The class must have a <code>static void main(String args[])</code> defined, and it must be available for loading via the classpath.</p>
<h3>Working Directory</h3>
<p>If it should be different from the current working directory (CWD) of the running process, then set it and JavaInvoke will change it in the environment.</p>
<h3>Command line arguments</h3>
<p>If the process needs any command line arguments, including VM options, specify them in a string array.  Note that not all of these arguments will necessarily make it to your main method, since the VM executable will parse it first and remove the VM arguments, passing through the program arguments.</p>
<h3>Java System Properties</h3>
<p>System properties can be used to control many aspects of how a VM runs.  You can set them programmatically in your code or you can set set them on the command line by passing <em>-Dkey=value</em>.  Our JavaInvoke implementation will take a Map<string,String> of properties as a convenience argument; all it does is rewrite the map into the command line.</p>
<h3>Process environment</h3>
<p>This is an operating-system level construct.  This is the set of environment variables, also in a Map<string,String> that you would like merged with the current environment.  This would be the place that you set things like LD_LIBRARY_PATH on Unix.</p>
<h2>Dealing with input and output</h2>
<p>So you might ask the question, &#8220;where does the output from the process go?&#8221;  Or more troubling, &#8220;How do I send the process some input?&#8221;  The Java <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html">Process</a> object has methods to deal with this, allowing you to get streams that give you access to the input, output, and error streams of spawned process. That API is straight-forward to deal with, just like any other use of the java.io streams.</p>
<p>However, we want to make the typical case really easy: pulling the output from the spawned process back to the parent that spawned it.  To that end, we add into the mix a class called OutputPiper.  It fires up a thread that pulls all input from the spawned process, tags it with an identifier, and then outputs to the spawner&#8217;s stdout/stderr.</p>
<h3>OutputPiper</h3>
<p>(as extracted from <a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a>)</p>
<pre class="brush: java;">
	public static class OutputPiper extends Thread  {
		InputStream in;
		PrintStream out;
		String tag = null;

		public OutputPiper(String tag, InputStream in,PrintStream out) {
			this.in = in;
			this.out = out;
			this.tag = tag;
			// make sure that we don't keep the VM alive
			this.setDaemon(true);
			this.setName(&quot;OutputPiper-&quot; + tag);
			out.println(&quot;Starting output piper for tag: &quot; + tag);
			this.start();
		}

		@Override
		public void run() {
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String line = null;
				do {
					line = reader.readLine();
					if(line != null) {
						out.println(tag + &quot;: &quot; + line);
					}
				}while(line != null);
			}
			catch (Exception e) {
				//
			}
			out.println(&quot;Output piper exiting for tag: &quot; + tag);
		}

		public static OutputPiper createOutputPiper(String tag, InputStream in, PrintStream out) {
			OutputPiper rc = new OutputPiper(tag, in,out);
			return rc;
		}
	}
</pre>
<p>Outpiper extends <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html">Thread</a> so that all the output will arrive back to the controlling process in a timely manner.  For each given process, we spawn off two OutputPipers, one for stdout and one for stderr, corresponding to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#getInputStream()">Process.getInputStream()</a> and the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#getErrorStream()">Process.getErrorStream()</a>.</p>
<h2>ProcessSpawner &#038; JavaInvoke</h2>
<p>There are two key classes in the example:</p>
<ul>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a> &#8211; Essentially a wrapper around <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html">ProcessBuilder</a>, a generic process spawner that makes it simple to invoke processes that that use OutputPipers to forward their output back to their parent. This class allows you to specify the working directory, process environment, and command line for the process to be invoked.</li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/JavaInvoke.java.html'>JavaInvoke.java</a> &#8211; a specialized subclass of ProcessSpawner, this class makes spawning new VMs a piece of cake, doing the necessary translation for Java system properties, setting the proper classpath environment variable with potential overrides, and fills in the fully qualified class name to run.</li>
</ul>
<h2>The Example &#038; Source Code</h2>
<p>I&#8217;ve put together a running example that implements a trivial client and server in JUnit test.  The setup() method spawns the server and then the tests run the client code against the server, tearing it down after each test.  It&#8217;s available in the <a href='/wp-content/uploads/2009/07/PalantirVMSpawnerExample.zip'>PalantirVMSpawnerExample.zip</a> zip file.  Unzip it, run the <i>run.sh</i> or <i>run.bat</i> script as appropriate.  It should generate output that looks like this:</p>
<pre class="console">
-----------------------------------------------------
Starting test testAck
INFO [main] JavaInvoke - CLASSPATH=./lib/devblog-vmspawner.jar
INFO [main] ProcessSpawner - Build process spawner for the following command line:
INFO [main] ProcessSpawner - /home/pteng/java/i586/jdk1.5.0_14/jre/bin/java com.palantir.blog.processspawner.Server
Starting output piper for tag: server-stdout
Starting output piper for tag: server-stderr
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler2]: Got message: some message
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler3]: Got message: SHUTDOWN
Output piper exiting for tag: server-stdout
Output piper exiting for tag: server-stderr
Finished test testAck
-----------------------------------------------------
-----------------------------------------------------
Starting test testShutdown
INFO [main] JavaInvoke - CLASSPATH=./lib/devblog-vmspawner.jar
INFO [main] ProcessSpawner - Build process spawner for the following command line:
INFO [main] ProcessSpawner - /home/pteng/java/i586/jdk1.5.0_14/jre/bin/java com.palantir.blog.processspawner.Server
Starting output piper for tag: server-stdout
Starting output piper for tag: server-stderr
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler3]: Got message: SHUTDOWN
Output piper exiting for tag: server-stdout
Output piper exiting for tag: server-stderr
Took 3 ms to send shutdown.
Took 335 ms for process to die.
Finished test testShutdown
-----------------------------------------------------
SUCCESS: all 2 tests passed
</pre>
<p>The source is included in the zip file, but if you wanted to look at it or link to it on the web, here are the classes involved:</p>
<ul>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Client.java.html'>Client.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Example.java.html'>Example.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/JavaInvoke.java.html'>JavaInvoke.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Server.java.html'>Server.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ServerSpawningTest.java.html'>ServerSpawningTest.java</a></li>
</ul>
<p>And as an added bonus, there&#8217;s an Ant <i>build.xml</i> that will let you tweak and rebuild the demo yourself.</p>
<p>Comments and questions welcome.  Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/07/28/javainvoke/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Data Model Change Eventing</title>
		<link>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/</link>
		<comments>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/#comments</comments>
		<pubDate>Wed, 27 May 2009 20:46:42 +0000</pubDate>
		<dc:creator>DerekC</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[user interface]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=968</guid>
		<description><![CDATA[One of the early architectural challenges that we faced in building the Palantir Finance product was coming up with a good design for firing events from data models to their listeners.  There are many different concepts in our product such as charts, portfolios, and indices which are all maintained by different developers.  Initially, [...]]]></description>
			<content:encoded><![CDATA[<p>One of the early architectural challenges that we faced in building the <a href="http://www.palantirtech.com/finance">Palantir Finance</a> product was coming up with a good design for firing events from data models to their listeners.  There are many different concepts in our product such as charts, portfolios, and indices which are all maintained by different developers.  Initially, each developer had their own system for firing events when a data model changed.  This quickly became a drag on development as tools became more integrated because we had to learn each others&#8217; event methodologies and translate between the different systems.</p>
<p>The solution was to select a single event firing system.  We wanted something that was easy-to-use yet powerful enough to express all the changes that might be made to a data model.  Java&#8217;s <a href="http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html">Property Change Support</a> (PCS) was a good fit because it can support arbitrary events in a very lightweight fashion.</p>
<p>Read on for details of our implementation&#8230;<br />
<span id="more-968"></span></p>
<h2>Property Change Support</h2>
<p>Java&#8217;s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/PropertyChangeSupport.html">PropertyChangeSupport class</a> (PCS) basically allows an object to easily fire events consisting of 4 pieces of information:</p>
<ul>
<li>source object &#8211; the thing that fired the event</li>
<li>property name &#8211; allows the listener to tell events for different things apart</li>
<li>old value &#8211; the old value for the property</li>
<li>new value &#8211; the new value for the property</li>
</ul>
<p>PCS handles all the bookkeeping for adding and removing listeners and firing events.  It is very useful for creating listenable models, but we wanted to make it just a little bit easier by having an abstract class that exposed the add/remove listener calls and took care of initializing PCS:</p>
<pre class="brush: java;">
public abstract class AbstractListenableModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private transient PropertyChangeSupport pcs;

    protected AbstractListenableModel() {
        this.init();
    }

    /**
    * Adds a property change listener to the model.
    */
    public final void addPropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.addPropertyChangeListener(listener);
    }

    /**
    * Removes a property change listener from the model.
    */
    public final void removePropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.removePropertyChangeListener(listener);
    }

    /**
    * Fires a property change event to listeners of the model.
    */
    protected final void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
        this.pcs.firePropertyChange(propertyName, oldValue, newValue);
    }

    /**
    * Initializes transient fields during deserialization.
    */
    protected Object readResolve() {
        this.init();
        return this;
    }

    /**
    * Initializes transient fields.
    */
    private void init() {
        this.pcs = new PropertyChangeSupport(this);
    }
}
</pre>
<p>AbstractListenableModel is basically just a simple wrapper for exposing the functionality of PCS.  By extending this abstract class, it&#8217;s very easy to create a listenable model:</p>
<pre class="brush: java;">
public final class MyModel extends AbstractListenableModel {

    public static final String PROP_FOO = MyClass.class.getName() + &quot;.Foo&quot;;

    private int foo;

    public int getFoo() {
        return this.foo;
    }

    public void setFoo(int foo) {
        //
        // The semantics of the following line are a little hard to unpack,
        // but it does exactly what it needs to do, and the tradeoff
        // for conciseness over immediate readability is worth it for
        // large models with lots of properties.
        //
        // First, the JVM starts to create a stack frame for the call
        // into firePropertyChange().  It begins binding parameter values
        // from the left to the right.  The pointer to the String contained
        // in PROP_FOO is passed in first, then the current value of
        // this.foo is passed in, then the expression
        //        this.foo = foo
        // is evaluated (setting this.foo to the new value of foo), which
        // returns the new value of foo.  All the parameters are then
        // passed down into firePropertyChange(), which checks whether
        // the oldValue is equal to the newValue.  If they're not equal,
        // it fires the event.  If they are equal, it ignores the event.
        //
        this.firePropertyChange(PROP_FOO, this.foo, this.foo = foo);
    }
}
</pre>
<p>In this example, MyModel contains a single property called foo.  When the value of foo is changed, a property change event will be fired to listeners of the model.</p>
<p>You may notice that the value of PROP_FOO is prefixed by the name of the class.  This ensure that naming collisions do not occur for scenarios in which the same listener is used to listen to multiple models which happen to use the same property name.  This scenario becomes much more likely in the case of event bubbling, which I&#8217;ll talk about next.</p>
<h2>Event Bubbling</h2>
<p>Imagine a scenario in which we have a nested model:</p>
<p>Normally, if a listener needs to receive events from both models A and B, it will need to add itself as a listener to each individual model.  While this solution would work, it’s a little cumbersome, especially when model B can get swapped out for model B’—the listener then has to keep itself synched to the internal state of model A.  It would be nice if model A could just automatically forward all the events from model B (or B’) via its PCS support so that a listener only needs to attach itself to one model instead of multiple models.  With a bit more code in AbstractListenableModel, this is possible:</p>
<pre class="brush: java;">
public abstract class AbstractListenableModel implements Serializable {

    private transient PropertyChangeListener childModelListener;

    ...

    /**
    * Registers a child model to this model.
    */
    protected void registerChildModel(ListenableModel childModel, String propertyName) {
        childModel.addPropertyChangeListener(this.childModelListener);
    }

    /**
    * Initializes transient fields.
    */
    private void init() {
        ...
        this.childModelListener = new ChildModelListener();
    }

    /**
    * Listener for property change events fired from child models.
    */
    private final class ChildModelListener implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent event) {
            // This is where the bubbling happens
            pcs.firePropertyChange(event);
        }
    }
}
</pre>
<p>Now, whenever model B fires a property change event, this event will also be fired by model A.  This makes it much easier for the listener to listen to events arbitrarily deep in the model hierarchy, because each event fired by a child model gets re-fired (bubbled) by all its ancestors.  All you have to do is attach a listener to the root model and you’ll automatically receive events from all models in the hierarchy.</p>
<p>Note that the registerChildModel method above takes an unused propertyName argument.  In the full implementation of this class, events with the provided property name are monitored.  When an event with the provided property name is fired, childModelListener is detached from the old child model and attached to any new child model.  This ensures that the listenable model is always listening to the current child models.</p>
<h2>Events for Collections</h2>
<p>Any model event support would not be complete without some consideration of how to handle collections such as sets and lists.  To solve this scenario, we created specialized collection classes called ListenableModelSet and ListenableModelList.  These collections hold AbstractListenableModels as their elements and fire events whenever their contents change.  Since the changes to collections can vary widely, the solution we came up for communicating collection changes with full fidelity is basically to fire events with a copy of the old set as the old value and the new set as the new value.  Listeners can then diff the old and new values to determine exactly what changed if necessary.  Additionally, each ListenableModelSet or List adds a ChildModelListener to all of its children (themselves AbstractListenableModels), thereby ensuring that events are bubbled from all models in the collection.</p>
<h2>Conclusion</h2>
<p>Just as we saw with the <a href="http://blog.palantirtech.com/2009/04/20/model-view-adapter/">Adapter</a> piece of the <a href="http://en.wikipedia.org/wiki/Model-view-adapter">MVA</a> triad, when we <a href="http://se.ethz.ch/~meyer/publications/patterns/visitor.pdf">componentize</a> the Model piece there are huge gains to be had.  Once we started using a base Model class and a consistent eventing infrastructure (PropertyChangeSupport), we could add features that made coding across our entire application a lot more pleasant.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Model-View-Adapter</title>
		<link>http://blog.palantirtech.com/2009/04/20/model-view-adapter/</link>
		<comments>http://blog.palantirtech.com/2009/04/20/model-view-adapter/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 20:00:17 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javatech]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=210</guid>
		<description><![CDATA[I used to think I understood MVC.  In undergraduate CS programs, MVC is taught as an off-the-shelf pattern, explained once and then ready for use in the real world.  Wikipedia also makes it seem pretty simple:
Model–View–Controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic [...]]]></description>
			<content:encoded><![CDATA[<p>I used to think I understood MVC.  In undergraduate CS programs, MVC is taught as an off-the-shelf pattern, explained once and then ready for use in the real world.  Wikipedia also makes it seem pretty simple:</p>
<blockquote><p><a href="http://en.wikipedia.org/wiki/Model-view-controller">Model–View–Controller (MVC)</a> is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.</p></blockquote>
<p>They go on to show the classic triangle diagram and how it&#8217;s baked into various GUI and web frameworks.  There&#8217;s only one clause in the entire article that hints at something deeper:  &#8220;Though MVC comes in different flavors…&#8221;</p>
<p>Different flavors indeed.  In fact MVC is not just <em>a</em> pattern but a whole family of patterns:  <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a>, <a href="http://en.wikipedia.org/wiki/Model-view-adapter">MVA</a>, <a href="http://en.wikipedia.org/wiki/Model_View_Presenter">MVP</a>, <a href="http://en.wikipedia.org/wiki/Presentation-abstraction-control">PAC</a>, <a href="http://c2.com/cgi/wiki?ModelDelegate">Model-Delegate</a>&#8230;.  It very quickly gets very hairy.</p>
<p>In this article I want to describe one of MVC&#8217;s lesser-known variants, the <a href="http://en.wikipedia.org/wiki/Model-view-adapter">Model-View-Adapter (MVA) pattern</a>, and talk about its advantages over traditional MVC in the context of a Java Swing application.</p>
<p><span id="more-210"></span></p>
<h2>Architecture</h2>
<p>The best place to start is with an architecture diagram.  While vanilla MVC is a triangle:</p>
<div class="postimg"><a href="/wp-content/uploads/2009/04/mvc.png"><img title="mvc" src="/wp-content/uploads/2009/04/mvc.png" alt="Model-View-Controller" /></a></div>
<p>MVA puts the Adapter in a position to strictly mediate between Model and View:</p>
<div class="postimg"><a href="/wp-content/uploads/2009/04/mva.png"><img title="mva" src="/wp-content/uploads/2009/04/mva.png" alt="Model-View-Adapter" /></a></div>
<p>Here a solid line represents a direct relationship while a dashed line represents an indirect relationship via the Observer pattern.  Put another way, the Adapter holds a pointer both to the Model and to the View and directly calls methods on both.  At the same time, it attaches itself as a listener both to the Model and to the View in order to receive events.  It receives property change events from the Model and action events (checkbox ticked, text entered, etc.) from the View, and then routes appropriate changes to the other side.  The Adapter is entirely responsible for keeping the Model and the View in sync; the Model and View are both relatively dumb structures, knowing nothing about the other.</p>
<p>The advantages to organizing code this way are:</p>
<ul>
<li>All &#8220;moving parts&#8221; are centralized in one place, the Adapter.  No worrying about where to add a listener; no hunting around to find isolated listeners.</li>
<li>Separation of concerns between the View and the Adapter.  The View is responsible for layout and visual presentation while the Adapter is responsible for synchronization and the dynamic aspects of the user interface.</li>
<li>Better decoupling between Models and Views.  Specifically, the View doesn&#8217;t need to know anything about the Model.</li>
</ul>
<p>Additionally, while it will never be possible to fully <a href="http://se.ethz.ch/~meyer/publications/patterns/visitor.pdf">componentize </a> any variant of the MVC pattern, MVA is more amenable to componentization and thus more of its implementation can be centralized (in a single class) and reused.  Once componentized, we can augment the basic functionality with things like:</p>
<ul>
<li>Automatic registration and unregistration of listeners when the View enters and exits the Swing component hierarchy, thereby preventing certain kinds of memory leaks.</li>
<li>Automatic unregistration of listeners when the program shuts down.  This can help free up resources like realtime subscriptions.</li>
<li>Method for swapping a new Model object in for an old Model object.</li>
<li>Ability to execute a task without listeners attached, to help prevent event-action-event loops.</li>
</ul>
<p>The downside to using MVA over MVC is that the Adapter tends to take on a lot of the responsibility and can get quite complicated.  But in my experience that can be mitigated by having good conventions about which pieces (M, V, A) are allowed to communicate with which other pieces and at what times.  Enforcing predictable control flow goes a long way toward managing complexity.</p>
<p>Read on for a code-level description of our implementation of the MVA pattern.</p>
<h2>Palantir MVA Implementation</h2>
<p>Our half-componentization of MVA resides in a single abstract class named Adapter:</p>
<pre class="brush: java;">
public abstract class Adapter&lt;ViewType extends Component, ModelType&gt; {
// constructor
protected Adapter(ViewType view, ModelType model); { ... }

/**
* Attach listeners to the View's subcomponents (checkboxes etc.).
* Listeners should be stored as member variables in the Adapter
* subclass.
*/
protected abstract void registerViewListeners();

/**
* Detach the same listeners (member variables) that were
* attached in registerViewListeners().
*/
protected abstract void unregisterViewListeners();

/**
* Attach listener(s) to the Model.
*/
protected abstract void registerModelListeners();

/**
* Detach the same listeners (member variables) that were
* attached in registerModelListeners().
*/
protected abstract void unregisterModelListeners();

/**
* Bring the View fully in synch with the Model.  Typically
* this involves querying state from the Model and
* reconfiguring subcomponents of the View accordingly.
*/
protected abstract void fullSynchronize();

protected ModelType getModel() { ... }
protected ViewType getView() { ... }

// other methods elided
}
</pre>
<p>New View components that want to stay synchronized with a Model must instantiate a subclass of Adapter and implement the abstract methods.  The Adapter parent class (itself an example of the Template Method design pattern) will then call into the appropriate abstract methods at the appropriate times.  For example, after the View is constructed, as soon as it&#8217;s displayed in the Swing component hierarchy the Adapter parent class will automatically call fullSynchronize() (whose implementation should bring the View in line with the Model) and then registerViewListeners() and registerModelListeners(), so the Adapter is poised to react to events.  Likewise, when the View is removed from the component hierarchy (when its containing frame is closed, say), both unregisterViewListeners() and unregisterModelListeners() will be called.  This can help ensure that no memory will be leaked when a long-life-cycle object (like a system-wide singleton) retains a pointer to a short-life-cycle object (the View) via the Observer pattern.</p>
<h2>Dealing With Listener Loops</h2>
<p>One problem that confronts UI developers is the problem of &#8220;listener loops&#8221;:  infinite loops that result when the View fires an event, the Adapter (or Controller) responds to it by setting some property on the Model, and an event is propagated from the Model back to the View, starting the whole cycle over again.</p>
<p>One way to combat this is to make sure your Model only fires events when the value that&#8217;s being set on the Model is different from the value currently stored in the Model.  (This will cut off the infinite loop after one and a half cycles.)  It&#8217;s a good practice but often isn&#8217;t enough, especially when your system is multithreaded and events start to queue up.  You can sometimes get into situations where an M-V-C triplet will thrash forever between two different values for one of the Model&#8217;s properties.</p>
<p>Our solution to this problem is a protected method (on our Adapter base class) called runWithoutViewListeners:</p>
<pre class="brush: java;">
/**
* Guarantees that the job r will be run:
*    - on the Swing thread
*    - with Model listeners attached
*    - with View listeners DEtached
*/
public final void runWithoutViewListeners(final Runnable r) { ... }
</pre>
<p>The implementation of this method checks to make sure the view listeners are attached when it&#8217;s called, detaches them via a call to unregisterViewListeners(), invokes the Runnable, then reattaches the view listeners via a call to registerViewListeners().  The code inside the Runnable can then make whatever changes it wants to the View without perturbing the Model downstream.  Listener loop averted!</p>
<h2>More To Come</h2>
<p>I hope that&#8217;s given you some sense of the territory out there in the wide world of MVC-variants.  In a week or two, Derek will show off some of the work he&#8217;s done on the M piece of the MVA triad related to &#8220;event bubbling.&#8221;  Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/04/20/model-view-adapter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Pokémon Problem: a new anti-pattern</title>
		<link>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/</link>
		<comments>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 03:59:45 +0000</pubDate>
		<dc:creator>John C</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=202</guid>
		<description><![CDATA[
It&#8217;s always fun to release a new piece of jargon into the wild. I&#8217;ve run into a number of bugs in our codebase that caused by an anti-pattern I&#8217;d like to dub The Pokémon Problem.
Much like the game of Whac-a-Mole, this is a class of bugs where fixing every occurrence does not prevent the bug [...]]]></description>
			<content:encoded><![CDATA[<div style="float: right; margin-left: 15px; margin-bottom: 15px;"><img src="/wp-content/uploads/2009/03/pokepic1.jpg" alt="Gotta catch 'em all!" width="220" height="245" /></div>
<p>It&#8217;s always fun to release a new piece of jargon into the wild. I&#8217;ve run into a number of bugs in our codebase that caused by an <a href="http://en.wikipedia.org/wiki/Anti-pattern">anti-pattern</a> I&#8217;d like to dub <strong>The Pokémon Problem</strong>.</p>
<p>Much like the game of <a href="http://en.wikipedia.org/wiki/Whack-a-mole">Whac-a-Mole</a>, this is a class of bugs where fixing every occurrence does not prevent the bug from returning in new code: it is easy for code delta to result in an instance of the bug being re-introduced into the code base. Even if you &#8220;<a href="http://www.youtube.com/watch?v=vZ3gPXVMWRY">catch &#8216;em all</a>&#8220;, nothing prevents someone else from introducing new Pokémon bugs later.</p>
<p>Not only is this bug easy to re-introduce, but it sometimes can be hard to find all currently existing instances of this pattern. Although tools like Eclipse make it easier to track down all the places that code is called,  sometimes you&#8217;re looking for things that happen in a certain sequence (which tools like Eclipse don&#8217;t do a good job of searching for) and dynamic invocation mechanisms like <a href="http://www.ibm.com/developerworks/library/j-dyn0603/">Java Reflection</a> can sometimes make it impossible to be exhaustive.  This type of bug is also resistant to automated refactoring: changing the protocol of dealing with this corner of your code will require you to track down all places it was touched and manually refactor them.  It generally signals a failure to use sufficient <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>.</p>
<p>In general, this anti-pattern is a result of <a href="http://en.wikipedia.org/wiki/API">APIs</a> that require the caller to be responsible for state management of resources that the API owns.  This can include things like an object that requires the caller to have run an initialization method before calling any other method on the object.  These bugs get even more insidious when a failure to do things in the right order does not cause a hard failure (like throwing an exception) but instead creates some sort of subtle corruption that may not be noticed or cause subsequent calls to fail unexpectedly.</p>
<p>Read on for some strategies on dealing with the Pokémon problem.<br />
<span id="more-202"></span></p>
<h2>Solving the Pokémon Problem</h2>
<p>How do we solve the Pokémon problem?  Sometimes it is as easy as writing a unit test to verify that no new Pokémon exist. More often than not, though, you&#8217;ll have to use better encapsulation to solve the problem.  If the Pokemon problem is the anti-pattern, <a href="http://en.wikipedia.org/wiki/Information_hiding">encapsulation</a> is its opposite.</p>
<p>For an example, I&#8217;ll turn to a real problem I ran into in the <a href="http://www.palantirtech.com/videos/">Palantir Government</a> codebase:  Let&#8217;s say I have class <em>Parser</em> and it has a method <em>getAttribute()</em>.  I want to add the ability to have shortened (obfuscated) tag names to the <em>Parser</em> class.</p>
<h3>The wrong approach</h3>
<p>One approach I can take:</p>
<ol>
<li>Create a class called <em>AttributeHandler</em> that wraps calls to <em>Parser.getAttribute()</em>. It handles detection of the short or full XML dialect and then returns the appropriate attribute value.
</li>
<li>Stick an instance of this <em>AttrbributeHandler</em> class in a member variable of <em>Parser</em> and make sure to call <em>AttributeHandler.getAttribute()</em> instead of <em>Parser.getAttribute()</em> when processing attributes.</li>
<li>Put comment on <em>Parser.getAttribute()</em> mentioning that it shouldn&#8217;t be called directly anymore.</li>
</ol>
<p>I just introduced a Pokémon problem.  The next person that edits this code may not read my comment and know that calling <em>Parser.getAttribute()</em> is a bug.  They may not test the short tag case and find the bug. How do I fix this Pokémon problem? </p>
<h3>The right approach</h3>
<p>Approaching this encapsulation problem has a number of different approaches one could take.  Here&#8217;s what I chose:</p>
<ol>
<li>Create a class called <em>AttributeHandler</em> that wraps calls to <em>Parser.getAttribute()</em>. It handles detection of the short or full XML dialect and then returns the appropriate attribute value.
</li>
<li>Stick an instance of this <em>AttrbributeHandler</em> class in a member variable of <em>Parser</em>.</li>
<li>Create a wrapper class around <em>Parser</em> that delegates the <em>getAttribute()</em> call to the <em>AttributeHandler</em> member when processing attributes.</li>
</ol>
<p>(You might ask why I used a delegate instead of sub-classing the parser and overriding the <em>getAttribute()</em> method: it didn&#8217;t fit for architectural reasons that aren&#8217;t relevant here). Now the developer no longer has access to the <em>Parser.getAttribute()</em> method that would cause the undesired behavior.</p>
<h2>In-depth Example: Resource Management</h2>
<p>Another common place you might run into the Pokémon problem is code that needs to clean up resources.  Some coders are lazy and don&#8217;t want to always write their try/finally/close blocks properly.  This can lead to resource leaks; for things like file handles, this usually isn&#8217;t a large issue, but for scarce resources like database connections, it&#8217;s critical that things get cleaned and returned to the pool.  For locks, it&#8217;s absolutely essential to avoid deadlocks.</p>
<h3>The wrong way</h3>
<p>Here&#8217;s a simple example of bad resource management.  In this (admittedly contrived) scenario, we have class that&#8217;s managing a resource for us, in this case it&#8217;s a status file.  Different parts of the app need to read the status file where, presumably, something is storing its status.</p>
<p>Here&#8217;s the naive implementation of the status manager class:</p>
<pre class="brush: java;">

public class PokemonStatusFileManager {

	final File statusFile;

	public PokemonStatusFileManager(File statusFilePath) {
		this.statusFile = statusFilePath;
	}

	public InputStream getStatusFileInputStream() throws FileNotFoundException {
		return new FileInputStream(this.statusFile);
	}
}
</pre>
<p>Based on this implementation, here&#8217;s some code that would use it.  Note that first method, <em>parseStatusFileIncorrectly()</em> does no error checking and may not close the <em>InputStream</em> properly if an exception is thrown.  The second method does proper resource handling, but it&#8217;s kind of ugly to read.</p>
<pre class="brush: java;">

public class PokemonParseStatusFile {

	/**
	 * This is not proper resource management.
	 * @param manager
	 * @throws IOException
	 */
	public static void parseStatusFileIncorrectly(PokemonStatusFileManager manager)
		throws IOException {

		InputStream statusFile = manager.getStatusFileInputStream();
		readFrom(statusFile);
		statusFile.close();

	}

	/**
	 * This is proper resource management, but it's tedious to have to write.
	 * Some coders are too lazy to always do this the right way.
	 * @param manager
	 * @throws IOException
	 */
	public static void parseStatusFileCorrectly(PokemonStatusFileManager manager)
		throws IOException {

		InputStream statusFile = null;
		try {
			statusFile = manager.getStatusFileInputStream();
			readFrom(statusFile);
		} finally {
			// carefully close the resource
			if(statusFile != null) {
				try {
					statusFile.close();
				} catch(Exception e) {
					System.err.println(&quot;Error closing statusFile!&quot;);
					e.printStackTrace(System.err);
				}
			}
		}
	}

	static void readFrom(InputStream statusFile) throws IOException {
		// do the reading here...
	}
}
</pre>
<p>So this produces a classic Pokémon problem: everyone who interacts with the StatusFileManager has to do proper resource handling.  Now imagine that this is an important lock instead of just a file handle: this Pokémon problem could cause deadlock (which would be bad).</p>
<p>So how do we fix this? <a href="http://en.wikipedia.org/wiki/Visitor_pattern">The Visitor Pattern</a>.</p>
<h3>Solving the Pokémon problem with the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a></h3>
<p>The Visitor Pattern is a potent weapon in fighting the Pokémon problem: it allows you to fully encapsulate access to a resource by injecting into the places it&#8217;s needed but preserving overall control of the resource in the code that &#8220;owns&#8221; the resource.  Classically used for controlling things like iteration order, here the visitor pattern is applied as a form of <a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> to enable lifecycle management.</p>
<p>The visitor pattern as applied to resource management is fairly straightforward:</p>
<ol>
<li>Define an interface, <em>ResourceVisitor</em> with one method, <em>visit(Resource r)</em> (where <em>Resource</em> is the type of resource we&#8217;re managing.</li>
<li>Define the resource manager with a method that takes a <em>ResourceVisitor</em> as a parameter.  Manage the lifecycle of the resource and call <em>ResourceVisitor.visit(r)</em> when appropriate, handling all initialization, error-handling and cleanup.</li>
</ol>
<p>Here&#8217;s our re-spin of the status file manager class.  You&#8217;ll notice that we&#8217;ve moved the resource handling code from the correct example above and encapsulated it in the visitor pattern:</p>
<pre class="brush: java;">

public class UnPokemonStatusFileManager {

	/**
	 * Visitor interface implemented by callers wishing to
	 * interact with the status file.
	 */
	public static interface StatusFileVisitor {
		public void visitStatusFile(InputStream statusFile) throws IOException;
	}

	final File statusFile;

	public UnPokemonStatusFileManager(File statusFilePath) {
		this.statusFile = statusFilePath;
	}

	/**
	 * Note that this method is now private.
	 */
	private InputStream getStatusFileInputStream() throws FileNotFoundException {
		return new FileInputStream(this.statusFile);
	}

	/**
	 * Here's the method that takes the visitor and
	 * fully encapsulates the lifecycle of the status file.
	 */
	public void parseStatusFile(StatusFileVisitor parser)
	throws IOException {
		InputStream statusFile = this.getStatusFileInputStream();
		try {
			parser.visitStatusFile(statusFile);
		} finally {
			// carefully close the resource
			try {
				statusFile.close();
			} catch(Exception e) {
				System.err.println(&quot;Error closing statusFile!&quot;);
				e.printStackTrace(System.err);
			}
		}
	}
}
</pre>
<p>Now that we&#8217;ve encapsulated the complexity of the resource handling the <em>UnPokemonStatusFileManager</em> class, code that needs to access the status file can be written in a highly correct manner without much work.</p>
<pre class="brush: java;">

public class UnPokemonParseStatusFile {

	public static void parseStatusFile(UnPokemonStatusFileManager statusFileManager)
		throws IOException {

		// generate anonymous visitor to do the processing
		StatusFileVisitor visitor = new StatusFileVisitor() {
			public void visitStatusFile(InputStream statusFile) throws IOException {
				readFrom(statusFile);
			}
		};
		statusFileManager.parseStatusFile(visitor);
	}

	static void readFrom(InputStream statusFile) throws IOException {
		// do the reading here...
	}
}
</pre>
<p>By encapsulating the full lifecycle of the status file in the visitor pattern, I&#8217;ve ensured that it&#8217;s always accessed properly.  If I change the place where we store status to be a database rather than a file, nothing needs to change except this one class; the calling code remains the same.</p>
<p>We now have easy re-factoring, no resource leaks, and have simplified calling code.  And finally: there are no new bugs to be introduced by callers that aren&#8217;t sure how to use our resource.  Looks like we caught &#8216;em all!</p>
<h2>Wrapping It All Up</h2>
<p>So there it is, your new piece of jargon: The Pokémon Problem anti-pattern.  You heard it here first!  Please post any other great examples to the comments section on this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Printing to Plotters in Java</title>
		<link>http://blog.palantirtech.com/2008/08/11/printing-to-plotters-in-java/</link>
		<comments>http://blog.palantirtech.com/2008/08/11/printing-to-plotters-in-java/#comments</comments>
		<pubDate>Tue, 12 Aug 2008 00:00:18 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[javatech]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=104</guid>
		<description><![CDATA[
Carl juggles with his creation
One of the things our customers love to do is print our beautiful object graphs and tape them to the wall for discussion.  What they hate to do is print 30 pages, line them up, and tape them to a poster one at a time.  So we bought a [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; width: 300px; text-align: center; margin-left:10px; margin-bottom: 10px'>
<a href='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles-thumb.jpg' title='carljuggles-thumb.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles-thumb.jpg' alt='carljuggles-thumb.jpg' /></a><br/><a href='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles-thumb.jpg' title='carljuggles-thumb.jpg'><em>Carl juggles with his creation</em></a></div>
<p>One of the things our customers love to do is print our <a href="http://blog.palantirtech.com/wp-content/uploads/2008/07/pg-timefilter.png">beautiful object graphs</a> and tape them to the wall for discussion.  What they hate to do is print 30 pages, line them up, and tape them to a poster one at a time.  So we bought a <a href="http://en.wikipedia.org/wiki/Plotter">plotter</a>, and I started plotting.</p>
<p>I needed to print directly to a Java <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics.html">Graphics</a> object.  Unfortunately, the available information on large output printing from Java is thin at best.  While there are lots of ways to successfully place ink on paper, I was only able to find one that reliably lets the application pick odd paper sizes that plotters use, like 24&#215;19.7 inches. (The term &#8220;plotter&#8221; used to mean something with pens for printing blueprints and such.  Now it just means a large format printer, commonly printers that can use roll paper as a source.)</p>
<p>One of the first things you&#8217;ll learn when you start working with printing in Java is that a language intended to be all things to all people (i.e., cross-platform) is utterly lousy at tasks highly specific to a given environment, such as printing.  It will not surprise you to hear that native print services on Windows are pretty different from those available on a Mac, which themselves are pretty different from the <a href="http://www.cups.org/">CUPS</a> system common to Unix systems.</p>
<p>So, by and large, you are reduced to the least common denominator of printing.  Part and parcel of this least common denominator is agreeing on what constitutes a piece of paper and sticking to it.  This is fine for people thinking, &#8220;My paper is 8.5 inches wide by 11 inches tall.&#8221;  It poses a bit of a problem for people with plotters who are thinking, &#8220;My paper is 24 inches wide by as many damned inches tall as I need.&#8221;  Even relatively powerful programs like PhotoShop or <a href="http://www.gimp.org/features/">GIMP</a> don&#8217;t seem to support plotters well.  I believe Photoshop works by specifying the exact paper size you want to use, but any technique in which the easiest solution for the user is to pull out a calculator does not meet with my approval.<br />
<span id="more-104"></span></p>
<h2>Advice in a nutshell</h2>
<p>A <a href="http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html ">tutorial by MartyHall</a> provides some valuable insights into printing which I applied to my printing component.  While it didn&#8217;t address my specific issues, props to a well-done starting point.</p>
<p>I&#8217;m starting with the assumption that you&#8217;ve got yourself a class that implements the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/Printable.html">Printable</a> interface so that once the Java printing subsystem is coerced into accepting the appropriate paper size,<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/Printable.html#print(java.awt.Graphics,%20java.awt.print.PageFormat,%20int)"> Printable.print(Graphics, PageFormat, int)</a> will be called correctly and your job will print properly.  Since my usage was screen-visible as well as printable, I simplified and asserted that one screen pixel is equivalent to one point (1/72 inch), which is how Java prepares the scaling on the Graphics object passed to Printable.print(&#8230;), thus making printouts look about the size of onscreen displays.  Then, knowing that the printout needed, for example, 1200 vertical pixels/points, I can automatically calculate that I want to use a paper size 18&#8243; tall or so (1200 / 72 dpi = 16.67&#8243; + margins).</p>
<p>Here&#8217;s a summary of the critical steps:</p>
<ol>
<li>Do the math yourself to get the paper size required in points (1/72 of an inch)
<li>Implement the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/Pageable.html">Pageable</a> interface to report page count (usually one) and the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/PageFormat.html">PageFormat</a> using the computed paper size.
<li>Create a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/PrinterJob.html">PrinterJob</a> configured with the correct <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/print/PrintService.html">PrintService</a>
<li>Set your Pageable on the PrinterJob instance
<li>Optionally display print setup dialog (PrinterJob.printDialog()) recognizing that changes to orientation or paper size will be ignored.
<li>call <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/print/PrinterJob.html#print()">PrinterJob.print()</a>
</ol>
<h3>Generally, don&#8217;t use the standard dialogs</h3>
<p>This might seem contrary to desired behavior, but I found that giving the user access to the usual native or cross-platform print dialogs can be a bit sticky because those are places where the user can alter the selected paper; in order to properly print to roll paper sources, we must override any paper settings the dialogs might provide. Ultimately this can be confusing for the user, but that&#8217;s an unfortunate side effect of supporting plotters.</p>
<h3>Don&#8217;t take any advice too seriously</h3>
<p>We still choose to display the dialog because complex printers like plotters have many options that the users may need to alter and would otherwise have no way to modify.</p>
<h2>StickFigure: looking at plotting in Palantir</h2>
<p>This work didn&#8217;t happen in a vacuum: we have a need to print large graphs for display.  Being able to print them in a large format is one of the simplest and most beloved methods of collaboration.</p>
<p>To give an example of why plotter printing is interesting, we created a stick figure on the graph in Palantir. After creating this monstrosity, we went go print it and examined the layout.  The first layout was with letter-size paper, and just by looking at the head, we could see that it was going to be a lot of pages:</p>
<p><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/letterzoom.jpg' title='letterzoom-thumb.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/letterzoom-thumb.jpg' alt='letterzoom-thumb.jpg' /></a><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/letterzoom.jpg' title='letterzoom-thumb.jpg'><em>Zoomed-in view of the head of the stick figure. (click for full image)</em><br/></a></p>
<p>Zooming out to view the entire graph, it&#8217;s clear that it&#8217;s going to be 35 pages!</p>
<p><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/letter.jpg' title='letterzoom-thumb.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/letter-thumb.jpg' alt='letter-thumb.jpg' /></a><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/letter.jpg' title='letterzoom-thumb.jpg'><em>Full pagination of the stick figure. (click for full image)</em><br/></a></p>
<p>Even switching to the largest standard paper size only gets us to two sheets:</p>
<p><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/arche.jpg' title='arche.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/arche-thumb.jpg' alt='arche.jpg' /></a><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/arche.jpg' title='arche.jpg'><br />
<em>Paginated out to largest standard paper size, still two pages (click for full image)</em></a></p>
<p>When we switch over to using the plotter layout, we finally get to the one sheet we were looking for:</p>
<p><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/roll.jpg' title='roll-thumb.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/roll-thumb.jpg' alt='roll-thumb.jpg' /></a><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/roll.jpg' title='roll-thumb.jpg'><br />
<em>Paginated onto a plotter roll. (click for full image)</em></a></p>
<p>And finally, Mr. StickFigure comes to life:</p>
<p><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles.jpg' title='carljuggles.jpg'><img src='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles-med.jpg' alt='carljuggles-med.jpg' /></a><a style='display: block; text-align: center' href='http://blog.palantirtech.com/wp-content/uploads/2008/08/carljuggles.jpg' title='carljuggles.jpg'><em>Carl juggles with his creation</em></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2008/08/11/printing-to-plotters-in-java/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>SSL HOWTO: using openssl to get keys into PKCS#12 format.</title>
		<link>http://blog.palantirtech.com/2008/06/23/pkcs12/</link>
		<comments>http://blog.palantirtech.com/2008/06/23/pkcs12/#comments</comments>
		<pubDate>Mon, 23 Jun 2008 08:00:57 +0000</pubDate>
		<dc:creator>Ari</dc:creator>
				<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=94</guid>
		<description><![CDATA[


Some of our customers are pretty serious about data security.  To that end, our products need to support and integrate with SSL for both data security and authentication.  SSL is very neat technology, but there is a dizzying maze of standards to navigate to figure how to get it all to work.
It turns [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; margin-bottom: 20px; margin-left: 20px;'>
<a href='http://www.xat.nl/enigma-e/desc/index.htm'><img style='width: 240px' src='http://www.xat.nl/enigma-e/desc/img/fulll.jpg'/></a>
</div>
<p>Some of our customers are pretty serious about data security.  To that end, our products need to support and integrate with <a href="http://en.wikipedia.org/wiki/Secure_Sockets_Layer">SSL</a> for both data security and authentication.  SSL is very neat technology, but there is a dizzying maze of standards to navigate to figure how to get it all to work.</p>
<p>It turns out that in this age of Google, the fastest way to figure out how to do something is often to Google for key terms and hope that someone has put the relevant details in a blog post somewhere.  In trying to figure out how to set up keys on a SunOne Directory Server for testing our <a href="http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol">LDAP</a> integration, I needed to figure out how to get keys into <a href='http://en.wikipedia.org/wiki/PKCS12'>PKCS#12</a> format after generating them with <a href="http://www.openssl.org/">OpenSSL</a>.</p>
<p>I&#8217;ll spare you the gory details of what it took to figure out how to do this; suffice to say there was some trial and error mixed with a bunch of <a href="http://www.catb.org/jargon/html/R/RTFM.html">RTFM</a>.  After the jump, the full howto.<br />
<span id="more-94"></span></p>
<h2>Introduction to PKCS#12</h2>
<p><a href='http://en.wikipedia.org/wiki/PKCS12'>PKCS#12</a> is used by a number of different vendors as their standard key-exchange format for key management, most notably IE and the SunOne/Netscape products. <a href='http://www.openssl.org/'>OpenSSL</a>, while remaining the Swiss Army-Knife of crypto tools, doesn&#8217;t use PKCS#12 as a native format.  However it knows how to convert to it.</p>
<p>The overall strategy here is to convert to PKCS#12 as a last step; we do normal key generation and signing using OpenSSL and then convert the results into PKCS#12 format.</p>
<p>To get a key-pair generated and signed by a <a href="http://en.wikipedia.org/wiki/Certificate_authority">certificate authority</a> and then ready for import into one of these tools follow these steps (user input has been bolded):</p>
<h2>Generate the key</h2>
<blockquote>
<pre>
#<strong> openssl genrsa -out  example-key.pem 2048</strong>
Generating RSA private key, 2048 bit long modulus
..................................+++
...........................................................................................+++
e is 65537 (0x10001)
</pre>
</blockquote>
<p>Your RSA, 2048-bit public/private key pair now reside in the file named <em>example-key.pem</em>.</p>
<h2>Generate the Certificate Signing Request (CSR)</h2>
<p>Next we generate the <a href="http://en.wikipedia.org/wiki/Certificate_signing_request">CSR</a> normally.</p>
<blockquote>
<pre>
#<strong> openssl req -new -key example-key.pem -out example.csr</strong>
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:US
State or Province Name (full name) [Berkshire]:<strong>California</strong>
Locality Name (eg, city) [Newbury]:<strong>Palo Alto</strong>
Organization Name (eg, company) [My Company Ltd]:<strong>Palantir Technologies</strong>
Organizational Unit Name (eg, section) []:<strong>Palantir TechBlog Examples</strong>
Common Name (eg, your name or your server's hostname) []:<strong>example.palantirtech.com</strong>
Email Address []:<strong>example@palantirtech.com</strong>

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
</pre>
</blockquote>
<p>A certificate signing request for the public key in <em>example-key.pem</em> is now in <em>example.csr</em> and will look something like this if you look at the contents:</p>
<blockquote><p>
&#8212;&#8211;BEGIN CERTIFICATE REQUEST&#8212;&#8211;<br />
MIIC/zCCAecCAQAwgbkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh<br />
MRIwEAYDVQQHEwlQYWxvIEFsdG8xHjAcBgNVBAoTFVBhbGFudGlyIFRlY2hub2xv<br />
Z2llczEfMB0GA1UECxMWUEcgQmFja2VuZCBFbmdpbmVlcmluZzEaMBgGA1UEAxMR<br />
ZmxpbnQueW9qb2UubG9jYWwxJDAiBgkqhkiG9w0BCQEWFXJlZ3NAcGFsYW50aXJ0<br />
ZWNoLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMWmxedFCqsx<br />
ypNNYTUbcwVxtTUFMS6pP0y78GAabFvDQHW48IQXgyMrqlLl4//dI7EO/K6+ZdEJ<br />
Go6fuXW5jd/1RuxQRkCsfdVUrrhghVOywpSeWCzwraFniPQOqstQHuWdfygFkpVZ<br />
xsY3pu9cVvs827wvjHZXPpmLRZu5xDom+r8aAdjrQdkCCqbzdNFcxnxdHM03LMCz<br />
BJcAUSMjhvynBRNgzB01bOJOk+72lAuaEhjF0TMvnRMo16mhd/dnaHkqqW+N8q9m<br />
yTH1cTrNrdgJKkJ44K1sSJhFVMgkC2R4GK6RmprwIDVD8YkYLG+Iahw18xQKbCn1<br />
8NomTXbZBAUCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4IBAQBGR/1jScSVekhy/aR2<br />
xePJcO4jzmMVW4NfxOknxLkDvuDhbP7wGWPtspLXNf45mc3AXtkNgQTwO0siZHyy<br />
HaSLo4BuB4A62ofZfTVn6KYVzxuwskkLRdhlHA6mpM01hMBhmzbIZDyAZqyWQAJ5<br />
rC0Xl+ai/AAdLXO664qR3f2awXCUhJ/vYg7Qw4FHCLeoKcWxJfq9X9Ho5UJaFYTW<br />
6QVFKeODF4Y2vMnBx63RcgOIuJXI38ZK4+k1ONKuB75IhbIu3DtMTIv3kYYtfd6G<br />
P5BXlmgQgxVnFJcDprjEjHEUY4B+0vaWbDqy7U6fucT7EJ+qrSfk0Hf89aaQPKFf<br />
DUwz<br />
&#8212;&#8211;END CERTIFICATE REQUEST&#8212;&#8211;
</p></blockquote>
<p>This CSR is sent of to your CA of choice and you get back a certificate, essentially a signature for your public key by the CA.</p>
<p>The contents of the file, PEM-encoded, will look something like this:</p>
<blockquote><p>
&#8212;&#8211;BEGIN CERTIFICATE&#8212;&#8211;<br />
MIIDdDCCAlwCAxAAIDANBgkqhkiG9w0BAQQFADB/MR4wHAYDVQQKExVQYWxhbnRp<br />
ciBUZWNobm9sb2dpZXMxEjAQBgNVBAcTCVBhbG8gQWx0bzETMBEGA1UECBMKQ2Fs<br />
aWZvcm5pYTELMAkGA1UEBhMCVVMxJzAlBgNVBAMTHlBhbGFudGlyIENlcnRpZmlj<br />
YXRlIEF1dGhvcml0eTAeFw0wODAyMjYwNjQ5NTVaFw0xMzAyMjQwNjQ5NTVaMH8x<br />
CzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMR4wHAYDVQQKExVQYWxh<br />
bnRpciBUZWNobm9sb2dpZXMxHzAdBgNVBAsTFlBHIEJhY2tlbmQgRW5naW5lZXJp<br />
bmcxGjAYBgNVBAMTEWZsaW50Lnlvam9lLmxvY2FsMIIBIjANBgkqhkiG9w0BAQEF<br />
AAOCAQ8AMIIBCgKCAQEAxabF50UKqzHKk01hNRtzBXG1NQUxLqk/TLvwYBpsW8NA<br />
dbjwhBeDIyuqUuXj/90jsQ78rr5l0Qkajp+5dbmN3/VG7FBGQKx91VSuuGCFU7LC<br />
lJ5YLPCtoWeI9A6qy1Ae5Z1/KAWSlVnGxjem71xW+zzbvC+Mdlc+mYtFm7nEOib6<br />
vxoB2OtB2QIKpvN00VzGfF0czTcswLMElwBRIyOG/KcFE2DMHTVs4k6T7vaUC5oS<br />
GMXRMy+dEyjXqaF392doeSqpb43yr2bJMfVxOs2t2AkqQnjgrWxImEVUyCQLZHgY<br />
rpGamvAgNUPxiRgsb4hqHDXzFApsKfXw2iZNdtkEBQIDAQABMA0GCSqGSIb3DQEB<br />
BAUAA4IBAQB0RbDK5D/6ndxSBermRwmUNkUFbSh+e6dB8g4GEnRiRKReoPaBkJeG<br />
UMZU2Rv9xZZBO+vN5USHbY8syfGNdHPNn8nndD5PJk4InBfBgcxlepzVK46sHuar<br />
+VRERk6b7RnP3vvbaBIAEG4h1+bdm5CANCexo8yptJp6m8d3AKmqv+mjTmoLc3Y7<br />
yTFVzCj8AyMJOHg1jE+paQSWDwe/Hya/01a8g6HaCLIVeLuHO0IWmIZ1oK+TiFt8<br />
H7cSCmNwGa9oojK3P9PH7sJbVsV1uhm0vYn0Qdmb7toWu1eKit1NRyeEUFlc2T9B<br />
h3N944gca4k+eMcAOrR7iBWUDwXMTVCr<br />
&#8212;&#8211;END CERTIFICATE&#8212;&#8211;
</p></blockquote>
<p>Stick it in its own file, <em>example.crt</em>.</p>
<h2>Create the PKCS#12 key</h2>
<p>Concatenate the cert with the key file and then have OpenSSL convert it to PKCS#12</p>
<blockquote><p>
# <strong>cat example-key.pem example.crt > example.pem</strong><br />
# <strong>openssl pkcs12 -export -in example.pem -out example.pkcs12 -name &#8220;example&#8221;</strong><br />
Enter Export Password: <strong><em>(password is not echoed here, but you must enter something)</em></strong><br />
Verifying &#8211; Enter Export Password: <strong><em>(password is not echoed here, but you must enter something)</em></strong>
</p></blockquote>
<h2>Verify it worked</h2>
<p>As they say: <a href="http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?tp=&#038;arnumber=999770&#038;isnumber=21574">if you didn&#8217;t test it, it doesn&#8217;t work</a>. So now we verify that another tool that claims to ingest PCKS#12,</p>
<p>verify that it worked with a different tool. Here I use Java&#8217;s <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/keytool.html">keytool</a>:</p>
<blockquote>
<pre>
#<strong> keytool -v -list -storetype pkcs12 -keystore example.pkcs12</strong>
Enter keystore password:  <strong>password</strong><em> (whatever you set it to above)</em>

Keystore type: pkcs12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: flint
Creation date: Feb 26, 2008
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=example.palantirtech.com, OU=Palantir TechBlog Examples, O=Palantir Technologies, ST=California, C=US
Issuer: CN=Palantir Certificate Authority, C=US, ST=California, L=Palo Alto, O=Palantir Technologies
Serial number: 100020
Valid from: Mon Feb 25 22:49:55 PST 2008 until: Sat Feb 23 22:49:55 PST 2013
Certificate fingerprints:
         MD5:  C2:4E:B0:62:D8:06:FB:10:77:A5:37:6C:C8:2F:2A:AF
         SHA1: D2:B4:6B:0C:9D:3B:A4:94:B9:BF:25:E5:57:D6:96:FA:FB:84:A6:A7

*******************************************
*******************************************
</pre>
</blockquote>
<p>You&#8217;re now good to go.  As usual: additions, oversights, and comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2008/06/23/pkcs12/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SwingUtilities.invokeAndWait&#8230; doesn&#8217;t.</title>
		<link>http://blog.palantirtech.com/2008/02/21/invokeandnotwaiting/</link>
		<comments>http://blog.palantirtech.com/2008/02/21/invokeandnotwaiting/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 08:07:51 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/2008/02/21/invokeandnotwaiting/</guid>
		<description><![CDATA[One of the most misunderstood aspects of multithreaded Swing applications is care and feeding of SwingUtilities.invokeAndWait.  Hans Muller and Kathy Walrath authored a nice article that includes an overview of when to use invokeLater or its slightly more risky sibling, invokeAndWait.
We often use worker threads to do some long-running process, so often run into [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most misunderstood aspects of multithreaded Swing applications is care and feeding of <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#invokeAndWait(java.lang.Runnable)">SwingUtilities.invokeAndWait</a>.  Hans Muller and Kathy Walrath authored a <a href="http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html">nice article</a> that includes an overview of when to use <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)">invokeLater </a>or its slightly more risky sibling, <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#invokeAndWait(java.lang.Runnable)">invokeAndWait</a>.</p>
<p>We often use worker threads to do some long-running process, so often run into two issues using SwingUtilities invokeLater/invokeAndWait, and have developed wrapper code to deal with it.  One issue is executing code from both worker threads and the <a href="http://en.wikipedia.org/wiki/Event_dispatching_thread">Event Dispatch Thread (EDT)</a>.  invokeLater and invokeAndWait both throw exceptions if executed on EDT.  Second, invokeAndWait isn&#8217;t guaranteed &#8212; interruption on the calling thread will resume execution before the job is finished.  The remainder of this post shows the code we used to solve these issues.</p>
<p><span id="more-84"></span></p>
<h2> Reducing repetitive code </h2>
<p>We often write functions that are executed from the Event Dispatch Thread (EDT) and also from other threads.  Since these methods will throw an exception if you&#8217;re already on the EDT, it makes sense for us to wrap them in a quick safety check so we avoid an extra three lines of code every place we want to use it.  Thus, a first minor improvement:</p>
<pre class="brush: java;">
public static runOnEDT(final Runnable r) throws InvocationTargetException {
	if ( SwingUtilities.isEventDispatchThread() )
		r.run();
	else
		SwingUtilities.invokeLater( r );
}
</pre>
<p>Note the use of invokeLater &#8212; that will be important to the next section.  invokeAndWait wouldn&#8217;t work the same.</p>
<h2> invokeAndWait doesn&#8217;t wait </h2>
<p>The second gotcha with invokeAndWait is that it doesn&#8217;t always.  Wait, that is.  If a thread is waiting for a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runnable.html">Runnable</a> to execute on the EDT and that thread is interrupted, execution of the waiting thread will resume immediately, BEFORE FINISHING the Runnable.  I had assumed this meant we failed to wait for the EDT, that the job was never executed and should I execute invokeAndWait again.  This was the <strong>wrong</strong> interpretation.  Turns out, all that happened was <em>waiting on completion of the job</em> was interrupted.  The Runnable is still enqueued on the EDT and will still execute.  Depending on how the timing works out, the EDT Runnable may even be executing at the same time.  I just have no idea when it will finish.  Very inconvenient.</p>
<p>invokeAndWait throws <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/InterruptedException.html">InterruptedException</a> so you can learn of this situation and deal with it, but it&#8217;s not really something you can solve after the error has already occurred.  So the following is our solution:</p>
<p>We create a FutureTask to wrap the provided Runnable.  We can await completion of the FutureTask via <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html#get()">FutureTask.get()</a> which tells us when the provided Runnable has finished (successfully or thrown exceptions, or whatever).  After the Runnable finishes, if there were any interruptions during execution, we re-interrupt Thread.currentThread() so the caller knows an interruption occurred and can choose to perform followup action.</p>
<pre class="brush: java;">
public static void runAndBlockSilently(Runnable r) {
	final FutureTask ft = new FutureTask(r, null);
	boolean wasInterrupted = false;
	runSafely( ft );
	while (! ft.isDone() ) {
		try {
			ft.get();
		}
		catch ( InterruptedException e ) {
			wasInterrupted = true;
			// Continue ...
		}
		catch(ExecutionException exEx) {
			Throwable cause = exEx.getCause();
			logger.error( &quot;Exception during BlockingRunnable: &quot;, cause );
			if(cause instanceof RuntimeException)
				throw (RuntimeException) cause;
		}
	}

	if(wasInterrupted) {
		Thread.currentThread().interrupt();
	}
}
</pre>
<p>Happy Swinging.</p>
<p>-Carl</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2008/02/21/invokeandnotwaiting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing JUnit tests for memory leaks</title>
		<link>http://blog.palantirtech.com/2007/11/06/writing-junit-tests-for-memory-leaks/</link>
		<comments>http://blog.palantirtech.com/2007/11/06/writing-junit-tests-for-memory-leaks/#comments</comments>
		<pubDate>Tue, 06 Nov 2007 08:01:38 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/2007/11/06/writing-junit-tests-for-memory-leaks/</guid>
		<description><![CDATA[Memory leaks are no fun &#8212; to find them, you usually have to do a work flow while using a profiler like YourKit, force garbage collection, capture a memory snapshot, and then manually go through the snapshot looking for objects that you expected to be gone but are still there.Even after you&#8217;ve finally fixed the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.palantirtech.com/wp-content/uploads/2007/11/leak.gif" align="right" alt="Leak" style="margin-left: 10px" />Memory leaks are no fun &#8212; to find them, you usually have to do a work flow while using a profiler like <a href="http://www.yourkit.com/">YourKit</a>, force garbage collection, capture a memory snapshot, and then manually go through the snapshot looking for objects that you expected to be gone but are still there.Even after you&#8217;ve finally fixed the memory leak, how can you make sure that the issue doesn&#8217;t resurface later? Every good developer knows that, if you fix a bug, you should probably also have    a <a href="http://www.junit.org/index.htm">JUnit</a> test for that bug so that it doesn&#8217;t happen again. But how can you test for memory leaks programmatically?Find out after the jump&#8230;<span id="more-79"></span><br />
<h2>How do you check for something that doesn&#8217;t exist?</h2>
<p>The main challenge with programmatically testing for memory leaks is figuring out how to know  whether or not you&#8217;re leaking memory. If you want to check to see whether a certain object is still allocated, it seems like you&#8217;d have to have a reference to it. However, if you have a reference to it, it&#8217;s not going to be garbage collected. But if you don&#8217;t have a reference to it, how are you supposed to check whether or not it&#8217;s been freed?<br />
<h2>The power of weak references</h2>
<p>Luckily, Java has just the construct for us: weak  references. Weak references &#8212; objects of class <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/WeakReference.html">WeakReference</a> &#8212; act as references to an object, but, unlike normal references, they will not prevent the object from being garbage collected. Thus, once an object reaches a state in which it is only referenced by weak references, it will be eligible to be reclaimed by the garbage collector.Weak references can also be associated with a <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/ReferenceQueue.html">ReferenceQueue</a>, which is a queue that holds WeakReference objects whose status has changed (for WeakReference objects, a status change occurs when the object that it is referring to is no longer reachable by strong references). We are guaranteed that, once an object becomes weakly reachable, it will be enqueued in its associated <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/ReferenceQueue.html">ReferenceQueue</a>.Note: I am simplifying some things and skipping over other things like <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/SoftReference.html">soft</a> references and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/PhantomReference.html">phantom</a> references. For a more detailed explanation of these topics, check out <a href="http://java.sun.com/developer/technicalArticles/ALT/RefObj/">this SDN article</a> and <a href="http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html">this Java.net blog entry</a>.<br />
<h2>Writing the unit test</h2>
<p>The properties of WeakReference objects make them perfect to use for tests where we want to see whether or not a certain piece of memory has been freed. The general process works as follows:
<ol>
<li>Create an object using a strong reference (assign it to a variable).</li>
<li>Create a ReferenceQueue object.</li>
<li>Create a WeakReference that refers to the desired object from step 1 and uses the ReferenceQueue from step 2.</li>
<li>Do whatever operations are needed to produce the suspected leak.</li>
<li>Release the known strong reference to your object (set the variable in step 1 to <code>null</code>).</li>
<li>Force garbage collection. (Technically, we are making a request for garbage collection using <a href="http://http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#gc()">System.gc()</a> &#8212; there&#8217;s no way to actually force it to occur. However, it&#8217;s the best we can do, and seems to work sufficiently well). If you&#8217;re having trouble with forcing garbage collection, anecdotal evidence seems to indicate that requesting garbage collection at least ten times will guarantee that garbage collection actually happens.</li>
<li>Check to see if your WeakReference from step 3 has been enqueued. If it has, then it will be freed, and there&#8217;s no leak. If it hasn&#8217;t, then there&#8217;s still a hard reference to it somewhere in your code, which means that it <em>is </em>being leaked.</li>
</ol>
<p>That&#8217;s it! You can now write unit tests that test for memory leaks in your code. This obviously isn&#8217;t very effective for leaks that only occur after extensive UI interactions, but we&#8217;ve found it extremely useful for testing things such as verifying that our models correctly free all of their child models in the correct manner.<br />
<h2>Sample code</h2>
<p>Here&#8217;s a simple sample unit test that tests to make sure that an object will be freed once its reference is set to <code>null</code>:</p>
<pre class="brush: java;">
	public void testMemory() {
		// create test object
		Object testObject = new Object();
		// create queue and weak reference
		ReferenceQueue queue = new ReferenceQueue();
		WeakReference ref = new WeakReference(testObject, queue);
		// set hard reference to null
		testObject = null;
		// force garbage collection
		System.gc();
		// soft reference should now be enqueued (no leak)
		assertTrue(ref.isEnqueued());
	}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2007/11/06/writing-junit-tests-for-memory-leaks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting equals() and hashCode() right</title>
		<link>http://blog.palantirtech.com/2007/09/05/getting-equals-and-hashcode-right/</link>
		<comments>http://blog.palantirtech.com/2007/09/05/getting-equals-and-hashcode-right/#comments</comments>
		<pubDate>Wed, 05 Sep 2007 17:44:28 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/2007/09/05/getting-equals-and-hashcode-right/</guid>
		<description><![CDATA[Whenever you override the equals() and hashCode() functions of a class, it is very important that you do so correctly.  Bugs in these functions are often quite insidious, because they will not fail catastrophically.  Your application will compile and probably do something reasonable, passing any smoke test you throw at it.  However, [...]]]></description>
			<content:encoded><![CDATA[<p>Whenever you override the <em><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals()</a></em> and <em><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#hashCode()">hashCode()</a></em> functions of a class, it is very important that you do so correctly.  Bugs in these functions are often quite insidious, because they will not fail catastrophically.  Your application will compile and probably do something reasonable, passing any smoke test you throw at it.  However, the output will be subtly incorrect.  Moreover, by the time you realize that some has gone wrong, there is little information about what caused the error.  This is because the error occurred 10 steps ago, nested five levels deep, when a member of a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html">HashSet</a> went MIA.  While a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NullPointerException.html">NullPointerException</a> is normally trivial to diagnose and fix, you can easily lose several hours tracking down an <em>equals()/hashCode() </em>bug.</p>
<p>There are many excellent tutorials out there on <em>equals()</em> and <em>hashCode()</em>.  The best source is probably <a href="http://java.sun.com/docs/books/effective/toc.html">Items 7 and 8</a> of <a href="http://java.sun.com/docs/books/effective/">Effective Java</a> by <a href="http://en.wikipedia.org/wiki/Joshua_Bloch">Josh Bloch</a>, and we have a couple copies of this book floating around the office.  A good online tutorial is <a href="http://www.ibm.com/developerworks/java/library/j-jtp05273.html">Java theory and practice: Hashing it out</a>, by another Java guru, <a href="http://www.briangoetz.com/">Brian Goetz</a>.</p>
<p>To test your understanding, make sure that you can answer the following questions.  I often ask variants of the first two during interviews.   The third comes from an error we&#8217;ve seen more than once in our code base.</p>
<ol>
<li> Suppose we have a Media class, composed of <em>title</em> and <em>contents</em> fields.  What can go wrong if <em>equals()</em> is based on both fields, while <em>hashCode()</em> is based solely on <em>title</em>?</li>
<li>Conversely, what can go wrong if <em>hashCode()</em> is based on both fields, but <em>equals()</em> is based solely on <em>title</em>?</li>
<li>Consider a class <em>A</em> which overrides <em>equals()</em> and <em>hashCode()</em>.  If you create a class <em>B</em> which extends class <em>A</em>, and use Eclipse to generate your <em>equals()</em> and <em>hashCode()</em> functions for class <em>B</em>, then the output of class B&#8217;s <em>hashCode()</em> function will depend on the value of <em>super.hashCode()</em>.  What happens if you refactor class <em>B</em> so that it no longer extends class <em>A</em>?</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2007/09/05/getting-equals-and-hashcode-right/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
