07
Jan
10

Designing Glassbox Tests and Failure focused Tests using Byteman

There is one thing that always intrigued me, the absence of tools that supported the design of GlassBox tests and tests that focused on failure scenarios up to the point that I ever thought about starting my own open source project but recently I stumbled upon Byteman project from JBoss.
The project description on the project site states that Byteman is:

Byteman is a bytecode injection tool which simplifies development of tests for Java applications using a technique called fault injection. Byteman works by inserting scripted side effects into application code, Test scripts may include actions which create and propagate conditions appropriate to the test scenario. Or they may simply verify correct execution of the application program.

Byteman has a good list of pros:

  • Powerful Scripting Language
  • Possibility of adding and updating the Scripts for code modification at runtime
  • Simple Java class for uploading scripts to a running JVM which makes it easy for integrating script updates into a JUnit test

I started to test the tool today and I can say that the first impression was incredible. I agree that the scripting syntax may improve a little (eg.: every rule has to have an IF what forces you to use IF true sometimes) but this can’t be considered an impeditive problem.
I’ll try to post here some examples of its usage.

05
Jan
10

Quartz Resource Adapter as an alternative to EJB Timers

Anyone developing a J2EE application probably faced the challenge of setting some fixed interval timers that need to be up upon application startup. This, in fact involves two challenges:

First one: J2EE provides no means of startup notification on EJB-Jars.

Second: EJB timers are persistent (they survive server restarts) and if you don’t cancel them upon application shutdown you’ll end up having lots of those timers.

So, wouldn’t it be fine if we had some mechanism of having a notification sent down from AppServer to our application in a timed manner? It’d be even better if we had some mechanism to specify the intervals using Unix Cron format.

Happily there is a simple solution: Quartz Resource Adapter from JBoss licensed as LGPL (as stated on its ra.xml) that makes it safely usable on commercial products. It comes packaged as a rar file on JBoss deploy directory as it seems to be used for JBoss internal purposes but nothing (or almost nothing) prevents you from using it into another AppServer.

By almost nothing I meant that as it is packaged on JBoss there is one quirk:

QuartzResourceAdapter.endpointActivation method does one trick to detect whether the endpoint configured is a stateless or stateful endpoint that renders it unusable on WebSphere for example (WebSphere prevents you from calling MessageEndpointFactory.createEndpoint from the Thread that invoked endpointActivation) and I am sincerely not sure whether this is something the spec enforces. I’ll paste the trick below:

 // allocate instance of endpoint to figure out its endpoint interface
      Class clazz = QuartzJob.class;
      MessageEndpoint tmpMe = endpointFactory.createEndpoint(null);
      if (tmpMe instanceof StatefulJob) clazz = StatefulQuartzJob.class;
      tmpMe.release();

And the best thing is that this trick can be safely replaced by two markup ActivationSpec classes, so we end up having the following code:

      // figure out endpoint interface through activationspec (WAS denies endpoint creation on main thread)
      Class clazz = null;
      if (spec instanceof QuartzStatelessActivationSpec) {
          clazz = QuartzJob.class;
      }
      else {
          clazz = StatefulQuartzJob.class;
      }

And the two markup classes:

package org.jboss.resource.adapter.quartz.inflow;

public class QuartzStatefulActivationSpec extends QuartzActivationSpec {

}
package org.jboss.resource.adapter.quartz.inflow;

public class QuartzStatelessActivationSpec extends QuartzActivationSpec {

}

And the ra.xml file for the RAR package gets changed from:

 <messagelistener>
               <messagelistener-type>org.quartz.Job</messagelistener-type>
               <activationspec>
                  <activationspec-class>org.jboss.resource.adapter.quartz.inflow.QuartzActivationSpec</activationspec-class>
                  <required-config-property>
                      <config-property-name>cronTrigger</config-property-name>
                  </required-config-property>
               </activationspec>
            </messagelistener>
            <messagelistener>
               <messagelistener-type>org.quartz.StatefulJob</messagelistener-type>
               <activationspec>
                  <activationspec-class>org.jboss.resource.adapter.quartz.inflow.QuartzActivationSpec</activationspec-class>
                  <required-config-property>
                      <config-property-name>cronTrigger</config-property-name>
                  </required-config-property>
               </activationspec>
            </messagelistener>

To:

 <messagelistener>
               <messagelistener-type>org.quartz.Job</messagelistener-type>
               <activationspec>
                  <activationspec-class>org.jboss.resource.adapter.quartz.inflow.QuartzStatelessActivationSpec</activationspec-class>
                  <required-config-property>
                      <config-property-name>cronTrigger</config-property-name>
                  </required-config-property>
               </activationspec>
            </messagelistener>
            <messagelistener>
               <messagelistener-type>org.quartz.StatefulJob</messagelistener-type>
               <activationspec>
                  <activationspec-class>org.jboss.resource.adapter.quartz.inflow.QuartzStatefulActivationSpec</activationspec-class>
                  <required-config-property>
                      <config-property-name>cronTrigger</config-property-name>
                  </required-config-property>
               </activationspec>
            </messagelistener>

Apart from this you’ll have to include jboss-common.jar (found on $JBOSS_HOME\lib) into the quartz-ra.rar file in the same level as quartz-ra.jar and quartz.jar.
Now you are done to install it into your application server and finally create your Activation Specs.
I am providing a PDF with Patched Quartz Resource Adapter for anyone willing to test on your preferred J2EE server and I also posted a message on JBoss AS Development forum to check whether they are interested in incorporating these changes.
Updates: It seems like this is going to get integrated into JBoss AS main code. I’ve submitted the patch as requested.

20
Dec
09

Hibernate SequenceGenerator with allocationSize=1 leads to huge contention

This post is a kind of warn for Hibernate users.

I sincerely don’t know which was the reason but accidentally someone annotated every entity on a software with:

@SequenceGenerator(allocationSize=1)

Doing a brainstorm to find the reason we can speculate:

  1. Minimise sequence gaps due to server reboots (unlikely)
  2. Misunderstanding of what the parameter really does. Probably the developer thought it had to do with the increment by parameter of the underlying database sequence (more likely)

Whichever the reason the truth is that whenever you annotate an entity with @SequenceGenerator Hibernate (at least I know up to 3.3.1.GA) delegates sequence generation to org.hibernate.id.SequenceHiLoGenerator which in turn generate method is as follows:

public synchronized Serializable generate(SessionImplementor session, Object obj)
	throws HibernateException {
		if (maxLo < 1) {
			//keep the behavior consistent even for boundary usages
			long val = ( (Number) super.generate(session, obj) ).longValue();
			if (val == 0) val = ( (Number) super.generate(session, obj) ).longValue();
			return IdentifierGeneratorFactory.createNumber( val, returnClass );
		}
		if ( lo>maxLo ) {
			long hival = ( (Number) super.generate(session, obj) ).longValue();
			lo = (hival == 0) ? 1 : 0;
			hi = hival * ( maxLo+1 );
			if ( log.isDebugEnabled() )
				log.debug("new hi value: " + hival);
		}

		return IdentifierGeneratorFactory.createNumber( hi + lo++, returnClass );
	}

If you compare the generate sequence above with the one from org.hibernate.id.SequenceGenerator below you’ll notice that this one in turn is not synchronized:

public Serializable generate(SessionImplementor session, Object obj)
	throws HibernateException {

		try {

			PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
			try {
				ResultSet rs = st.executeQuery();
				try {
					rs.next();
					Serializable result = IdentifierGeneratorFactory.get(
							rs, identifierType
						);
					if ( log.isDebugEnabled() ) {
						log.debug("Sequence identifier generated: " + result);
					}
					return result;
				}
				finally {
					rs.close();
				}
			}
			finally {
				session.getBatcher().closeStatement(st);
			}

		}
		catch (SQLException sqle) {
			throw JDBCExceptionHelper.convert(
					session.getFactory().getSQLExceptionConverter(),
					sqle,
					"could not get next sequence value",
					sql
				);
		}

	}

The synchronized keyword on the previous one isn’t any surprise since SequenceHiLoGenerator does some of its sequence generation in memory and it may be accessed concurrently by multiple threads.

But the fact is that SequenceHiLoGenerator wasn’t designed to have an allocationSize=1 (strangely enough it has a separate flow for this situation).

Reproducing this scenario seems to be very easy, sincerely I have not tried to do a syntetic reproduction but I guess that spawning a few threads with a simple entity configured with allocationSize=1 and having all the threads call a Session.persist might do the trick. All you will need to do is have a thread dump after a few minutes (3 or 5) of execution and import it into a dump analyser (IBM Support Assistant if you are running on an IBM JVM) and you’ll notice that a great deal of threads will be waiting on a lock (before entering the generate method on AbstractSaveEventListener.saveWithGeneratedId).

But what would be possible alternatives for this?

If you want to have the entities IDs reflecting the value of the database sequence use the following annotation:


@GenericGenerator(strategy="sequence")

Another possibility is removing the allocationSize (which leads to the default value of 50) or configuring it with a greater value. But, in this case you’ll need to update the database sequence so that you don’t end up with a gap on your IDs since SequenceHiLoGenerator employs the following formula for sequence generation:

DBSequence*allocationSize<= IDs < (DBSequence+1)*allocationSize

And upon startup it already increments sequence by one acquiring a new slot of IDs.

So you’ll have to restart your sequence with the following value:


select round(max(id)/allocationSize) from table;
19
Dec
09

WebSphere eXtreme Scale 6 book

As already stated I’ve been invited to review WebSphere eXtreme Scale book from Packt Publishing. The book is an excellent choice for anyone interested in adopting WebSphere eXtreme Scale in a solution.

WebSphere eXtreme Scale

WebSphere eXtreme Scale Book

The book starts on chapter one with basic concepts about a data grid and ends up with a hello world like application.

On chapter two it starts to take a deeper dive into WebSphere eXtreme Scale concepts. The first one explored is the ObjectMap API which is composed by the ObjectMap and the BackingMap objects.

Chapter three is the one that specially took my attention since it presented me a feature I had no clue eXtreme Scale had: a JPA like implementation. This is one of the things that makes eXtreme Scale such a nice tool. By now you will probably be thinking: “but what is the difference of having this and eXtreme Scale acting as an ORM cache?”. In fact there’s a great deal of differences – first one: on an ORM solution you’re caching data that when “hydrated” (as Hibernate calls it – this article explains something about hibernate 2nd level cache) becomes objects, so, you still have the time lapse and the memory losses derived from hydrating objects on each request. Another major advantage is that ORM caches are usually invalidated upon some update scenarios which leads to reload of data.

Chapter four covers how to integrate a data grid with a database store. As the book states you’d need to integrate with a database backend to provide a richer and wider set of tools for report generation, to integrate with legacy application that still interact with database, etc.

Chapter five is dedicated to handling increased load. If you thought: “Do I still need to care about load increse?” the answer is “YES! For Sure!”. All and every software needs to be proper configured for increased load, by no means eXtreme Scale would be an exception and this chapter covers important topics of performing planning  for increased load.

Chapter six is devoted to keeping data available, so now it focus on replication and other important points.

Chapter seven (which is also freely available online) presents a rather different pattern of performing tasks in a distributed application – pushing the operation instead of pulling the data.

Chapter eight is dedicated to present some common patterns when using a data grid.

Chapter nine covers some facilities for Spring integration.

And finally chapter ten covers a complete example of a project that is built open eXtreme Scale.

One thing I’d like to see on the books next edition is the ability of replacing WebSphere’s Application Server DynaCache with an eXtreme Scale cache implementation. But it is no surprise for me that this was missing on book since they (the book and this feature) were released almost at the same time, invalidating any possibility of this being covered on the book.

In summary: this is a book I really recommend for anyone interested in picking a data grid solution for Java. It is also more recommended if you are already inclined to use an IBM solution and stick with eXtreme Scale.

01
Dec
09

Mapping JavaEE and .NET stack components

Recently I started to research how to develop on .NET as I’ve been developing for JavaEE.
First thing that came to my mind as a JavaEE architect was: “Okay, IIS and ASP.NET are some of the presentation tier alternative I have for .NET but what for business tier?” or rephrasing as someone that has
been using JavaEE for a long time: “What would be the .NET EJB?”.
JavaEE-DotNETComparisonFirst thing I missed was the concept of the MDB that in .NET stack that seems to be replaced by an MSMQ message trigger.

Another major .NET difference is that even though it seems to have the concept of the VM process (as Java does) it has the concept of a shared library, or the Global Assembly Cache. If you think in terms of Java then you have to either manually replicate the jar or share them using a shared storage and having it on the classpath.

As we are on the classpath subject, .NET and its CLR seems to avoid (and limit it to J#) the concept of a ClassLoader. Although sometimes problematic, the Java concept of the ClassLoader allows very sofisticate scenarios of application composition and also for hot code generation (by the application) at runtime.

I hope this post has helped anyone in the situation as I were before and I also hope it does not sound as a comparison of which platform is better as you might guess that I sincerely know that each one has its applications, strengths and weaknesses.

16
Nov
09

WebSphere eXtreme Scale 6 book review

Anyone designing a high performance transaction processing system has already needed at least a caching solution for increasing response time on frequently used data. But sometimes these data might become bigger than usual, those are times when you need a sofisticate

WebSphere eXtreme Scale

WebSphere eXtreme Scale Book

solution, something that can automatically fetch data from a slower storage, offload when not necessary, split its contents between various nodes, …

If you require something like this then you’ll notice that you need a DataGrid solution.

By now you’ll be asking yourself why I am on that subject? Recently I’ve been kindly invited to review a book about IBM WebSphere eXtreme Scale from Packt Publishing.

Apart from this, I work on a project where we were already evaluating WebSphere eXtreme Scale as a replacement for WebSphere DynaCache.

If you are in a hurry and want to have a sneak peak on the book contents, take a look at the sample chapter (Chapter 7: “The DataGrid API”) available for free on Packt Publishing website.

01
Oct
09

Anatomy of an inbound jca connector

Continuing with the posts about JCA lets now have a look on the specifics of an Inbound JCA connector. As already mentioned in a previous post the term inbound is related to the flow of the call on your application.
The endpointActivation method plays a key role in an Inbound adapter. This is the method that is triggered by the container on each of the Activation Specs you have configured on your Application Server instance. This is also the point where you start your monitoring thread (FooMonitor in our example). Remember that this monitoring object has to have access to a number of key container classes such as MessageEndpointFactory implementation and also WorkManager.
Apart from container objects you’ll certainly need to have the ActivationSpec object passed on the endpointActivation method since it carries on the configuration provided for this activation spec (taking JMS as an example it’d be host, queue, username, …).
Another point to remember is that you’ll need to have a reference to the monitor threads that were activated since on container shutdown it’ll invoke the endpointDeactivation method and you’ll need to retrieve the related monitor thread and stop its execution.

Inbound Connector classes

Too much text lets now have a look on some diagrams:
FooInboundAdapterClassDiagram
As you may have already guessed, FooMonitor is the thread that will poll for events and schedule their notifications through the WorkManager. You should never use the monitor thread for the notification since it’ll be blocked during notification denying the sending of other notifications. That’s the reason you should schedule an asynchronous notification using WorkManager.

FooNotification implementation

Skipping to the FooNotification class, its implementation will be something like the following code:

public void run() {
	MessageEndpoint endpoint = null;
	try {
		endpoint =  messageEndpointFactory.createEndpoint(null);
		((FooListener) endpoint).onMessage(msg);
	} catch (Exception ex) {
		logger.error("Error on foo notification" ,ex);
	} finally {
		if (endpoint != null)
			endpoint.release();
	}
}

As already mentioned, that’s the point where the MessageEndpointFactory is used. It provides us proxies for FooMDB classes. Remember to ALWAYS invoke release after using this proxy otherwise your container may run out of proxies since it’ll think you are still using them.
Another aspect not really detailed is the msg parameter on the onMessage method: this one is dependent on your ResourceAdapter – You are the one responsible for defining it (unless you have chosen a regular API like JMS).

09
Sep
09

Disabling Seam Deployer

This post is only an update to the previous post. Recently I found an even more elegant solution in order to disable seam.deployer. Instead of removing the package from JBoss AS deployers folder we can provide a jboss-scanning.xml file which as documented on JBoss Wiki is able to remove certain files from scanning process.
So, a better (and also less instrusive) workaround is to provide under war/WEB-INF/classes a jboss-scanning.xml file with the following contents:

<scanning xmlns="urn:jboss:scanning:1.0">
  <path name="servlet-1.0.war/WEB-INF/classes">
    <exclude name="seam.properties"/>
  </path>
</scanning>
06
Sep
09

Seam on JBoss 5.x without Seam Deployer

Recently I started a proof of concept for a new project that will run on JBoss 5.1. The reason for picking JBoss 5.1 instead of the mature 4.2 series was due to its full support for JavaEE 1.5 (4.2 supports only EJB3 spec, no servlet injection, etc) as well as its longer support (4.2 will start an EOL cycle soon).
As soon as I decided to use JBoss 5.x the classloading nightmare started. First of all, Seam uses a kinda strange hack for detecting its components (its scanner class makes use of java.io.File which in turn does not work on newer VFS system released on JBoss 5.x).
Recommendation on Seam forums is to include no Seam file at you EAR/WAR and let Seam deployer do the trick but thiss comes with much obvious limitations:

  1. You’ll need a separate packaging for your application on JBoss (this is probably the worst limitation)
  2. Seam (and its dependencies) upgrades will involve patching Application Server files

But although recommended you can still deploy a regular Seam application without Seam Deployer. I’ll try to provide a step-by-step guide on how to circumvent this limitation:

First step: remove seam.deployer from $JBOSS_HOME/server/default/deployers (an alternative and less intrusive solution that I just found after writting this post is described over here)
Second step: add all Seam dependencies (jboss-seam-ui.jar, jboss-seam.jar, etc) inside EAR (I sincerely suggest under a lib folder).
Third step: place a jboss-app.xml with the following content on you EAR/META-INF folder

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE jboss-app
    PUBLIC "-//JBoss//DTD J2EE Application 4.2//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-app_4_2.dtd">
<jboss-app>
      <loader-repository>
            myapp.ear=MyAppEar
      </loader-repository>
</jboss-app>

Fourth step: place a jboss-classloading.xml also on EAR/META-INF folder with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<classloading xmlns="urn:jboss:classloading:1.0"
              name="myapp.ear"
              domain="MyAppEar">
</classloading>

Fifth step: place jboss-seam-int-jbossas.jar from seam.deployer/lib-int into your EAR/lib folder. (this jar contains org.jboss.seam.integration.jbossas.vfs.VFSScanner)
Sixth step: place another jboss-classloading.xml on WAR/WEB-INF folder with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<classloading xmlns="urn:jboss:classloading:1.0"
              name="mywebapp.war"
              domain="MyWebAppWar">
</classloading>

Seventh step: Place a jboss-web.xml under WAR/WEB-INF with the following contents:

<jboss-web>
	<class-loading java2ClassLoadingCompliance="false">
		<loader-repository>
			mywebapp.war:loader=MyWebApp
			<loader-repository-config>java2ParentDelegation=false
			</loader-repository-config>
		</loader-repository>
	</class-loading>
</jboss-web>

Eighth step: place a seam-deployment.properties anywhere in the classpath (anywhere but before seam jar) with the following contents:

org.jboss.seam.deployment.scanners=org.jboss.seam.integration.jbossas.vfs.VFSScanner

Ninth step: Add all Seam dependencies on MANIFEST.MF file under WAR/META-INF and remember to include jboss-seam-int-jbossas.jar on the classpath.

That’s all you need to avoid having a separate packaging for a Seam enterprise application running on JBoss 5.x (sincerely I guess that you risk having to remove the seam-deployment.properties only). This also makes it easier to replace the JSF implementation on your application.

17
May
09

Accessing a HMC through a SSH tunnel

For sysadmins this might be a rather easy task, but as a HMC end-user I had to search a little bit.
If you never used an IBM server you might be wondering what is an HMC. At first it seems like a notebook in a blade format as you can see on the picture below:

HMC

HMC (source: http://www.fz-juelich.de/jsc/index.php?index=1979)


But apart from its similarity to a fancy notebook, its purpose is to allow administration of IBM LPARs (or DLPARs after Power6 arrival).
There you can boot, shutdown, change CPUs and memory for LPARs, etc.
Apart from allowing the administration in loco, it provides a Java based application that can be installed either through a Java Web Start launcher or using an MSI installer.
I’ll try to explain the steps involved in running it using the JNLP Java Web Start launcher.

Setup SSH tunnel and Download JNLP

Open the SSH connection between you and any host on the same network as your HMC (this can even be the HMC itself) and tunnel the following ports from your machine to HMC’s IP.

  • 30000 up to 30009
  • 9090
  • 9960
  • 8443
  • 443
  • 80

Sincerely, I did not check if, strictly speaking, all the ports are necessary but feel free to test them and leave  a comment. These ports were the result of a few searches over the internet.

After setting up the tunnel, point your preferred browser to http://localhost and download the JNLP file at the following link:

HMC html page

HMC html page

I had to edit the codebase property of the JNLP file, but I guess it wont be necessary as I still had to edit the hosts file and add an alias for the machine name (eg.: hmc.my-server.mylocalnetwork).  You’ll end up having codebase as follows:

codebase="http://127.0.0.1/wsmship/codebase"

Edit hosts file

The next step is to edit your hosts file so it will have an extra alias pointing to 127.0.0.1. Copy the host name from the original value of the codebase property.
Then launch the JNLP file with Java Web Start. If you have the mime type correctly associated at your operating system, double click the file and wait for its launch. Sometimes it may complain at the first connection attempt, retry it and it’ll connect successfully. I guess I might still be missing some ports from the 30000~30009 range, since my first attempt was using ports from 30001~30009 and it always complained at the first attempt.