Twitter icon.
Random notes on software, programming and languages.
By Adrian Kuhn

Archive for the ‘Java’ Category

ZIP Code Map of Switzerland


Wednesday, October 15th, 2008

Inspired by Robert Kosara’s US ZIP Scribble Map as well as Stefan Zeiger’s ZIP Code Map of Germany, I’ve done a small script that renders Switzerland as a ZIP code map.

Edit: obviously, Robert Kosara has also done a ZIP scribble map of Switzerland, but it is broken. On the US original he explores the correlations of 1000-blocks of ZIP codes and state boundaries. On his Swiss map however, he directly groups the lines by cantons! Which is obviously not the same since we have 26 cantons but only nine blocks of 1000 ZIP codes.

In particular interesting is how the red and brown ZIP code blocks are dividing the canton Valais by its two languages: French and German! (For foreigners: the valais is the huge valley in the south-east which is covered half by red lines and half by brown lines.)

The script is written in Pimon, a small visualization framework for VW Smalltalk. Of course, Pimon has a DSL! The layout- and drawing DSL of Pimon offers a fluent interface that targets the end-users of common Desktop applications. Figures are grouped, aligned and positioned as you would do it in an Desktop application, rather than forcing the programmer to wrap his head around vector algebra with all its x’s and y’s.

The following bunch of Pimon code specifies a tree layout (the same in Java):

TreeLevel >> arrange
    | group |
    group := Group new
        addAll: self treeChildren;
        horizontalWithGap: 4;
        alignTop.
    Group new
        add: self treeParent;
        add: group;
        verticalWithGap: 16;
        alignCenter.
    self resizeToElements.

I started porting Pimon to Java last year, but only got 80% done and thus never released it to the public. However, it is sad to let code decay without being used and maybe the parts that are working turn out to be useful for your projects, thus I published it today:

The Rabbit Will Die in Java


Monday, July 14th, 2008

Since some days, an army of mad rabbits has been invading my brain. DWEMTHY’S ARRAY, GIEV US DWEMTHY’S ARRAY, MOAR, MOAR SAUCE, MOAR!!!!!1!!1, they cry.

Finally, I have given in and did Dwemthy’s Array … in Java.

“In this game, you are a rabbit who is going to die. A dragon is going to do it. Deep in Dwemthy’s Array.” – why the lucky stiff

new Creature("Dragon") {{
    life = 1340;     // tough scales
    strength = 451;  // bristling veins
    charisma = 1020; // toothy smile
    weapon = 939;    // fire breath
}};

More on this code in a moment.

For those unfamiliar with Dwemthy’s Array, it is a Ruby meta-programming example that is along the lines of a text-based game. The game has been put on Ward’s wiki as a challenge to Smalltalk advocates: “Go ahead and reimplement DwemthysArray!” Darren Hobbes and, recently, Nicholas Chen have taken the challenge. But never has nobody been so insane to met the challenge in the vast quagmires of Java meta-programming—not until, NOW.

*   *   *

You can not enter the Array unprepared, let us face the ScubaArgentine first:

new Creature("ScubaArgentine") {{
    life = 46;
    strength = 35;
    charisma = 91;
    weapon = 2;
}};

Creature r = new Rabbit();
Creature s = new_("ScubaArgentine");

Now use the little boomerang!

r.send( '^', s )

>> [You hit with 2 points of damage!]
>> [Your enemy hit with 28 points of damage!]
>> [Rabbit has died.]

How does it work? We use double brace initialization to define an anonymous subclasses with pre-initialized fields. And, a custom binding mechanism is used to create instances of that class.

Even though most Java programmers are familiar with double brace initialization, I will explain it for the n00bs. The idiom combines two features of Java: anonymous inner classes and instance initializers (think anonymous constructors). Thus, the first brace creates a new anonymous inner class, the second declares an instance initializer block that is run when the anonymous inner class is instantiated.

Being anonymous, the inner class is not bound to any identifier. Therefore we can not simply use new to create new instances. Instead, we must setup a custom binding mechanism. The name “ScubaArgentine” is passed to Creature’s constructor, which binds name and anonymous class in a static lookup table. The same table is consulted by a static new_ method to create custom instances.

This is implemented in Creature as follows:

private static final Map<String, Class<? extends Creature>> INDEX = new TreeMap();
protected String name;

public Creature(String name) {
    INDEX.put(name, this.getClass());
    this.name = name;
}

public static Creature new_(String name) { try {
    return (Creature) INDEX.get(name).getDeclaredConstructors()[0].newInstance(name);
}
//handle
     catch(Exception e) { throw new RuntimeException(e); }}

Once you’re done with the example guy, it’s time to enter The Array.

You have six foes.

new Creature("IndustrialRaverMonkey") {{
    life = 46;
    strength = 35;
    charisma = 91;
    weapon = 2;
}};

new Creature("DwarvenAngel") {{
    life = 540;
    strength = 6;
    charisma = 144;
    weapon = 50;
}};

new Creature("AssistantViceTentacleAndOmbudsman") {{
    life = 320;
    strength = 6;
    charisma = 144;
    weapon = 50;
}};

new Creature("TeethDeer") {{
    life = 655;
    strength = 192;
    charisma = 19;
    weapon = 109;
}};

new Creature("IntrepidDecomposedCyclist") {{
    life = 901;
    strength = 560;
    charisma = 422;
    weapon = 105;
}};

new Creature("Dragon") {{
    life = 1340;     // tough scales
    strength = 451;  // bristling veins
    charisma = 1020; // toothy smile
    weapon = 939;    // fire breath
}};

Creature dwary = new DwemthysArray(new_("IndustrialRaverMonkey"),
                                   new_("DwarvenAngel"),
                                   new_("AssistantViceTentacleAndOmbudsman"),
                                   new_("TeethDeer"),
                                   new_("IntrepidDecomposedCyclist"),
                                   new_("Dragon"));

In Ruby, DwemthysArray is a subclass of Array that delegates unknown methods to its first creature. Whenever the first creature dies, it is removed from the array, and thus, a new enemy emerges.

Alas, the implementation of DwemthysArray in Java is not as elegant. Why? Java has neither method_missing hook, nor does it support duck typing. And even worse, Java arrays are a built-in type which can not be subclasses. Thus, to keep the demons of static type checking at bay, we extend Creature and include the array as private array field only.

In order to let a new creature emerge whenever the current is found to be dead, we must intercept any boolean check that compares the life field against zero. As we can not override a field access, the Java implementation uses alive() wherever live <= 0 is used in Ruby.

Edit: Clinton Begin has refactored my code to be even MOAR META!!!. He implements DwemthysArray using a dynamic proxy, which is much closer to the original Ruby code.

Here, I shall unmask the Array Creature for you:

public class DwemthysArray extends Creature {

    private Creature[] array;

    public DwemthysArray(Creature... array) {
        super("$");
        this.array = array;
    }

    public boolean alive() {
        if (life > 0) return true;
        if (array.length == 0) {
            puts( "[Whoa.  You decimated Dwemthy's Array!]" );
            return false;
        } else {
            life = array[0].life;
            strength = array[0].strength;
            charisma = array[0].charisma;
            weapon = array[0].weapon;
            name = array[0].name;
            array = Arrays.copyOfRange(array, 1, array.length);
            puts( "[Get ready. %s has emerged.]", this.name );
            return true;
        }
    }

}

“Fight the Array and the monsters will appear as you go. Godspeed and may you return with harrowing tales and nary an angel talon piercing through your shoulder.”

Start here:

while (dwary.alive() && r.alive()) {
    puts( r );
    r.send( gets().charAt(0), dwary );
}

The remainder of the implementation is (except for some additional syntactic noise) almost a genuine port of the Ruby code. Reflection is used to dispatch Rabbit’s overloaded operators to methods and to mimic the output of Ruby’s inspect method. And there are a couple of static convenience methods, like puts and gets.

The full source code is available online.

Class Once, Class Separator


Saturday, July 12th, 2008

Every once a while, you stumble upon one of those rare programming gems that immediately make it into your personal utils project. Today, this happened when I stumbled upon class Once and class Separator by Yossi Gil of the Technion.

Let’s start head first, with an example:

Separator s = new Separator(", ");
for (String n : names) {
    System.out.println(s + n);
}

This prints a comma separated list of names, excluding trailing comma—without using any if statement or referring the loop’s underlaying iterable! Wooow, that’s what I call mastering the art of code fu. Moar, pleaze, moar!

The implementation of class Separator is straight forward. It wraps a string that is returned on every call of toString() except for the first call, which returns an empty string.

The class Once is implemented in the same way, but with reversed logic. In the first call of toString(), the initial value is returned. In all subsequent calls, the empty string is returned.

You can find the sources of both classes on the SSDL wiki:


NB for the interested reader, my previous stumble was the internal implementation of List, ListBuffer and Pair in the Java compiler sources.

5 Minute Guide to JExample


Tuesday, April 29th, 2008

JExample is an extensions of JUnit that improves defect localizaton. JExample introduces first-class dependencies. If test B depends on A, the return value of A can be used as B’s fixture. And if test A fails, then B and all other dependents of A are skipped and marked as white. In an upcoming XP 2008 paper, we show that JExample improves performance, and defect localization compared to plain JUnit tests.

In this tutorial, we are going to write a simple JExample test. We write a test for Java’s Stack class. Testing a stack is not trivial, there is an intrinsic dependency between pushing and popping elements. An element can not be popped without pushing it first. Intrinsic dependencies are evil. If there is a bug in push, both push’s and pop’s test fail, even if there is no bug in pop! In a large project, it may happen that a single bug causes dozens if not hundreds of tests to fail. Usually, only one of these tests covers the actual failure, whereas all others are false positives.

Download either the JAR file or use the Eclipse update-site to install the library plug-in.

We start with a simple test case, annotated with @RunWith. This annotations is provided by JUnit as an extension point for plugins. To run the test case with JExample, we pass JExample.class as the annotation’s value.

  import ch.unibe.jexample.JExample;
  import org.junit.runner.RunWith;

  @RunWith(JExample.class)
  public class StackTest { 

  }

Next we create our first test method: testEmpty creates an empty stack and asserts that its size is indeed zero. As JExample extends JUnit, the test method is annotated with @Test. But unlike with JUnit, the test yields its unit under test as return value! When executing the method, JExample caches that value for later use.

  import static org.junit.Assert.*;
  import java.util.Stack;
  import org.junit.Test;

  @Test
  public Stack<Integer> testEmpty() {
      Stack<Integer> stack = new Stack<Integer>();
      assertEquals(0, stack.size());
      return stack;
  }

Now, we are going to write a consumer test that uses the above return value as its fixture: testPush takes an empty stack as input parameter, adds an element and, again, returns the under under test. The dependency is declared using JExample’s @Given annotation. To inject the result of testEmpty, we pass "testEmpty" as the annotation’s value. When executing the method, JExample will pass the cached result of testEmptyStack as input parameter to testPush. This is called dependency injection.

  import ch.unibe.jexample.Given;

  @Test
  @Given("#testEmpty")
  public Stack<Integer> testPush(Stack<Integer> stack) {
      stack.push(42);
      assertFalse(stack.isEmpty());
      return stack;
  }

The same is done for testPop, which depends on testPush.

  @Test
  @Given("#testPush(java.util.Stack)")
  public void testPop(Stack<Integer> stack) {
      int element = stack.pop();
      assertEquals(42, element);
      assertTrue(stack.isEmpty());
  }

Now, let’s assume there is a bug in Stack.push(). The framework will run testEmpty, inject its return value into testPush, run it—which fails!—and thus skip testPop. Given these results we can quickly locate the bug.

More information is available on the JExampe wiki pages

For.example is Digg proof thanks to caching by WP Super Cache!