Matt Stine’s Blog

Thoughts on Java, Groovy, Grails, Agile Development, etc. etc. etc.
Options:

LOTY/TOTY for 2010

If anyone’s interested, here’s a clue as to what I’m working on in 2010:

helloiphone

So you’ve just installed the handy dandy Spring Security plugin (http://grails.org/plugin/acegi), which makes it incredibly easy to secure entire Grails controllers and/or controller actions with annotations, such as the following:

This is enabled by turning on controller annotations in your SecurityConfig.groovy file:

So all is now good in our project. We can secure either controllers or actions with annotations, enabling us to declaratively setup security side-by-side with the code that we’re securing in a very straightforward manner. You can continue developing your Grails applications with glee, fully assured that security is no longer an issue. But wait, one day you decide to install one of the many useful Grails plugins that add controller artifacts to your application. Lo and behold, you have no way to secure those controllers! Of course, you could descend into $USER_HOME/.grails/$GRAILS_VERSION/projects/projectName/plugins/pluginX and hack the source code for your individual instance of the plugin. This ought to work, but you’re now rather constrained in that every time you update the plugin you’ll need to remember to go make this manual change. That doesn’t sound very agile at all, does it? OK, so how about forking the plugin? This is a little bit better, but now you have the burden of merging changes from the global plugin repository to yours every time a new release happens. This is better, but still a bit cumbersome. How about becoming a committer and adding it to the global source? Of course not. Not everyone will want to secure their plugins the same way you do, and you’ve just introduced a rather unnecessary dependency on the Spring Security plugin. I say all this in an attempt to paint a grim picture. In reality, we’re actually in very good shape. Grails Filters to the rescue!

All that you need to do is create a Grails filter that will match requests to the plugin artifact in question and then delegate to Spring Security for authorization. If they are authorized, you simply return true. If not, you can direct them to your login screen. It’s this simple:

As you can see here, I’ve secured both the Blurb plugin and the Settings plugin in this manner by requiring that the logged in user be in the ROLE_ADMIN role. Now as Glen Smith would say, that’s a snack!

Update: Burt Beckwith enlightened me to an approach that will get this done without the use of filters that will also direct you to the requested URL after login rather than the main page. Unfortunately I’ve never been able to track this down before. Just add the following to SecurityConfig.groovy:

Pomodoro: The First Iteration

I spent about an hour last night reading through Francesco Cirillo’s e-book The Pomodoro Technique. Up until this point I knew the basics of the technique, but I really wanted to drill down and get the details. I won’t explain those here - visit http://www.pomodorotechnique.com/ to get the lowdown. What I want to talk about is my experience applying the technique this morning.

I managed to complete two Pomodoros. Each of the Pomodoros was filled with internal interruptions of various kinds. One of the first things that I observed was something that I already knew from yesterday’s TADD post: I am definitely not used to focusing on one distinct task for any prolonged length of time. My mind was constantly bouncing around from idea to idea, almost as if my R-mode had a “memory leak.” My first Pomodoro was primarily a reading task - I used it for my daily Bible reading and meditation. This part of my day brings it’s focus challenges anyway, as I’m not doing anything tactile. I find its much easier to focus when I’m typing or writing something. The Pomodoro offered no relief from this, save a plan for dealing with the interruptions as they came up. First, note down that one happened with an apostrophe, and second, write the todo item or idea down on my inventory. This definitely helped to refocus my mind on the work at hand, but I still wish I could find a way to prevent those streamer thoughts from landing in the first place.

The second thing that I observed was that my workspace is not at all setup to encourage focus. In recent months I’ve stopped using task-focused desktops in OS X, something that Neil Ford recommends in The Productive Programmer. I was reminded of this later in the day today reading his latest blog entry. I think it would be a good idea to use my first Pomodoro of the day to setup task-based desktops for each of the tasks on my TODO list. I could fire up all of the programs necessary and drop them on to a space. Since a lot of my work is focused on web-based applications, I think I’ll probably use Fluid (http://fluidapp.com/) to create site specific browsers for the web applications that I need for each task. Another thing that I need to do is turn off the ringer on my phones and the new message notifications on Entourage. One tool that I did already have in my arsenal is Doodim, which blacks out everything except for the currently focused window on OS X. The only problem with Doodim (http://www.lachoseinteractive.net/en/products/doodim/) is that it doesn’t work with external screens, so only my MacBook Pro’s screen gets the benefits. I counteracted this by making sure that the window I was actively using was on the external screen and maximized, but this won’t work for some tasks during which I might have multiple small windows to interact with.

The final thing that I observed is that I still definitely live in an interruption-based work environment. My third attempt to complete a Pomodoro was repeated three times, and none of these times did I make it without having to stop and actively handle an external interruption. The difference? My office door was open. My first two Pomodoros were completed with the office door closed and my “Ssshhh…Genius at work!” sign on the door. This is going to be a tough one to handle. I don’t want to keep my office door closed all day, for more reasons than one. First, I don’t want to seem completely unapproachable. I’m a manager these days, and a huge part of my job is being available for people. For me, some interruptions will always be OK. But how can I sort those out prior to them happening? This is something I’ll be stewing on over the next couple of days. Second, my office turns into an absolute OVEN when the door is closed for too long. We have a really strange HVAC system that completely overreacts to small changes in the temperature. Unfortunately, it always seems to think I need to be slow cooked. ::SIGH::

So, there you have it. I’ve learned a lot - I observed quite a view things about my work patterns and my environment, and will be working over the next few days to make changes to both to support better focus. If you have any comments or suggestions, please feel free to comment. Thanks!

Yes, it’s true. I came to the realization that there is such a thing as TADD…technology attention deficit disorder. Ironically, I came to this realization while reading a sample chapter from the upcoming book from the Prags, Pomodoro Technique Illustrated: Can You Focus - Really Focus - for 25 Minutes? You see, it’s Pragmatic Programmer Writing Month (follow the trail that begins here), and I finally set aside an hour today to begin writing. At present, I just can’t make up my mind what book topic I want to focus on. I have the following in mind:

  • Polyglot Programming
  • Agile Testing Strategies
  • Groovy/Grails Automated Testing
  • Functional Programming in a JVM World
  • Or, perhaps, a topic that hasn’t churned up from my R-mode brain yet…

So, I have decided that I want to write an article detailing my development of http://www.duckduckgoosedesigns.com in Grails, an article that I hope will appear in an upcoming issue of Groovymag. It seemed like a good idea - write on something that I know very well and that I think could be helpful to others. Not only that, but it just might prime the writing pump for a bigger work like, maybe, a book! So, as I started writing, it occurred to me that I needed to let WebDevPub know that the entire source code for the online store was available at GitHub, so I jumped into the article submission site and added a note. This reminded me that I had not yet applied license headers to my source files, so I jumped into IDEA to use the Copyright Plugin to do so. It was at this point that I figured out that the Copyright Plugin does not support Groovy or GSP files, so I decided it would be a good idea to write a Grails script that would automatically do this. In the process, I decided to jump over to TweetDeck and let the world know of my intentions. It was at this point that I realized I had not yet followed @praglife on Twitter, so I fired that off. Realizing I wasn’t quite sure of the @praglife Twitter handle, I jumped over to the blog, and while looking for it noticed the news item about the Pomodoro book. I clicked on it and downloaded the sample chapter on interruptions. While scanning through and reading about internal interruptions, I realized that I was in the middle of one. My simple task - to focus on writing an article, had been interrupted by a stream of internal interruptions that led me to reading about internal interruptions. I have TADD. I’m out of denial, so what’s the next step? ;-)

It’s now Wednesday night, day 2.5 of SpringOne/2GX in New Orleans, LA. Normally I like to blog about each session that I attend when I make it to SpringOne, but as this has been my first year here as a speaker, I’ve spent practically all of my free time tweaking my presentation and demos. So, I wanted to summarize my reflections thus far before I forget them.

First of all, my talk went off fantastically. I presented Case Study: SRM 2.0 - A next generation shared resource management system built on SpringSource dm Server, which summarized our experiences using OSGi and SpringSource dm Server as the foundation for the enterprise application that we’re about to release into production. There was a small but very enthusiastic crowd, and I fielded quite a few questions both during the talk and immediately following. I was very encouraged to see nothing but green in the evaluation bucket at the back of the room, and this tweet was the icing on the cake.

Second, I’ve been extremely impressed with the venue. After attending the last two years in Hollywood, Florida, I can’t help but think that this move was one of the best that was made. The Roosevelt Hotel is very charming, and the banquet staff here is top notch. I’ve attended quite a few conferences, and the food here is definitely some of the best I’ve ever had. Not only that, but there is an entirely different energy level here in New Orleans - just hearing the live jazz piping into my hotel room every night from the French Quarter below is very nice.

Third, the combination of SpringOne and 2GX, the Groovy and Grails conference, into one event has topped my expectations. Being able to bounce back and forth between two of my favorite technologies has been awesome. Getting the latest scoop on Spring 3.0 and diving into Griffon during the same morning was great. Not only that, but getting to interact with my tweeps from SpringSource and the G3 community during the same week has been a blast. My only regret is that I didn’t have my talk more finalized before the event so that I could spend more time with the hallway conversations.

Quick reviews of the sessions that I’ve attended thus far:

  • What’s New in Spring 3.0 (Arjen Poutsma) - This was a great overview of the new and notable in Spring 3.0. I was very excited to see just how simple and powerful the REST support that is now built directly into Spring MVC will be. The only letdown was that Arjen didn’t dye his hair this year.
  • Intro to Griffon: Grails for RIAs (Danno Ferrin) - This was my first opportunity to hear a full blown talk on Griffon. Danno did a fantastic job walking us through how to use Griffon to develop a simple weather dashboard widget. I absolutely can’t wait to write my first Griffon app. Now that my session is done, I may start tonight!
  • Grails Internals (Jeff Brown) - Jeff Brown is live coding at its best. I love his ZERO slides approach, and I learned quite a bit about the different metaprogramming aspects used to deliver Grails functionality. I’m more than inspired to contribute to plugins at a higher level now.
  • MOPing up Groovy (Venkat Subramaniam) - Whether you’re interested in the topic or not, one must attend AT LEAST one Venkat talk whenever he’s in the same town as you. This talk was mostly focused around the metaprogramming topics that Venkat covered in Programming Groovy, but seasoned with Venkat’s unique blend of off the cuff humor. From no one else will you hear, “We don’t want to duplicate code…at least not in public.”
  • Grails for the Enterprise (Robert Fischer) - I must admit, I didn’t really NEED to go to this talk. I was mainly interested in checking out Robert as a speaker and hearing his strategies for driving Grails adoption. I liked his approach, and I really enjoyed his live coding session at the back end of the talk. He has quite a bit of energy and created a very rich interaction with the crowd.
  • Functional Groovy (Hamlet D’Arcy) - This was by far the best session of the conference for me thus far. Hamlet walked us through the 10 commandments of functional programming using Groovy as the syntax for exploration, sprinkled in a healthy amount of The Little Schemer, explained that using a non-functional language to learn functional programming was like learning OO in Cobol, and found a way to tie in Zen and the Art of Motorcycle Maintenance, Plato, Aristotle, elephants, and ducks.
  • What’s new in dm Server 2.0 (Ben Hale) - Ben walked us through the new and notable in dm Server 2.0. A great app server has gotten even better!

So there you have it. I’m looking forward to a nice relaxing day tomorrow (now that I don’t have demos and slides to tweak all day) and a quick flight home to rejoin my wife and kids. See you tomorrow Grant and the girls!

I spent the better part of yesterday tracing my way through the codebase for a large-scale enterprise application that my team is building right now, and I happened upon the following piece of code:

//...imports excluded for clarity
public class BusinessActivityBinMetaClassHelper {
//...
   public static List<Long> getSrmMetaClassIdListJava(List<BusinessActivityBinMetaClass> businessActivityBinMetaClassList) {
      List<Long> srmMetaClassIdList = new ArrayList<Long>();	

      if(businessActivityBinMetaClassList != null) {
         for(BusinessActivityBinMetaClass businessActivityBinMetaClass : businessActivityBinMetaClassList) {
             if(businessActivityBinMetaClass.getSrmMetaClass() != null && businessActivityBinMetaClass.getSrmMetaClass().getSrmMetaClassId() != null) {
               srmMetaClassIdList.add
                  (businessActivityBinMetaClass.getSrmMetaClass().getSrmMetaClassId());
            }
         }
      }

      return srmMetaClassIdList;
   }
//...
}

As I read this code, I thought “This just SCREAMS a need for Groovy’s closure iterators.” So, last night I quickly hacked out fully-equivalent Groovy version of the code:

class GroovyExample {

   static def getSrmMetaClassIdListGroovy(def businessActivityBinMetaClassList) {
      businessActivityBinMetaClassList?.collect { it?.srmMetaClass?.srmMetaClassId }.findAll { it != null } ?: new ArrayList<Long>();
   }
}

Whew! Much nicer. What did we get out of this? Well…

  • Groovy’s dynamic typing cleaned up all of the unnecessary type declarations - the only static typing is where we return an empty ArrayList of Longs if the argument to our method is null (a bit of odd behavior, but required to make this code equivalent to the parent Java code.
  • We were saved 4 painful null checks by the use of Groovy’s null safe dereferencing operator (?.) and the simplified ternary operator otherwise affectionately known as the “Elvis Operator” (?:).
  • Using Groovy’s collect method, we were able to transform the original list into a list containing Long values by passing in a closure that pulls out the property value of interest.
  • Because we’re using null safe dereferencing, we are actually inserting nulls into our list if any of the dereferencing fails. Therefore, Groovy’s findAll Collection filtering method comes to the rescue. We simply provide it with a closure that returns true for all of the values we want to keep - in this case, “it != null.”
  • Perhaps most importantly, we’ve shorted our code from 11 lines (including whitespace lines for clarity) to ONE LINE that much more clearly expresses the intent of the code.

Great - why don’t we just rewrite the entire application is Groovy? Well, hold on just a minute. At the time we started this application, as much as some of us loved Groovy, we just didn’t have enough Groovy mindshare to go there yet. On top of that, we were already experimenting with several new architectural ideas and technologies, and Groovy would have added yet one more risk to the puzzle. I say all this to acknowledge that sometimes you just can’t move to another language for one reason or another, regardless of how attractive its features may be.

But let’s take a queue from the Pragmatic Programmer and explore the LOTY (Language of the Year) concept one more time. One of the reasons that you’re encouraged to learn new languages is to change the way you program in your main language. You may learn Groovy, Scala, Clojure, Ruby, etc., etc., etc. and never use them in your day job - and yet the experience of coding in a new language with new constructs and idioms will necessarily change the way you THINK about programming in every other language.

So, let’s think about the possibility of coding something that is much more similar to the Groovy version and yet stick with regular Java code. Fortunately, there are several libraries out there that bring much of the flavor and power of Groovy’s closure iterators to Java. I’d like to focus in on one of them, LambdaJ (http://code.google.com/p/lambdaj/).

LambdaJ provides constructs that allow us to “…manipulate collections in a pseudo-functional and statically typed way.” Let’s take a look at this example implementing using LambdaJ:

//...some imports excluded for clarity
import ch.lambdaj.function.convert.Converter
import static ch.lambdaj.Lambda.*
import static org.hamcrest.Matchers.*

public class BusinessActivityBinMetaClassHelper {
//...
   public static List<Long> getSrmMetaClassIdListJava(List<BusinessActivityBinMetaClass> businessActivityBinMetaClassList) {
      return (businessActivityBinMetaClassList != null) ? filter(notNullValue(),convert(businessActivityBinMetaClassList, new IdExtractor())) : new ArrayList<Long>();
   }

   class IdExtractor implements Converter<BusinessActivityBinMetaClass,Long> {
	Long convert(BusinessActivityBinMetaClass from) {
	   if (from.getSrmMetaClass() != null && from.getSrmMetaClass().getSrmMetaClassId() != null) {
	      return from.getSrmMetaClass().getSrmMetaClassId();
	   }
   }
}

Not quite as nice as the Groovy code - we got A LOT out of the null-safe dereference and Elvis operators. However, our overall intent is still a bit clearer. Let’s analyze:

  • First we need to implement one of LambdaJ’s Converters. A Converter is nothing more than a generic Interface that defines one method: T convert(F from), where F is the type we’re converting from and T is the type we’re converting to. In this case, we want to convert an object of type BusinessActivityBinMetaClass to an object of type Long. Our implementation determines how this conversion takes place, in this case by extracting the id property from its child.
  • Next, after statically importing the methods of ch.lambdaj.Lambda, we call the convert method, passing it our List and our newly implemented Converter. This gives us the equivalent of Groovy’s collect method, with the Converter taking the place of the closure.
  • We’re still shoving nulls into our List with this implementation, so we further filter our list using LambdaJ’s “filter” method, passing it the list returned by “filter,” and a Hamcrest matcher that returns only notNullValue()’s.
  • Finally, we use our old friend the ternary operator to return the empty ArrayList of Long values if our method argument is null.

If you don’t count the Converter implementation, we’ve gotten ourselves down to 2 lines of code (1 if you don’t mind long lines). In this case I implemented IdExtractor as a named inner class - you could do this with an anonymous inner class and it would look a lot more like a closure, but the added noise of all of the null checking made the undesirable for me. Perhaps if your code has less noise (or guarantees that values aren’t null), that would be a better approach.

Another alternative is to make IdExtractor a top-level class that, if general enough, could be reused throughout the codebase. The benefit of this is that you now have a nice code unit rather than a battery of static methods in a utility class, and unit testing becomes much more clean and elegant.

So, we’ve still made some progress and made our code a bit more Groovy. I encourage you to explore LambdaJ’s feature set and see how it might make your code a bit more concise with clearer intent. And just to stir up a little controversy, look what would have happened in Java 7 had the null safe dereference and Elvis operator’s made the Project Coin cut:

//...some imports excluded for clarity
import ch.lambdaj.function.convert.Converter
import static ch.lambdaj.Lambda.*
import static org.hamcrest.Matchers.*

public class BusinessActivityBinMetaClassHelper {
//...
   public static List<Long> getSrmMetaClassIdListLambdaJ(List<BusinessActivityBinMetaClass> businessActivityBinMetaClassList) {
      return filter(notNullValue(),convert(businessActivityBinMetaClassList,
         new Converter<BusinessActivityBinMetaClass,Long> {
            Long apply(BusinessActivityBinMetaClass from) { return from?.getSrmMetaClass()?.getSrmMetaClassId()}
         })) ?: new ArrayList<Long>();
   }
}

Nice, huh? ;-)

Test Driven Development Worked for Me!

Our team got to spend a few days with Jared Richardson this week, talking tech leadership, agile, and automated testing. At some point during the opening day’s discussion, I related the story of how I initially got into Test Driven Development (TDD) and how it seriously ramped up my productivity and decreased my defect count.

In early 2003, we were slowly dragging through development of the first version of our Shared Resource Management system. At the time our development model looked a little something like this:

1) Code until you run into an unimplemented dependency;
2) Repeat until one of the dependencies is checked in;
3) Big Bang Integration!
4) Debug, debug, debug…
5) Repeat until something pseudo-demoable is ready.

As you might imagine, this wasn’t a very productive way to work, but unfortunately it was all most of us knew. At the time I thought we really needed to improve on our testing so that we could eliminate a lot of the defects that at the time I didn’t realize were being caused by our development model. I asked my boss if I could start a QA effort and not too much later found the XP/Agile Universe conference that was held in August 2003. It was my hope that we could learn about how to properly test/QA our software there as there seemed to be a lot of talks about this “TDD” thing. I got approval to attend, and while down there I was immersed in this new culture of Extreme Programming (XP) and Agile.

At one point I ventured into a room that was setup like what many of us would call a SCRUM/Team room today, where a group of folks were all coding away on a system and making its “Fit” tests pass. I quickly paired up with a gentleman and we went to work. At some point Brian Marick came over and asked what we were working on. I fumbled through a description of the requirement and he then asked, “Well, where’s your test?” I said that we didn’t have one, and he then said something that at the time was very profound to me, “Well, you can’t write any code until you have a failing test!”

I spent most of my time waiting in the airport to return to Memphis reading Uncle Bob’s “Agile Software Development: Principles, Patterns, and Practices.” Needless to say, I was fired up.

When I returned to work in the following weeks, I essentially tried two different tactics in parallel to share what I learned with my team.

First, I practiced what Jared calls “2×4 Development,” or, beating your team in the shins with a 2×4 until they start doing TDD, pair programming, continuous integration, etc. I even delivered my own version of the agile manifesto to the entire department, and the most profound comments I got out of that were “I can’t ever imagine us paying two developers to sit at the same computer and work on the same code,” and “Well, who’s going to test the test code?!?!”

Needless to say, this didn’t work very well. My second tactic was much more guerrilla in nature. I told the guy that I was working with that I didn’t care what he did with the rest of his time, as long as he checked in his interfaces before he started to code. Now I had something to mock! I then proceeded to TDD all of my code. I advertised my productivity in terms of test cases passing with a little counter on my whiteboard. Development was fun again, as I could get instant feedback on how my code was working and I knew that it was interacting properly with its dependencies. Sure enough, when those big bang integrations happened, my code rarely seemed to be the source of the defects, and I quickly found myself getting pulled into other parts of the code to help develop since I had already gotten my typical assignment finished!

We delivered the section of the system that I developed using TDD much faster than any part that I had worked on up to that point (no hard numbers, but I have a pretty good memory of that time), and in addition, I wrote the CLEANEST code I had ever written up to that point.

So, while Jared wouldn’t recommend you try TDD if the rest of your team isn’t on board - you’re never going to get someone who doesn’t care about tests to fix one that they broke - this guerrilla tactic worked well for me and got me some recognition as a guy who could write good clean code fast! If I could go back to that point, I think I would have tried Defect Driven Testing first or in addition to my GTDD.

So, how are you getting your team test infected?

Isabella featured on Totally Tots

meet_bella

Isabella, my second oldest daughter, just made the cutoff to be featured on one of the very popular “Mommy Blogs” out there, Totally Tots. Way to go Bella!

I promised that I would post the links I mentioned in my talk last night at the Memphis JUG…here they are:

General Session Replays: http://java.sun.com/javaone/2009/general_sessions.jsp

BlogTalkRadio: http://www.blogtalkradio.com/JavaOne

JavaOne Minute: http://channelsun.sun.com/video/channel-you/javaone+minute/23867338001

Technical Sessions 2008-2009: http://developers.sun.com/learning/javaoneonline/ (Must be SDN Member - FREE!)

The Da Vinci Machine Project: http://openjdk.java.net/projects/mlvm/

Groovy: http://groovy.codehaus.org

Java.net Community Corner: http://wiki.java.net/bin/view/Javaone/CommunityCorner

JUGS Community: http://community.java.net/jugs/

Scala: http://scala-lang.org

SpringSource: http://www.springsource.com

JUG-USA: https://jug-usa.dev.java.net/

OpenSolaris: http://opensolaris.org

Neal Ford: http://nealford.com (Can download his slides here)

Findbugs: http://findbugs.sourceforge.net

Grails: http://grails.org

Grails Podcast: http://www.grailspodcast.com

JavaFX: http://javafx.com

Griffon: http://griffon.codehaus.org

Java Store: http://store.java.com

Jython: http://jython.org

Clojure: http://clojure.org

JRuby: http://jruby.codehaus.org

Sun Cloud: http://cloud.sun.com

Project Kenai: http://kenai.com

Zembly: http://zembly.com

NetBeans: http://netbeans.org

I’ve finally published my review of the EXCELLENT book by Jared Richardson and Matthew Bass at DZone. Check it out here: http://books.dzone.com/reviews/career-20-take-control-your.



View Matt Stine's profile on LinkedIn

Speaking Engagements

Memphis/Mid-South Java User Group
Real Developers Read! - Delivering Value
January 21, 2010 - 6 PM

Memphis/Mid-South Java User Group
Polyglot OSGi
April 15, 2010 - 6 PM

The Lambda Lounge
St. Louis, MO

Polyglot OSGi
February 4, 2010 - 6 PM

No Fluff Just Stuff

Mid-South Software Symposium
April 23-25, 2010
Memphis, TN

Northern Virginia Software Symposium
April 30-May 2, 2010
Reston, VA

Categories

Leader of the Memphis/Mid-South JUG

Pandora