Category Archives: Uncategorized

Better Spring management of Javascript resources with Bakehouse

Bakehouse is a new project I’ve put together in an attempt to help with the workflow of writing web-apps with Spring.

Spring itself does a bunch of stuff right.  Specifically, with the new @Profile support introduced in 3.1, it’s become very easy to generate a single WAR that can be distributed in all environments (Dev, QA, Production, etc).

This is great server-side.  However, as more and more code is moved to the client-side, different frameworks and practices are emerging that require pre-processing of resources.

For example, on a typical app you might:

  • Be compiling your CSS with LessCSS or SASS
  • Concatenate and Minify your JSS when moving into production
  • Use a javascript abstraction such as Typescript or Coffeescript that require compiling
  • Use local versions of 3rd party libs (eg., JQuery) during development, but the CDN hosted version in production

Typically, these tasks require different compilation options, depending on where you’re deploying to.   This is at odds with Spring’s goal of a single distributable.

Additionally, depending on your toolset, as you’re coding you’ll need to recompile your assets down to javascript, to use them.  This adds friction to the development process.

That’s where Bakehouse comes in.

Bakehouse allows you to define the resources in your jsp, and provide different sets of processors depending on the active profile.

For example:

<%@ taglib prefix="bakehouse" uri="" %>
    <bakehouse:resource src="angular.js" cdn=""/>
    <bakehouse:resources configuration="javascript" type="text/javascript">
        <bakehouse:resource src="file1.js"/>
        <bakehouse:resource src="file2.js"/>
    <bakehouse:resources configuration="typescript" type="text/javascript">
        <bakehouse:resource src="typescript.ts"/>

This defines the resources that our page will use.  Next, wire up a configuration that tells the page how to process them.  The configuration itself can vary between profiles.

public class ExampleBakehouseConfig implements BakehouseConfigProvider {

    @Override @Bean
    public BakehouseConfig build(BakehouseConfigBuilder builder) {
            return builder
                .process("typescript").with(new TypescriptProcessor("TypescriptCode.js"))

Now, in Production, the following is generated:

    <script src='' type='text/javascript'></script>
    <script src='/bakehouse-example/generated/AppCode.js' type='text/javascript'></script>
    <script src='/bakehouse-example/generated/TypescriptCode.js' type='text/javascript'></script>

However, perhaps in development, you’d rather use a local version of AngularJs (that hasn’t been minified), and you’d rather not have your javascript concatenated.

Simple – just define another @Profile:

public class ExampleBakehouseConfig implements BakehouseConfigProvider {

    @Override @Bean
    public BakehouseConfig build(BakehouseConfigBuilder builder) {
        return builder
            .process("typescript").with(new TypescriptProcessor("TypescriptCode.js"))

Now, the default processing is applied to javascript resources, (which means CDN’s are ignored), and only our Typescript is processed.

Bakehouse is intended to be extensible – making it easy to write your own processors. Currently, there’s only support for Javscript concatenation and Typescript processing. However,more is planned, and implementing your own is easy.

Reducing development friction

Bakehouse monitors resources declared, and recompiles them whenever the underlying source changes.  This removes the need to drop out of Eclipse to recompile your LessCSS, Coffescript or Typescript (for example).

The resulting files are cached, to ensure that they’re served speedily.

Getting started

Kicking things off is simple.  In your Spring config, just ensure that is enabled, and declare a BakehouseSupport bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:annotation-config />
    <context:component-scan base-package="com.mangofactory.bakehouse.example" />
    <bean class="com.mangofactory.bakehouse.config.BakehouseSupport" />

There’s a working example project available here.

Wanna see more?  Tell me!

Bakehouse is currently a POC project.  I’m using it internally on a project, but if you’re interested in seeing open source development continue, you’ll need to let me know.  Either star the project on Github, or leave a note on this issue.

A new Parsley Extension: The DynamicServices tag

I just pushed a new Parsley extension project to GitHub – support for the <DynamicService /> tag.

Typically in a project, I like to structure my services layers pretty cleanly – for each service I would declare the following:

  • An interface which defines the services contract
  • A concrete implementation of the interface, which abstracts away the RemoteObject
  • A stub implementation of the interface, for testing when the services layer is unavailable

For example, a simple EchoService might look a little something like this:

public interface IEchoDelegate
     function echoMessage(source:String):AsyncToken;

public class EchoDelegate
   public function service:RemoteObject;

   public function echoMessage(source:String):AsyncToken
      return service.echoMessage(source);

Here, you can see the concrete delegate is really just boiler-plate code.  It’s pretty repetitive, and while I find lots of value in the pattern, the actual implementation can be a bore.

So, I put together a Parsley extension to generate these delegates on the fly.

Here’s an example:

<?xml version="1.0" encoding="utf-8"?>
      <services:DynamicService type="{IEchoService}" endpoint="http://localhost:8080/testdrive/messagebroker/amf" destination="echoService" />

This definition combines the Interface and the remote object defininition in the context. An implementation of the interface is generated on-the-fly at runtime, and is available to be injected into classes as required.


	public class EchoCommand
		public var service:IEchoService;

		public function execute(message:EchoMessage):AsyncToken
			return service.echo(message.source);

		public function result(result:String):void
			trace("Received from the server:" + result);


The source for this is available now on github.  There’s also a demo project available here

A word of warning

Under the covers, this extension makes use of the ASCommons-Bytecode library to build an implementation of the interface.

Unfortunately, this dynamic goodness is not free, and incurs a one-off cost at startup when the ByteCode library parses the bytecode of the swf into memory.  As a result, you’ll notice that Parsley takes a little longer to intitialize than you might be used to.  This is a tradeoff that must be considered before using this approach.

Tagged ,

Returning to Australia

A short personal post in a blog otherwise filled with Flex & dpHibernate geekery.

After several years of working abroad in both USA and London, I’m returning to Australia, touching down in June 2011.

I’ll be looking for new consultancies to partner with, and new projects to work on.  If you’re at all interested, please drop me a line.

For reference, my current CV (That’s résumé for you North American folk) is available here

I look forward to hearing from you!

Spring Security 3.0.0-RC1 and Spring BlazeDS Integration

Just a quick one : After much pain of trying to upgrade to Spring 3.0.0-RC1, it turns out that the security is not compatibale with Spring BlazeDS 1.0.x. It results in the following error:


So, head over to Spring and go vote on this issue:

I hope this gets resolved before 3.0.0-GA


Rule based & asynchronous validation in Flex forms

Sometimes in Flex, you’ll need to perform asynchronous form validation. where rather than simply checking that a string matches certina criteria, you’ll need to take a trip to the server — Eg., checking to see if a username is already used during signup.

In scenario’s like this, the out-of-the-box validation framework just doesn’t cut it. I’ve tried shoe-horning the standard Validator class to block validation, and it’s just not pretty.

However, I remain a fan of declarative form validation. It’s possible to write screeds of validation code in Presentation Model / Mediator classes, but I still prefer a simple bit of markup that describes the validation being applied.

To address this, I’ve put together a very small validation framework that handles asyncronous validation, amongst others. Instead of decalring Validators in your view, instead decalre a ValidationCollection with a bunch of ValidationRules. Here’s an example:

 <mx:Button label="Register" enabled="{ validationRules.isValid }" /> <validation:ValidationRuleCollection id="validationRules"> <validation:UsernameIsUniqueValidationRule username="{ txtUsername.text }" targetComponent="{ txtUsername }" /> <validation:EmailIsUniqueValidationRule email="{ txtEmailAddress.text }" targetComponent="{ txtEmailAddress }" /> <validation:PasswordsMustMatchValidationRule password1="{ txtPassword.text }" password2="{ txtPasswordConfirm.text }" targetComponent="{ txtPasswordConfirm }" /> <mx:StringValidator required="true" source="{ txtUsername }" property="text" requiredFieldError="{ ResourceManager.getInstance().getString( ResourceBundles.ERROR_MESSAGES , 'REQUIRED_FIELD_ERROR' )}" /> </validation:ValidationRuleCollection> 

The ValidationCollection serves to aggregate the results of all it’s enclosing validation rules, and give a single point useful for databinding. In the above example, the Register button is not enabled unless all the validation rules have passed.

Declared inside are a series of discreet validation rules. The interface here is a lot less prescriptive than using the Validator base class, and it’s possible to write rules as simple or as complex as required.

Eg., in the above example there’s asyncronous checks to see if username & email are both available. In another case, there’s a rule which compares the text values of two passwords to make sure they match.

Also note that you can mix and match validation rules and Validator subclasses (such as the StringValidator above). This prevents you from having to re-invent the wheel by utilising all the validators that come out-of-the-box with Flex.

Under the covers, Validator instances are decorated to instances of IValidationRule to get things working.

Source code is available here, (or as a zip file here) along with some sample validation rules… should you find it useful.


Wow, this is the most popular blog on my whole site.  I’ve fixed the broken link, and have ported the code across to GitHub.  Please feel free to fork and contribute!

BlazeDS, Enums, and a comedy of very small errors

For the past two nights while working on my side project, I’ve been banging my head against the wall trying to pass Enums back and forth across BlazeDS to my Flex Client.

I know it’s possible, after all, I’ve seen it on the internet….

However, depsite what ol’ man google said, I was getting errors when sending the enums back from Flex to my server (though they went fine the other way).

In addition to the standard Flex / BlazeDS stack, I’ve been using two very handy open source tools :

  • dpHibernate to assist with serialization of Hibernate Lazy proxies
  • DTO2FX for some really funky AS class generation

Turns out that very small bugs inside each of these were to blame.  I post here in case — through some odd twist of fate —  you, dear reader, have the same stack:


dpHibernate was attempting to deserialize Enum classes as a hibernate proxy.  Adding a test for Enum inside the isSimple method of the HibernateSerializer took care of that:

    private boolean isSimple(Object obj)
        return ((obj == null)
                || (obj instanceof String)
                || (obj instanceof Character)
                || (obj instanceof Boolean)
                || (obj instanceof Number)
                || (obj instanceof Date)
                || (obj instanceof Calendar)
                || (obj instanceof Document))
                || (obj instanceof Enum);


DTO2FX uses an (IMHO) overly complicated template for their generated Enums.  Rather than just use the method discussed here, which allows for a simple enum client side class, they use a much more complex template.  It requires the use of a custom Serializer / Deserializer within Blaze.

Here, I thought of a few approaches:

Change the template used by DTO2FX and recompile my custom version

This requires downloading no less than 5 seperate open source projects from CVS (who the hell uses CVS anymore?) and working out what was going on.  I have previously given up on changing DTO2FX as a simple task, so didn’t even bother this time.

Don’t use DTO2FX to generate the Enums — do it by hand

I’m not using a large number of Enums in my project, and I can live with hand coding them.  However, one of the wonderful features of DTO2FX, is that it uses compile time checking of your Java project to ensure that every dependent type has been generated.  If you miss a type out (even intentionally), you get an error at compile time.  Sadly, there’s no way to turn this behaviour off — which meant I had to consider:

Stop using DTO2FX completely

I seriosuly considered this.  I love DTO2FX because it’s quick to use, maintains my classes in the background, and uses the Generation Gap pattern, meaning that in my generated classes I can still put custom code.  However, this is not the first time that I’ve ground to a halt because of some quirk in the way that DTO2FX generates it’s code.

Also, I find that having to make an architectural decision on my project because a tool won’t generate code in a specific way is unacceptable.  If it wasn’t so good in other ways, I’d have ditched it.

I googled for an appropriate replacement for DTO2FX, but couldn’t find one.  Which left me with….

Make DTO2FX’s Enums work.

Although the fix is simple, the debugging and locating the fault was the hard part.

In the end, all it took was adding this override to EnumPropertyProxy :

    public Object createInstance(String className)
        Class cl = AbstractProxy.getClassFromClassName(className);

        if (cl.isEnum())
            return new EnumHolder(cl);
            throw new IllegalArgumentException("**** samples.EnumProxy registered for a class which is not an enum: " + cl.getName());

And from there, (after I reverted all my other hackery) it worked.



Tagged ,

FB – Internal build error

Just a quick post on a flex builder 3 bug I just found.

Defining a constant on an interface causes Flex Builder to give you the ever helpful message at compile time :

“An internal build error has occurred.  Right click for more information”

Of course, there is no more information, you have to find what you did to break it through old fashioned sleuth work.

Anyway, constants on interfaces :  A stupid mistake, yes… but it’d be to have the compiler issue a stern telling off rather than flex builder throw it’s hands in the air and give up on me completely.

Really, Flex Builder – after all you and I have been through!?

Faithfully yours,


Morgan Stanley – Matrix

I’m now finally allowed to post information about a project I worked on : Morgan Stanley’s  “Matrix

It’s by far the biggest flex application I’ve ever worked on, and probably one of the most significant uses of the Flex platform to date.

The client, Morgan Stanley is one of the biggest investment banks in the world, and their product – Matrix is a trading platform that allows rich, real time collaboration through chat, video, sharing of trade ideas, charts.  

The development team was full of some of the top developers I’ve ever worked with, working on the project was a priveledge and a non-stop learning experience!

Check out the site, and take the tour!

dpHibernate and Spring transactions

I’ve recently been getting my feet wet in Java, and starting integrating with dpHibernate to facilitate lazy loading across to Flex.

Here’s what my stack looks like:

  • Spring 2.5.6
  • Hibernate 3.3 (including annotations, and transaction management)

Trying to get dpHibernate wired in, I was getting lots of errors along the lines of the following:

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here


The problem here is that using transaction management, things get a lot tighter on how and when you can get access to a hibernate session.  dpHibernate tries to get it’s session by essentially calling sessionManager.getCurrentSession();

However, as far as Spring’s transaction manager (which is wired into the SessionManager) is concerned, the thread which is executing has no session, and has no business trying to create one — specifically, outside of a transaction.

After spending several hours trying to work out how to sidestep Springs transaction management, I realized the trick was simply to wire dpHibernate closer to spring.  This is tricky, because dpHibernate is using an extension of the flex’s JavaAdapter, and exists completely outside of the Spring infrastructure.

HibernateSerializer makes a call to a dpHibernate object called SessionManager, which returns the current session outside of a valid Spring transaction.

So, I ditched the SessionManager completely, and replaced it with a good old fashionsed SessionFactory object, as follows:

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;

The @Resource tag there tells Spring to give me a wired up sessionFactory instance.

I also decorated the HibernateSerializer with a @Transactional tag, so that Spring knows the context in which this will operate:

public class HibernateSerializer implements ISerializer

Now, if I add the HibernateSerializer as a bean, Spring knows to give it access to a sessionManager, and to do so in the context of an active transaction.

Add the bean declaration as follows:

<bean id="hibernateSerializerBean" class="net.digitalprimates.persistence.translators.hibernate.HibernateSerializer" />

Nearly there. Finally, I just need to tell dpHibernate to go and fetch this wired up Serializer from Spring, rather than instantiate it’s own. Inside SerializationFactory, I modified the getSerializer() call to read as follows:

    public static ISerializer getSerializer(String type)
        if( HIBERNATESERIALIZER.equals(type) )
            ServletContext ctx = FlexContext.getServletContext();
            WebApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
            ISerializer serializer = (ISerializer) springContext.getBean("hibernateSerializerBean");
            if (serializer == null)
                throw new RuntimeException("bean named hibernateSerializerBean not found");
            return serializer;

        throw new RuntimeException("unsupport serialization type: " +type);

Note that I’ve hard coded the name of the bean here for simplicity sakes. Chances are you’ll want to paramaterize that.

That’s it! Now, calls that pass through dpHibernate happen with a Spring managed transactional session. Great!


Edit: Espen came up with a simpler alternative over on his blog — check it out :

Tagged , , ,

Conditional compilation in Flex using nAnt

Here’s a trick which you may already know about (after all, it’s in the docs) but I only discovered it today when I needed it.

Conditional compilation allows you to vary the classes and functions included in a compilation based on a config value.

Eg., You may have a slightly different codebase used for your debug build than for your release build.

For example, on my current project we have a couple of convenient hacks in use in our test environment to prevent us from needing to log in every time we launch a debug session.

However, somewhat predictably, one of these hacks recently made it through to our testing team, and broke all sorts of stuff.

So, I figured I’d find a way to automatically remove it as part of our build process.

The class got modified to look a little something like this:

public class PrepCommand extends SimpleCommand
      public override function execute(notification:INotification):void

      private function doDebugLogon():void
            trace("This is where the logon should happen");

      private function doDebugLogon():void {}

Note that the doDebugLogon() method is defined twice within the method, varied by the CONFIG attribute.

This attribute defines under which compilation configuration to include the method. You can do the same thing for a full class.

Next, I modified the compiler-config.xml file used for our project to include this snippet:


Then, simply swapping the values of debugging & release would modifiy which of the function calls are included in the compiled source.

Not bad, but still not very automatic.

Because we’re a .NET shop here, our build tool of choice is nAnt. Most of our config files for the flex build are generated from template files, using nAnt variables to give us nice flexible builds. (pardon the pun).

So, I introduced a new target into our build file for performing a release compile:

    <target name="release" description="Performs a release, setting appropriate config values.">
        <property name="debug" value="false" />
        <call target="build" />

…and added a couple of new variables to the properties file:

    <property name="useDebugConfig" value="true" />

    <!-- Derived from useDebugConfig.  Set the value of useDebugConfig rather than setting useReleaseConfig.
        Note that only one of these values must be true, or compilation will fail -->
    <property name="useReleaseConfig" value="${string::to-lower(not(useDebugConfig))}" />

Then, I tweaked the compiler-config described above to look like this:


Now, ensuring the correct code is included is as simple as:

nant // Calls 'build', our default target using the debugging compilation options
nant release // Uses release compilation options

That’s it.

It’s worth reading up on conditional compilation in the docs, as there’s a bunch of great examples in there.

Questions / comments welcome.