Friday, February 8, 2013

Poor man's BDD with JUnit Rules

There's plenty of buzz in the agile circles around Behavior Driven Development (BDD) as a compliment (or replacement) for standard TDD development. Plenty of really powerful frameworks like Cucumber, JBehave and easyB have popped up to give full stack implementations for developing Java apps with BDD. These are great frameworks and provide a lot of features, but if you work in a place where change is a dirty word, trying to get a team to use one of these great frameworks might be a little more than you can handle.

Another option to slowly move toward a BDD model, would be to use what I call "Poor Man's BDD". Have the 3 Amigos (DEV, SME/BA, QA) sit together and define your stories or acceptance criteria by highlighting behaviors. For example, in a BDD style that might look like: From there you can use this simple java annotation to add business friendly documentation/reporting your JUnit tests.
The last part you need is a way to run a report and show your business and QA counterparts that you have coded the tests according to the specification. For that, you can use a JUnit rule and your favorite logging solution (I picked Log4J, because...why not).
The only change your team mates need to make is to annotate their tests with our annotation like this: That's it! Your developers don't have to stray from their JUnit big green bar in eclipse (it was hard enough to get the team to use TDD, you can't change it now!), you have achieved some readable documentation of what the test is actually testing AND you can export the results of your tests into a file that you can give to your business stakeholders with a report that shows I have addressed the business cases with tests and they all pass. Like so:

Is it comprehensive? No. Does it actually prove that you are asserting the right things within the guts of your test? No. What it does is add some simple sugar to team's existing JUnit skill-set to build requirements based on examples of business behaviors. The next step is to start looking into easyB or Cucumber and start building executable business specifications.

Here's the code => clicky. Hope this simple solution is helpful.

Thursday, October 20, 2011

Spring 3.1 @Profile and @PropertySource

Today, I'd like to go over a cool new feature that the good folks at Spring are releasing as part of Spring 3.1...Profiles.

I won't go into too much detail about how profiles work because SpringSource's Chris Beams has already done a good job of that already -> Read about it here

Instead, I'd like to take on a very simple use case where this feature will be VERY helpful. Most developers have run into a scenario where they needed to bootstrap their application with beans that are slightly different based on the environment. For example, a datasource might be different for dev, test and prod. With the help of Spring @Profile and the @Configuration classes, this is a complete snap to do now. Let's dive into the example.

My project has two beans: CommonBean which is the same for all environments, and EnvBean which has environment specific configuration (in the real world, EnvBean could be a datasource, jms connectivity beans, etc..). The last wrinkle to this app is that my EnvBean requires environment specific properties as well. A very simple use-case, but complete enough to demo the new capabilities.

Here's the source for my application beans:

You see they are simple Java POJOs. Now, I create a per environment properties file for dev, test and prod with the properties, I am calling them -app.properties.

Now here's where @Profile comes into the picture. To distinguish the various environments, I create a common @Configuration class called AppBootstrap and a per environment @Configuration class to configure the EnvBean.

That's it. Now my app is configured to have a different configuration PER environment. So I can run a test to prove this out:

Voila! With each run*Example() test you will notice that the appropriate @Profile was invoked and the environment specific properties file was used to configure my EnvBean.

Pretty slick new feature from the guys at Spring! Did I mention, this whole thing was done with NO SPRING XML!!!

If you want the source for this, you can grab it from Bitbucket => click here

More to come and as always, I hope this helps! Cheers!

Tuesday, May 3, 2011

Maven 3 Polyglot Support

A while back I wrote a post where I created a little demo which used Groovy, Maven, JPA and Hibernate. The code is here.

I was taking a look at the Maven 3's new polyglot POM support and decided to convert that application's build to use the Groovy DSL. If you take a look at the Maven 3 Polyglot code, you will notice it is simply converting the Groovy DSL into the same POM object that would be created with the XML config. Still, it does make the configuration much more terse. Compared to the pom.xml, the pom.groovy is less than half as many lines. Moreover it just seems to be a bit cleaner and flows nicely.

For example, where we would have declared a dependency in the pom.xml as:

You can do the same thing in the Groovy DSL as:


Before getting too excited about this new Polyglot support, there are a few cons. First, and perhaps a deal breaker for some would be tooling support. Eclipse doesn't support this form of configuration, so you'd have to use Maven eclipse .project/.classpath plugin in order to develop in Eclipse....yet another reason to code in Textmate ;P

Second, as I said before, the DSL really only converts the config into the same POM object as the XML version would. You can't write executable Groovy code in the DSL unless you use the gmaven plugin. That's sort of a bummer.

The DSL is nice and makes configuring a Maven project MUCH cleaner. I will most likely use it for Maven projects in the future. I have also heard great things about Gradle, and will take a look at that build tool next.

In the meantime, if you want the code with the Polyglot Maven build, here's the link.

Tuesday, October 19, 2010

Event Sourcing

It's been a while since I made a blog posting so this one might be a little lengthy. Let's chat up Event Sourcing...

What is Event Sourcing and why do I care?

First off, Event Sourcing is not new. It has been around a long time, but the buzz around Command Query Responsibility Separation and DDD has pushed it back into the nerdy mainstream. The basic concept behind event sourcing is that we record state changes in the form of events, instead of the entire state of the object each time.

Using this technique adds a few nice benefits too; First, a reliable audit log becomes a first class citizen in your architecture, and not an after-thought. Second the persistence code becomes remarkably simpler. Third, your event storage can be implemented by as many options as you can imagine (RDBMS, flat file, xml, Object DB, BigTable, CouchDB, etc). Finally, you can replay these events to create the state of an object at any point in time...which kicks up the cool many, many notches.

Let's cover a little bit about one way you could implement event sourcing to persist and recreate a domain object. Before I begin, a little proviso to keep the bliki piranha at bay: this code is taken from a Contact Manager sample app I am in the process of writing in java to demonstrate the CQRS architecture. It is definitely a work in progress. Before you say it, yes I am well aware that implementing a contact manager in CQRS is crazy over-architected ;}

The code can be found on BitBucket here if you are interested in following along.

With that out of the way, the first thing we should discuss is how to develop your domain objects to take advantage of Event Sourcing. This snippet comes from my Contact object, which is an aggregate root in my domain. Each of the methods that modify the state of my object, translate that state change into an Event. For example,

The HomeAddressChanged object represents an Event. It is representative of the fact that the state of the address changed in my domain. Notice also that it is a past tense verb. This is important if you are trying to create DDD type UL. That said, DDD is out of scope for this posting, so let's move on.

After you've made all of your state changes, it's time to save the entity. The Contacts object, which is an implementation of the Repository pattern, will pull the events generated by state changes from the Contact aggregate (1 to *), and store them in the event store. Finally, the markChangesCommitted() method clears the event cache in my contact object.

The last part of persistence is saving these events in the event store. My example is *extra* simple because I am simply using an InMemoryEventStore, but your event store can literally be just about anything. I may do a separate post on the event store to delve into that topic a bit more.

A couple of key points. First, we ONLY ever insert into the event store, never update or delete. This is to preserve the lifecycle of the aggregate and build a solid audit trail. Second, it is very helpful if your aggregate has a identity that is unique throughout your enterprise. I chose a UUID for simplicity, but it isn't the only way to generate uniqueness.

Ok, now we have a series of events in the event store, lets talk a bit about replaying events to recreate an aggregate. First step is to get the events for a given id. In my case, I just grab them out of the event store:

Then I loop through this collection of events and in order, invoke the replay method of the aggregate to rebuild its state.

Notice the vanilla replay(Event event) method which uses Reflection to invoke the correct replay method for the type of event it is. This is not the most efficient way to build this functionality, but it is pretty darn simple to maintain, so I'm sticking with it for now. I'd be interested in hearing about other ways java folks have implemented this same piece without Reflection..perhaps an AOP implementation?

So when this loop finishes, you have the aggregate back in the exact state it was in when you stored it last. Here's an example of testing the storage and then the replay:


That concludes this little ditty about Event Sourcing. In a future post, I will demonstrate different types EventStore implementations. When I am satisfied with my CQRS Demo I will also do a series of posts about that topic.

If you are interested in CQRS, here are two great presentations by Greg Young and Udi Dahan.

That's it for now, I am interested to hear your experiences with Event Sourcing and ways I can tweak my code to make it more efficient or amp up the cool.

Thursday, July 8, 2010

How to URL Rewrite in Spring MVC

I am in the process of writing a Groovy based web app with Spring MVC and I wanted to use URL Rewriting. I scoured the boards for HOWTO's and from all my research Tuckey.org's URLRewrite is the best one out there. Here's a quick tutorial on how to set it up.

First, you need to add the dependency to your pom:


Next you need to map the URL Rewrite filter and your Spring Dispatcher servlet in your web.xml:

Then in src/main/webapp/WEB-INF you need to define a urlrewrite.xml. This file defines the filters for your webapp. For my app, I keep all JSP files under WEB-INF/jsp and use Spring's InternalResourceViewResolver to forward to them. This is great, except since my filter takes all request, I have to supply rules for the static files like html, javascript, css, images etc.

Here's how you do that. In urlrewrite.xml add the following:

That's it, URL rewriting is enabled on your app. Now anytime someone hits a URL in your app like http://[server]:[port]/[context-root]/[controller]/[action] (depending on which HandlerMapping you use) the filter will forward the request to the dispatcher servlet and your appropriate controller. For anything that goes to /images /js /css or /html, they will be forwarded to those resources.

I hope this is helpful.