Category Archives: Java

Deploying with Continuum and Maven

We are now deploying to our staging servers from our Maven repository using wget (the url is like ‘http://maven:8080/nexus/service/local/artifact/maven/redirect? r=snapshots&g=com.armstrongconsulting.controlcenter.server &a=controlcenterwebapp&v=LATEST&e=jar&c=jar-with-dependencies’.). The runnable jars (or wars) in the Maven repository are built, unit-tested and deployed to Maven by Continuum automatically. If any errors are found, the developer who made the offending commit to SVN is informed by Continuum. Works great, highly recommended. Thanks to Gabriel for setting it all up.

Wicket and focus

Our first approach was to create a DefaultFocusBehavior (as described by Julian Sinai) and attach it to the component which should receive the focus. The problem with this is that after a validation error during a submit, you usually want the focus to jump to the first invalid field, so the user can easily correct his erroneous input. The problem with the DefaultFocusBehavior is that the component to which you added it still has it and will try to grab the focus again. We created two methods for handling focus in our BasePage class (from which all of our application pages are inherited) – setFocus and setFocusToFirstInvalidComponent. The first one is called during page initialization and the second on validation failure. They share enough class variables which allow them to ensure that only one component has the DefaultFocusBehavior at a time.

A Wicket form validator for a list of email addresses

I needed to validate a list of email addresses entered into a Wicket text area (a cc: list of email addresses). To do this, I created a simple form validator which breaks up the list from the text area into individual email addresses and then uses the EmailAddressValidator to validate them individually. It illustrates a few Wicket techniques: (a) how to validate a field containing several values which need to be validated individually and (b) how to use a Validator against a string instead of a form component. Anyway, here’s the code in case its of use to anyone.

To use it, add it to the form as follows:

Installing JRebel

We just started using JRebel on a wicket project with hibernate and Spring. JRebel (formerly known as JavaRebel) provides true hot-swap development under Eclipse – i.e. you never have to republish and wait for hibernate and Spring to reload everything – whenever you save a class JRebel notices and simply reloads the class into the JVM. This greatly increases productivity on larger projects and, perhaps more importantly, removes a major annoyance factor relative to other languages which handle this better.

Installation was a bit confusing because JRebel does not watch for changed classes in the directory where Eclipse puts them by default (at least that was the case for our installation of Eclipse on Mac OS X). To workaround this, you need to add a rebel.xml file to the WEB-INF/classes directory of your project as follows:


<?xml version="1.0" encoding="ISO-8859-1"?>
<application
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.zeroturnaround.com"
xsi:schemaLocation="http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">
<classpath fallback="true">
<dir name="/Users/userx/Documents/workspace/projectx/build/classes"/>
</classpath>
</application>

where the “dir name” element is set to the directory where Eclipse writes the compiled .class files for your project.

In eclipse, you need to modify the launch configuration for tomcat and add the following to the arguments:


-noverify
-javaagent:/path/to/jrebel.jar
-Drebel.trace.log=true
-Drebel.wicket_plugin=true

“label for” in wicket panels

Labels for checkboxes weren’t working as I expected in wicket panels (i.e. when I clicked the label, the checkbox didn’t react). Looking at the output html I saw that the id of the checkbox had been changed by wicket, so the “label for” was no longer associated with the checkbox. The solution was to use the label without the for (and nest the checkbox within the label tag).

Instead of:

use:

Annotated constraints

We were wondering how to use Hibernate annotations to automatically create constraints (HTML “maxlength”) and validators (required fields, string length validation). After searching around, I found a wicket behavior for this in wicket-stuff from Ryan Sonnek. It was in wicket-stuff 1.3 and apparently had been removed from 1.4. Anyway, I patched it up a bit to make it work in wicket 1.4 and here it is (I also took the liberty of renaming it to AnnotatedConstraintBehavior in case we wanted to use it for annotations other than hibernate):

To use it, you’ll need to have @Length(min=x,max=y) and/or @NotNull hibernate annotations on your objects. The behavior will find these in component models and react accordingly, adding the maxlength attributes to the markup, string validator and setting required.

Wicket PasswordTextField with Strength

I implemented a simple extension of the wicket PasswordTextField which provides you with an indication of the strength of the entered password (using regular expressions and returning “empty”, “weak”, “medium” or “strong”). Strong means at least 7 characters with mixed alphanumeric and non-alphanumeric characters. Medium means at least 6 characters with mixed alpha and non-alpha characters.

Originally I intended to make it a panel with a visual indicator (the usual spectrum from red through yellow to green), but then I figured that allowing the caller to make the styling decisions is better (if you want to display a spectrum, then add images to your styles and set the style on the component using an AttributeModifier – come to think of it, maybe I’ll do another post on how to do that…).

Anyway, here’s the component:

And here’s how to use it:

Keeping your database schemas in sync with your model

Hibernate’s hbm2ddl.auto setting allows you to create, update, and validate a database schemas based on the mapping configuration. The create & update settings are great in development environments, since they will ensure your database schema will always be in sync with your model. We would not recommend these settings in an production environment because, there we need to have more fine grained control over database updates (hbm2ddl is too “magical” for production). Additionally, there may be updates to the data which cannot be handled by Hibernate’s hbm2ddl.auto implementation (e.g. content-related updates rather than structural).

Some people would say, “such database updates should not be done by the application, but rather by the database administrator”. However, for most applications, you want the code to maintain the database structure – otherwise you have terrible trouble keeping test and staging databases up to date.

To achieve this we “upgrade” our databases with our own implementation, using plain JDBC. A meta table in the schema holds a version number which gets checked during the application’s start up. If the version in the database does not match the code version, the application upgrades the database schema accordingly.

We need to have our own database upgrade execute before Hibernate intercepts. Otherwise Hibernate will complain that tables or columns which should be created by our upgrade procedure are not yet available.

This can be achieved by a bean, which implements the BeanFactoryPostProcessor.

All what’s missing now is the definition of the bean in the applicationContext.xml file.

That’s it. The application context auto-detects BeanFactoryPostProcessor beans in their bean definitions and applys them before any other beans get created. If you are concearned about the order of loading, your bean can implement the “Ordered” interface in addition.

Adding scripting to java applications

Many of our applications require scripting support (allowing users to create scripts to customize workflow within the application). Java provides very straightforward scripting via the javax.script script-engine library. A simple integration is shown below where a Javascript onSave method provided by the user is called, if available, passing a business-logic object “item”:

Note: the javax.script library supports multiple scripting engines including javascript, python, groovy and java. Javascript was the easiest to get working because the Rhino Javascript engine is included in JDK 6.

A sessionless login page for Wicket applications

We’re big fans of Apache Wicket, but as with most frameworks, sometimes the simplest things appear to be hard to do (or at least its hard to find out how to do them). Application session handling is great in Wicket, but I immediately ran into the problem that the problem that the login page of my application would timeout like any other page of the application. If the user logged out (at which point the login page is displayed), left the browser window open and then tried to use the same browser window to login again an hour later, he’d get a “sorry, your session has timed out, please login again”.  This message obviously makes no sense on the login page.

The solution (thanks Doug Donohue for the help on this) is to use a stateless form for the login page (which causes Wicket to only create a temporary session for the page) and when the user has successfully logged in, convert the session to a regular session.

The relevant code fragments are shown below:

Note however that you have to be very careful what components you use in a stateless page – otherwise you’ll suddenly find it to be stateful again (i.e. it will bind its session automatically and you’ll be back in the same situation). Basically anything which requires remembering a specific page instance (e.g. Ajax) will cause your page to become stateful.

There is some logic built into Wicket which should warn you when a page which you expect to be stateless becomes stateful, but it seems that in the latest versions of Wicket, these warnings are disabled. We ended up creating our own StatelessPage super-class which, in onBeforeRender, calls isPageStateless() and if that returns false, it runs through the components on the page and checks isStateless() for each and reports the wicket id for each component which is not stateless. That way, during development we can show a warning like “This page should be stateless, but isn’t because the following components are stateful: component1, component2…”