Aug 24 2010

JUnit: Rules

JUnit has a nice feature now: Rules.
While I don’t like every detail of the implementation, they are basically a very good thing.

This is a short introduction how to use them…

What are rules

Rules are basically wrappers around test methods. They offer a nice way to prepare before a test run and clean up afterwards.
Basically they replace that awful setup/tearDown method stuff…

How to use them

Just create a public (non-static) field for the rule. And add the annotation @Rule.

Example

One of my favorite rules is TemporaryFolder. That rule creates a temporary folder and an easy way to create files and folders…

public class RulesTest {
@Rule
public TemporaryFolder tmp = new TemporaryFolder();

@Test
public void testIt() throws IOException {
  System.out.println( "Creating tmp folder @ " + tmp.newFolder( "aFolder" ).getAbsolutePath() );
  assertTrue( tmp.newFile( "a file" ).exists() );
}
}

The output of this test is (at least on my system):

Creating tmp folder @ /tmp/junit8120700871928645940/aFolder

What to do now?

1. Create a template for your IDE that adds the rule field…

It really is worth it. Please. I know the human being tries to avoid the initial setup costs (of maybe 3 minutes) and prefers to type the same lines several hundred times…

2. Enjoy writing Unit tests (again)

No more long and ugly setup/tearDown methods. No more files accidentally left in the tmp folder…

In the next posts I will show you some more rules that I find very useful….


Aug 7 2010

[Maven + Git] Releasing and Branching done right…

Maven is really awful. I hate it.

But it is by far the best tool available… Therefore I am using it for several years now. And since it is a tool one has to struggle with, I have invested a lot of time into optimizing my build environment. So I know Maven quite well now – better than I wanted…

And of course I am using Git. And I really love it. But unfortunately Git is just a second class citizen in Maven land. The basic things work, but other things don’t (like mvn release:branch).

I have created this checklist for doing a release. Just take a look and compare it with the steps you are doing. I’d like to hear some opinions and ideas for improvements.

Small scripts

I use some scripts that make my life easier:

The setup

The version numbers

The upcoming release will be 1.0.0 (the first release for this project). Therefore no maintenance branches exist yet.

Currently the master branch is set to 1.0.0-SNAPSHOT.

The branches

Branch Description
master Contains the current development version (that will be released as next major release).

(I have an additional pu branch that is merged to master automatically when all tests have been run successfully, but that doesn’t matter for this entry)

next Contains some experimental code (that will be merged to master one day)
maint-[VERSION] Maintenance branches for every version. Just bugfixes are commited here and merged up.

Release: What has to be done

The master branch contains the latest peace of software that shall be released (that means that all bugfixes have been merged in from the maint* branches).

  • Tag for the release
  • Creating a new maint-* branch with updated version number
  • Updating the version number for master
  • Probably updated the version number for next, too

And: Of course release one version of our software…

The Checklist

1: Ensure all bugfixes have been merged into master

git log master..maint-[VERSION]

2: Creating the maint-branch

git checkout master
git checkout -b maint-1.0.0
git publish-branch

3: Releasing on maint

mvn release:prepare
mvn release:perform

4: Merging maint to master

git checkout master
git merge maint-1.0.0

5: Updating the version on master

mvn versions:set -DnewVersion=1.1.0-SNAPSHOT -DgenerateBackupPoms=false
git commit -a -m "preparing for next major release: updated version in master"

6: Merging master to next

git checkout next
git merge master

That merge has probably one merge conflict: The version in the pom.xml. Just keep the value of the next branch.

7: Updating the version for next (optional/if necessary)

mvn versions:set -DnewVersion=2.0.0-SNAPSHOT -DgenerateBackupPoms=false
git commit -a -m "preparing release: updated version in next"

8: Pushing the changes

git push

The result

Now there are three branches with different version numbers:

Branch Version
maint-1.0.0 1.0.1-SNAPSHOT
master 1.1.0-SNAPSHOT
next 2.0.0-SNAPSHOT

Aug 6 2010

Code Generation done right…

Code Generation solves a lot of problems. And everybody uses it all the day: Ever generated Getters/Setters using your IDE? Or method stubs? Or constructors?

And sometimes complete classes are generated. One famous example is Hibernate that is able to generate Java classes from a database schema.

Most of the projects I have seen so far use a templating engine (FreeMarker or Velocity) to create the source files. Hibernate switched from Velocity to FreeMarker some years ago…

This approach is quite good for simple cases. Those can be solved quite fast using that approach.

Complexity

But things get worse, if you have to generate more sophisticated code. Of course FreeMarker supports conditions and you can do quite amazing things using complex model classes. On the other hand those templates start to get really complicated and hard to debug over time.
And of course you always have two sources: The template file and your data model.

Imports

One thing special to Java source files are the imports. When you conditionally use a class somewhere, you also have to add the import statement conditionally… Nothing that can be solved easily using FreeMarker.

So sometimes one might wish to have a nice API that does all the dirty work for you…

The alternative: Codemodel

I have looked around to find such an API. And it took me quite a long time to find one.
And that API is quite near beside you. Just a little bit hidden.

JAXB has a sub project called codemodel. This is an API that allows you to create Java classes by just using an API…

How to use Codemodel

There is no separate jar for codemodel. But the classes are shipped with every JAXB installation. So since JDK 1.6 the classes are just here and waiting to be used. But since they have renamed the package as “internal” I suggest to import the JAXB jar manually:

For Maven users this should be enough:

<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-xjc</artifactId>
  <version>2.2.1</version>
</dependency>

A quick introduction

The API is not perfect yet. And it is not documented very well. But it is nearly complete and I didn’t miss much.
Here is a short example that should give you a fast start:

JCodeModel codeModel = new JCodeModel();
JDefinedClass foo = codeModel._class( "a.b.c.Foo" ); //Creates a new class

JMethod method = foo.method( JMod.PUBLIC, Void.TYPE, "doFoo" ); //Adds a method to the class
method.body()._return( JExpr.lit( 42 ) ); //the return statement

The code can be written to the file system. But it can also be written to a single output stream. This is great for testing:

ByteArrayOutputStream out = new ByteArrayOutputStream();
codeModel.build( new SingleStreamCodeWriter( out ) );

This code outputs that code:

-----------------------------------a.b.c.Foo.java-----------------------------------

package a.b.c;

public class Foo {

public void doFoo() {
return 42;
}

}

Great, isn’t it?


Aug 5 2010

Java Surprise: Setters/Getters and Collections

Inspired by the Java Killers series, I wanted to post a problem I stumbled across some years ago:

Imagine a bean containing a field.

class Car {
private final List tires = new ArrayList();

public void setTires( List tires ) {
this.tires.clear();
this.tires.addAll( tires );
}

public void addTire( Tire tires ) {
this.tires.add( tires );
}

public List getTires() {
return Collections.unmodifiableList( tires );
}
}

What is the output of that code?

Car car = new Car();
car.addTire( new Tire() );
car.addTire( new Tire() );

List carTires = car.getTires();
System.out.println( "before: " + carTires.size() );
car.setTires( carTires );
System.out.println( "after1: " + car.getTires().size() );
System.out.println( "after2: " + carTires.size() );

The first part is easy:

before: 2

But the rest?

Continue reading


Jul 15 2010

Maven: Fixing table bug for site plugin 2.1

Some time ago a new big release for the site plugin has been done.
Unfortunately they have introduced a small bug:

The table tags now contain the alignment attribute set to “left”.

This results to some strange bugs. Take a look at that page:
http://fest.easytesting.org/javafx/maven/compile-mojo.html

Table Bug in maven-site-plugin:2.1

Look at the background of the table. The following h3 gets resized and its background is drawn behind the table…

To fix it, just add those lines to the CSS:
[cc lang="css"]
table {
float: none;
}[/cc]


Jul 10 2010

JUnit @Theory oddities

At the moment I try to switch my tests for serialization.cedarsoft.org over to JUnit Theories (4.8.1).

And I run into some problems:

No DataPoints

@RunWith( Theories.class )
public class TheoriesTest {
@Theory
public void aTheory( String arg ) {
System.out.println( "TheoriesTest.aTheory(" + arg + ")" );
assertNotNull( arg );
}
}

Throws an exception: java.lang.AssertionError: Never found parameters that satisfied method assumptions. Violated assumptions: []

Very nice. A theory doesn’t make any sense without any DataPoints.

A DataPoint method

Okay, now I created a DataPoints method:

@DataPoint
public static String getParam() {
return "daParam";
}

And everything works as expected.

Removing the static keyword

In my test cases I try to avoid every unnecessary key press as good as I can. Therefore I would like to create an abstract method that I just have to implement (IDE creates the method stub for me then).

So I just removed the static keyword from the method to try if it is possible…

And guess what?

The test method did not run – but is reported as succeeded…


Jul 6 2010

JavaFX2Java Bridge added to JFXtras (step 2)

Thanks to Stephen: He has prepared a branch for the upcoming 0.7 release of JFXtras. Now it has been possible to merge the latest changes to the JFXtras default branch.

There are a lot of changes waiting in line. While the 0.7 release will be a huge step, I am really looking forward for 0.8…

So if you want to take a look at the latest changes, just check out the source code at http://code.google.com/p/jfxtras/source/checkout.


Jul 3 2010

JavaFX2Java Bridge added to JFXtras (step 1)

It has taken a long time since I promised to integrate the JavaFX2Java bridge to JFXtras until I finally did it…

At the moment the code is located at a clone that will be integrated as soon as JFXtras 0.7 has been released.

The clone can be accessed there:

https://js-mavenization.googlecode.com/hg/

The package is named “org.jfxtras.bridge”.


Jun 18 2010

JFXtras: 0.7 RC1 released

Hi guys,

the first release candidate for JFXtras 0.7 has been released. This version is (should be) fully functional with JavaFX 1.3
Downloads can be found at http://jfxtras.org/


May 11 2010

Closing the gap between Java and JavaFX

There is a huge gap between Java and JavaFX: While it is very easy to bind JavaFX objects to each other there has been no way to bind JavaFX objects to Java properties (and vice versa).

It has taken me some time to figure out how this could be solved. And at the moment I am in the progress of adding that stuff to the JFXtras project.
This will take some time until I have taken all necessary steps.

Until then i want to give you a quick jar that can be used to try that stuff…

To try it, download that jar and add it to the classpath of your JavaFX project:
bridge-1.0.0-SNAPSHOT-jar-with-dependencies

There are two ways of synchronization. At first it is possible to listen for changes to Java objects and update an JavaFX object accordingly. At the moment I have implemented two ways to listen for updates.

Java to JavaFX

  • PropertyChangeEvents: This is the recommended way: Just make your Java bean fire PropertyChangeEvents whenever a property has changed.
  • Busy waiting: I have added a hackish way of busy waiting. This should not be used in production code. But it offers a fast way to test things

JavaFX to Java

The reverse way has also two ways implemented:

  • Calling of setters: If a JavaFX var is updated, this bridge calls the corresponding setter of your Java object (using reflection or optionally your own optimized implementation).
  • PropertyChangeEvents: It is possible to create a bridge that converts the JavaFX binding
    updates to PropertyChangeEvents.

With inverse…

Of course it is also possible (and most of the time necessary) to create bindings with inverse. I give you a small sample how this might work here:

We create our Java “model”:
[cc lang="java"]package fxbindingtest;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class JavaClass {
private float amount = 99;

public float getAmount() {
return amount;
}

public void setAmount(float amount) {
pcs.firePropertyChange(“amount”, this.amount, this.amount=amount);
System.out.println(“Changed amount to ” + amount );
}

final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

public void addPropertyChangeListener( PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener( PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
}
[/cc]

And here comes our JavaFX stage. This stage contains just a slider that is bound to the Java object (with inverse).
Every five seconds the model object is updated (amount+=10) – and reflected by the slider.

[cc lang="c"]package fxbindingtest;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import com.cedarsoft.fx.JavaFxBridge;
import com.sun.javafx.runtime.FXObject;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;

/**
* @author johannes
*/
var slider: Slider;

//The java model class. Contains the property “amount” and a PropertyChangeSupport
def javaModel = new JavaClass();

Stage {
title: “Application title”
scene: Scene {
width: 800
height: 600
content: [
slider = Slider {
min: 1
max: 100
snapToTicks: true
}
]
}
}

//Create the binding from the java model to the slider
//Using the defaults:
// Java –> FX: PropertyChangeEvents
// FX –> Java: Calling setters by reflection
JavaFxBridge.bridge( javaModel ).to( slider as FXObject ).connecting(
JavaFxBridge.bind( “amount” ).to( “value” ).withInverse()
); //sorry for the stupid API – needs some polishing…

//Add a timeline to simulate changes to the model
Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 5s
action: function() {
println("changing amount on model");
javaModel.setAmount( javaModel.getAmount() + 10 );
}
}
];
}.play();
[/cc]

And here a JNLP to run the demo (open Java Console to see the updates printed to System.out):
webstart

Disclaimer:
This is just a working-in-some-situations-prototype. It is not production-ready by far.
But if you have any comments/ideas/bugs, please mail me.

The source code can be downloaded here. But I will add that stuff to JFXtras very soon…