St.Louis Java SIG Google Collections Presentation

June 10th, 2010 by James Carr

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”

February 5th, 2010 by James Carr

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.

Read More »

Express Your Dependencies

December 29th, 2009 by James Carr

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 {
	@Autowired
	private Dao dao;
}

I’d prefer to do this:

public class SomeServiceImpl {
	private Dao dao;

	@Autowired
	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

October 21st, 2009 by James Carr

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();
		customerService.setCustomerDao(customerDao);
	}
	public void testShouldReturnTheNumberOfActiveAccounts() throws DataFormatException{
		List customers = Arrays.asList(new Customer[]{new Customer(3), new Customer(4)});
		when(customerDao.getActiveCustomers()).thenReturn(customers);

		assertEquals(7, customerService.getTotalActiveAccounts());
	}
	public void testShouldSaveCustomerIfHeHasAccounts(){
		Customer customer = (Customer) mock(Customer.class);
		when(customer.getNumberOfAccounts()).thenReturn(new Integer(1));

		customerService.saveCustomerWithAccounts(customer);

		((CustomerDao) verify(customerDao)).save(customer);
	}
}

Good Luck! :)

Off to St.Louis

March 7th, 2008 by James Carr

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)

March 2nd, 2008 by James Carr

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

March 2nd, 2008 by James Carr

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. ;)

Where Is Java Going to Go From Here?

February 13th, 2008 by James Carr

Ever since I attended the NFJS Gateway Symposium almost 2 years ago, I’ve been hearing the same theme over and over:

Java is the new COBOL.

Everywhere you go, you can’t seem to avoid hearing this. An ex-coworker commented when I ran into him at Agile 2007: “I’m surprised you guys aren’t using JRuby.” Two sessions I attended there also had speakers throwing in a little rant that Java is a dinosaur that is going way. With all the new languages that can run on top of the JVM now, there has been a lot of fuss on what is going to become the next language of choice for Java developers.

DZone’s Steven Devijver is placing his bets on Groovy. This was brought up quite a bit at NFJS last year as well. It’s hard to argue against it… with JRuby, java developers have to learn a completely new language with different characteristics than what their used to, whereas Groovy combines the best of both worlds with all of the nice characteristics Ruby has (and more) as well as a familiar syntax… java code is completely valid in Groovy.

Scala has also captured my interest as of late and I really think that 2008 will be the year that it breaks into the mainstream (much like a year or two ago was for Groovy). Only time would tell I suppose… I like both languages so it is difficult to place any bets on which is going to become the new replacement for Java.

What do you think?

Extending Selenium Via Javascript

February 8th, 2008 by James Carr

Looks like I’ve already accomplished one of my new year’s resolutions by doing some polygot programming at work today embedding javascript within java. And it happened completely by accident.

Lately we’ve had a handful of Selenium Remote Control based fitnesse fixtures crop up at work… there’s a nice generic one, and several custom ones designed to tackle specific front end domain problems. On our latest project we have your run of the mill tabbed layout, you know… click on tabs and and you see different content, nothing special. What made things interesting, however, is that marketing wanted to track some specific usage information when each tab is clicked. Fine enough, just whip up some ajax and register some event handlers for the click event, and we’re ready to go. Well, hold on… what about testing?

Everything on the server side was unit tested and functionally tested to a T… in fact I am rather proud of the partner I worked with and myself on how well the tests are written and how many scenarios are covered. However, I still wanted to test the front end… I want to be sure that each time someone promotes, they didn’t do something to, as our team’s QA member would say, “jack it up.”

So I quickly wrote some selenium tests in fitnesse (note: this violates everything I believe FIT should be for, but fitneese is a convenient poor man’s application server) to get to the vehicle history report and test it. Speed bump number one. The interface that lets users run reports uses a target attribute on the form to open the report in a new window, and apparently selenium can’t focus on a window unless you explicitly use window.open to open the window. Drats… foiled. Or was I?

After a bit of searching, I found out that selenium remote control has a method called getEval that will simply evaluate any javascript you pass into it, which is handy for checking variable values for example. From there, you can access the runner via this.browserbot, which provides a whole slew of awesome commands you can use for manipulating the runner, including accessing the current window. And that’s where it sinks in… I can do anything in the world (almost) with javascript, and if I can access the window, I can make things happen. Bypassing the earlier speed bump was a simple matter of opening a new window with the same name as the target, and then focusing on it once the form is submitted. Piece of cake.

Since we have a lot of forms like this, I wrote a simple script to open new windows for any forms with a target on it using the name of the target, and wrapped in a java method. So that was step one… I now had a java method in a fitnesse fixture with javascript code inside a string indented all nicely… and evaluated on demand.

Now. at the new tabbed page is where things got immensely interesting… I wanted to intercept xmlHttpRequest calls, capture them, and be able to access them later. Redefining jQuery’s XHR methods were a piece of cake, the code was something like this (and whipped up in about 5 seconds):

var _d = this.browserbot._caughtValues = []
this.browserbot.getCurrentWindow().jQuery.post = function(a,b,c){
	_d[_d.length] = b;
}

the second parameter here was the data packet being passed in, which is what I was interested in the most. Different meta data is fired off on different tab clicks.

Then topping this off was a simple matter. I created a method that would return a ListFixture (because I wanted to loop over the meta-data packets in the order they were fired, and also because it is vastly supperior to RowFixture) and got to work scraping the values out, which became a mix of BOTH java and js, together.

Building a list of java objects from the captured values was a matter of:

  1. Getting the length of the _caughtValues array and converting it to a java int (getEval only returns strings)
  2. iterate a number of times equal to the length to visit each value on the array
  3. do an eval against _caughtValues with an index specified to get the json packet:
    String packet = getSelenium().getEval("this.browserbot._caughtValues["+index+"]");
                   
  4. parse it into a java.util.Map by making a call to a nice JSON parsing library
  5. populate a java object representing the packet with the map, add it to a list, and return a new ListFixture containing that list.

I wrestled a little to get it work, but I’ll have to admit it felt oddly great when I saw the table of expected packets light up green… and then red for the last 4 rows (good to know it was able to catch the invalid packets). There’s also a sense of joy in seeing it run consistently… for a session it worked, but would randomly fail.

It’s pretty interesting, but I think my coworkers might hate me for the embedded javascript code inside of java. So far they either think it’s really cool, or really insane. ;)

Making extJS More Accessible to Java Developers

January 22nd, 2008 by James Carr

With my recent interest in extjs, I was playing with the idea of making a Struts2/WebWork component library or a tag library to handle a lot of the boilerplate extjs code (i.e. creating layouts and such) but, luckily, discovered someone beat me to the punch!

I randomly came across ExtTLD this morning while sifting through my rss feeds, and I must say I am rather impressed. Although I consider myself a pretty good javascript developer, there seems to be a lot of java developers who aren’t that hot at javascript… which is why whenever I attend any java related conference there is always several sessions touting “javascript free ajax!” frameworks like GWT, Ajax4JSF, or IceFaces. Although I’ve always been skeptical of such frameworks, I do see their benefits… especially for the java developer who excels at serverside JEE development but generally sucks when it comes to adding javascript behavior to the presentation layer.

So far it looks good, but I haven’t had a chance to play with it yet. Basically, I’ll have to see if it passes my “good javascript generator framework” test. I’m a pretty staunch advocate of unobtrusive javascript, and generally hate any presentation layer framework that seeks to dump several hundred (or thousand) lines of javascript inline in the html document. This is the reason I totally hate Struts 1’s client side validation plugin.