Enabling JMX in Gradle’s jetty Plugin

It’s another day, which means another gradle tip. I have been experimenting with JMX lately and using MBeanExporter to export spring beans so that I can interact with them over JMX (specifically, stopping and starting rabbitMQ consumers). I can get this working on any container easily enough but I really wanted to get it working with my locally running jetty instance launched by gradle.

First you’ll set a jettyConfig for the jettyRun task. I usually do this for both jettyRun and jettyRunWar:

The additionalRuntimeJars is needed because of a transitive dependency on mx4j. I don’t know why this is, but it is required. I add mx4j as a providedRuntime dependency along with jetty-management:

Finally you need to setup your jetty configuration to startup a JMX server. There’s a bit of freedom here with what you can do but here is one that I stole shamelessly from the jetty website:

Now run gradle jettyRun and have jconsole open a remote connection to service:jmx:rmi://localhost:2100/jndi/rmi://localhost:2099/jmxrmi and go do whatever you want to do with JMX. 🙂

Cache Abstraction in Spring 3.1.0.M1

Another new feature released yesterday came in parallel with me tryingo ut some annotation based caching strategies. Caching Abstraction basically takes convention from an existing project and makes it part of spring core.

Essentially it introduces a new interface, CacheManager, which can be implemented by a specific cache implementation. From there it adds a few new annotations to make methods cacheable. Here’s an example using my previous posts objects.

Here you’ll notice that the finder method has a @Cachable annotation on it with a name that specifies the cache to store to. it can also use additional attributes, for example a key which uses an expression language to determine a key from the arguments that are passed in. The default is the value of all the method arguments. On the save method I use @CacheEvict to remove the cached element from the cache if it already exists.

This of course won’t work on it’s own, so you’ll have to enable it yourself (which is good… the last thing you need is to discover a production app caching things it shouldn’t be caching). Sadly as of the time of this writing I haven’t discovered how to do this in non-xml, so here is the spring xml file to enable it and use ehcache as the implementation.

The ehcache configuration:

And finally adding this to the AppConfiguration, which includes doing a simple @ImportResource.

When running this example there should be a log message for the first time the method is hit, then it is not seen the second time (since it is being pulled from the cache. This is definitely pretty awesome for implementing Memoization for methods that might just have some CPU intensive computations (but give the exact expected results given a set of of inputs). I’m excited about doing some more work in this area… I’ve done method level caching before (it’s common) but it is awesome to be able to use it without having to DIY. 🙂

JSON Message marshalling in spring-amqp

I’ve been doing a bit of exploration in spring-amqp lately and came across some of the built-in features to automatically marshall/unmarshall AMQP messages to java objects. Although you can get away with just having java objects implement Serializable but that just means you’ll only be dealing with java to java communication and that’ll break down the amount of flexibility you have.

Luckily there’s JsonMessageConverter, which allows you to marshal and unmarshal messages as JSON. By default this uses a _TypeID_ header which maps to the java class name. For this me this just didn’t work as I have an app in node.js communicating with a Consumer and Producer living in java land. The solution comes from a little undocumented feature.

Essentially you just need to set a map of class mappings on the java side of things:

Then assign it to the JsonMessageConverter you’ll be using to marshall messages… in this example it’s used for both a consumer and producer, but I’ll just focus on the consumer:

And the actual consumer (which is just a plain java object).

Now whatever messages get published will just refer to the _TypeId_ header to map json objects to classes behind the scenes (no JAXB annotations or anything needed). For example, publishing a message from node.js:

As a final note, I didn’t like the default header field _TypeId_. The only way to change this with the current API is to override getClassIdField in DefaultClassMapper to return the header field name you want to use. For my purposes I just changed this to the field type:

Pretty sweet stuff. Feel free to check out some of the examples in the github repository for this.

St.Louis Java SIG Google Collections Presentation

Tonight I gave a presentation at the St.Louis Java SIG on Google Collections. Here is the presentation that I made with Prezi, but like always the presentation is much more effective in person as it mostly served as a visual aid to talking and live examples.

If I really had to sum up my points from the talk, I’d say it was this:

  • Immutability for the win!
  • Explore the API
  • MapMaker is SWEET

Using Gradle For Your “Enterprise Java Project”

Yesterday evening I fooled around with gradle quite a bit, finally sitting down and taking some time to learn it as I’ve been hearing lots of good things about it. And man, I like it!

I decided to use it to build the kind of project that enterprise architects go ga-ga over: a multi module project that contains a shared module with an interface (containing JAXWS annotations), a services war module to create a service implementation, and a client implementation to call it. It was a breeze and I finished it in a couple hours.

Continue reading

Express Your Dependencies

Recently I gave a presentation on Test Doubles at a client site and while fielding questions at the end, one person asked how they could use Mockito (which I used to demonstrate Test Doubles) when autowiring fields with Spring. The problem he had was he was autowiring the fields, which were private, and which had no setters to use for injection. Although he could use reflection and cheat, I stated what I believe to be philosophically correct; dependencies should be expressed in your implementation (I often don’t express them in interfaces unless they are an argument based dependency) and as such you should always provide an injection method for them (constructor or setter) to realize that dependency to those who might use the concrete implementation.

So, rather than doing this:

public class SomeServiceImpl {
	private Dao dao;	

I’d prefer to do this:

public class SomeServiceImpl {
	private Dao dao;
	public void setDao(Dao dao){
		this.dao = dao;

Although one can argue that the setter is only used for substitution in tests/examples and there’s no client code at all that will inject the dependency besides Spring, I’d argue that your tests/examples are clients themselves… I’d also argue it’s just plain good design to express the external dependencies that your class requires. 🙂

Mockito for JVM 1.4 Released

For those of you who didn’t know, I’m currently contracted at a workplace that is still stuck using java 1.4 (I heard they might ring in 2010 by upgrading, but we’ll see). This has create a number of difficulties, chief amongst them (in my view) that I can’t use Mockito and most people use EasMock… version 1.2 (yeah, the one with that MockControl nonsense).

Not to be foiled, I used retrotranslator to translate mockito to 1.4 so I can use it for TestCases… it is now available on the Mockito project site.

This is pretty much a direct port, and I added the class MockitoTestCase which basically has all the methods you’d normally statically import off of the Mockito base class. Here’s a quick demo of usage:

public class CustomerServiceTest extends MockitoTestCase{
	private CustomerDao customerDao;
	private CustomerService customerService;

	public void setUp(){
		customerDao = (CustomerDao) mock(CustomerDao.class);
		customerService = new CustomerService();
	public void testShouldReturnTheNumberOfActiveAccounts() throws DataFormatException{
		List customers = Arrays.asList(new Customer[]{new Customer(3), new Customer(4)});
		assertEquals(7, customerService.getTotalActiveAccounts());
	public void testShouldSaveCustomerIfHeHasAccounts(){
		Customer customer = (Customer) mock(Customer.class);
		when(customer.getNumberOfAccounts()).thenReturn(new Integer(1));
		((CustomerDao) verify(customerDao)).save(customer);

Good Luck! 🙂

Off to St.Louis

I’m at work finishing up some emails and waiting for the morning huddle to communicate a few things to my team, then it’s off to St.Louis for No Fluff Just Stuff …or as Than keeps calling it, “No Stuff Just Fluff.” 😉

I’ll be posting live from the conference for anyone interested in the content of the sessions that I’ll be attending. Looking over the schedule, it looks like today’s sessions will be a little “light”, but only because I’m familiar with the technologies being discussed OR I have attended them in the past. For example, I have no need to attend yet another introduction to JSF… nor do I need to find out about GWT, dojo, Adobe Flex (I already know and use these!). And of course… how many groovy sessions have I attended? I have 2 Groovy books and a Grails book on my bookshelf, but I MAY still attend one of the sessions on groovy again.

Anyhow, here’s my projected schedule for today, subject to change:

Spring+JPA+Hibernate: Standards Meeting Productivity for Java Persistence by Ken Sipe
Well the standards created EntityBeans…. yea. and the community created Hibernate. Fortunately the standards body learned some lessons and created JPA. JPA requires a vendor implementation and none make a better choice then Hibernate. Combined with Spring this trio is a powerhouse when it comes to developer productivity on applications requiring persistence.
Spring 2.5 – Spring without XML by Ken Sipe
Spring 2.5 is brand spanking new, with a number of fantastic features. With growth of large and complex Spring applications which struggle with xml manageability and with the added pressure of Guice and SEAM there is a push for less XML, with solution leaning towards annotations. Spring 2.5 adds to the toolset provided in Spring 2.0 to provide a development environment where XML is greatly reduced… or eliminated if you so choose.
Grails for (Recovering) Struts Developers: A Groovy Alternative by Scott Davis
Struts enjoys an unprecedented marketshare in the Java web development space — 60%-70% according to most surveys. As newer, modern web frameworks come to the scene, very little attention is paid to the real costs of migrating an existing Struts application. This talk shows you ways to mix Groovy into a legacy Struts application, dramatically reducing both the lines of code and the complexity. We’ll also introduce you to Grails (a Groovy-based web framework) whose URL-mapping capabilities allow it to replace your Struts application without breaking legacy URLs.

On an unrelated note… I put in a contract on a house last night. If everything goes according to plan, I’ll be moving into my very own house April 2nd (I couldn’t close on April Fools Day 😉 )! Suffice to say I’m very excited… although I had a bit of doubt in my mind because I kept thinking “what if I get an amazing job offer? Then I have to sell it!” But decided to settle. Let’s think about it: I have a pretty good job that I love, friends that are great, a decent salary, and a town that is a great place to live. What if I live here for 5 more years? I don’t want to keep living in an apartment based on a mistaken assumption I may some day move.. and besides, I think my next job would have to offer enough that selling my house is the least of my concerns.

Anyhow, come April 2nd I (should) have my own chunk of land that I can call my own. WOO HOO!! 😉

NFJS Coming Up (Yet Again)

Only a mere five days from now I’ll be attending the NFJS Gateway Software Symposium for the 4th time… and I’m pleased to say I’m quite excited. NFJS is one of those conferences that just has a knack for being fun, small, easily accessible, and very very educating.

The “educating” part however is the only aspect that has me a little worried, since this being my 4th NFJS conference I worry there may not be much new to see… and a quick initial glance at the sessions I easily spot many of the usual sessions they’ve had in the past… so what to do? 😉

Without a doubt, I’ll have to attend Michael Nygard’s session “Failures Come In Flavors.” I actually had the pleasure of meeting Michael last year at the GSS Fall edition at the hotel lobby bar… from the discussion we had about software development I could tell the session would be interesting, but unfortunately missed it due to having to head back to Columbia early on Sunday. So I’ll be “making it up” this time around. Additionally, he is also giving another session titled The 90 Minute Startup that sounds pretty interesting too.

The session that stands out is Nathaniel Schutta’s Designing for Ajax (Part 2). Why am I only interested in part 2? One reason… one reason only… Google Gears. Google Gears is one of the most interesting things I’ve toyed with lately that sadly your average developer has no idea what it is (but should).

Anyway, feel free to hit me up if you happen to be attending. If not, keep an eye here as I’ll try to post some fresh content daily from the sessions, if not just quick notes on what’s going on. Hopefully I’ll have something enlightening to post! 🙂

Smarter Javascript for Java Web Applications With JAWR

One thing that has always annoyed me a little about javascript is the burden induced by modularity. Sure, you can keep your javascript in many small, testable files… but good grief it’s annoying when you have to put 10 or 15 script tags in the head of your document and thereby inducing much overhead on the client side. I mean, first you have a good chunk of markup taking up bandwidth and then you have the overhead of each http request for each javascript file. Once you take into consideration that some browsers only allow two http connections at a time things start to slip. Jamming everything in one file is annoying too, and always feels sloppy.

Recently I’ve discovered jawr, and it’s alieviated all of my javascript modularization problems. Jawr is cool in that it allows me to define “modules” that consist of many javascript files… I can either list the files I need, in the order they should be included, point to a directory to include all scripts in it, or even use some pattern matching. The simply define a mapping for the module to serve up the javascript (i.e. /js/all-the-scripts-i-need.js) and jawr goes to work, stitching the javascript together and serving it up… minimized and gzipped. I’ve only began delving into it, but so far it’s been great. On a single page on our site we had about 60KB of js, 30KB of it jQuery. After defining a module, the resulting file served to the client side was a mere 22Kb. Similarly it also can do the same for CSS, which slimmed our 8 css files from a total of 28KB to a single 5Kb file.

The idea is pretty sweet… keep a collection of javascript objects/functions with appropriate namespaces, fit together into modules for each place they are needed. Inside of each of those modules though will probably be our usual “binder” functions… you know, the usual “hunt down and find the DOM elements I need to bind events to” type behavior.

My only annoyance so far? Sometimes the minification process exposes javascript that, shall we say, does not minify well thanks to it’s layout. In my case, there was a javascript file with a multi-line string used for templating… my deployment just outright failed because of a “unterminated string literal” and took a bit of mucking around to find exactly what file it was that it hated. Other than that, it’s well worth the look. 😉