Article about Wicket 1.5 at JAXenter (German)

An article I did on Wicket 1.5 just gut published on the German JAXenter.

Tomcat 7 with full JTA

Everytime I clean my home directory I purge something important.

Just like a week week ago when I  realized my Tomcat 7 installation was gone and with it all the things I had to do to get JOTM running in there.

Once again I spent a while to get everything back together.
But THIS time I am writing it down.

Tomcat Setup

So I want to have Tomcat 7 with full JTA (should also work on older Tomcat versions).
I will be using JOTM as it provides everything I need.

After downloading the JOTM-distribution copy the following jars to <tomcat-home>/lib.

  • commons-logging-api.jar
  • jotm-core.jar
  • log4j.jar
  • ow2-connector-1.5-spec.jar
  • ow2-jta-1.1-spec.jar
I will also add the tomcat connection pool to show a full example later on.
Download the distribution and add the following jars to <tomcat-home>/lib.
  • tomcat-jdbc.jar
  • tomcat-juli.jar

JNDI

Now we need to tell Tomcat how to create the required JNDI-resources.

Note:
Everything created using the Resource-tag will end up in java:comp/env/. Tomcat doesn’t provide functionality to put it somewhere else (or I was simply too blind to find it).

To make resources available we need to edit <tomcat-home>/conf/context.xml.
The first thing we need to add is a connection pool to showcase the useage of JTA later on.

<ResourceLink global="jdbc/myDB" name="jdbc/myDB" type="javax.sql.DataSource"/>
<Resource
	driverClassName="org.h2.Driver"
	factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
	name="jdbc/myDB"
	password=""
	type="javax.sql.DataSource"
	url="jdbc:h2:tcp://localhost/~/test"
	username="sa"/>

Now we need to add the actual JTA-related resources, starting with the the TransactionSynchronizationRegistry.
Remembering what I wrote above we have to be aware that the TransactionSynchronizationRegistryFactory will end up at java:comp/env/TransactionSynchronizationRegistry and not at java:comp/TransactionSynchronizationRegistry as the JEE-spec requires.
More on that later.

<Resource
	name="TransactionSynchronizationRegistry"
	auth="Container"
	type="javax.transaction.TransactionSynchronizationRegistry"
	factory="org.objectweb.jotm.TransactionSynchronizationRegistryFactory"/>

The final step is to add the actual transaction manager. In older versions of Tomcat one had to register the JTA-factory as a resource.
Today we got a specialized tag for that.

<Transaction
	factory="org.objectweb.jotm.UserTransactionFactory"
	jotm.timeout="60"/>

The main difference between the Transaction-tag and the Resource-Tag is that the transaction manager will end up at java:comp/UserTransaction, which is the name required by JEE.
That’s it for installing the JOTM as JTA-provider in Tomcat.

To make things available in the web application we need to add a couple of lines to web.xml in our webapplication.

<resource-env-ref>
	<description>DB Connection </description>
	<resource-env-ref-name>jdbc/myDB</resource-env-ref-name>
	<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

<resource-env-ref>
	<description>JTA transaction manager</description>
	<resource-env-ref-name>jta/UserTransaction</resource-env-ref-name>
	<resource-env-ref-type>javax.transaction.UserTransaction</resource-env-ref-type>
</resource-env-ref>

<resource-env-ref>
	<description>JTA Transaction Synchronization Registry</description>
	<resource-env-ref-name>TransactionSynchronizationRegistry</resource-env-ref-name>
	<resource-env-ref-type>javax.transaction.TransactionSynchronizationRegistry</resource-env-ref-type>
</resource-env-ref>

Putting it all together

A little example on how to use JTA in your webapplication via spring:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<property name="jpaVendorAdapter">
		<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
			<property name="showSql" value="false"/>
		</bean>
	</property>
	<propertyname="jpaProperties">
		<props>
			<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
		</props>
	</property>
</bean>

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDB" resource-ref="true"/>

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
	<property name="transactionSynchronizationRegistryName" value="java:comp/env/TransactionSynchronizationRegistry"/>
	<property name="transactionManagerName" value="java:comp/UserTransaction"/>
</bean> 

The only thing I don’t really like about this configuration is this line:

<property name="transactionSynchronizationRegistryName" value="java:comp/env/TransactionSynchronizationRegistry"/>

This is no problem, as long as your only deployment target is Tomcat.

If Tomcat  is only used for local deployments for development and the production system is some sort of JEE-server you will have to change the JNDI-location to the JEE-default.

This is easily achieved using maven-profiles.

OpenMBeans, rocket science from the 70s

(Sorry for the messed up layout, Scribefire destroied the post and I had to fix it manually)

Nope, no Scala in here. This time it is good old java.
I was working on small project of mine to get some size information about wicket pages (for the
interested: it’s here).
One would think things like AspectJ or figuring out the best strategy for estimating object sizes would be the hard things on such a project.
I can still hear the distant laughter of Murphy.

Up to now I never had to/wanted to display table data in JMX so this was the first time tackled OpenMBeans.
To get a decent tutorial for these is a frickin nightmare. People (Developers are people, too, just to make sure …) seem to always insist on demonstrating things using a higly intricated usecase to show off their coding skills.
If it didn’t come across what I wanted to say:

IF YOU WANT TO SHOW SOME TECHNOLOGY DON’T REQUIRE ME TO UNDERSTAND YOUR F…ING USECASE.

A SIMPLE OpenMBeanExample.

OpenMBeans feel weird as the way you build them is different from anything you normally do in Java (at least as of today).
Looking at the amount of imports required for a very small OpenMBean might give you an idea on what lies ahead. That’s why I am to go through this step by step.

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenMBeanAttributeInfoSupport;
import javax.management.openmbean.OpenMBeanConstructorInfoSupport;
import javax.management.openmbean.OpenMBeanInfoSupport;
import javax.management.openmbean.OpenMBeanOperationInfoSupport;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;

To get started we need to implement DynamicMBean

public class PageSizeResultOpenMBean implements DynamicMBean {

The next step is to initialize all the parameters you are going to need for this simple example:

itemNames contains the names of properties representing a row in your tabular data.

private static String[] itemNames = { "page", "before", "after" };

itemDescriptions will contain the table headers for display in a JMX tool.

private static String[] itemDescriptions = { "Page class", "Before detach", "After detach" };

itemTypes defines the type of each row.

private static OpenType[] itemTypes = { SimpleType.STRING, SimpleType.LONG, SimpleType.LONG };

indexNames defines the itemName to be used to guarentee uniqueness of a row.

private static String[] indexNames = { "page" };

We are going to define the actual tabular data in the following static block:

private static TabularType pageTabularType = null;
private static CompositeType pageType = null;
 static {
    try {
       pageType = new CompositeType("page", "Page size info", itemNames,
          itemDescriptions, itemTypes);
       pageTabularType = new TabularType("pages", "List of Page Size
          results", pageType, indexNames);
    } catch (OpenDataException e) {
       throw new RuntimeException(e);
    }
 }

In this case pageType uses the definitions from above to describe a row in the table and pageTabularType defines the table.
In the constructor we are going to create a container for the content of the table, called pageData and the OpenMBeanInfoSupport object to hold the information required for the MBean server.

 private TabularDataSupport pageData;
 private OpenMBeanInfoSupport PSOMBInfo;
 public PageSizeResultOpenMBean() throws OpenDataException {
    OpenMBeanAttributeInfoSupport[] attributes =
          new OpenMBeanAttributeInfoSupport[] { 
             new OpenMBeanAttributeInfoSupport( "PageInfos", 
                "Page Infos sorted by class name", pageTabularType, 
                true, false, false) };
    PSOMBInfo = new OpenMBeanInfoSupport(this.getClass().getName(),
          "Page Size OMB", attributes, 
          new OpenMBeanConstructorInfoSupport[0], 
          new OpenMBeanOperationInfoSupport[0], 
          new MBeanNotificationInfo[0]);
    pageData = new TabularDataSupport(pageTabularType);
 }

In this case we are only defining one attribute, holding the tabular data, and no operations or constructors. We don’t need constructors as we are going to register an instance of the OpenMBean manually.Just a few methods left to implement.This method is going to be called from getAttribute and provides a cloned table to the client for display purposes:

public TabularData getPageInfos() {
   return (TabularData) pageData.clone();
}

getAttribute is called with an attribute name. In the constructor we defined an attribute named ‘PageInfos’. We simply check if that’s the attribute the client was asking for and return it.
public Object getAttribute(String attribute_name) throws 
      AttributeNotFoundException, MBeanException, ReflectionException {

    if (attribute_name == null) {
    throw new RuntimeOperationsException(
       new IllegalArgumentException("Attribute name cannot be null"), 
          "Cannot call getAttributeInfo with null attribute name");
    }
    if (attribute_name.equals("PageInfos")) {
       return getPageInfos();
    }
    throw new AttributeNotFoundException("Cannot find " + 
       attribute_name + " attribute ");
 }

We are not allowing to set the attribute. Let it crash’n'burn.
public void setAttribute(Attribute attribute) throws 
   AttributeNotFoundException, 
   InvalidAttributeValueException, 
   MBeanException, 
   ReflectionException {
    throw new AttributeNotFoundException("No attribute can be set in 
       this MBean");
 }

A shortcut method used by clients to get several attributes at once. In our case we are only
returning one attribute and this might never get called, but it doesn’t hurt to do a clean implementation ;)


public AttributeList getAttributes(String[] attributeNames) {
    if (attributeNames == null) {
       throw new RuntimeOperationsException(
          new IllegalArgumentException("attributeNames[] cannot be null"), 
          "Cannot call getAttributes with null attribute names");
    }
    AttributeList resultList = new AttributeList();
    if (attributeNames.length == 0)
       return resultList;
    for (int i = 0; i &amp;lt; attributeNames.length; i++) {
       try {
          Object value = getAttribute(attributeNames[i]);
          resultList.add(new Attribute(attributeNames[i], value));
       } catch (Exception e) {
          e.printStackTrace();
       }
    }
    return (resultList);
 }
 public AttributeList setAttributes(AttributeList attributes) {
    return new AttributeList();
 }

We are not providing any operation so this methos is going to throw an exception if somebody tries to invoke one.

public Object invoke(String operationName, Object[] params, String[] signature)
   throws MBeanException, ReflectionException {
      throw new RuntimeOperationsException(
         new IllegalArgumentException("No operations defined for this 
            OpenMBean"), 
         "No operations defined for this OpenMBean");
}

Used by JMX-clients to get to now what we got here.

public MBeanInfo getMBeanInfo() {
    return PSOMBInfo;
}

A little internal method my aspect uses to actually ad some data to the table. This is just an example on how to modify the data stored by the MBean.

   public void addPageSizeResult(PageSizeResult pageSizeResult) {
      Object[] itemValues = { 
         pageSizeResult.pageClass.getName(), 
         pageSizeResult.sizeBeforeDetach,
         pageSizeResult.sizeAfterDetach
      };
      try {
         pageData.put(new CompositeDataSupport(pageType, itemNames, 
            itemValues));
      } catch (OpenDataException e) {
         e.printStackTrace();
      }
   }

That’s it.

Source code available on github.

IntelliJ IDEA, Scala and Continuous Builds (with some Mac OS X details)

My last post focused on how and why I picked IntelliJ Idea to be my Scala-IDE.
This short post illustrates on how I am using it.
The only things required are a working installation of Maven (2.x or 3.x for added flavor) and IntelliJ 10. I expect people reading this blog to be able to install both so I won’t spend time on this.

Note for Mac OS X and Maven:

For some reasons Idea wouldn’t pick up my Maven installation (even when using the overrides). Looks like this is a known problem. The fix is a little invasive but pretty simple:

  • Do ‘sudo su’ to become root
  • edit/create the file ‘/etc/launchd.conf’
  • insert ‘setenv M2_HOME <path-to-maven-install>’
  • restart

After starting the IDE we need to add the Scala Plugin. Go to Preferences -> Plugins and seelect the Scala Plugin, not the Scala Power Pack.
Scala plugin selected, not Scala Tools
After installing we can now continue to create a new Scala project. As we want to use Maven we will use the Maven archetype.
Create a new project with ‘Create project from scratch’, then select ‘Maven Module’. In the following screen select the org.scala-tools.archetypes:scala-simple-archetype and continue. The resulting project is a Maven-Java project and we need two things to turn it into the Scala project we wanted.
First thing to do is to change the Scala version in the pom.xml.

&lt;br /&gt;<br />  &lt;properties&gt;<br />    &lt;scala.version&gt;2.6.1&lt;/scala.version&gt;&lt;br /&gt;<br />  &lt;/properties&gt;<br />

Simply replace 2.6.1 with 2.8.1.
Now we need to turn the project into a Scala project. Right-click on the project and select ‘Add Framework Support…’
And adjust the following screen to look like this:
Select Scala and fill in the text fields

Add Scala Framework support

We are almost there.

The last remaining step in Idea is to turn off compilation from the IDE.
Create a run configuration and open it. Uncheck ‘Make’ in ‘Before Launch’.

Uncheck Make

Adjust build settings.


The only thing remaining is to start the continuous compile.
Open a terminal, cd to the directory with your new project (the one containing the pom.xml) and execute ‘mvn scala:cc’.
Maven will now watch the project for changes and compile everything that changes.

Now back to the 99.

Scala + IDE (looking for the holy grail)

Real Programmers (from XKCD)

This post is going to touch one of the most religious topics in coding: the IDE.

It doesn’t matter if it’s Eclipse vs Netbeans or Idea vs all of them, a developer loves and defends his IDE (most of them).

For a long time I have been a true follower of the Eclipse way of things. I loved its extensibility and the amount of available plugins. I really liked doing RCP projects and to work with Eclipse.

But since I started working with Scala I also wanted to take a look at the different IDEs out there.

I gave them all a little rundown. These are the results.

What I wanted to do

I already did some stuff with Scala and SBT and decided to start a small pet project.

Nothing too fancy. Some jMonkeyEngine flavor, playing with actors and reimplementing some algorithms.

After some playing around with jEdit, Git and SBT I started playing with the big three Java-IDEs.

Chapter 1: Eclipse

Naturally I started out using Eclipse.

Sure, I already knew the m2eclipse plugin was crap.

Crap like in

  • I can’t believe I got caught in the endless cycle of recompile again.
  • Dammit, it compiles on the cmdl but gives error warnings in the IDE?
  • Why, what, … ahhhhh it crashed again

I could continue for hours ranting about this abomination but it’s not the topic of this post. In the end I ended up uninstalling it and using the maven eclipse plugin like everybody else.

The next thing I tried was Eclipses Git support. The plugin looks very solid and didn’t give me any problems.

Finally I got to Eclipses Scala support. Eclipse features set of plugins (http://www.scala-ide.org/) to integrate Scala.

Sadly the state of these plugins is rather discouraging. Right now Eclipse (3.6 Helios in my case) will frequently hang while working on Scala files. Autocomplete looks more like guesswork and often misses some entries. Several times my whole Eclipse crashed while either refreshing a file I just had edited or trying to autocomplete.

Ah, and not to forget about the popup warnings.

A message to developers: If there is a problem that doesn’t crash your app or causes your project to spontaneously go up in flames don’t show a popup warning and make me click on a button. This makes the whole thing completely unusable for an impatient person like me.

Sadly, there is no other option for Eclipse. Right now I’d consider this thing an absolute no go.

The good news is that the Martin Odersky (creator of Scala) just joined the eclipse scala-ide which will hopefully lead to a way better IDE.

Chapter 2: Netbeans

Some history about my relationship to Netbeans.

I started out doing java in vi, then I switched to JBuilder. For a brief time I used Netbeans. I hated it.

It was horrendous experience. It was slow, a memory hog and slow. Did I mention it was slow.

So, after battling a full week against my mixed feelings towards Netbeans I downloaded and installed it (for this I tried both, 6.9 and 7.0 Beta 2).

I loved it. Netbeans allowed me to use the same shortcuts as Eclipse (relearning shortcuts is something I really wanted to avoid). The interface is clean and feels snappy. It comes with maven integration out of the box. And the maven support actually works.

So, things looked good on that front.

Next thing I tried was git support. From my limited testing I would say things look pretty solid. No crashes, no problems. But again: I just did very basic things there.

Note: Right now Oracle is developing an official plugin for Git.

And finally I tested the scala support.

Sadly Netbeans Scala support is as bas as Eclipses.

It crashes, it hangs, it doesn’t do auto complete most of the time and things sometimes get outright weird.

And again a message to developers: If there is a problem that doesn’t crash your app or causes your project to spontaneously go up in flames don’t show a popup warning and make me click on a button. This makes the whole thing completely unusable for an impatient person like me.

Chapter 3: IntelliJ IDEA

I haven’t payed for a Java IDE since JBuilder and I want to keep it that way. Luckily IntelliJ decided to change the way they do things and since IDEA 9 there is a free version. I got IDEA 10, the most current version as of this writing.

IDEA comes with maven support out of the box, just like Netbeans. Things simply work and I don’t have to perform black magic when importing a project, a big plus compared to Eclipse.

Git also worked without any problems.

Now for the scary part: Scala support.

It works.

Yes, autocompletion needs some work as sometimes not all options show up but it doesn’t crash and doesn’t force me to click on a damn pop-ups everytime something goes wrong.

It even comes with SBT support and decent syntax highlighting. There is still some work needed but it does a lot of the things I wanted and all I needed.

Wrapping up

Eclipse:

Git support is the only thing out of my list of requirements that did its job.

Maven support is utterly broken and the Scala IDE causes way more pain than is justifiable.

Netbeans:

Great Maven integration, Git worked without any problems. Scala support is broken.

I still really like the IDE and I am hoping to get back to it at some point.

IntelliJ Idea:

The clear winner.

Flawless Maven support. Working Git integration. A Scala plugin that solves more problems than it causes.

That’s it for now.

I am going to revisit the whole thing in a few months.

I love Open Source

So, while being on parental leave I didn’t really have time for coding.
I decided to pick up a book on scala to read between changing diapers and cooking for my wife.
Naturally I didn’t really get the time to look into the scala book until the very end of my leave.
When I started to read the book I realized the need o have some pet project.
Having worked with the jmonkey 3d engine before I decided to give it a shot and set up a small project in maven.
Going to their homepage I was completely blown away by the progress they had made since the last time I worked with the engine (Note: At the time I switched companies they had lost their lead dev).
The engine looks very polished and got a good set of tools to work with.
After poking around in the demos for a while I tried getting a scala project going. The only problem was the lack of maven support.
So after posting on their forum to get some infos on the state of maven support it became clear that the core devs had no intentions to provide it.
But people started talking about implementing it on their own. Somebody had already done some work and we decided to do a project to get things going.
People provided their code, the jme-devs got us some git-space and I got the nexus-repo.
Today I submitted the final fixes and we now got full maven support including archetypes.
I love open source and the mentality of cooperation behind it.
Just saying.

P.S.: Still didn’t have time to start the scala book but the stage is set.

Back on the Blog

To make it short:
A year of big changes lies behind me.
A new year of even bigger changes just began and it started with the birth of my son.
Let’s see how this year works out for this blog :)

Scala, SBT, Maven and a little Idea

After playing around with a lot of IDEs I settled with IntelliJ Idea for Scala development.

This was during the time of Scala 2.8 development where every week brought a new version.

I just wanted to play around with Scala and didn’t mind to stick with 2.7.

Eclipse was way to fragile at that time, netbeans just didn’t work at all and Idea at least had some working code completion and syntax highlighting.

The cool thing about Idea is its capability to let an outside tool do the building without breaking completely (curse you, Eclipse workspace). So the next thing was to look for a cool build system. I have to use Maven a lot in other projects so I was looking for something that would allow me to reuse the Maven repository infrastructure.

SBT was exactly what I have been looking for.

SBT is very convenient replacement for Maven as it supports its Repositories and uses Scala as its scripting language.

  • Download SBT
  • Run it in an empty directory
  • Answer the questions
  • Get to see the glorious SBT-shell

This is the SBT-shell which allows interacting with SBT. From here you just type “run” or “test” or “update” or some other commands to interact with SBT.

Now let’s take a look at the directory layout:

  • lib
  • project
    • boot
    • build.properties
  • src
  • target

Src and target save the same purpose as in a Maven build, the layout beneath is the same.

The next step is to create a Project class in project/boot:

import sbt._ 
class MyProject(info: ProjectInfo) extends DefaultProject(info) {
      val derby = "org.apache.derby" % "derby" % "10.4.1.3" 
}  

The above sourcecode defines a dependency to apache derby. So this project file is used to configure dependencies and a lot of other things.
In my case I wanted to be able to also build the project from Maven to allow non-Scala-developers to use my stuff.
The docs told me about SBTs pom-support so went for it and build my pom. I put it into the root directory and Maven was happy.
SBT wasn’t. It complained about not being able to locate artifacts.
Turnes out that setting a property in the project file does the trick:

import sbt._  
class MyProject(info: ProjectInfo) extends DefaultProject(info) {
      val mavenLocal = "Local Maven Repository" at "file://"+Path.userHome+"/.m2/repository"  
}  

Now that SBT is actually using the local Maven repository everything is working fine.
Now start SBT in your project-dir, start Idea and import the pom.
Happy Coding :D

Java Forum Stuttgart 2010

Long time not writing.

I was busy preparing a talk about Complex Event Processing for the Java Forum Stuttgart which basically ate away a lot more of my freetime than I had expected.

From next week on I will start putting a couple of technical articles on IDEs, jBPM and CEP online.

But right now I am happy about my working demo app, the slides I have prepared and that I will be able to give a talk at JFS.

CU there.

Sonatype Nexus on JBoss

After our main Nexus broke through an updat from 1.3.6 to 1.5.0 I had to create a temporary Nexus.
I already had a working JBoss (5.1.0.GA) install on my machine and wanted to deploy the nexus webapp there.
After installing and trying to acces it I got:

javax.servlet.ServletException: non-HTTP request for response …

After digging around for a while I discovered a servlet-api.jar inside the nexus.war.
Removed it and now everything is working finde.
Thought this one was worth sharing.

Next Page »


My tweets


Follow

Get every new post delivered to your Inbox.