lundi sept. 12, 2011

Rentree 2011 chargée

Je ne sais pas si les classes seront chargées mais l'inspection académique a mis le paquet sur le nombre d'événements Java pour cette rentrée 2011.

JUG Summer Camp le 16 septembre, déjà une tradition (La Rochelle)
Soirée CDI au Mars JUG le 20 septembre (Marseille)
Programme NormandyJUG, début le 20 septembre (Rouen)
Open World Forum fait la Java, le 23 septembre (Paris)

Le tout donc sur une semaine et toutes ces conférences/réunions sont gratuites.

mercredi août 24, 2011

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

This blog has moved to alexismp.wordpress.com
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
        break;
    case "sparky":
        vip = true;         // another VIP
        break;
}

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 :


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

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

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

... 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) :


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

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)
        .setLockMode(LockModeType.PESSIMISTIC_WRITE)
        .getResultList();
    if (customers.isEmpty()) {
        doesExist = false;
        Customer c = new Customer();
        c.setName(name);
        em.persist(c);
    } 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)
        .setLockMode(LockModeType.PESSIMISTIC_WRITE)
        .getResultList();
    if (customers.isEmpty()) {
        doesExist = false;
        Customer c = new Customer();
        c.setName(name);
        em.persist(c);
    } 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 java.io 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.
try-with-resources.
Multi-catch and precise rethrow.

jeudi juil. 28, 2011

Java EE 6 does Java 7 (with GlassFish 3.1.1)

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

Java 7 is here! and so is GlassFish 3.1.1! Get them while they're hot!

New Java versions can sometimes take a bit of time before they're adopted because:
a/ your IDE doesn't support the new version and associated language constructs
b/ you're a server-side developer and it'll be a while before your application server supports that new version of the JDK

Well, with Java 7, things are different with the quasi-simultaneous releases of JDK 7, NetBeans 7.0.1 (coming up very soon) and GlassFish 3.1.1! Here's a new screencast on the GlassFish Youtube Channel showing Java EE 6 development taking advantage of the project Coin features and running on GlassFish 3.1.1 and Java 7 :

lundi juil. 18, 2011

Lancement Java 7 au LyonJUG ce jeudi

Julien Ponge et moi-même serons à Lyon pour la soirée Java 7 du LyonJUG. En attendant, voici un entretient croisé réalisé par Agnès Crépet et Cédric Exbrayat sur Java 7 et autres sujets connexes et posté sur le site Duchess France.

Rendez-vous Jeudi 19h, à l'INSA de Lyon!

mardi juin 28, 2011

JPA/EclipseLink multitenancy screencast

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

I find JPA and in particular EclipseLink 2.3 to be particularly well suited to illustrate the concept of multitenancy, one of the key PaaS features en route for Java EE 7.

Here's a short (5-minute) screencast showing GlassFish 3.1.1 (due out real soon now) and its EclipseLink 2.3 JPA provider showing multitenancy in action. In short, it adds EclipseLink annotations to a JPA entity and deploys two identical applications with different tenant-id properties defined in the persistence.xml descriptor. Each application only sees its own data, yet everything is stored in the same table which was augmented with a discriminator column.

For more advanced (or more realistic) uses such as tenant property being set on the @PersistenceContext, XML configuration of multitenant JPA entities, and more check out the nicely written wiki page.

lundi mai 30, 2011

Brno Oracle Java Developer Event - Success!

I spent last Thursday in Brno to deliver a number of Java EE talks and a keynote at the Oracle Developer Java Conference. It was great because it had a good developer feel and was similar in spirit to other community-driven conferences that I recently attended. Maybe the best part was the attendance - well over 400 (excluding Oracle employees and speakers) which is great for a first time.

Dalibor Topic fought the ash cloud and managed to reach Brno to kick off the day with a Java keynote with updates on Java 7 and current thinking about Java 8 and beyond. Doug Clarke, Java Persistence Director of Product Management at Oracle was here to cover advanced JPA features as well as recent evolution in EclipseLink with a nice multi-tenancy demo (I understand there's a screencast coming soon). I took this opportunity to interview Doug on EclipseLink. The recording will soon be up on the GlassFish Podcast.

And of course, last but not least, the Prague web services engineering team was strongly represented and covering JAX-RS and Jersey. Given how the last session overran by more than half an hour I'd say this was a successful and engaging presentation. Both Marek (JAX-RS co-spec lead) and Jakub (Jersey lead) blogged about the event and shared code demo.

That's a pretty poor photo there that I have but I'm hoping to see better ones given the presence of a profesional photographer (doing a keynote and three sessions I sure felt like a rockstar with photos of me taken at each of them...).

mardi mai 24, 2011

Intercepting startup and shutdown events

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

Startup and shutdown actions is a pretty common use-case for enterprise development and GlassFish 3.x offers at least two different ways to implement such call-backs: lifecycle modules and EJB 3.1 startup beans.

GlassFish Lifecycle modules

The first one has been around for a little while and is called Lifecycle modules. These are specific to GlassFish and thus not portable to other application servers but they offer a simple and effective way to implement behavior that applies to the entire application server instance (or to an entire cluster), independently of any deployed application.

A single class implementing com.sun.appserv.server.LifecycleListener (available from as-install/glassfish/modules/glassfish-api.jar) can intercept five different events: Initialization, Startup, Ready, Shutdown, and Termination (check the documentation for more details). Here's a canonical example :

public class GlassFishEvents implements com.sun.appserv.server.LifecycleListener {

    private static final Logger logger = Logger.getLogger("admin.events");

    @Override
    public void handleEvent(LifecycleEvent le) throws ServerLifecycleException {
       switch (le.getEventType()) {
          case LifecycleEvent.INIT_EVENT:
             logger.severe("INIT_EVENT");
             break;
          case LifecycleEvent.READY_EVENT:
             logger.severe("READY_EVENT");
             break;
          case LifecycleEvent.SHUTDOWN_EVENT:
             logger.severe("SHUTDOWN_EVENT");
             break;
          case LifecycleEvent.STARTUP_EVENT:
             logger.severe("STARTUP_EVENT");
             break;
          case LifecycleEvent.TERMINATION_EVENT:
             logger.severe("TERMINATION_EVENT");
             break;
          default:
             logger.severe("UNKNOWN event");
       }
    }
}

Registering the lifecycle module can be done via the admin console or the CLI (asadmin create-lifecycle-module) with optional ordering (relative to other modules, similar to servlets), an enabled/disabled state (default is enabled) and the ability to prevent the server from starting if the module fails to load.


Startup and singleton EJB

An alternate way is to use EJB 3.1 (part of Java EE 6) and in particular a bean combining the @Startup and @Singleton annotations. Its lifecycle methods marked with JSR 250 common annotations will contain the event callback logic. Here's a simple example simulation the creation of database tables :

@javax.ejb.Singleton
@javax.ejb.Startup
public class CreateTables {
    @PostConstruct
    public void init() {
       logger.warning("Creating tables");
    }

    @PreDestroy
    public void cleanup() {
       logger.warning("Dropping table...");
    }
}

While this offers a more portable solution, it has some notable differences with GlassFish lifecycle modules.

First of all there are only two events that can be intercepted: @PostConstruct, @PreDestroy which are application events, not runtime system events. Undeploying the application is also the only way to disable the behavior and since this is an application-level event interception, there cannot be action taken on other parts of the runtime on failure (arguably you can do a lot more in the rest of you application).

Finally there is no notion of ordering but rather you can express explicit dependencies using @DependsOn as shown here to simulate populating tables that need to be previously created :

@javax.ejb.Singleton
@javax.ejb.Startup
@javax.ejb.DependsOn("CreateTables")
public class PopulateTables {
    @PostConstruct
    public void init() {
       logger.warning("Populating tables");
    }

    @PreDestroy
    public void cleanup() {
       logger.warning("archiving table data");
    }
}

Also note that a Singleton approach only applies to a single instance (not a cluster-wide singleton). If you're wondering which approach to chose, it really boils down to whether you want to implement system-level or application-level events.

Of course you can combine the two approaches which would trigger a log similar to this one on a startup/shutdown cycle :

SEVERE: INIT_EVENT
WARNING: Creating tables
WARNING: Populating tables
SEVERE: STARTUP_EVENT
SEVERE: READY_EVENT
...
SEVERE: SHUTDOWN_EVENT
WARNING: archiving table data
WARNING: Dropping table...
SEVERE: TERMINATION_EVENT

samedi mai 07, 2011

Welcome to the new Bistro!

After almost 7 years and almost 1000 entries, this blog was moved to the new blogs.oracle.com infrastructure (based on the very fine Apache Roller). Whether you're reading this in a feed aggregator or on the webpage, redirects should make everything transparent for you.

Clearly with the rise of twitter and the time spent on TheAquarium I have little time left for this blog, but do expect some activity on a weekly (or so) basis.

I resisted doing so for all those years, but with the move to pre-defined templates I felt it was time to put a photo up on the blog to differentiate the page a bit.

mercredi avr. 27, 2011

Visiting BruJUG

Quick note to share that I'll be in Brussels tomorrow (April 28th 2011) for a GlassFish session at the BruJUG. Details on this page.

dimanche avr. 10, 2011

JavaOne Russia - Да здравствует Москва!

I'm taking off tomorrow for Moscow to attend and present at JavaOne Russia. It'll certainly be fun to see snow after a 26deg week-end in Paris.

I'll probably record another Java Spotlight Podcast with the rest of the crew and we'll see how much Russian cuisine and walking around I'll get to do in the little time I'll stay there...

This is the first time JavaOne goes to Russia and I'm curious to see how different it'll be from the several Sun Tech Days I've attended in the past in St. Petersburg. It'll probably be one of my busiest conferences with multiple talks and hands-on labs. See you there!

lundi mars 21, 2011

GlassFish 3.1, the devops appserver

Of course you can consider using the new GlassFish 3.1 because it is operations-friendly with full clustering and centralized admin or because it offers a great developer environment with fast startup, a modular architecture or application versioning but I'd like to argue that the GlassFish value is greater than sum of the parts and a devops appserver. Today.

In fact GlassFish is pursuing what it's been doing since version 2.x: hit a middle ground between the requirements from developers (latest APIs, lightweight runtime) and those from operations (manageable, stable, centralized admin). Here are some features which I believe to be relevant to developers, operations and QA :

• Fast startup: whether you're developing, testing or deploying an application, the time it takes to bring a service online is critical. GlassFish has had this for a while (even before 3.0) but the full modular architecture offers yet greater flexibility.

Embedded API: while the new standard EJBContainer API is a great step forward, it mostly addresses the unit testing use-case while this feature offers an API to drive the entire set of GlassFish services and features.

Maven plugin: easily integratable into your favorite continuous integration server. In a continuous deployment scenario and generally for automation, Maven and CI's are key tools to rely on.

Domain-driven administration: the concept of a domain has been around for a while in GlassFish and with 3.1 the entire admin tools (CLI, Web and REST) scale from a single instance development or production config to a full multi-cluster environment. This makes for easy transfer of work from development to QA and/or to production and back.

• More questionable features (wrt Devops) are active redeployment and application versioning. While the former is recommended only in development the versioning feature can be used in many different ways for testing and potentially in production (with the caveat that only one application version can be active at a given point in time).

Of course there's much more to devops than just a product or technology. Is your application server devops-friendly?

jeudi mars 17, 2011

Portable Java EE 6 Web Maven Archetype

This blog has moved to alexismp.wordpress.com
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.

mercredi mars 16, 2011

Nouveau livre Java EE 6 aux Editions Eni

Jérôme Lafosse, ancien du CNAM et consultant formateur Java, vient de sortir son nouveau livre: "Développements n-tiers avec JavaEE".

Un nouveau livre sur Java EE et sur GlassFish, ça commence à devenir une habitude! J'ai participé à la relecture de plusieurs livres autour de Java et je dois dire que je trouve que les auteurs sont fous de consacrer autant d'énergie à rédiger le contenu et à le refaire plusieurs fois avant la sortie finale de l'ouvrage. Celui-ci n'échappe pas à la règle.

Au delà d'être écrit en français, ce livre est différent dans la mesure ou il ne se consacre pas exclusivement aux nouveautés de Java EE 6 mais s'adresse plutôt aux personnes qui souhaitent une couverture exhaustive de Java EE et n'ayant que des connaissances minimales sur le sujet. Par "exhaustif" j'entends qu'il couvre des technologies récentes comme CDI, Bean Validation, JAX-RS, comme des plus "traditionnelles" comme Servlet, EJB ou JSF mais aussi toutes les étapes de mises en oeuvre, y compris versioning d'applications, clustering GlassFish. Jérôme a suivi de près les développements de GlassFish 3.1 pour pouvoir proposer son livre seulement quelques jours après la sortie de GlassFish 3.1.

Le livre est imposant avec ses 900 pages (!) mais il couvre le développement complet d'une application ainsi que l'installation et l'utilisation de GlassFish, Hudson, NetBeans, Subversion, ANT, Eclipse, JUnit, et Selenium. Et pour ne rien gâcher l'éditeur propose la version numérique pour toute personne achetant le livre (c'est fou que ça ne soit pas une pratique plus répandue).

mardi mars 08, 2011

JavaOne Russia - Moscow on April 12-13th 2011

The next JavaOne conference is scheduled for in little over than a month (April 12-13, 2011) in Moscow, Russia, planning is well on its way and I'm happy to report that I'll be presenting a number of sessions there.

JavaOne Keynote speakers are none other than Steve Harris (Senior VP of Application Server Development) and Henrik Stahl (Senior Director of Product Management).

The preliminary schedule is here (expect a few minor changes). As you can see there is plenty of Java EE and GlassFish content.

Встречаемся на JavaOne !

lundi févr. 28, 2011

GlassFish 3.1 est là!

GlassFish 3.1 est désormais disponible en version finale et il y a beaucoup de choses à dire (et comme d'habitude je n'ai pas le temps de faire quelque chose de court...).

Vu d'avion l'objectif de cette version majeure (à mon gout c'est presque une 4.0) c'est de réintroduire le clustering et l'administration centralisée sur un socle modulaire (OSGi) et complètement certifié Java EE 6. Dans les faits, il y a eu beaucoup d'améliorations autour du provisioning SSH (à la Hudson/Jenkins ou autres Hadoop), de la scalabilité du domaine multi-cluster, multi-instances, mais aussi des nouveautés comme le versioning d'applications contribué par Serli, les "scoped-resources", ou l'intégration de Coherence\*Web (sous le nom de ActiveCache for GlassFish).

Toutes ces fonctionnalités sont ou seront traités dans des blogs et énumérés sur TheAquarium. Il y aura également un nombre de videos égrainés au rythme d'une par jour. Bien entendu il y a également la documentation complète pour le produit (versions open source et Oracle): glassfish.org/docs.

Ah oui, j'oubliais, si vous insistez il y a même une version en français (dite "multilingual").

About

This blog has moved

Alexis Moussine-Pouchkine's Weblog

GlassFish - Stay Connected

Search

Archives
« avril 2014
lun.mar.mer.jeu.ven.sam.dim.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today
Blogroll

No bookmarks in folder

News

No bookmarks in folder