All posts by roger

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):

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.application.IComponentOnBeforeRenderListener;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.IPropertyReflectionAwareModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.validator.StringValidator;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;

/**
 * Configure a Wicket Component based on Hibernate annotations (@NotNull and @Length(min=x,max=y)).
 *
 * Inspects the Model of a FormComponent and configures the Component according to the declared Hibernate Annotations used on the model object.
 * NOTE: This means the Component's Model mustbe known when configuring a Component.
 *
 * This object can be used as a Behavior to configure a single Component.
 * NOTE: this object is stateless, and the same instance can be reused to configure multiple Components.
 *
 * public class MyWebPage extends WebPage {
 * 	public MyWebPage() {
 *     TextField name = new TextField("id", new PropertyModel(user, "name");
 *     name.addBehavior(new AnnotatedConstraintBehavior());
 *     add(name);
 *   }
 * }
 *
 * This object can also be used as a component listener that will automatically configure all FormComponents based on Hibernate annotations. This ensures that an entire application respects annotations without adding custom Validators or Behaviors to each FormComponent.
 *
 * public class MyApplication extends WebApplication {
 * 	public void init() {
 * 		addPreComponentOnBeforeRenderListener(new AnnotatedConstraintBehavior());
 * 	}
 * }
 *
 * @see http://jroller.com/page/wireframe/?anchor= hibernateannotationcomponentconfigurator
 * @see http ://jroller.com/page/wireframe/?anchor=hibernate_annotations_and_wicket
 */
@SuppressWarnings("serial")
public class AnnotatedConstraintBehavior extends AbstractBehavior implements IComponentOnBeforeRenderListener {
	@SuppressWarnings("unchecked")
	private static Map configs = new HashMap() {
		{
			put(NotNull.class, new HibernateAnnotationConfig() {
				public void onAnnotatedComponent(Annotation annotation, FormComponent component) {
					component.setRequired(true);
				}
			});
			put(Length.class, new HibernateAnnotationConfig() {
				public void onAnnotatedComponent(Annotation annotation, FormComponent component) {
					int max = ((Length) annotation).max();
					component.add(new AttributeModifier("maxlength", true, new Model(Integer.toString(max))));
					component.add(StringValidator.maximumLength(max));
				}
			});
		}
	};

	@Override
	public final void bind(Component component) {
		super.bind(component);

		configure(component);
	}

	public final void onBeforeRender(Component component) {
		if (!component.hasBeenRendered()) {
			configure(component);
		}
	}

	void configure(Component component) {
		if (!isApplicableFor(component)) {
			return;
		}
		FormComponent formComponent = (FormComponent) component;
		IPropertyReflectionAwareModel propertyModel = (IPropertyReflectionAwareModel) component.getDefaultModel();
		for (Annotation annotation : getAnnotations(propertyModel)) {
			Class annotationType = annotation.annotationType();
			HibernateAnnotationConfig config = (HibernateAnnotationConfig) configs.get(annotationType);
			if (null != config) {
				config.onAnnotatedComponent(annotation, formComponent);
			}
		}
	}

	private Collection getAnnotations(IPropertyReflectionAwareModel propertyModel) {
		Field field = propertyModel.getPropertyField();
		if (field == null) {
			//Log.warn("Unable to find annotations for model: " + propertyModel);
			return Collections.emptyList();
		}
		return Arrays.asList(field.getAnnotations());
	}

	private boolean isApplicableFor(Component component) {
		if (!(component instanceof FormComponent)) {
			return false;
		}
		IModel model = component.getDefaultModel();
		if (null == model || !IPropertyReflectionAwareModel.class.isAssignableFrom(model.getClass())) {
			//Log.warn("No valid model is available for configuring Component: " + component);
			return false;
		}

		return true;
	}

	/**
	 * simple interface to abstract performing work for a specific annotation.
	 */
	private static interface HibernateAnnotationConfig {
		void onAnnotatedComponent(Annotation annotation, FormComponent component);
	}
}

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:

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

public abstract class PasswordTextFieldWithStrength extends PasswordTextField {
 private static final long serialVersionUID = 1L;

 public abstract void onUpdate(String passwordStrength, AjaxRequestTarget target);

 public PasswordTextFieldWithStrength(String id) {
  super(id);

  add(new OnChangeAjaxBehavior() {
   private static final long serialVersionUID = 1L;

   @Override
   protected void onUpdate(AjaxRequestTarget target) {
    String strength = getPasswordStrength(PasswordTextFieldWithStrength.this.getDefaultModelObjectAsString());
    PasswordTextFieldWithStrength.this.onUpdate(strength, target);
   }
  });
 }

 public String getStrength() {
  return getPasswordStrength(getDefaultModelObjectAsString());
 }

 private String getPasswordStrength(String password) {
  if (password.isEmpty())
   return "empty";

  String alphaPresent = ".*\w.*"; // at least one alpha character
  String nonAlphanumericPresent = ".*[^a-zA-Z0-9].*"; // at least one non-alphanumeric character
  String nonAlphaPresent = ".*[^a-zA-Z].*"; // at least one non-alpha character

  if (password.matches(alphaPresent) && password.matches(nonAlphanumericPresent) && password.length() >= 7)
   return "strong";

  if (password.matches(alphaPresent) && password.matches(nonAlphaPresent) && password.length() >= 6)
   return "medium";

  return "weak";
 }
}

And here’s how to use it:

// put a label on the form which will display the strength of the entered password
final Label passwordStrengthLabel = new Label("passwordStrength");
passwordStrengthLabel.setOutputMarkupId(true);
form.add(passwordStrengthLabel);

PasswordTextFieldWithStrength passwordField = new PasswordTextFieldWithStrength("password") {
  private static final long serialVersionUID = 1L;

And here's how it looks in an application
And here's how it looks in an application
@Override public void onUpdate(String strength, AjaxRequestTarget target) { // strength will be one of "empty", "weak", "medium", "strong" // you can put it into a label, use it as a key to load a localized string, use it to construct a style etc passwordStrength = getLocalizer().getString("passwordStrength_" + strength, this); target.addComponent(passwordStrengthLabel); } }; form.add(passwordField);

Corporate backup 2.0

Anyone who has a Mac is familiar with Time Machine, the almost magical, continuous backup capability of OSX. What many people may not know is that Time Machine is based on concepts which have been freely available for quite some time and which can easily be applied to corporate-wide backups. Because corporate backup is considered expensive to implement, many companies have outdated legacy backup systems based on tapes, tape-robots and offsite transport and storage of tapes. These systems are hopelessly outdated and can no longer keep up with the every increasing storage capacity of the disks they should be backing up and the decreasing backup time window in which backups should be completed.

We have approximately 3TB of data (consisting of about 40 databases, 200 virtual machines and hundreds of thousands of files) on our servers and workstations which need to be backed up. About a year ago we installed a comapny-wide backup to disk with offsite replication and versioning which has been providing us with continuous backup ever since. It continuously replicates a 4TB local RAID-6 disk-array offsite to a versioning 5TB RAID-6 disk array over a dedicated 4Mbps line, 24 hours a day, using rsync for the replication and snapshots based on Linux filesystem hard-links for versioning. Its implemented entirely on standard Linux components (zero license costs) and has been running without a glitch for over a year. Thanks to this system, we not only have an offsite backup of all business-critical data, but we can step back to any version of a database or virtual machine from yesterday, two days ago, four days ago, a week old, a month old etc. I can’t imagine why any company would still want to install a propietary backup system when such perfect technology is freely available.

Turnkey appliances

This blog is running on a Turnkey WordPress appliance (www.turnkeylinux.org). Virtual appliances are of course fantastic if they work – a fully configured, just-works server which you can download and provision in seconds (this blog took about 5 minutes to download, install on a VMWare Server virtual machine and get running). Until now, most appliances we tried had enough gotchas to make us return to manual installation on a generic distribution, but the Turnkey appliances seem to be perfect. Based on Ubuntu or Debian and with just enough stuff pre-installed to make them useful, while still being compact enough to compete with a manual installation. Thanks Turnkey!

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”:

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Scripting extends Base {
 private ScriptEngineManager mgr;
 private ScriptEngine engine;
 private Invocable invocable;

 private boolean initialize (String script) {
  mgr = new ScriptEngineManager();
  engine = mgr.getEngineByName("js");
  try {
   engine.eval(script);
  } catch (ScriptException e) {
   warn("The script could not be loaded: " + e.getMessage());
   return false;
  }
  invocable = (Invocable)engine;
  return true;
 }

 public void onSave(Item item) {
  try {
   invocable.invokeFunction("onSave", item);
  } catch (ScriptException e) {
   warn("The onSave method of the script caused an error: " + e.getMessage());
  } catch (NoSuchMethodException e) {
   // no onSave method provided by the user - that's OK, just ignore it
  }
 }
}

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:

final StatelessForm form = new StatelessForm("loginForm", new CompoundPropertyModel(this)) {
 private static final long serialVersionUID = 1L;

 @Override
 protected void onSubmit() {
  try {
   validateUser(userid_or_email, password);
   if (getSession().isTemporary()) getSession().bind();
   // this makes the temporary session used by the stateless login page permanent
   ...
  }
  catch (Exception e) {
   error(e.getMessage());
  }
 }
};

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…”

public class MyStatelessPage extends BasePage {

	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();

		if (Settings.isOperatingModeDevelopment())
			checkIfPageStateless(this);
	}

	private void checkIfPageStateless(Page p) {
		if (!p.isPageStateless()) {
			// find out why
			final List statefulComponents = new ArrayList();
			p.visitChildren(Component.class, new IVisitor() {
				public Object component(Component component) {
					if (!component.isStateless())
						statefulComponents.add(component);
					return CONTINUE_TRAVERSAL;
				}
			});

			String message = "Whoops! this page is no longer stateless";
			if (statefulComponents.size() > 0) {
				message += " - the reason is that it contains the following stateful components: ";
				for (Component c : statefulComponents) {
					message += Settings.getNewLine() + c.getMarkupId();
				}
			}
			p.warn(message);
		}
	}
}