mercredi août 24, 2011

Java EE 6 does Java 7 with GlassFish 3.1.1, the making-of

This blog has moved to
Follow the link for the most up-to-date version of this blog entry.

I recently posted a screencast showing how a simple JavaEE 6 web application can take advantage of Java 7's new language features (aka project coin). Here are more details on the code for the three Java 7 new language features shown. The full code is available here.

The first Project Coin feature shown (Java 7 refactorings start at 7:37 into the screencast) is Strings in switch statements. This is rather straightforward (a number of folks thought this was already supported) and if probably a good candidate to use with web frameworks which take user input as Strings.

String name = request.getParameter("name");
if ("duke".equals(name)) {
    vip = true;
    name = name.toUpperCase(); // let's visually recognize DUKE
} else if ("sparky".equals(name)) {
    vip = true;         // another VIP

becomes :

String name = request.getParameter("name");
switch (name) {
    case "duke":
        vip = true;
        name = name.toUpperCase(); // let's visually recognize DUKE
    case "sparky":
        vip = true;         // another VIP

Of course you can also have a default: section equivalent to an else statement.

The second feature is try-with-resources and is shown here in the initializing sequence of a stateless EJB. It uses JDBC to ping a well-known system table. The code specifically relies on the fact that multiple classes in JDBC 4.1 (Connection, Statement and ResultSet) now implement the new Java 7 java.lang.AutoCloseable interface. This is what allows for the following code requiring proper closing of resources :

public void pingDB(){
    try {
        Connection c = ds.getConnection();
        Statement stmt = c.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT * from SYS.SYSTABLES");
        while ( {
            System.out.println("***** SYSTEM TABLES" + rs.getString("TABLENAME"));

    } catch (SQLException ex) {

... to be rewritten as follows (resources initialized in a single statement, no closing required as the compiler takes care of it when they go out of scope) :

public void pingDB() {
    try (Connection c = ds.getConnection(); Statement stmt = c.createStatement()) {
        ResultSet rs = stmt.executeQuery("SELECT * from SYS.SYSTABLES");
        while ( {
            System.out.println("***** SYSTEM TABLES" + rs.getString("TABLENAME"));
    } catch (SQLException ex) {

As you can see in the source code, the DataSource is actually created using a @DataSourceDefinition annotation which is a new feature in Java EE 6.

The third and final part of the demonstration uses a somewhat convoluted piece of JPA code to illustrate the multi-catch feature. For the purpose of the demo, the JPA query (also in the above EJB) uses a LockModeType.PESSIMISTIC_WRITE (new in JPA 2.0) when building the JP-QL query and adds two catch blocs for PessimisticLockException and LockTimeoutException :

try {
    List customers = em.createNamedQuery("findAllCustomersWithName")
        .setParameter("custName", name)
    if (customers.isEmpty()) {
        doesExist = false;
        Customer c = new Customer();
    } else {
        doesExist = true;
    } catch (final PessimisticLockException ple) {
        System.out.println("Something lock-related went wrong: " + ple.getMessage());
    } catch (final LockTimeoutException lte) {
        System.out.println("Something lock-related went wrong: " + lte.getMessage());


Which can be refactored to this equivalent code using multi-catch :

try {
    List customers = em.createNamedQuery("findAllCustomersWithName")
        .setParameter("custName", name)
    if (customers.isEmpty()) {
        doesExist = false;
        Customer c = new Customer();
    } else {
        doesExist = true;
    } catch (final PessimisticLockException | LockTimeoutException ple) {
        System.out.println("Something lock-related went wrong: " + ple.getMessage());


This new language feature is *very* useful for reflection or File manipulation, not quite the most common Java EE code out there.

Of course all of the above only works with JDK 7 at runtime and if running NetBeans 7.0.1 you'll also need to set the source level to Java 7 for the quick fixes to light up. I've also successfully executed this under Mac OS X using the OpenJDK Mac OS binary port.

Some resources :
Full Source code.
Screencast showing this "in action".
String in switch statements.
Multi-catch and precise rethrow.

jeudi mars 17, 2011

Portable Java EE 6 Web Maven Archetype

This blog has moved to
Follow the link for the most up-to-date version of this blog entry.

With the growing use of Maven in enterprise projects, starting off with the best possible pom.xml is important. The good news is that there are a number of Java EE 6-related archetypes which can help you get started while offering IDE independance. The bad news is that their quality and portability in particular varies significantly.

The Java EE 6 platform APIs are now in Maven central : javaee-api:6.0 and javaee-web-api:6.0. These should be used with a provided scope and your POM should contain dependencies for the actual implementation (check this 3.1 download page for how to work with GlassFish).

Consider using that simple platform dependency rather than replying on archetypes introducing a long list of dependencies mixing APIs and implementations.

mardi nov. 16, 2010

A day @ Devoxx, all about Java EE 6

My first day at Devoxx was exhausting but quite satisfying. Our "Java EE 6 Tutorial, reloaded" session went very well, with all 15 demos working flawlessly, including the 4 new client demos, new slides for CDI, a "Gotchas" section and an overall pass on the slide deck. The feedback (questions, discussions, tweets, ...) was very good and many asked about the address for the demos, so here it is: (code is in the trunk, we'll tag it soon). The slides are here.

In the afternoon, Antonio and myself decided that three hours of talking wasn't enough so we took on to run a Hands-On Lab for another 3 hours. This was another set of reasons for satisfaction: 40+ people (full room) with no one leaving because of technical issues (quite rare in HOLs) and lots of good conversations comparing NetBeans to other IDEs, JSF to Struts, CDI/EJB to Spring, etc...

Overall it seems people attending were happy going through the (admittedly simple) three exercises on JSF, JAX-RS, and CDI. Those exercises and the instructions document are available from this URL. Check the README.txt file which will tell you which projects to use (with or without Maven).

Of course, as always, lots of familiar faces and fun discussions. Now looking forward to the keynote sessions tomorrow (JavaSE) and Thursday (JavaEE).

vendredi juil. 23, 2010

Module initialization order in Java EE 6

This blog has moved to
Follow the link for the most up-to-date version of this blog entry.

One of the new features in the umbrella Java EE 6 specification is the ability to define the order in which modules (web applications for instance) from a given Java EE application are initialized by the container. This might be useful if you want for example a given module to serve as resource initializer to create a database table before any other module can be accessed (note this does not apply to application client modules). Previously, the order in which Java EE application modules were initialized was unspecified and by default this is still the case in Java EE 6.

To explicitly request modules to be started in a particular order, the application should use <initialize-in-order>true</initialize-in-order> in the the EAR's application.xml deployment descriptor. The container will then start the modules in the order they are declared in that same configuration file (note that application.xml is optional by default and should be placed in the EAR's top-level META-INF/ directory). The short example below shows an EJB singleton creating a database table upon creation and dropping it before destruction. With this setup, the database table should always be accessible to the web application. (a singleton packaged in OrderMatters-ejb.jar) :

public class InitDB {
     void createDBtable() {

     void dropDBtable() {

The application.xml deployment descriptor for OrderMatters.ear :

<application version="6"

Full details are available in the Java EE 6 platform specification, section EE.8.5.4. Of course you can use this today in GlassFish.

As an alternate solution if you're willing to use features in GlassFish 3 beyond what Java EE 6 provides, you may also solve the problem by breaking the application into different OSGi bundles and using a combination of BundleActivator and ServiceTracker as shown in this sample from Sahoo). This can in some cases offer a more suitable and loosely-coupled approach.

mercredi mai 05, 2010

RDV à Lausanne ce jeudi 6 mai 2010 - GlassFish et Java EE 6

Karim et le reste de l'équipe du LausanneJUG m'ont convié à venir aujourd'hui jeudi 6 mai à présenter sur Java EE 6 et sur GlassFish v3.

Comme d'habitude j'espère pouvoir faire un maximum de présentations et que les questions seront nombreuses. RDV à 18h30 dans les locaux d'Octo.

La copie d'écran à droite est tirée de la page d'usage de GlassFish : qui propose désormais un petit champ de recherche pour localiser votre ville.

dimanche mars 21, 2010

Session Java EE 6 (JPA 2 et JSF 2) à Solutions Linux (Mars 2010)

Solutions Linux cette année était pour moi l'occasion de présenter Java EE 6 de manière un peu différente avec Jérôme Molière (il n'y a vraiment que des Jérôme dans ce métier! ;). Plutôt que de proposer en 45 minutes une recette de cuisine sur tout ce qui est nouveau, Jérome s'est concentré sur JPA 2.0 et ses nouvelles capacités de caching alors que j'ai de mon coté couvert JSF 2.0. Dans le temps imparti ca reste un survol dont le but est surtout de donner envie aux participants d'aller regarder de plus près. Voici la présentation utilisée :

Jérôme m'a promis travailler sur une démo pour la partie JPA 2.0. Dans les prochains jours si tout va bien!

Pour le reste le salon s'est déroulé sans Sun (stand Oracle), Novell (qui avait habituellement une des plus grands stands), RedHat (ils se sont passé le mot?), mais avec Microsoft (grand stand rempli d'hôtesses). Quelques discussions intéressantes mais clairement pas un cru exceptionnel.

mercredi mars 10, 2010

Java EE 6 Virtual Conference content on the GlassFish Podcast

The virtual conference that was held for the launch of Java EE 6 and GlassFish v3 is now being progressively being pushed out to the GlassFish Podcast. Make sure you subscribe to the podcast to catch all 16 presentations :

Java EE 6, GlassFish v3, EJB 3.1, JAX-RS/Jersey, Servlet 3.0, JPA 2.0, JSF 2.0, JAX-WS/Metro, CDI, Modularity with OSGi, Dynamic languages in GlassFish v3, Java EE 6 Tooling, the Grizzly framework, GlassFish management and monitoring, and Java EE 6 Connectors.

I'll be releasing the episode once every 2 days or so to let your favorite podcatcher get some rest between each.

dimanche févr. 21, 2010

Just say no to Scarlett Johansson, Brad Pitt and the rest (but say yes to Bean Validation)!

This blog has moved to
Follow the link for the most up-to-date version of this blog entry.

Every single application with user interaction needs some sort of validation. Java EE 6 now has its very own standard Bean Validation API (JSR 303) with a number of easy-to-use built-in constraints (@NotNull, @Size, ...). GlassFish v3 ships with the Hibernate Validator reference implementation which offers some additional annotations such as @Email. I've decided for the sake of this blog entry that it was not good enough for me as it considers null, empty and foo@barcom as all valid (and does the check as part of the ConstraintValidator, not in the definition of the @Email annotation).

So here's my new implementation of a constraint to check for valid email addresses with the additional feature of rejecting dummy data, such as (too bad it it was the real one trying to post a comment to your blog or mine!). In my implementation the annotation constraint is called @EmailAddress and defined as follows :

@Size(min=5, message="{}")
@Pattern(regexp="[a-z0-9!#$%&'\*+/=?\^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'\*+/=?\^_`{|}~-]+)\*" +
                 "@" +
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface EmailAddress {
     String message() default "{}";
     Class[] groups() default {};
     Class[] payload() default {};

Things to note:
• A constrained value can fail one or more validation tests in no particular order. Each failure will be reported and available upon validation. In particular you cannot assume that the data passed to the constraint validator will not be null (and the use of @NotNull could arguably be removed since nullability is tested in the validation code below).
• I'm using the @Pattern annotation here rather than manipulating the regex in the explicit validation code (the regex itself comes from a slightly simplified version of the one defined by RFC 2822).
• error messages use externalized strings located in a resources bundle file.

Here's the rather straightforward validation code (see @Constraint above) :

public class EmailValidator implements ConstraintValidator<EmailAddress, String> {
     ArrayList<String> blackListedDomains;
     ArrayList<String> blackListedNames;

     public void initialize(EmailAddress constraintAnnotation) {
         // a better implementation would probably retrieve data
         // from a file, a database or a web service.
         blackListedDomains = new ArrayList<String>();

         blackListedNames = new ArrayList<String>();

     public boolean isValid(String value, ConstraintValidatorContext context) {
         int at = value.indexOf('@');
         if (value == null || "".equals(value) || at<0 ) return false;

         String username = value.substring(0, at).toLowerCase();
         String domainname = value.substring(at+1).toLowerCase();

         if ( blackListedDomains.contains(domainname) ) return false;
         if ( blackListedNames.contains(username)) return false;

         return true;

The main thing to notice in the code above is the use of generics in ConstraintValidator interface which in turn defines the argument types in the initialize() and isValid() methods.

This newly defined @EmailAddress constraint can now be applied to class attributes or getters. In the case of JPA entities or JSF attributes there is no extra step, all the glue is provided to validate data upon calling the JPA life-cycle methods and applying the JSF request life-cycle, with error messages surfaced to the user via those two APIs. In other cases, Bean Validation offers API to explicitly validate the data illustrated in this sample unit test :

public class TestEmailConstraint {
    Validator validator;
    Customer myCustomer;

    public void setUp() {
       ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
       validator = factory.getValidator();
       myCustomer = new Customer();

    public void testEmailBV() {
       Set<ConstraintViolation<Customer>> violations = validator.validate(myCustomer);
       for (ConstraintViolation<Customer> violation : violations) {
          System.out.print(violation.getInvalidValue() + " => ");
       assertTrue(violations.size() > 0);

mardi janv. 26, 2010

The code for all 15 demos Antonio and myself have been using in our 3-hour long sessions at Devoxx, and today at the jFokus conference is now online at This set of small demos build on top of one another and illustrate a large number of the new Java EE 6 features.

The code is in the "tutorial" part (the rest is related to the Java EE 6 book). Check out the 2009Devoxx and 2010jfokus tags for stable versions.

The setup has a "To Be Completed" directory with each project hosting a detailed README.txt file to carry out the demo to reach the "Completed" stage. All projects are Maven 2.0-based and have been tested inside NetBeans and IntelliJ. It should work just as well in Eclipse and of course you can mvn clean install from the command-line. GlassFish v3 is used throughout the demos.

Being hosted on Kenai gives us SVN (other options are available), a wiki, forums, an issue tracker, and mailing lists. And those using NetBeans even have a nice integration of all these features. So join the project, ask questions and contribute!

jeudi janv. 21, 2010

Move to Java EE 6 and slash your number of lines of code by more than half

My first reaction when I started to help Paul and the team run and test Bill Burke's ex11_1 sample on GlassFish v3 was that this code could be refactored to be much simpler and more portable with Java EE 6 and JAX-RS 1.1. This wasn't the best approach to show the portability of existing JAX-RS code so the porting happened with minimal (really small) changes. Yet, I wanted to share the simplifications here.

Remove web.xml altogether. The Jersey servlet no longer needs to be declared and mapped, and the EJB local references now have well known and portable names. This is replaced with a @ApplicationPath("mypath") annotation placed on the ShoppingApplication class.

Put those EJBs in a WAR. The initial project has three artifacts: WAR, EJB jar, and a global EAR, each having a separate Maven pom.xml. This can all be boiled down to a single WAR file.

Morph resources and Beans into a single class. The dichotomy between \*Resource and \*ResourceBean is no longer necessary. A resource can simply now be a transactional EJB by adding the @Stateless along side the @Path annotation.

Test. This is made easy by the simplified packaging but essentially is the same as what's described here (uses the GlassFish Maven plugin).

The end-result has 60% less lines of code (and I'm sure you could get even remove more without hurting the code).
These are all simplifications made possible by Servlet 3.0, EJB 3.1 and JAX-RS 1.1 (all part of Java EE 6).

lundi déc. 21, 2009

Java EE 6 and GlassFish v3 Virtual Conference replays

Only 4 days after the "Java EE 6 and GlassFish v3" event no less than 16 events are now available for replay.
All the slides are also available.

jeudi déc. 10, 2009

Three new GlassFish podcast episodes for the GlassFish v3 launch - Java EE 6, Tooling, and JSF 2

To celebrate the GlassFish v3 launch, I've posted the following three GlassFish Podcast episodes :
Episode #038 - Java EE 6 released! Interview with Roberto Chinnici
Episode #039 - GlassFish v3 is out! With tooling! Interview with Ludo Champenois
Episode #040 - JSF 2.0 discussion with Ed Burns and Roger Kitain

I have at least one more coming up tomorrow (most likely).

GlassFish v3 est disponible! Une nouvelle ère commence.

GlassFish v3 est désormais disponible en version finale et du coup Java EE 6 est lui aussi désormais final (depuis les votes récents, il manquait l'implémentation de référence et le TCK, c'est maintenant chose faite!).

Bien entendu il y a le support complet de Java EE 6 (ejb 3.1, jax-rs 1.1, jsf 2.0, cdi 1.0, etc...) et son profil web (40MB tout mouillé) qui apporte une flexibilité à tous les serveurs d'applications qui en ont besoin, mais il y a beaucoup de choses dans GlassFish v3 qui vont bien au delà de la spécification et du rôle d'implémentation de référence. Il y a les fonctionnalités pour le développeur (temps de démarrage hyper-rapide) et préservation de session sur redéploiement (lui aussi très rapide), son coeur HK2/Grizzly et ses fonctionnalités, la modularité et le support de OSGi (Apache Felix par défaut), le système de packaging IPS (à la apt-get) et son update center, le monitoring basé sur Btrace, ou encore son support dès maintenant dans les trois outils de développement qui comptent: NetBeans, Eclipse et IntelliJ.

Cette sortie du produit c'est selon moi le début d'une nouvelle ère à plusieurs égards. Bien entendu il y a cette nouvelle architecture modulaire qui donne à GlassFish un pérennité technologique que d'autres produits concurrents nous envie, mais c'est aussi un aboutissement d'une histoire mouvementé des serveurs d'applications chez Sun. Je suis rentré il y a 10 ans chez Sun avec pour objectif de "vendre" du NetDynamics (on ne parlait pas de J2EEà l'époque), un produit leader sur son marché et racheté par Sun. Quelques mois plus tard AOL rachète Netscape et Sun hérite du serveur d'application du même nom (lui aussi avec beaucoup de parts de marché) et qui sera finalement choisit au détriment de NetD. S'en suivent les années iPlanet, mauvais souvenirs d'un mauvais produit et beaucoup de projets avec BEA WebLogic...

Avec Sun Application Server 7, c'est un vrai reboot technologique qui sera complété par l'approche Open Source de GlassFish en 2005. La route fût longue (détails ici), beaucoup avaient enterré Sun (difficile de leur en vouloir) sur ses chance de survivre dans ce marché. Le renaissance se sera faite au prix d'un effort important en trois étapes: GlassFish v1 en 2006 (conformité à Java EE 5 et Open Source), GlassFish v2 (qualité des produits commerciaux au prix de l'open source), GlassFish v3 (innovation et business model en place). Le parallèle entre GlassFish et J2EE/JavaEE est d'ailleurs frappant. Les critiques étaient sévères (et méritées) dans les années 2000-2006 avant que Java EE 5 et GlassFish ne viennent changer radicalement les avis. Bien entendu la question de l'avenir sous un bannière potentielle Oracle se pose maintenant. Si vous ne l'avez pas déjà fait, je vous invite à lire le passage qui concerne GlassFish dans cette FAQ d'Oracle. Coté Java EE non plus je pense qu'il n'y a aucun souci à se faire.

Vous devriez voir dans les prochaines 24 heures tout le florilèges des annonces de presse, des articles, de posts sur twitter, des blogs (entre autre par Sun que vous pouvez suivre avec les balises glassfishv3 et javaee6), et autres commentaires. Pour vous faire votre propre idée, téléchargez donc GlassFish v3 maintenant! Enfin, je vous invite à ne pas oubliez la conférence virtuelle Java EE 6 / GlassFish v3.

vendredi déc. 04, 2009

JUG Toulouse ce mardi 15 décembre (et conférence virtuelle GlassFish v3)

Ce mardi 15 décembre j'interviens au JUG Toulouse (un des plus beaux site web de JUG!) sur GlassFish v3. Voici l'annonce. Je compte passer que peu de temps du Java EE 6, non pas par manque d'intérêt ou overdose mais plus parce que Antonio est bien plus doué que moi pour traiter ce sujet en si peu de temps. Il sera donc plus question de GlassFish v3 qui sera sorti d'ici là (je croise les doigts!).

Pour tous ceux qui ne seront pas à Toulouse ce soir là, l'équipe GlassFish organise une conférence virtuelle à l'occasion de la sortie de GlassFish v3 et de Java EE 6. Spec leads, project leads, et autres ingénieurs seront tous là dans votre fureteur/navigateur. Pour s'inscrire. Les présentations seront ensuite disponibles en rediffusion.

Enfin, 2010 s'annonce pleine de visites de JUG et je dois dire que j'aime assez ces formats.

mardi nov. 24, 2009

Back from Devoxx 2009 (a JavaEE 6/GlassFish v3 perspective)

This was Devoxx' 8th edition and my personal 5th (I think).

I think the Java EE 6 and particularly GlassFish v3 were very well received at this year's Devoxx 2009 conference. Of course some of it has to do with the fact that both are almost final (Java EE 6 spec lead Roberto Chinnici announced at the event that it'll be done on December 10th 2009). But I like to think that there's much more to it.

The Java EE 6 session that Antonio Goncalves and myself ran as a university 3-hour talk was packed and (this is the real test), all came back after the break. We went through 12 or so demos (with minimal failure I should say) from a simple managed beans to a working application with JSF 2, Servlet 3.0, JAX-RS 1.1, JPA 2, EJB 3.1 (including testing, Antonio's favorite). It seems that people enjoyed the level of information and the step-by-step approach. As any other talks at the conference, this one should be made available on parlays (for a fee) real soon. We're working to make to code for the samples available one way or another. Stay tuned. Update: the session is now live on Parleys: Part 1 and Part 2. Antonio's 1-hour talk is here. All talks are for a fee.

The Java EE BOF (a last minute addition) was packed and a good moment, and to me what BOF's should look like (too many people use it do deliver regular PPT-based presentations). With a panel of JSR and project leads, the discussion centered around availability of Java EE 6 implementations, new features such as managed beans and JSR 299, how JSR's can produce multiple specs, etc... Nice interactive crowd. The speaker's diner that evening was an occasion to meet Oracle's Steve Harris, the keynote speaker for the next morning.

The first "conference" day had three keynotes : Oracle, Sun, and Adobe. The feedback on Oracle's keynote via tweets, blogs, and discussions wasn't so good but I think that with the given circumstances it made clear that Oracle cared and was no stranger to how the Java community is structured, how it evolves, and what the challenges are. The demos were what people remembered it seems. Sun's keynote was given by Roberto and Ludo (already available on Parleys) and, in 30 minutes, covered Java EE 6 and demoed GlassFish v3 - fast startup, deploy on change, preserve session on redeploy, and OSGi bundle invocation straight from a servlet were all shown in only a few minutes. I think that this is the first conference in a while where people don't ask me about GlassFish's future (and I did talk to many people during the event). This is both the result of what they saw and of the recently updated FAQ by Oracle.

JBoss was pretty well represented this year but for some (planning?) reason there was no dedicated talk on JSR299. It was certainly very nice to see JBoss strongly supporting Java EE 6 (beanvalidation, 299, JSF 2, etc...). Other highlights for me at the conference were the JDK 7 closure proposal, project Lombok looks interesting (including in a Java EE context), not quite convinced by Gradle (Maven 3 releasing in January may steal its thunder), and Kees Jan's monitoring/performance talk was pretty good. I'm amazed to see the number of people attend those performance talks - the GC is no longer the issue and there hasn't been any technology or performance tool break-through in a while (btrace is the only thing that comes close and Simon covered that). Clearly SOA is disappearing from the agenda year after year (although people had good things to say about SOA in Practice session), and leaving room for the cloud talks.


This blog has moved

Alexis Moussine-Pouchkine's Weblog

GlassFish - Stay Connected


« avril 2014

No bookmarks in folder


No bookmarks in folder