mardi mai 24, 2011

Intercepting startup and shutdown events

This blog has moved to
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("");

    public void handleEvent(LifecycleEvent le) throws ServerLifecycleException {
       switch (le.getEventType()) {
          case LifecycleEvent.INIT_EVENT:
          case LifecycleEvent.READY_EVENT:
          case LifecycleEvent.SHUTDOWN_EVENT:
          case LifecycleEvent.STARTUP_EVENT:
          case LifecycleEvent.TERMINATION_EVENT:
             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 :

public class CreateTables {
    public void init() {
       logger.warning("Creating tables");

    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 :

public class PopulateTables {
    public void init() {
       logger.warning("Populating tables");

    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 :

WARNING: Creating tables
WARNING: Populating tables
WARNING: archiving table data
WARNING: Dropping table...

lundi sept. 27, 2010

javaOne 2010 : Java EE 6 Panel "What do we do now?" notes

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

I was privileged to be moderating this year's Java EE panel at JavaOne (session 313278). We had a great list of panelists and a lively discussion. Here are my notes:

Panelists (from left to right)
• Adam Bien (individual)
• Jim Knutson (IBM)
• Emmanuel Bernard (JBoss, Red Hat)
• Reza Rahman (individual, Caucho)
• Krasimir Semerdzhiev (SAP)
• Roberto Chinnici (Oracle, spec lead)
• David Blevins (OpenEJB, Apache Geronimo)
• Alexis MP (Oracle, moderator)

Platform and API Adoption
JBoss is feature-complete (RC1) for the Web Profile, probably final in the Fall. Two more months before Caucho Resin is final. WebSphere is in Beta and WebLogic is working on it (GlassFish of course, has had a full implementation since the spec was released in December 2009).

Jim (IBM): adoption for JSF 2.0 (performance), servlet 3.0 and JPA 2.0 (mappings) seem to be very strong. Also JAX-RS (which unfortunately is not in the web profile and as such not part of the upcoming Resin 4 release). Krasimir (SAP) mentions EJB 3.x. Reza says people are very satisfied after studying Java EE 6. In some cases Java EE is back in people's radar. Emmanuel (JBoss): people like the consistency and tight integration of the platform. David (OpenEJB) : achievements with EJB's in WARs, singletons, asynch may replace JMS. Roberto (Oracle) on JAX-RS having helped REST become a mainstream technology for Java developers. Adam: migrated all his EAR's to WAR's, removed Quartz and replaced it with EJB Timer, removed a bunch of interfaces. RESTful resources as EJB removes layers, this is good. Event model in CDI is maybe one of the best features. Some of Adam's customers use EJB's and CDI without knowing that it's JavaEE which is the best possible sign that they're focusing on business logic.

CDI is a bit of a special case. Some think that it's powerful but that this power comes with complexity attached. Adam disagrees in terms of complexity of code (@Inject is really all you need to get started). JBoss/Emmanuel says that people are excited by CDI but portable extensions still not known by most. Jim: not that much demand for the time being, complexity might be causing some people to shy away from it but there is a lot of power there and adoption will come no doubt about it. Reza: the fact that it's part of the web profile is the reason they're certifying, also all Resin early adopters are coming for its CDI implementation. Need to re-align more of the platform in Java EE 7. Adam: CDI is like insurance, if there's a need for integrating additional frameworks, anything's possible with portable extensions, yet 90% of the projects don't need it. SAP: CDI is great but some people still haven't gotten their heads around Java EE 5 yet.

Java EE vs. Spring
Adam: I would never put Spring and Java EE together because there's too much overlap. Also from a business point of view, you'd need support from two companies (Spring and AS vendor) which typically don't like each other, so that's a big risk. Reza: there are a several reasons to integrate both: gradual migration, leveraging Spring's work (integration APIs). Adam replies that for new applications, there really should only be one as the injection styles overlap too much. IBM says it's hard to align technologies like Spring with the specification planing requirements, in particular JSR 330 does not quite allow for the integration of Spring, using a CDI-style of injection will offer greater fidelity. EE needs more work there. David Blevins says they're looking at a Guice implementation of CDI. Krasimir agrees that many projects do start from scratch so Java EE is the right choice.

Impact on tooling and testing
Krasimir: EJBContainer is a huge step forward. Emmanuel: tooling should help the developer and not be a requirement. For testing, JBoss has the Arquillian project (sort of next-generation Cargo), also works with GlassFish. David: would be neat to be able to inject resources in test code (OpenEJB working on that). Reza says trend in JavaEE is towards annotation and being more Java-centric (type-safe). Resin has no tooling plans but will integrate with Arquillian and is also developing and end-to-end testing solution. Adam: just use APIs, wizards are always suspicious and prevent people from using different tools (often the case in projects). Still looking for good unit tests (currently using junit 4, jmock, mockito). OpenEJB and GlassFish embedded help too. Roberto says that tools are also there to help people learn (NetBeans has a lot in store for that). Wizards also now produce clean annotation-based code if you decide to use them. Krasimir: tools are key because this is how most people experience and use the platform so they need to improve on a regular basis. Calling people to contribute to Eclipse. IBM: tooling evolved mainly in EE 5. Now more coverage with EE 6.

Questions from the audience
• CDI vs. JSF annotations (@ManagedBeans for instance) ? => Need to streamline some of this in future releases. CDI beans build on top of JSR 250 ManagedBeans. Need more of that throughout the platform.
• SpringMVC and CDI? => Technically possible: use CDI beans as controllers (but Reza says they're not seeing enough demand for SpringMVC to do the work).
• Java EE vs. Spring? => Reza: different approaches, make your own decision. Jim: don't reap out what works well. David: chose the platform you believe in and that will listen to you in the long run.

Roberto (see also his technical keynote for details): Cloud as a focus, modularity as enabler (built on top of what JDK will offer). Also need to track emerging technologies (WebSockets, HTML 5). Need to evolve the specification and not let it up to vendors to implement. Jim: JavaEE can mostly run in the cloud today, bigger problem is dealing with putting large app together: need a modules system. Krasimir: really wanted modules to be there in EE 6 so couldn't agree more. David: more generalization of the various annotations across the platform. Reza: modularity can't be the only value-proposition of, also need realignment of underlying technologies.

Java EE 6 is here today, go ahead and try it out!

dimanche mai 09, 2010

EJB 3.1 asynchrony and transactions

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

When presenting Java EE 6 and GlassFish v3 at the Lausanne JUG last week I was bombarded with questions (I like that) and I think I didn't do an ideal job answering the following question (paraphrasing) :

How does the new async feature in EJB 3.1 work wrt transactions?

The precise answer is easy to find in the EJB 3.1 specification itself (paragraph 4.5.3) :

Client transaction context does not propagate with an asynchronous method invocation. From the Bean Developer’s view, there is never a transaction context flowing in from the client. This means, for example, that the semantics of the REQUIRED transaction attribute on an asynchronous method are exactly the same as REQUIRES_NEW.

By the way, the entire section on EJB 3.1 asynchronous methods is only two pages.

lundi janv. 25, 2010

EJB 3.1 interview (part 1 and part 2) on the GlassFish Podcast

Quick note on the release of both parts of the EJB 3.1 interview I did with spec lead Ken Saks.
Part 1 focuses mainly on the new features of the specification (packaging, no-interface view, singleton, etc...)
Part 2 discusses improved EJB testability, how EJB's relate to other part of the specification, EJB clients, and more.

lundi oct. 05, 2009

Using the EJBContainer API with or without Maven (but with GlassFish v3)

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

This blog is still pretty accurate but do note that GlassFish v3 and NetBeans 6.8 have been released in final version

The typical way to start GlassFish is to use $asadmin start-domain but you could also start it using java -jar modules/glassfish.jar. Both start a standalone instance of GlassFish. The following paragraphs discuss GlassFish Embedded (i.e. start it using an API).

There are at least two ways to start GlassFish in embedded mode: using org.glassfish.api.embedded.Server and associated classes but also using the (now standard in EJB 3.1) EJBContainer.createEJBContainer() API. Let me describe here the latter one and reserve the more general embedded case for a later blog entry.

The goal is to write something like as simple as this to test your EJB :

    EJBContainer c = EJBContainer.createEJBContainer(); // new in EJB 3.1!
    Context ic = c.getContext();
    SimpleEjb ejb = (SimpleEjb) ic.lookup("java:global/sample/SimpleEjb");

EJB's found in the classpath of the running code above will automatically be deployed and made available via lookups.

Calls to EJBContainer.createEJBContainer() are likely to be made from your tests. If you're making those calls by constructing yourself the execution classpath, then you simply need to add glassfish/lib/embedded/glassfish-embedded-static-shell.jar, an empty jar with a Class-Path: listing the required jars and that is part of the GlassFish distro. In fact, if you're using recent builds of NetBeans 6.8 (and the soon-to-be-released beta), the IDE does this for you when GlassFish is the target server. If you are using Maven, it's a bit trickier.

To use EJBContainer.createEJBContainer() from Maven tests, you'll need to add the following dependency to your POM (updated to final version of GlassFish v3):


You could restrict this to a smaller set of GlassFish artifacts but for non-trivial tests (if you use JPA for instance), you would start to have a fairly long list of dependencies so the above sounds like a reasonable thing to do. This will require Maven to download the GlassFish All-in-one JAR file (40MB or so). The reason I wrote it would be trickier with maven is that you need to pass a property during the createEJBContainer() call indicating the location of a GlassFish v3 install. The above Java code would need to read something like this:

     Map p = new HashMap();
     p.put ("org.glassfish.ejb.embedded.glassfish.installation.root",
           "/path/to/glassfish"); // include trailing "/glassfish"
     ec = EJBContainer.createEJBContainer(p);

As of build 69 (maybe 70?), this is no longer needed - i.e. you can simply have glassfish-embedded-all.jar as a dependency or simply in your classpath. A full install of GlassFish is no longer required (although it may be interesting if you want to use JDBC configurations). Read this blog by Thomas for another interesting approach: Nice follow-up blog here:

Starting the appserver this way (with or without Maven) exercises the actual GlassFish code, not another implementation or a customized fork. There are some limitations to what you can run and in particular port configuration is ignored (not listening on any) and only local EJB interfaces are available (the spec only requires EJB 3.1 lite support). On the other hand, JPA calls are very much possible.

This should all work with v3 promoted build 66 (I just tested this with promoted build 70, see above simplification). Adam Bien beat me to covering that topic, but I hope you get some additional info here. In my case the start-up, setup, deploy and shutdown of GlassFish Embedded are worth about 6 seconds. Note that there is no OSGi involved here.

For a complete working example with JPA calls, check out this sample code.
The EJB 3.1 specification has a chapter (#22) on "Embeddable Usage". Check it out for further details about EJBContainer.

Update: some people are facing classpath/maven issues that causes the test to fail to find any EJB to test. The above is meant to run with an existing install of GlassFish (sorry this wan't clear) and this great thread has more data on what the issues can be. Marina describes the expected behavior and Laird goes into details about the use of maven-surefire-plugin and its <forkMode> configuration parameter. Make sure you read this if you have similar issues.

Update 2: per the EJB 3.1 specification EJBContainer is only required to support "EJB light" (no remote interfaces for instance).

vendredi juin 19, 2009

GlassFish v3 a la carte screencast - Part 3 - Jersey and EJBs

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

In the first screencast, I installed a minimal GlassFish v3 from a small bootstrap (IPS toolkit), created a domain and started the server. The second entry did something actually useful with GlassFish and two containers: Java Web and Spring. In this screencast, I layer a custom distribution on top of a GlassFish kernel. Enough to deploy a JAXR-RS / EJB 3.1 (lite) application.

For the sake of brevity this screencast is mostly command-line. It starts with the 5MB ips bootstrap and installs a pre-defined custom distribution which is enough to deploy the jersey-ejb sample application. The custom distribution is essentially an IPS package with no artifact, only a set of dependencies on other packages. For the curious out there, here is the step-by-step for the screencast :

bin/pkg set-publisher -P --enable -O
bin/pkg set-publisher --enable -O http://localhost:10001 localRepo
bin/pkg install sample-distro
bin/asadmin create-domain --instanceport 8080 --adminport 4848 mydomain
bin/asadmin start-domain
bin/asadmin deploy ~/jersey/jersey/samples/jersey-ejb/target/jersey-ejb.war
open http://localhost:8080/jersey-ejb/

I hope this series of screencasts demystifies the IPS/packaging side of GlassFish and shows the interesting possibilities it offers to end-users.

mardi sept. 30, 2008

WebCast EJB 3.1 ce jeudi 2 octobre

EJB 3.1 sera une des composantes importantes de Java EE 6 l'année prochaine. Le travail est déjà bien avancé et Ken Saks (le spec lead JSR 318) vous propose un WebCast ce jeudi à 20h15 (heure de Paris). RDV donc sur le canal "TheAquarium" de La présentation sera mise à disposition sur cette page.

je trouve assez agréable à utiliser comme spectateur et clairement très simple coté "production". Le précédent WebCast sur OSGi par Rich Hall (lead Felix et nouvel embauché Sun) est disponible en replay.

En attendant jeudi ou si vous ne pouvez pas être disponible à cette heure là, je vous invite à lire le blog de Ken et celui de Mahesh qui explique les points importants de EJB 3.1 et comment tester un certain nombre de ces fonctionnalités dès à présent dans GlassFish v3.

Ma fonctionnalité EJB 3.1 préférée? J'hésite entre packaging simplifié et EJBContainer.createEJBContainer();.

Maj: the "Public Draft" est deesormais disponible.


This blog has moved

Alexis Moussine-Pouchkine's Weblog

GlassFish - Stay Connected


« février 2017

No bookmarks in folder


No bookmarks in folder