Type Safe Enumeration with Java Generics

July 28th, 2009

I’ve been working with Java 5 Generics for about one year now and one pattern that emerged from my experience is the use of generics to create enumerations that provide type safety (I don’t claim to be the inventor of that pattern, actually I don’t even claim it is a pattern).

Often type safety can be achieved by using method type variables like

public abstract <N extends Number> createNumber(Class<? extends N> numberType, String stringValue);

The drawback of this solution is that all the classes must belong to the same hierarchy, in that example they all need to be a subclass of java.lang.Number. The most direct workaround is to free the type variable from its upper bound java.lang.Number. That makes the choice very large since any subclass of java.lang.Object can be accepted.

It is also impossible to prevent some subclass to be used as type argument at compilation time. Failure would have to happen at runtime with an java.lang.IllegalArgumentException thrown for instance.

Those two limitations makes the method not easy to understand the first time you see it, specially when it is part of an API, and it is not possible to make it type safe (actually not as far as I know :-) ) as Java Enums cannot be used as a generic declaration.

So I had to find a way to express an enumerated type that would be type safe. The solution I found is actually not an enumeration in the old/classic way we use to know it before Java 5 Enums (i.e it is class that has a private constructor with public static fields) and therefore it cannot be used in a switch statement. That probably is the only drawback I found but it is a more acceptable issue than the two problems I had before.

Let’s assume we represent a concept of simple types which are arbitrarily defined by String, Boolean and Integer with

public class SimpleType<S> {

   public static final SimpleType<String> STRING =
      new SimpleType<String>(String.class);

   public static final SimpleType<Integer> INTEGER =
      new SimpleType<Integer>(Integer.class);

   public static final SimpleType<Boolean> BOOLEAN =
      new SimpleType<Boolean>(Boolean.class);

   private final Class<S> javaType;

   private SimpleType(Class<S> javaType) {
      this.javaType = javaType;
   }
}

Now we can easily use it as a type safe enumeration, for instance here is how I would write a parse method:

/*
 * Note : yeah this is not really OO and it could be
 * possible to have an abstract parse(String s)
 * method on the SimpleType class and have the static
 * method delegate to it. I leave it as an exercise
 * for the reader.
 */
public <T> T parse(SimpleType<T> simpleType, String s) throws NullPointerException {
   if (simpleType == null)
      throw new NullPointerException("No null simple type is accepted!");
   if (s == null)
      throw new NullPointerException("No null string can be parsed!");
   if (simpleType == SimpleType.STRING)
      return s;
   if (simpleType == SimpleType.INTEGER)
      return Integer.valueOf(s);
   if (simpleType == SimpleType.BOOLEAN)
      return Boolean.valueOf(s);
   throw new AssertionError("impossible!);
}

This way we enforce the set of types that can be passed as arguments in our method and we do it in a manner that will enforce the developer to write type safe code.

Next time I’ll show you have it is possible to improve the pattern efficiency and usability by adding methods on the Type Safe Enumeration class.

Advanced Java reflection framework needs a (good enough) name

July 17th, 2009

I have been working during the past few days on a reflection framework for Java. Beside the complexity of the actual reflection layer, the developer is pretty much left to himself to perform advanced operations such as type variable resolution or annotation discovery based on the type inheritance hierarchy.

Furthermore this reflection framework is implemented with the runtime java reflection API (java.lang.reflect.Type and its implementations) and the compile time java reflection API (javax.lang.model.type.*). It means you can perform compile time reflection or runtime reflection with the same code. I forgot to mention that the java compile time API is awful.

The first reason I wrote this framework was to perform type variable resolution based on a specific class. I needed to perform such operations for a new project (that I will announce soon, stay tuned).

Let me give you an example:

public class A<V> {

  private final V value;

  public A(V value) {
    this.value = value;
  }

  public V getValue() {
    return value;
  }

public class B extends A<String> {
  public B(String value) {
    super(value);
  }
}

Now if we want to know what is the value of the type variable V at runtime for the class B, the code to perform the resolution is pretty tricky to write and requires a fairly good knowledge of the java type system, although it’s a very intuitive operation to do. Let me give you another example:

public class Event<S> {

  private S source;

  public Event(S source) {
    this.source = source;
  }

  public S getSource() {
    return source;
  }

}
public interface Listener<S> {

  void onEvent(Event<S> event);
}

public class FooListener implements Listener<String> {
  void onEvent(Event<String> event);
}

Although we all know that Java type erasure will not give us the type of S at runtime from instances of the Event class, any implementation of the Listener interface will carry the information about the type variable. Note that it may not be possible to resolve it if the subclass does not bind the variable to a type. It is therefore possible for the framework broadcasting events to know if a listener is able to receive events from a particular source.

Since Java 6 it becomes very easy to process source code at compile time (as exhibited by Gavin King during his researches about the type safe criteria API for JPA). For instance it would be possible to replace the need for CGLib at runtime by a library that would perform a similar work at compile time (actually I wrote pretty much that in the forthcoming project). The advanced Java reflection framework helps to hide the java compile time reflection API. The compile time API is source code oriented but does expose the same semantics as the runtime API.

Another neat feature is the resolution of annotations along a type hierarchy which is very useful if you want to determine the annotation of a type or a method taking in account the type hierarchy. Very useful in the following situation

@Foo
public interface A {
  @Bar void m();
}

public class B implements A {
  public void m() {
  }
}

Finally the framework has some nice stuff coming in, such as the inclusion of the visitor pattern that allows you to perform an operation along the hierarchy of a type, the obtention of the raw class type of any type which attempts to unify the raw type of a parameterized type and the elimination of the synthetic methods due to the return type covariance.

I plan to host that reflection framework project soon somewhere (under LGPL) because I think it will be useful to anyone performing advanced operations with the Java reflection. What is missing for now is a decent name for the project since I haven’t been able to come up with something nice. If you have a good suggestion, don’t hesitate to send me an email (go on www.julienviet.com for the @).

Marseille JUG au BarCamp Marseille 2!

April 19th, 2009

Vendredi 7 avril j’ai participé au BarCamp Marseille 2 pour promouvoir la création du Marseille JUG.

Les évènements orientés nouvelles technologies sont plutot rares sur Marseille et c’est ma première participation à un BarCamp. A vrai dire je ne connaissais pas ce concept avant cette occasion dont j’ai connu l’existence via le Twit de Charles, rencontré de visu justement durant l’occasion.

L’école d’ingénieur Supinfo Marseille hébergeait le BarCamp pour l’occasion ce qui m’a donné l’occasion de visiter les docks qui ont été rénovés il y a quelques années. J’avais déjà visité un peu les docks et j’ai constaté que l’intérieur des batiments est aussi beau que l’aspect extérieur le laisse penser.

A présent, venons en aux faits! furent présents lors de la réunion:

  • Alain Defrance formateur Java à Supinfo
  • Yann Vigara revenu de Paris il y a quelques mois et qui démarre une activité d’hébergeur Java
  • Alexandre Terasson et Florien Berton élèves à Supinfo
  • Cyril Bourgès étudiant en master SIS de Luminy
  • Moi même

La réunion a d’abord commencé par les cordialités d’usage à savoir la présentation de chacun des participants.

Il faut savoir que notre aventure du Marseille JUG a débuté il y a quelques semaines.  Khaled, Colin, Alain et moi même nous sommes déjà rencontré plusieurs fois avant le BarCamp (malheureusement Khaled et Colin n’ont pas pu participer au meeting BarCamp). Nous avions donc déjà donné une direction au JUG et cela a été l’occasion d’exposer nos décisions. Je rassure tout de même, celles ci sont assez standard et nous n’auront pas une gouvernance basée sur le totalitarisme, en fait la plupart d’entre elles émargent de la lecture de la mailing list des JUG leaders français. Voici donc les points que nous avons discutés:

  • Direction collégiale avec des status basés sur la notion de co présidents. Cela nous est apparu comme le mode idéal et a suggéré par un JUG ayant ce mode de gouvernance
  • Volonté de faire une réunion unique avant fin juin 2009 et mise en place d’un calendrier de réunions pour la saison 2009/2010
  • Recherche de partenaires et de sponsors financiers pour aider le JUG

Il apparaît que Supinfo fournira un partenariat afin que le JUG puisse profiter des locaux de l’école. Ceux ci semblent idéaux car modernes et avec une position géographique très avantageante. Nous souhaiterions effectuer une réunion mensuelle du JUG, vraisemblablement le mercredi qui est un jour où nous pourrions utiliser la salle aussi bien l’après midi que le soir (probablement 18h).

Finalement nous avons conclu qu’à présent la prochaine action à effectuer est de s’occuper de tout le travail administratif qui fondera le JUG en tant qu’assocation 1901. Ceci est un mal plus que nécéssaire pour la création du JUG.

Longue vie au Marseille JUG!

Soirée SOA au Riviera JUG le vendredi 10 avril 2009

April 3rd, 2009

Le Riviera JUG organise sa deuxième rencontre le 10 avril sur le theme SOA, si vous êtes intéressé vous trouverez plus d’information sur cette page.

Marseille JUG

April 2nd, 2009

Depuis quelques mois une folie créatrice de groupes d’utilisateurs Java (JUG) envahit la France et un JUG se monte naturellement dans la région de Marseille. Si vous êtes intéressé de quelque manière que ce soit, vous pouvez prendre contact avec l’équipe du JUG.

How to mount a remote AFP drive on AppleTV Take Two

January 11th, 2009

I suppose that you have already installed NitoTV on your AppleTV as you need it to get remote drive access (note that it’s probably possible to do without it by doing everything through SSH).

The AppleTV with a native firmware above 2.0, does not have the AFP protocol in its recovery partition. So even though you upload the MacOSXUpdCombo10.4.9Intel.dmg on the AppleTV and create the recovery.dmg it will not give you access to the AFP protocol. The main reason is that the recovery.dmg image does not contain it! But if you would have an AppleTV with a 1.0 firmware it would have worked since it’s still in the recovery partition (it makes sense, doesn’t it) ?

Someone found a solution to workaround this issue, and I think it’s interesting to blog about it, since it’s in a forum post on the atvflash forums (it’s also like a note to myself, in case the post would disappear). So here is verbatim the solution:

  1. Do a factory restore of the ATV, update the firmware to the latest version and then run the patchstick again. You may be able to uninstall NitoTV but I couldn’t get this to work after a failed smart installer attempt. A freshly hacked box seems to be the most reliable method.
  2. On ATV: SSH in with terminal and enter sudo dd if=/dev/disk0s2 of=recovery2.dmg bs=1m
    This makes a recovery image of your Take 2 recovery partition.
  3. On the Mac: sFTP into the ATV, I used an app called Fugu to do this, and download recovery2.dmg to your desktop.
  4. On the Mac: Open recovery2.dmg. Once it’s mounted you’ll see a number of files in there but the one we’re interested in is called “OS.dmg”. Rename this to anything you want.
  5. On the Mac: Copy in the 1.0 recovery image you have managed to obtain. Mine was called OS-dot-DMG 1.0.dmg and the md5 = 55b909196952ff72c93aaf3553cf661e
  6.  On the Mac: Rename the image file you have just copied to “OS.dmg” and then unmount recovery2.dmg. You will now have an image of your ATV’s recovery partition called recovery2.dmg but the OS.dmg file contained within has been replaced with the 1.0 version.
  7. On the Mac: sFTP into the ATV and upload the edited recovery2.dmg to the Documents folder. Then rename this file recovery.dmg
  8. On the Mac: sFTP into the ATV and upload MacOSXUpdCombo10.4.9Intel.dmg to the Documents folder.
  9. On ATV: With the remote navigate to the DVD/NitoTV menu and select Settings > Install Software. I then ran ‘Install Perian’, ‘Install mPlayer Codecs’ and ‘Install Turbo’s kextloader’ in that order. This probably wasn’t necessary and most of it is probably already there but worth doing just to be safe.
  10. On ATV: Once all this is done you’re ready to run smart installer.
  11. 11) Unplug the ATV, plug it back in and then you should be able to mount the box on your mac and see your shares on the ATV. I’ve found that streaming video from your Mac via afp in NitoTv/DVD is a bit choppy. Streaming through the “Files” menu seems much smoother.

The only thing I need to add is that the so called “OS-dot-DMG 1.0.dmg” is the original firmware of the AppleTV that you can obtain if you own an AppleTV Take One.

The original forum post can be found here and all the credits go to Scrubadub and Magic, whoever you are.

Nikon D80 HDR bracketing tutorial

January 6th, 2009

Recently I dived into High Dynamic Range photography (also known as HDR) using my Nikon D80.

My interest for the HDR technology is the capability to produce images that would be almost impossible to take with a digital camera. An HDR image reveals details in the light and dark areas of your images.

HDR

HDR

For instance, on this picture we can see the details in the clouds but also on the rock and it would be very hard to achieve it without HDR.

This tutorial does not explain how to create an HDR image because there are already very good tutorials on that subject, for instance you can read Vanilla Days tutorial, it is based on the Photomatix software but it does not hurt and you could use another software.

I will rather focus on explaining how to configure a Nikon D80 to leverage a built in feature called Auto Exposure Bracketing (AEB) that makes easier the creation of HDR images. I found all the relevant informations in the user manual but they were not clear enough and I had to spend some time on it in order to get it effective.

HDR imaging works by combining the same image with different exposures into a single image using an appropriate software. No need to emphasis on the fact that the images should rigorously be the same as possible. It can be done manually by shooting several times the same pictures with different exposure time and keeping the same aperture size, but it has at least two drawbacks:

  • you need to physically touch the camera to change the exposure and it could change slightly the different images
  • it take time to reconfigure the camera and your image may change during that time (clouds may move for instance)

The Nikon D80 has a feature called bracketing that allows to shoot three times the same pictures with the same aperture but with different exposures in that order:

  1. The normal image
  2. The underexposed image
  3. The overexposed image

Here is my howto for configuring the D80 appropriately:

Configure the image quality

The first step is to set the image quality to RAW. You can change it by pressing the QUAL button and rotate the the main command until you get RAW.

Configure the ISO sensitivity

Set the ISO sensitivity to the lowest value you can afford, for instance ISO 100 works well most of the time for me.

Configure the focus mode

Focus mode should be configured to manual (perhaps it’s possible to use automatic but I never tried).

Configure the mode

Set the D80 into Aperture-priority mode (A). Exposure bracketing works with that mode.

Configure the bracketing

Press the BKT button and rotate the main dial to chose 3 shoots and the sub-command dial to choose the bracketing increment with the value 2.0EV. At this moment you configured the D80 to change the exposure of the photo each time you shoot. Therefore the first picture you take is a normal one, but the second one will be underexposed by 2EV and the third one will be overexposed by 2EV. The forth one will be exposed normally.

Configure the shooting mode

The final step is to configure the shooting mode to continuous.

Et voilà!

The next time you will take a picture keep the finder pressed and the D80 will take the three shoots for you. Now it’s up to you to make great HDR pictures!

I’ll be at Devoxx 08

December 8th, 2008

Long time no blog, just a quick note that tell you that I will be at Devoxx 08 as a representative of eXo in the exhibition center.

See you there!

The WebOS Vision

October 15th, 2008

The initial vision

When I was a JBoss contributor, we used to name the infrastructure kernel as WebOS, it was Marc Fleury’s vision I think. Actually for many years the banner of our source code was:

/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/

It may sound a bit marketingish but it is a simple and powerful concept that was pioneered by JBoss in 2000 and followed by a large crowed since then. The fundamental idea is to provide a system for managing services. That system can be simplified as the equation WebOS = deployer + registry + controller , I won’t go farther in the gory details. Today JBoss as rewritten from scratch the system as JBoss Microcontainer, we assume that it is as of today the most complete system and will be for many years.

So JBoss Microcontainer provides a runtime for your services, do you think it is sufficient ? that would surely work out if you would use services the way we used computers 30 years ago (or maybe 40) with a shell as unique user interface.

Toward a more complete vision

To complete the picture we need an infrastructure to deliver an user interface that is adapted to the web and that’s our business at eXo. What we provide can be simplified as WebOS = deployer + registry + aggregation + identity.

The deployer takes care of deploying visual components such as portlets or widgets. Both are connected to your service infrastructure but in a different manner. Portlet adapts your existing applications (JSF, Tapestry, Struts, et…) to the portal world. Widgets are more stateless and access services through Rest. Components are registered in the registry. Nothing really fancy here.

The aggregator and identity are the real value add

The aggregator provides rich front end capabilities to deliver the user interface adapted to your needs based on flexible layouts and skinning. the Ajax technology came to the rescue a few years ago and is now naturally involved to improve the end user experience. It comes in two flavors, the classic portal and the WebOS portal (here literally an operating system like OS X or Vista).

The identity part takes care of linking your existing user back-end to the portal. It integrates the profile and the various roles of the user (I am not talking here about the social aspect of the user identity as it is out of scope of this blog, we’ll have more announcements about that soon).

The vision

The vision we have sketched so far is almost complete. Our WebOS is able to deliver services and applications to your users, but it comes as an empty shell. To make it more sexy it would be nice to have applications to deploy in it. It is also what eXo delivers as professional and powerful application products  that comes bundled with our offering providing a full fledged WebOS solution.

What’s new and cool in Portlet 2.0

September 18th, 2008

I just made my presentation available on SlideShare!