<?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>Just Java</title>
	<atom:link href="http://blog.cedarsoft.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.cedarsoft.com</link>
	<description>A blog about Java and (related) Open Source tools...</description>
	<lastBuildDate>Wed, 25 Jan 2012 12:02:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaFX 2.* for Linux is coming&#8230;</title>
		<link>http://blog.cedarsoft.com/2012/01/javafx-2-for-linux-is-coming/</link>
		<comments>http://blog.cedarsoft.com/2012/01/javafx-2-for-linux-is-coming/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 12:02:25 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[preview]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=515</guid>
		<description><![CDATA[Yeah. Finally:
http://blogs.oracle.com/javafx/entry/javafx_2_0_is_cross
Download:
http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
I think I will take a closer look in a few days&#8230;
]]></description>
			<content:encoded><![CDATA[<p>Yeah. Finally:</p>
<p><a title="Announcement" href="http://blogs.oracle.com/javafx/entry/javafx_2_0_is_cross">http://blogs.oracle.com/javafx/entry/javafx_2_0_is_cross</a></p>
<p>Download:</p>
<p><a href="http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html">http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html</a></p>
<p>I think I will take a closer look in a few days&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2012/01/javafx-2-for-linux-is-coming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[JUnit-Rule] Fail tests on exceptions/failed assertions in other threads</title>
		<link>http://blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/</link>
		<comments>http://blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 21:51:54 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[rule]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=510</guid>
		<description><![CDATA[I use JUnit a lot. But obviously it has its problems. Fortunately rules are a great way to solve a lot of those problems. At least one can work around them in most of the cases&#8230;
On speciallity that got me more than once:
JUnit ignores exceptions/assertions in other threads
JUnit tests only fail on exceptions that are [...]]]></description>
			<content:encoded><![CDATA[<p>I use JUnit a lot. But obviously it has its problems. Fortunately rules are a great way to solve a lot of those problems. At least one can work around them in most of the cases&#8230;</p>
<p>On speciallity that got me more than once:</p>
<h3>JUnit ignores exceptions/assertions in other threads</h3>
<p>JUnit tests only fail on exceptions that are thrown within the &#8220;main&#8221; thread. Exceptions (and also failed Assertions!) in all other Threads are simply ignored.</p>
<p>Simple test case:</p>
<pre class="brush:java">  @Test
  public void ignoredAssertion() throws Exception {
    Thread thread = new Thread( new Runnable() {
      @Override
      public void run() {
        //Of course only one of the following lines is executed. Just comment one of those lines out...
        assertFalse(true); //will not be reported!
        throw new RuntimeException( "This one is ignored by JUnit, too" );
      }
    } );
    thread.start();
    thread.join();
  }</pre>
<p>This test will be run successfully. (I don&#8217;t wanna discuss whether this behavior is correct or not. I know there are a lot of use cases where this is an important feature). And that is quite surprising for a lot of developers.</p>
<p>More important: It is very easy to miss some failed assertions if your code under test is multi threaded&#8230;</p>
<h1>One rule to catch them all&#8230;</h1>
<p>I have written a small rule that catches all exceptions on all threads and fails the test if at least one exception has been caught.</p>
<h3>How to use the rule</h3>
<p>Just add those lines to your test class:</p>
<pre class="brush:java">  @Rule
  public CatchAllExceptionsRule catchAllExceptionsRule = new CatchAllExceptionsRule();</pre>
<p>And it is guaranteed that your test fails on all (really all) uncaught exceptions.</p>
<p>The rule is deployed to Maven Central:</p>
<pre class="brush:xml">&lt;dependency&gt;
    &lt;groupId&gt;com.cedarsoft.commons&lt;/groupId&gt;
    &lt;artifactId&gt;test-utils&lt;/artifactId&gt;
    &lt;version&gt;5.0.9&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>The rule itself:</p>
<pre class="brush:java">/**
 * This rule catches exceptions on all threads and fails the test if such exceptions are caught
 *
 * @author Johannes Schneider (&lt;a href="mailto:js@cedarsoft.com"&gt;js@cedarsoft.com&lt;/a&gt;)
 */
public class CatchAllExceptionsRule implements TestRule {
  @Nullable
  private Thread.UncaughtExceptionHandler oldHandler;

  @Override
  public Statement apply( final Statement base, Description description ) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        before();
        try {
          base.evaluate();
        } catch ( Throwable t ) {
          afterFailing();
          throw t;
        }

        afterSuccess();
      }
    };
  }

  private void before() {
    oldHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException( Thread t, Throwable e ) {
        caught.add( e );
        if ( oldHandler != null ) {
          oldHandler.uncaughtException( t, e );
        }
      }
    } );
  }

  @Nonnull
  private final List&lt;Throwable&gt; caught = new ArrayList&lt;Throwable&gt;();

  private void afterSuccess() {
    Thread.setDefaultUncaughtExceptionHandler( oldHandler );

    if ( caught.isEmpty() ) {
      return;
    }

    throw new AssertionError( buildMessage() );
  }

  private String buildMessage() {
    StringBuilder builder = new StringBuilder();
    builder.append( caught.size() ).append( " exceptions thrown but not caught in other threads:\n" );

    for ( Throwable throwable : caught ) {
      builder.append( "---------------------\n" );

      StringWriter out = new StringWriter();
      throwable.printStackTrace( new PrintWriter( out ) );
      builder.append( out.toString() );
    }

    builder.append( "---------------------\n" );

    return builder.toString();
  }

  private void afterFailing() {
    Thread.setDefaultUncaughtExceptionHandler( oldHandler );
  }
}</pre>
<p>You need some code to get this fixed.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JUnit: Tired of those remaining Threads&#8230;</title>
		<link>http://blog.cedarsoft.com/2011/12/junit-tired-of-those-remaining-threads/</link>
		<comments>http://blog.cedarsoft.com/2011/12/junit-tired-of-those-remaining-threads/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 15:03:39 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[rule]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=506</guid>
		<description><![CDATA[This happens more often that it should:
Unit tests run in isolation. But when you start the hole buch, some of the tests fail randomly.
Static initialization
This is the main reason for this behavior. Something is configured somewhere. And since static fields are involved, that (mis)configuration will have an impact on other tests. Very hard to discover. [...]]]></description>
			<content:encoded><![CDATA[<p>This happens more often that it should:</p>
<p>Unit tests run in isolation. But when you start the hole buch, some of the tests fail randomly.</p>
<h3>Static initialization</h3>
<p>This is the main reason for this behavior. Something is configured somewhere. And since static fields are involved, that (mis)configuration will have an impact on other tests. Very hard to discover. Good luck on that.</p>
<h3>Remaining Threads</h3>
<p>Another typical problem when running lots of unit tests are remaining threads.</p>
<p>When a unit test has finished, nobody checks for remaining threads. So those threads sill run, do some work, throw Exceptions that end up on the console, print debug statements, interrupt at break points during debugging&#8230;</p>
<p>Combined with some static initialization they guarantee for a lot of fun&#8230;</p>
<h3>How to detect them?</h3>
<p>I have written a short rule that detects whether some threads have been left after a unit test has finished. That rule stores all threads running at the beginning of the test. Then this set is compared with the set of all running tests at the end of the of a unit test.</p>
<p>While it does not detect all errors in all cases, it is very helpful to find some remaining ExecutorServices or BackgroundJobs. Just give it a try:</p>
<p>The rule can be used like all other rule (must be public):</p>
<pre class="brush:java">  @Rule
  public ThreadRule threadRule = new ThreadRule();
</pre>
<p>If there are threads left after each test, an exception is thrown with the stack traces of each of the remaining threads:</p>
<pre class="brush:plain">java.lang.IllegalStateException: Some threads have been left:
// Remaining Threads:
-----------------------
---
Thread[Thread-0,5,main]
	at java.lang.Thread.sleep(Native Method)
	at com.cedarsoft.test.utils.ThreadRuleTest$2.run(ThreadRuleTest.java:34)
	at java.lang.Thread.run(Thread.java:662)
---
Thread[Thread-1,5,main]
	at java.lang.Thread.sleep(Native Method)
	at com.cedarsoft.test.utils.ThreadRuleTest$3.run(ThreadRuleTest.java:44)
	at java.lang.Thread.run(Thread.java:662)
-----------------------

	at com.cedarsoft.test.utils.ThreadRule.after(ThreadRule.java:67)
	at com.cedarsoft.test.utils.ThreadRule.access$200(ThreadRule.java:18)
	at com.cedarsoft.test.utils.ThreadRule$1.evaluate(ThreadRule.java:34)
	at org.junit.rules.RunRules.evaluate(RunRules.java:18)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
[...]
</pre>
<h3>The code</h3>
<p>The rule is available as part of cedarsoft test-utils deployed to Maven Central. Just give it a try:</p>
<pre class="brush:xml">&lt;dependency&gt;
    &lt;groupId&gt;com.cedarsoft.commons&lt;/groupId&gt;
    &lt;artifactId&gt;test-utils&lt;/artifactId&gt;
    &lt;version&gt;5.0.8&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>com.cedarsoft.test.utils.ThreadRule</p>
<p>For easy copy/pasta:</p>
<pre class="brush:java">import com.google.common.base.Joiner;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Nonnull;

import org.junit.rules.*;
import org.junit.runner.*;
import org.junit.runners.model.*;

public class ThreadRule implements TestRule {

  public static final String STACK_TRACE_ELEMENT_SEPARATOR = "\n\tat ";

  @Override
  public Statement apply( final Statement base, Description description ) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        before();
        try {
          base.evaluate();
        } catch ( Throwable t ) {
          afterFailing();
          throw t;
        }
        after();
      }
    };
  }

  private Collection&lt;Thread&gt; initialThreads;

  private void before() {
    if ( initialThreads != null ) {
      throw new IllegalStateException( "???" );
    }

    initialThreads = Thread.getAllStackTraces().keySet();
  }

  @Nonnull
  public Collection&lt;? extends Thread&gt; getInitialThreads() {
    if ( initialThreads == null ) {
      throw new IllegalStateException( "not initialized yet" );
    }
    return Collections.unmodifiableCollection( initialThreads );
  }

  private void afterFailing() {
    Set&lt;? extends Thread&gt; remainingThreads = getRemainingThreads();
    if ( !remainingThreads.isEmpty() ) {
      System.err.print( "Some threads have been left:\n" + buildMessage( remainingThreads ) );
    }
  }

  private void after() {
    Set&lt;? extends Thread&gt; remainingThreads = getRemainingThreads();
    if ( !remainingThreads.isEmpty() ) {
      throw new IllegalStateException( "Some threads have been left:\n" + buildMessage( remainingThreads ) );
    }
  }

  @Nonnull
  private Set&lt;? extends Thread&gt; getRemainingThreads() {
    Collection&lt;Thread&gt; threadsNow = Thread.getAllStackTraces().keySet();

    Set&lt;Thread&gt; remainingThreads = new HashSet&lt;Thread&gt;( threadsNow );
    remainingThreads.removeAll( initialThreads );

    for ( Iterator&lt;Thread&gt; iterator = remainingThreads.iterator(); iterator.hasNext(); ) {
      Thread remainingThread = iterator.next();
      if ( !remainingThread.isAlive() ) {
        iterator.remove();
      }

      //Give the thread a very(!) short time to die off
      try {
        Thread.sleep( 10 );
      } catch ( InterruptedException ignore ) {
      }

      //Second try
      if ( !remainingThread.isAlive() ) {
        iterator.remove();
      }
    }
    return remainingThreads;
  }

  @Nonnull
  private String buildMessage( @Nonnull Set&lt;? extends Thread&gt; remainingThreads ) {
    StringBuilder builder = new StringBuilder();

    builder.append( "// Remaining Threads:" ).append( "\n" );
    builder.append( "-----------------------" ).append( "\n" );
    for ( Thread remainingThread : remainingThreads ) {
      builder.append( "---" );
      builder.append( "\n" );
      builder.append( remainingThread );
      builder.append( STACK_TRACE_ELEMENT_SEPARATOR );
      builder.append( Joiner.on( STACK_TRACE_ELEMENT_SEPARATOR ).join( remainingThread.getStackTrace() ) );
      builder.append( "\n" );
    }
    builder.append( "-----------------------" ).append( "\n" );

    return builder.toString();
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2011/12/junit-tired-of-those-remaining-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fixing Maven Artifact: Jaxen</title>
		<link>http://blog.cedarsoft.com/2011/12/fixing-maven-artifact-jaxen/</link>
		<comments>http://blog.cedarsoft.com/2011/12/fixing-maven-artifact-jaxen/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 13:48:27 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Jaxen]]></category>
		<category><![CDATA[JDOM]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=499</guid>
		<description><![CDATA[I have created some utility classes for testing purposes. Those depend on JDOM (used for XML formatting).
And JDOM itself has a dependency on jaxen:jaxen. But unfortunately the artifact deployed to Maven Central is broken (at least kind of).
To work around those issues with Jaxen use the following excludes:
      &#60;dependency&#62;
  [...]]]></description>
			<content:encoded><![CDATA[<p>I have created some utility classes for testing purposes. Those depend on JDOM (used for XML formatting).</p>
<p>And JDOM itself has a dependency on jaxen:jaxen. But unfortunately the artifact deployed to Maven Central is broken (at least kind of).<br />
To work around those issues with Jaxen use the following excludes:</p>
<pre class="brush:xml">      &lt;dependency&gt;
        &lt;groupId&gt;jaxen&lt;/groupId&gt;
        &lt;artifactId&gt;jaxen&lt;/artifactId&gt;
        &lt;version&gt;1.1.3&lt;/version&gt;
        &lt;!--

http://jira.codehaus.org/browse/JAXEN-217

        --&gt;
        &lt;exclusions&gt;
          &lt;exclusion&gt;
            &lt;groupId&gt;maven-plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-cobertura-plugin&lt;/artifactId&gt;
          &lt;/exclusion&gt;
          &lt;exclusion&gt;
            &lt;groupId&gt;maven-plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-findbugs-plugin&lt;/artifactId&gt;
          &lt;/exclusion&gt;
        &lt;/exclusions&gt;
      &lt;/dependency&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2011/12/fixing-maven-artifact-jaxen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Nexus on Ubuntu/Debian</title>
		<link>http://blog.cedarsoft.com/2011/10/installing-nexus-on-ubuntudebian/</link>
		<comments>http://blog.cedarsoft.com/2011/10/installing-nexus-on-ubuntudebian/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 12:12:07 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[DEB]]></category>
		<category><![CDATA[Debian]]></category>
		<category><![CDATA[Nexus]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=476</guid>
		<description><![CDATA[Installing Nexus manually is not a lot of fun. Thankfully a nice guy has created a working deb:
Repository:
http://build.discursive.com/apt/
It also configures Apache2 as proxy for the nexus instance.
]]></description>
			<content:encoded><![CDATA[<p>Installing Nexus manually is not a lot of fun. Thankfully a <a href="http://www.discursive.com/blog/4635">nice guy</a> has created a working deb:</p>
<p>Repository:<br />
<a href="http://build.discursive.com/apt/">http://build.discursive.com/apt/</a></p>
<p>It also configures Apache2 as proxy for the nexus instance.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2011/10/installing-nexus-on-ubuntudebian/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maven: Compiler Plugin configuration &#8211; showing compiler warnings on console</title>
		<link>http://blog.cedarsoft.com/2011/10/maven-compiler-plugin-configuration-showing-compiler-warnings-on-console/</link>
		<comments>http://blog.cedarsoft.com/2011/10/maven-compiler-plugin-configuration-showing-compiler-warnings-on-console/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 22:03:18 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[Jenkins]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=469</guid>
		<description><![CDATA[The default compiler plugin configuration hides all warnings. To get all messages on the console, this configuration can be used:
&#60;plugin&#62;
  &#60;groupId&#62;org.apache.maven.plugins&#60;/groupId&#62;
  &#60;artifactId&#62;maven-compiler-plugin&#60;/artifactId&#62;
  &#60;version&#62;2.3.2&#60;/version&#62;
  &#60;configuration&#62;
    &#60;source&#62;1.6&#60;/source&#62;
    &#60;target&#62;1.6&#60;/target&#62;
    &#60;encoding&#62;${project.build.sourceEncoding}&#60;/encoding&#62;
    &#60;showWarnings&#62;true&#60;/showWarnings&#62;
    &#60;showDeprecation&#62;true&#60;/showDeprecation&#62;
    &#60;compilerArgument&#62;-Xlint:all&#60;/compilerArgument&#62;
  &#60;/configuration&#62;
&#60;/plugin&#62;
This configuration [...]]]></description>
			<content:encoded><![CDATA[<p>The default compiler plugin configuration hides all warnings. To get all messages on the console, this configuration can be used:</p>
<pre class="brush:xml">&lt;plugin&gt;
  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
  &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
  &lt;version&gt;2.3.2&lt;/version&gt;
  &lt;configuration&gt;
    &lt;source&gt;1.6&lt;/source&gt;
    &lt;target&gt;1.6&lt;/target&gt;
    &lt;encoding&gt;${project.build.sourceEncoding}&lt;/encoding&gt;
    &lt;showWarnings&gt;true&lt;/showWarnings&gt;
    &lt;showDeprecation&gt;true&lt;/showDeprecation&gt;
    &lt;compilerArgument&gt;-Xlint:all&lt;/compilerArgument&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;</pre>
<p>This configuration is for example useful if you want to use &#8220;Compiler Warnings Plugin&#8221; for Jenkins/Hudson.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2011/10/maven-compiler-plugin-configuration-showing-compiler-warnings-on-console/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: Units done right(!?)</title>
		<link>http://blog.cedarsoft.com/2010/11/java-units-done-right/</link>
		<comments>http://blog.cedarsoft.com/2010/11/java-units-done-right/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 16:29:01 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[units]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=461</guid>
		<description><![CDATA[Did you ever hear that sentence?
&#8220;Marks will be removed for missing units&#8221;
Probably yes. And there is a reason why teachers force their students to always use units.
But whatever API you look at, there is (almost) never any hints which unit one should use. Of course reading the Javadoc might give you the right hint &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>Did you ever hear that sentence?<br />
&#8220;Marks will be removed for missing units&#8221;<br />
Probably yes. And there is a reason why teachers force their students to always use units.</p>
<p>But whatever API you look at, there is (almost) never any hints which unit one should use. Of course reading the Javadoc might give you the right hint &#8211; sometimes&#8230;<br />
And the results are well know. The most popular one is the<br />
<a href="http://en.wikipedia.org/wiki/Mars_Climate_Orbiter">Mars Climate Orbiter</a>.</p>
<h2>Solutions so far</h2>
<p>There have been several approaches so far. For example <a href="http://www.jcp.org/en/jsr/detail?id=108">JSR 108</a> with some very interesting ideas.</p>
<p>All those approaches wrap the value and the unit into a container object. This obviously has several disadvantages.<br />
The API will become cluttered. And therefore all those approaches have been dismissed sooner or later.</p>
<p>But not having any information about the unit is a bad idea either&#8230; So what to do?</p>
<h2>Why not using annotations?</h2>
<p>Annotations are (one more time) the answer to the question. Look at that sample code:</p>
<pre class="brush:java">@mm
public double pixelsToMm( @px int pixels, @dpi double resolution ) {
  return pixels / resolution * 25.4;
}</pre>
<p>Readable and comprehensible instantly. No magic. No problems with backwards compatibility. No additional objects, wrapping or other stuff. No loss of precision or performance penalty&#8230;</p>
<h2>Small library</h2>
<p>I have created a small library containing several predefined annotations. But of course it is just a matter of seconds to create your own.</p>
<p>Download manually from<br />
<a href="http://repo2.maven.org/maven2/com/cedarsoft/unit/1.0-beta1/">http://repo2.maven.org/maven2/com/cedarsoft/unit/1.0-beta1/</a></p>
<p>For Maven users:</p>
<pre class="brush:xml">&lt;dependency&gt;
  &lt;groupId&gt;com.cedarsoft&lt;/groupId&gt;
  &lt;artifactId&gt;unit&lt;/artifactId&gt;
  &lt;version&gt;1.0-beta1-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>More informations can be found at <a href="http://cedarsoft.org/unit/">http://cedarsoft.org/unit/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2010/11/java-units-done-right/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Setting &quot;java.library.path&quot; programmatically</title>
		<link>http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/</link>
		<comments>http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/#comments</comments>
		<pubDate>Tue, 02 Nov 2010 19:27:59 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[classloader]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[java.library.path]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=454</guid>
		<description><![CDATA[When messing around with JNI, one have to set the &#8220;java.library.path&#8221; accordingly. Unfortunately the only way is to add a system property *before* the application is started:
java -Djava.library.path=/path/to/libs
Changing the system property later doesn&#8217;t have any effect, since the property is evaluated very early and cached.
But the guys over at jdic discovered a way how to [...]]]></description>
			<content:encoded><![CDATA[<p>When messing around with JNI, one have to set the &#8220;java.library.path&#8221; accordingly. Unfortunately the only way is to add a system property *before* the application is started:</p>
<p>java -Djava.library.path=/path/to/libs</p>
<p>Changing the system property later doesn&#8217;t have any effect, since the property is evaluated very early and cached.<br />
But the guys over at <a href="https://jdic.dev.java.net/">jdic</a> discovered a way how to work around it. It is a little bit dirty &#8211; but hey, those hacks are the reason we all love Java&#8230;</p>
<pre class="brush:java">System.setProperty( "java.library.path", "/path/to/libs" );

Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );</pre>
<h3>Explanation</h3>
<p>At first the system property is updated with the new value. This might be a relative path &#8211; or maybe you want to create that path dynamically.</p>
<p>The Classloader has a static field (sys_paths) that contains the paths. If that field is set to null, it is initialized automatically. Therefore forcing that field to null will result into the reevaluation of the library path as soon as loadLibrary() is called&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Hierarchical structures with Java Enums</title>
		<link>http://blog.cedarsoft.com/2010/10/hierarchical-structures-with-java-enums/</link>
		<comments>http://blog.cedarsoft.com/2010/10/hierarchical-structures-with-java-enums/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 15:46:38 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[enum]]></category>
		<category><![CDATA[hierarchy]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=451</guid>
		<description><![CDATA[I love Enums. There are a lot of use cases, where they become really handy. Especially since I have learned that you can override methods in enums&#8230;
Some days ago Alexander Radzin came up with another nice idea: He created a hierarchical structure using enums. The idea is very simple: Just add a reference to the [...]]]></description>
			<content:encoded><![CDATA[<p>I love Enums. There are a lot of use cases, where they become really handy. Especially since I have learned that you can override methods in enums&#8230;</p>
<p>Some days ago Alexander Radzin came up with <a href="http://alexradzin.blogspot.com/2010/10/hierarchical-structures-with-java-enums_05.html">another nice idea</a>: He created a hierarchical structure using enums. The idea is very simple: Just add a reference to the parent to your enum.</p>
<p>While the idea is really nice, the implementation seems to be a little bit too complicated. I think using reflection is not a very nice thing at all. Therefore I have modified his implementation.</p>
<p>And this is the idea. That idea has a lot of potential &#8211; I am sure I will find a lot of nice use cases&#8230;</p>
<pre class="brush:java">public enum OsType {
OS(null),
Windows(OS),
WindowsNT(Windows),
WindowsNTWorkstation(WindowsNT),
WindowsNTServer(WindowsNT),
Windows2000(Windows),
Windows2000Server(Windows2000),
Windows2000Workstation(Windows2000),
WindowsXp(Windows),
WindowsVista(Windows),
Windows7(Windows),
Windows95(Windows),
Windows98(Windows),
Unix(OS) {
@Override
public boolean supportsXWindowSystem() {
return true;
}
},
Linux(Unix),
AIX(Unix),
HpUx(Unix),
SunOs(Unix),
;

private final OsType parent;
private final List children = new ArrayList();
private final List allChildren = new ArrayList();

OsType( OsType parent ) {
this.parent = parent;
if ( parent != null ) {
parent.addChild( this );
}
}

public OsType parent() {
return parent;
}

public boolean is( OsType other ) {
if ( other == null ) {
return false;
}

for ( OsType osType = this; osType != null; osType = osType.parent() ) {
if ( other == osType ) {
return true;
}
}
return false;
}

public List children() {
return Collections.unmodifiableList( children );
}

public List allChildren() {
return Collections.unmodifiableList( allChildren );
}

private void addChild( OsType child ) {
this.children.add( child );

List greatChildren = new ArrayList();
greatChildren.add( child );
greatChildren.addAll( child.allChildren() );

OsType currentAncestor = this;
while ( currentAncestor != null ) {
currentAncestor.allChildren.addAll( greatChildren );
currentAncestor = currentAncestor.parent;
}
}

public boolean supportsXWindowSystem() {
if ( parent == null ) {
return false;
}

return parent.supportsXWindowSystem();
}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2010/10/hierarchical-structures-with-java-enums/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[Unit Testing]: Time zone and stuff&#8230;</title>
		<link>http://blog.cedarsoft.com/2010/08/unit-testing-time-zone-and-stuff/</link>
		<comments>http://blog.cedarsoft.com/2010/08/unit-testing-time-zone-and-stuff/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 09:46:33 +0000</pubDate>
		<dc:creator>Johannes Schneider</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[joda]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[Rules]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[unit]]></category>

		<guid isPermaLink="false">http://blog.cedarsoft.com/?p=448</guid>
		<description><![CDATA[Do you know those nasty time zone related bugs, too?
They are quite common &#8211; but often they are discovered when it is too late. Often every developer and tester lives in the same time zone. So sometimes the software is never ever run in a different time zone until it is shipped&#8230;
The problem
The idea of [...]]]></description>
			<content:encoded><![CDATA[<p>Do you know those nasty time zone related bugs, too?<br />
They are quite common &#8211; but often they are discovered when it is too late. Often every developer and tester lives in the same time zone. So sometimes the software is never ever run in a different time zone until it is shipped&#8230;</p>
<h2>The problem</h2>
<p>The idea of time zones makes calculating with dates/times really difficult.<br />
But probably we have to live with them for a few more years&#8230;</p>
<p>So as developers we have to handle them properly.</p>
<p>And handling them properly means two things</p>
<h3>Using a nice API</h3>
<p>I am certain that it is impossible to write bug free code using just the standard Calendar stuff.<br />
Maybe James Gosling is able to do that &#8211; but I even doubt that&#8230;</p>
<p>So just use one of those APIs that work. My personal favorite is <a href="http://joda-time.sourceforge.net/">Joda Time</a>. Many cases then just work.</p>
<h3>Testing time zones</h3>
<p>As soon as your software handles dates/times it is necessary to test that code.<br />
But my experience shows that hardly anybody tests anything that needs a lot of work to test. And changing the time zone manually needs some (too much?) work.</p>
<h2>The solution</h2>
<p>JUnit offers rules. Very simple but powerful feature. I have created several custom rules that make live much easier&#8230;</p>
<p>And I have created a timezone rule (based on Joda Time) that allows me to run my unit tests in different time zones.<br />
Here it comes:</p>
<pre class="brush:java">import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTimeZone;
import org.junit.rules.*;
import org.junit.runners.model.*;

/**
* Rule that sets the TimeZone
*
* @author Johannes Schneider (js@cedarsoft.com)
*/
public class DateTimeZoneRule implements MethodRule {
@NotNull
protected final DateTimeZone zone;

public DateTimeZoneRule() throws IllegalArgumentException {
this( "America/New_York" );
}

public DateTimeZoneRule( @NotNull @NonNls String zoneId ) throws IllegalArgumentException {
this( DateTimeZone.forID( zoneId ) );
}

public DateTimeZoneRule( @NotNull DateTimeZone zone ) {
this.zone = zone;
}

private DateTimeZone oldTimeZone;

@Override
public Statement apply( final Statement base, FrameworkMethod method, Object target ) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} finally {
after();
}
}
};
}

private void before() {
oldTimeZone = DateTimeZone.getDefault();
DateTimeZone.setDefault( zone );
}

private void after() {
DateTimeZone.setDefault( oldTimeZone );
}

@NotNull
public DateTimeZone getZone() {
return zone;
}

@NotNull
public DateTimeZone getOldTimeZone() {
if ( oldTimeZone == null ) {
throw new IllegalStateException( "No old zone set" );
}
return oldTimeZone;
}
}</pre>
<p>No magic, nothing special, no rocket science.</p>
<p>Just start using rules &#8211; if will change the world into a better place&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.cedarsoft.com/2010/08/unit-testing-time-zone-and-stuff/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

