Enterprise grade Java.
You'll read about Conferences, Java User Groups, Java, Integration, Reactive, Microservices and other technologies.

Friday, December 24, 2010

Season's Greetings and Happy Holidays

09:40 Friday, December 24, 2010 Posted by Test No comments:
It's nearly done. 2010 is almost over and we finally reached Christmas. Time for eCards, postcards and greetings. I've seen many good ones this year and it's hard to come up with a picture, that visualizes all the good wishes and hopes I have for the many readers out there. Thanks for reading and contributing to my blog this year! Thanks for listening to my thoughts!

Now it's time to wish you and your family all the best this holiday season. Have some silent times for Christmas and between the years. And last but not least a great start into 2011!

Wednesday, December 15, 2010

One thing you did not know about Java EE class loading in GlassFish 2.x

11:10 Wednesday, December 15, 2010 Posted by Test No comments:
, ,
As you might have read, I am working on a couple of WebLogic to GlassFish migration projects occasionally. Most of them are WLS 10.0 to GlassFish 2.1.1 and therefore stick to the Java EE 5 specification without removing or adding anything. A couple of projects failed to pass the regression tests on GlassFish because of a class loading issue I was not aware of. So, if you are not willing to make the same mistake, read on ...

Class Loader Hierarchy: What I knew.
Class loaders in the Enterprise Server runtime follow a delegation hierarchy. Note that the class loader hierarchy is not a Java inheritance hierarchy, but a delegation hierarchy. In the delegation design, a class loader delegates classloading to its parent before attempting to load a class itself. A class loader parent can be either the System class loader or another custom class loader. If the parent class loader cannot load a class, the class loader attempts to load the class itself. In effect, a class loader is responsible for loading only the classes not available to the parent. This is true for most application servers out there. Transfered into practical experiences this should tell you, that you have a great example if you look at two web application archives packaged in an ear. Non of the two should have access to the classes loaded by the other class loader. This is, what I believed to be the single truth out there. And the image to the right (taken from Sun GlassFish Enterprise Server v2.1.1 Developer's Guide) seems to support this. You can also compare a little bit smaller documentation without the image in the latest Oracle GlassFish Server 3.0.1 Application Development Guide. On the first read, both seem to tell me the same.... I have a strong class loader hierarchy and one war can not access the classes of the other.

The test case
Ok. Here we go. Build a simple maven project. Two wars in one ear.
[INFO] [dependency:tree {execution: default-cli}]
[INFO] net.eisele:ear:ear:1.0-SNAPSHOT
[INFO] +- net.eisele:web1:war:1.0-SNAPSHOT:compile
[INFO] +- net.eisele:web2:war:1.0-SNAPSHOT:compile
[INFO] +- javaee:javaee-api:jar:5:provided
Put a simple Servlet into war1 and a simple bean with a simple getName() which returns a String into War2. Now access the bean from your Servlet (you need to trick around a bit to get this to work. If anything else fails, put the bean into War1 also and remove it from the war afterwards). Now deploy it to GlassFish 2.x and start being amazed. It works. Even if it should not according to the documented class loading mechanisms.
If you switch over to GlassFish 3.x you get the expected behavior. The class loading from here on is save and you have separate class loaders (Archive class loader) for every module in your application and the test case fails :) Thank god!

The Spec
Now you are wondering, what the specification tells you about this. Look at the latest javaee_platform-6_0-fr-spec.pdf and read:
Components in the web container may have access to the following classes and resources. [...]
The classes and resources accessible to any other web modules included in the same ear file, as described above.

Bottom line
Wow. That was unexpected. In fact, I did expect something else. Now we all are a bit wiser. Be careful migrating apps from one app server to the other. And don't expect to have a strong hierarchical class loader in place. That is especially true for GF 2.x class loading.

Friday, December 10, 2010

Who is afraid of Java EE 6? Get rid of your fears!

13:24 Friday, December 10, 2010 Posted by Test 1 comment:
Believe it or not. From time to time I get the chance to make a proposal for a technology stack to use. And it happened recently, that I did this. And after following my post about choosing the right Java EE version I dediced to make a proposel for using Java EE 6 with GlassFish 3.0.1. And this proposal finally raised my awareness about possible risks, people could remark being confronted with such a decision. Here is how you could address them. And please note, that this is only one possible way that is drawn with a strong technology background skipping all the "maybes" and "technical details". If you have to argue for it, it's most likely, that you will see business decisions driving this more often.

Nothing changed (basicaly)
If you look at Java EE 6 from a technology point of view, you have a couple of single specifications contained in an umbrella. We are talking about roughly 35 technologies. Let's split them apart to see, what's important. Compared to the plain numbers, the heart of Java EE 6 is still Java EE 5. 52% of the specifications did not even get an update. They simply stay unchanged. We have 23% regular updates, 14% major updates (reworks) and only 11% of the stack is completely new. So nobody has to fear, that already taken investments in Java EE 5 skills or infrastructure will be wasted. It's more like a concrete evolution of what we have with Java EE 6. If you stay at 5 these days, you'll be betting on 4-year old technology and increasing your Technical Debt.

Advantages and opportunities of the new ones
Let's look at how the 11% new stuff could influence our development and which opportunities are in there. First two are Contexts and Dependency Injection (JSR 299) und DI for Java (JSR 330). Both promise to make mature dependency injection capabilities know from frameworks like Spring and Guice available within the industry standard.
Next in line is the new Bean Validation (JSR 303) framework. It's presence allows for standardized and annotation based validation within your applications. And finally there are the RESTful Web Services (JSR 311). They allow a lightweight approach to connecting clients and servers. RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it.

Significantly less workarounds and overhead
As one primary goals of Java EE 6 was to optimize the webstack and because of this it is primarily JSF 2.0 (JSR 314) which holds the biggest opportunities. Beside the fact, that you now can use facelets without having to deal with it as a library, you have many other advantages available. Think about scopes, resource handling, system events and native AJAX integration, to name but a few. All this is directly followed by Java Persistence 2.0 (JSR 317). It's the first usable JPA standard out there. You no longer have to use other persistence frameworks to get a working application. Sticking to the standard is now possible without workarounds or additional effort. The topping are the Enterprise Java Beans 3.1 (JSR 318). Forget about ejb.jar files and containers. Deploy everything in a single war. Use the new no interface beans, the singleton support and benefit from the new annotation driven timerbeans. To make it short. The reworked specifications consequently addresses issues from the field. Compared to Java EE 5 you now have significantly less workarounds and overhead in terms of third party libraries to handle.

How to manage the new kids
But there is still the risk, that the new kids on the block will fail and the concepts are not usable in a productive environment. How to address this? The first step is to have it on the list somewhere. Don't tell anybody, you are going to base everything exclusively on them. For a real life project it's best to find a strategy for staggered and suitable use of the new features. In fact, you could think about the right time to introduce the new features. Having a mature Java EE 5 stack at hand it's probably best to start with whatever you have. Straight away and think about the need to introduce any of the new specifications following these simple rules: 1) One at a time. 2) And always have a fall back strategy. The little graphic shows a possible scenario for this. Start with what you know best and introduce what you could handle. JSF 2.0 is a good starting point in general.

GlassFish is dead!
If you are done with discussing Java EE 6 and its advantages in general, you have the next point to talk about. The application server to use. To make it short: You only have exactly one choice at the moment. And this is something that could scare people to death. Be careful talking about it. But it's true, so you have to commit this somewhere during the discussion. The worst argument I heard lately was that someone read, that "GlassFish is dead". Wow. Awesome. Thanks manager magazines around the world. If this is not the message, you are willing to spread: This is how it arrives at your readers. Even if Oracle has it's own way of driving Java and even if they are not Sun and even if there are many things happening in the community at the moment. GlassFish is anything but dead! It's freaking alive and rocking. 24 million downloads since 2005. The reference implementation for both Java EE 5 (JSR 244) and Java EE 6 (JSR 316). The choice for many big accounts like Peugeot, Verizon, Xerox, Telefonica, T-Mobile and many others. And it's there since 11/2008. A stable version is available since 12/10/2009. So it's happy first birthday for Java EE 6 and GlassFish 3 today. But to be honest, the first tests started two years ago. And if you look at the release plan on the right you can see, that the commercial 3.0.1p1 fixed additional 7 bugs compared with the 3.0.1 released 6/18/10. That's a sign, isn't it? A good one!

Why everything has to be this hard
I know. The honest way would be to simply share the personal excitement: "Java EE 6 with GlassFish 3 is freaking hot and we need all those fancy new specifications.". But the truth is, that your daily jobs are there because of people asking you questions about risks and taking them into account. And there are still some scenarios, where I honestly don't want to use Java EE 6. But it's also true, that beside all political considerations there is nothing to worry about using it. If you are not working for one of those customers or shops requiring you to use blue or other colored commercial application servers, you are free to give it a shot. And it is worth it. Beside the technical advances it will save you real money.

Tuesday, December 7, 2010

Seven ways to get things started. Java EE Startup Classes with GlassFish and WebLogic

09:04 Tuesday, December 7, 2010 Posted by Test 9 comments:
, ,
This is a blog about a topic that I realy don't like. But it comes across my ways over and over again and it's no doubt that you need it from time to time. Enough reasons for me to collect some information about it and publish it for your reference. I am talking about Startup-/Shutdown classes with Java EE applications or servers.

What are those and why?
Most Java EE applications require you to invoke some functionality at the server startup or application deployment time. For example, you may want to preload some data or invoke some business logic or invoke some logic at server shutdown to gracefully disconnect from a service or release some resources. The right place to do most of the stuff is a so called startup- and/or shutdown class. If you look into the most recent Java EE 6 specification you only find one application construct, the @Startup annotation to do the job. But you have a couple of other options. Here you are:

EJB 3.1 @Startup
The introduction of singletons also provides a convenient way for EJB applications to receive callbacks during application initialization or shutdown. By default, the container decides when to instantiate the singleton instance. However, you can force the container to instantiate the singleton instance during application initialization by using the @Startup annotation. This allows the bean to define a @PostConstruct method that is guaranteed to be called at startup time. In addition, any @PreDestroy method for a singleton is guaranteed to be called when the application is shutting down, regardless of whether the singleton was instantiated using lazy instantiation or eager instantiation. In lazy instantiation, the singleton isn't instantiated until it's method's are first needed. In eager instantiation, the singleton is instantiated at startup time whether or not it gets used.

public class StartupBean {

private void startup() { ... }

private void shutdown() { ... }

If you are in a clustered environment this probably will not work for you out of the box. This only works within a single VM. You will have your StartupBean called on every server instance starting up or shutting down. If you have special cluster requirements (e.g. only initialize once for the complete cluster) you have to think about synchronizing your StartupBeans by using a database. Usable on any EJB 3.1 compliant container and highly portable. This even should work with the lightweight Java EE 6 Webprofile.

Startup Servlet
The old fashioned way. You can do whatever logic is needed within your startup servlet. This is a simple servlet in general which gets a >load-on-startup< parameter in your web.xml or the @WebServlet(name="startup", loadOnStartup="2") annotation.
This servlet has a load-at-startup priority of 2, meaning any servlet with a load priority lower than 2 will be loaded before this one, and those greater than 2 after.
If you have an init() method which is called by the servlet container to indicate to a servlet that the servlet is being placed into service and a destroy() method which is called by the servlet container to indicate to a servlet that the servlet is being taken out of service.

public class StartupServlet extends javax.servlet.http.HttpServlet {

public void init(ServletConfig config) throws ServletException {

public void destroy() {

There are a couple of disadvantages to this approach. First of all, this obviously only works with web applications. And second, there is nothing that prevents the servlet from being called a couple of times. To ensure this, you probably would have the need to implement the singleton pattern. Biggest plus here is, you can port it to any Java application server you like.

A better way to implement an application startup class is by using the servlet context listener. It listens to application startup and shutdown events by implementing the methods contextInitialized() and contextDestroyed(). You can configure the listener in your web.xml (<listener-class>) or even use the @WebServletContextListener annotation.

public class StartupListener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {

public void contextDestroyed(ServletContextEvent sce) {

Drawback again; there is one context per "web application" per Java Virtual Machine. So you would have to handle cluster problems yourself. But positive about this is, that you don't have to care about anybody calling it externally, like this could happen with startup servlets. But it's portable and can be used on any Java EE server.

Resource Adapter to Perform as a Startup Class
Another way would be to implement a resource adapter with a minimal resource adapter class that implements javax.resource.ResourceAdapter, which defines a start() and stop() method. When the resource adapter is deployed, the start() method is invoked. When it is undeployed, the stop() method is called.

public class StartupRA implements ResourceAdapter
public void start( BootstrapContext bsCtx ) {
public void stop() {
// Because of the definition of the ResourceAdapter interface,
// you must also define the endpointActivation(), Deactivation() and getXAResource() methods.

You can use this approach if you have the Java EE full profile at hand. This is a very mature way of initializing your application in general. Nevertheless you have to add an Resource Adapter to your project and you have to package and deploy it. Compared with the other approaches this is additional complexity. But it will work for any of the containers available providing an RA implementation.

Using JMX notification objects with WebLogic Server
JMX provides two ways to monitor MBeans: MBeans can emit notifications when specific events occur (such as a change in an attribute value), or a special type of MBean called a monitor MBean can poll another MBean and periodically emit notifications to describe an attribute value. You create Java classes called listeners that listen for these notifications and respond appropriately. To receive a notification when a server starts or stops, register a listener with each server's ServerLifeCycleRuntimeMBean in the Domain Runtime MBean Server and configure an AttributeChangeNotificationFilter. Find a detailed description in the Oracle WebLogic Server documentation Listening for Notifications from WebLogic Server MBeans: Main Steps.

Biggest drawback here is the complexity. You have to handle the many notifications and filter them according to your needs. I still do not feel JMX is the easiest API to work with. At the end of the day, this will still be no portable solution. You have to use the WLS specific ObjectNames (e.g. DomainRuntimeServiceMBean).

WebLogic Startup- and Shutdown classes
Prior to release 10.x of WLS, you could have used application-scoped startup and shutdown classes. Application lifecycle listener events provide handles on which developers can control behavior during deployment, undeployment, and redeployment. You create a listener by extending the abstract class weblogic.application.ApplicationLifecycleListener. The container then searches for your listener.

public class MyListener extends ApplicationLifecycleListener {
public void preStart(ApplicationLifecycleEvent evt) {

public void postStart(ApplicationLifecycleEvent evt) {

public void preStop(ApplicationLifecycleEvent evt) {

public void postStop(ApplicationLifecycleEvent evt) {


If you are not willing to use any WebLogic Server-specific interfaces, you can also declared it in the weblogic-application.xml deployment descriptor.


This is a very easy way of implementing startup- and shutdown functionality. Too sad, that it is deprecated and should not be used anymore. And it's not portable and and and ... forget about it :)

GlassFish Server Life Cycle Events
A similar construct is available within GlassFish. The so called Server Life Cycle Events. A lifecycle module (implementing LifecycleListener) listens for and performs its tasks in response to events. Upon start up, before initializing its subsystems application server posts lifcycle modules the INIT_EVENT. This is followed by server posting the STARTUP_EVENT to the lifecycle modules upon which server starts loading and initializaing the applications. Once this phase is completed, the READY_EVENT is posted to the lifecycle modules. When the server is shutdown, server posts the SHUTDOWN_EVENT to the lifecycle modules and then shuts down the applications and subsystems. Once this phase is completed the TERMINATION_EVENT is posted.
You only have to implement the com.sun.appserv.server.LifecycleListener to get this going. It has one method handleEvent(LifecycleEvent event) which gets notified.

public class StartupListener implements LifecycleListener {

public void handleEvent(LifecycleEvent event) throws ServerLifecycleException {
if (LifecycleEvent.INIT_EVENT == event.getEventType()) {

if (LifecycleEvent.STARTUP_EVENT == event.getEventType()) {

if (LifecycleEvent.SHUTDOWN_EVENT == event.getEventType()) {

if (LifecycleEvent.TERMINATION_EVENT == event.getEventType()) {

After you have implemented it, you can put the jar to the domain/lib directory and add the needed configuration to the domain.xml.

<application name="StartupTest" object-type="user">
<property name="isLifecycle" value="true" />
<property name="class-name" value="net.eisele.StartupListener" />

This could also be done via the admin console or the asadmin command.
Things to keep in mind are that the configured properties for a lifecycle module are passed as properties after the INIT_EVENT. The JNDI naming context is not available before the STARTUP_EVENT. If a lifecycle module requires the naming context, it can get this after the STARTUP_EVENT, READY_EVENT, or SHUTDOWN_EVENT.

In general it's the same as with the WebLogic startup mechanisms. They are not portable and you should consider using them only in very special cases.

Bottom Line
Now you know about seven ways to get things started. Only four of them are portable and also usable with other Java EE servers. You should try to stick to the first four presented. But there could be reasons for using server depended ways of initializing. If you have the need for threads in general you are almost save starting them the proprietary way, as this is most likely the only way that is supported. Or you have a (customer) blueprint to stick to. Or you need guarantees for your startup classes, that could not be meet by the standardized ways (e.g. classloading, order) ... At the end of the day, it's up to you to make the right decision. Or ask your favorite architect about it :)
If I have missed an approach .. let me know, happy to read your comments!

Thursday, December 2, 2010

NetBeans in large teams. Rollout and preconfiguration.

08:21 Thursday, December 2, 2010 Posted by Test No comments:
, ,
I have spend a couple of hours with Java EE 6 since December 2009 and now it finally seems as if the time is right for doing the first real Java EE 6 project. Beeing an Eclipse advocate for years now, Java EE 6 and the IDE support made me think about NetBeans (again). I guess, I used the 3.x in the past and was happy but switched to Eclipse because of the fast growing infrastructure and the number of available plugins. Being in need of Java EE 6 support everything changed. The first bits are out for Eclipse, but I need the full stack. And there is probably no better place to look at, than NetBeans. Here we go. This are the findings from our first steps for using NetBeans in a larger development team. Thanks to Wolfgang for figuring out all this, and thanks to the NetBeans Team (Jesse, Antonin, Petr) for listening to our questions!

Why you should care!
Having a small team at hand this is nothing but a big deal. You talk about the prerequisits and everybody installs the stack. If you are trying to run a midsize or even large development team, you are in need of a defined, structured and preconfigured development environment. There are many reasons for this. First is the time. You don't want:
- everybody to spend a day or two on installing, reading and configuring his IDE.
- different versions around (IDE itself, plugins, server, java)
- different templates, code check configurations or settings around.
And you probably want to be able to scale the team to your needs. One important part of this is a simple and easy development environment and project setup.

Which parts?
In the past, I used to have some archives around with preconfigured Eclipse bundles. They contain different plugins and configurations. One of them was chosen for a new project. If someone came on board, I gave her/him the archive and told her/him to unzip it somewhere. Next was to checkout the project. This is the simple setting. Depending on the projects size, I also decide to rollout the "one" right version of the JDK, Appserver and build tools. For me the optimal set for bigger teams should be:
- IDE itself (with appropriate plugins for your Java EE stack)
- Code Templates
- Quality Checker configuration
- Appserver and it's domain
- Build Tool

How to do this with NetBeans?
Have you ever tried to move a NetBeans installation around or rename the folder? Not a big deal, isn't it. But what happens, if you archive it and put it onto another maschine? You probably will experience, that some configurations are broken and you end up with a freshly installed NetBeans or even an error message telling you, that the configured jdkhome is invalid.
You need to take a look at a couple of places to get this right. As always, there are some solutions to this problem and they are OS dependend. I am asuming, that you are using a Windows maschine as dev envorinment.
The best place to start is a clean NetBeans install. You should prepare yourself a bit, to make this easier later on. Create a local project folder somewhere and map a drive letter to it. On windows you can use SUBST [drive1: [drive2:]path] for that. This is only one approach. You could also use whatever folder you like and provide a wrapper.bat where you set all the folders as variables for NetBeans (find some hints about it in the PortableWorkingEnvironmentFaq). I personally like the single mapped drive a bit more.
Next is to download and install the Java SE Development Kit, that you are planning to use. Don't try to install it to the logical drive, this will fail (Don't know, if it's a bug .. trying to figure it out). You will have to install it to the real folder behind the drive. Now start installing your freshly downloaded NetBeans to this logical drive. During the installation process, you should select the appropriate JDK install. Don't care about the "wrong" drive letter for now. Once finished, go and open your X:\ folder and create a new one. Name it whatever you like. It should contain the future default user settings. I'll call it "nbsettings" from now on. Caution: It must NOT reside inside your NetBeans installation folder! Now open the etc\netbeans.conf in your favorite editor and change the netbeans_default_userdir to "../../nbsettings". Next is to change the netbeans_jdkhome to a relative path: "../../jdk1.6.0_22". Now, open a cmd-line and start bin/netbeans.exe.
You should now have a setup like this:
Java Home               = X:\jdk1.6.0_22\jre
  System Locale; Encoding = de_DE (nb); Cp1252
  Current Directory       = X:\NetBeans7.0Beta\bin
  User Directory          = X:\nbsettings
  Installation            = X:\NetBeans7.0Beta\nb
Whatever configuration you are working on now should only make changes to your newly created user directory.

What else?
If you have the basic setup up and running, you can now go, archive the complete logical folder, add a setDrive.bat file containing the subst command and adding some env variables and give everything to your developers. Assuming, that they all run the IDE from a logical drive x:\ you are done. For convenience you should think about adding an up-to-date application server (glassfish or weblogic, of course ;)) and you could even think about pushing out the SQE-Quality Plugin. I recommend, that you place every single needed bit (including Maven and Ant in versions your project will be using) to your IDE template. Another point are the Java Templates. I highly recommend, that you configure them to your projects needs and include them in your bundle. And don't forget to insert subversion keywords.

I like NetBeans a lot. It is fast, has a rich feature-set and everything you need to get started with Java EE 6 is included. Even if the lates 7.0 is still beta I am really looking forward using it. I especially like the maven, hudson and server integration. This looks very smooth from a developers point of view. Compared with Eclipse the missing plugin infrastructure could be an issue. But who cares, if everything you really need is already bundled with the IDE? One other point, I like is the size. My latest helios packages have an average of 550MB and 11,0k files. The NetBeans 7.0 beta comes with 370MB and 4,5k files. That's a big plus if you are zipping everything together ....