Oct 4 2011

Maven: Compiler Plugin configuration – showing compiler warnings on console

The default compiler plugin configuration hides all warnings. To get all messages on the console, this configuration can be used:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
    <encoding>${project.build.sourceEncoding}</encoding>
    <showWarnings>true</showWarnings>
    <showDeprecation>true</showDeprecation>
    <compilerArgument>-Xlint:all</compilerArgument>
  </configuration>
</plugin>

This configuration is for example useful if you want to use “Compiler Warnings Plugin” for Jenkins/Hudson.


Nov 4 2010

Java: Units done right(!?)

Did you ever hear that sentence?
“Marks will be removed for missing units”
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 – sometimes…
And the results are well know. The most popular one is the
Mars Climate Orbiter.

Solutions so far

There have been several approaches so far. For example JSR 108 with some very interesting ideas.

All those approaches wrap the value and the unit into a container object. This obviously has several disadvantages.
The API will become cluttered. And therefore all those approaches have been dismissed sooner or later.

But not having any information about the unit is a bad idea either… So what to do?

Why not using annotations?

Annotations are (one more time) the answer to the question. Look at that sample code:

@mm
public double pixelsToMm( @px int pixels, @dpi double resolution ) {
  return pixels / resolution * 25.4;
}

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…

Small library

I have created a small library containing several predefined annotations. But of course it is just a matter of seconds to create your own.

Download manually from
http://repo2.maven.org/maven2/com/cedarsoft/unit/1.0-beta1/

For Maven users:

<dependency>
  <groupId>com.cedarsoft</groupId>
  <artifactId>unit</artifactId>
  <version>1.0-beta1-SNAPSHOT</version>
</dependency>

More informations can be found at http://cedarsoft.org/unit/


Nov 2 2010

Setting "java.library.path" programmatically

When messing around with JNI, one have to set the “java.library.path” 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’t have any effect, since the property is evaluated very early and cached.
But the guys over at jdic discovered a way how to work around it. It is a little bit dirty – but hey, those hacks are the reason we all love Java…

System.setProperty( "java.library.path", "/path/to/libs" );

Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );

Explanation

At first the system property is updated with the new value. This might be a relative path – or maybe you want to create that path dynamically.

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…


Oct 9 2010

Hierarchical structures with Java Enums

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…

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 parent to your enum.

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.

And this is the idea. That idea has a lot of potential – I am sure I will find a lot of nice use cases…

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();
}
}

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


Jan 25 2010

cedarsoft Serialization 1.0.0 released

cedarsoft Serialization (GPL with Classpath Exception) offers version aware serialization of java object trees with maximum control. Its goal is to provide some simple classes (very small framework) that enables rapid development of versioned serialization.

Serialized XML contains version informations and might look like that:

<?xml version="1.0" encoding="UTF-8"?>
<businessObject xmlns="http://yourcompany.com/path/2.0.1">
  <name>theName</name>
  ...
</businessObject>

It does not contain any “magic” code. It just offers plain and very fast serialization.

It follows those main ideas:

  • Version support as first class citizen (Every serialized object gets its version information attached –>necessary for stability)
  • Minimized boiler plate code (–> fast results), but:
  • No magic (no bad surprises)
  • KISS
  • Performance, performance!
  • Flexibility and therefore stability: Serialized objects can be read with all future versions.

Do not believe the wrong “everything can be done automatically” promise. Write that code that matters. And nothing more.


Sep 10 2007

Splitting up your pom.xml into multiple files

Ever had to deal with a really, really huge pom.xml? As soon as you start not only to declare the dependencies but also to add informations about the distribution (repositories, site), mailinglists or developers, the pom.xml starts to become really huge.

It is hard to find the informations you search. And it is much harder to find that revision a dependecy has changed if there is so much noise due to changes in other sections.
Many applications with huge configuration files started to convert their files into directories over the last years. Apache now has its “conf.d” directory, crontab uses “cron.d” and so on.

Why not take the same step, too? Why not split up the pom.xml into several files that are placed within a directory called “pom.d”?
So I have created a proposal for Maven 2.1.

What do you think?