I resolve, version 2.0

2011 is gone and with new year comes new resolutions. Some of last year’s resolutions got resolved, others fell to the wayside, and now I’ve come to write down a few more.

I never got back into grails – although I still feel like I want to. That one stays on the list!

Revisited some old text books, but I still have more to revisit. I forgot a lot about design patterns. Some of that is interview fodder, but still among the things I like to know.

The tracker app never went out, but an equally cool side project did – http://alianosbatavia.com – an implementation of a turn-key restaurant web app. Fairly successful so far, gave me a reason to write a production rails app, learn more about SEO, etc. Still not sure what my next idea is, but I want to get another app out this year…

Is Java still relevant? I go back and forth on this. I am thinking of either learning Play! or Scala/Akka. Not sure I care about either one. I think this is at the bottom of the list.

Lastly, I need to write the posts I talked about writing last year, including my favorite anonymous inner class mock madness.

Hopefully, I’ll be back soon.

SpringOne2GX, Day 2 Recap

Another good day at SpringOne.

The first session of the day was with Burt Beckwith going over the Spring Security plugin(s) for Grails. The last Grails work I did was with the Shiro/JSecurity plugin, which worked well, but I’ve always been interested in the extended feature set of Spring Security and it’s extensions. I thought the UI plugin looks useful, and the OpenID support looks like it’s got some nice features. Much of the rest still seems to be up in the air, but it’s maturing nicely. Glad to hear the demo code will be available.

Second talk was on the Google track, and was covering Spring Roo (which I promptly got stoked about yesterday) and it’s integration with GWT. I understand all of the browser compatibility advantages of GWT, but I’m still not convinced the complexity is worth it. Thankfully, Spring Roo does what it does best when it comes to GWT – generates and tucks away your boiler plate code. I’m not as excited about GWT as I thought I would be.

Third talk was with Burt Beckwith again – this time about strategies for handling database migrations in Grails apps. This is an aspect of Rails that I think is far superior to Grails. I didn’t get much from this talk other than how to correctly use Liquibase, but it was good to hear that this is something is being addressed in the upcoming version of Grails.

Fourth talk was about Extreme Scaffolding with Jean Barmash. We saw demos of a few interesting plugins for scaffolding and other UI enhancements, but I didn’t see anything really groundbreaking. It seems that a good command of grails templates, layouts and keeping DRY in mind would accomplish the same thing. It might even take longer to put all of these plugins in, and learn how to correctly use them, rather than just focus on writing good code and pushing out useful functionality.

Finishing the day with Stefan Schmidt and another great talk on the versatile persistence functionality available in the latest version of Spring Roo. The incremental reverse engineering is awesome and blows hibernate right out of the water. Grails and Rails are great for greenfield development, but this really makes Roo a compelling solution for developing new apps on existing databases. The JPA2 and NoSQL support were interesting. The one part I didn’t get was the discussion on Hades. Hades is a Roo add-on that generates the DAOs that Roo is made to get rid of (or at least hide). Maybe I missed something – it sounded interesting – I just didn’t see how it fit with the rest of the features of Roo, other than code generation, of course.

In all, not as good a day as the first, but I learned some interesting things. Spring Roo really seems like an exciting alternative Grails, especially if you’re developing in a dynamic language resistent environment. Looking forward to tomorrow.

SpringOne2GX, Day 1 Recap

It was an interesting day today at SpringOne2GX. There were many interesting presentations – here’s some thoughts on the 5 I attended today:

Guillaume Laforge’s talk on Gaelyk first thing in the morning was very interesting. I’ve been casually following the Gaelyk project for a while and was happy to hear more about it from the project’s founder. It looks like a great toolkit to easily take advantage of all of the features of the Google App Engine using a familiar and concise language in Groovy. A nice departure from Grails, Gaelyk is packed with a lot of interesting options and flexibility being on the Google App Engine. Definitely worth checking out for lightweight web apps with simple persistence needs.

Arjen Poutsma’s talk on the new features of Spring-WS was interesting also – good to see the familiar patterns and usages of Spring MVC making their way into the integration side. I’m currently on a Spring 3 project, and I’m quite sure there’s a compelling reason to roll this in. Definitely looking forward to getting into the details.

The Spring Roo presentation by Rod Johnson was a real eye-opener and definitely renewed my interest in the static-typed side of the Spring ecosystem. Grails, for straight java – what a cool idea. Pseudo-dynamic, clean code with boilerplate code woven in using AspectJ ‘side files’. I can’t wait to fire this one up, although I’m skeptical about how well I will work with it outside of eclipse/STS, which is not my first choice in regards to an IDE. The scaffolded UIs look very impressive. Looking forward to learning more about Roo + GWT tomorrow.

Another interesting Groovy-related talk was by Guillaume Laforge and Paul King on building DSLs with Groovy. A few very cool tricks and what I’m sure will be useful strategies for building DSLs using Groovy.

Wrapped up the day checking on the Grails 1.3 update with Graeme Rocher. Definitely a lot of stuff coming up that will be useful as the framework continues to grow. The GORM implementations at tonight’s keynote were awesome. New dependency management will be nice and clear with the right amount of control.

Looking forward to tomorrow!

Just call me Casey Jones

I’ve recently found myself involved in some RoR work. It took a bit to take my java blinders off, but since they’ve been off, the work has been great. With past Grails experience in mind, here are a few first observations after a couple of weeks of being a Rails dev under my belt.

I like migrations
I used to think I liked the “declare everything in the model” style of defining models in grails, but since then I’ve come to appreciate having to write migrations for the (dare I say?) discipline they force upon the author. Writing those migrations makes me think carefully about how the model change I’m trying to make impacts what’s already in the database.

Plugin/gem maturity
The community is strong – there are far more useful plugins/gems available for RoR apps than there are for Grails apps. You get just a few key choices in a Grails app. With an RoR app, and this sometimes can be cause for concern, there are many plugins to choose from – authorization and authentication gems are a good example. There are basically two choices in Grails – Spring Security and JSecurity. There are many choices for RoR apps, and further, they can be mixed and matched with the authorization and authentication components being separate.

So useful. I’d like to have the option of choosing a celebrity voice-over for them, though. Homer Simpson and/or Snoop Dogg would be my choices. http://railscasts.com/

The learning curve
Groovy & Grails has a definite advantage in being easier to pick up for someone with a java background. I think this is also a downfall of groovy/grails, because it is so easy to fall back to java instead of learning a new (or more efficient) way to solve a problem (ie with a new language and framework a la RoR).

The enterprise and it’s architects
Code that runs on hardware they’ve already got, that leverages existing resources (people and hardware), and is at least somewhat familiar to them is appealing. RoR is not this.

C to tha I
If I can’t roll a build and have Chuck Norris give me the thumbs up afterwards, I am somehow not satisfied. Autotest, rspec, and growl can get me by in the meantime.

… I just wrote a rake task. I’ll write about that later.

Find the Grails in Spring MVC

As I mentioned earlier, I recently moved back to the Java world after a brief and enjoyable foray into Groovy & Grails. After a few minutes of becoming reacquainted with Spring MVC, I found myself wanting to make my Spring MVC app behave more like a Grails app. I’m lazy, what can I say?

The request mapping annotations are the obvious first piece to the puzzle. The second piece is using model attributes. The third is a bit of javascript to get some flexibility in the view. Here we go.

Obviously, the class marked with the ModelAttribute annotation can be an actual model object or a command object.

The controller will look something like this:

 * A simple controller, use it to display and update values in the command object.
 * @author justin
public class SampleController {

    public ModelAndView displayYourPage() {
		//build your command object
		ModelOrCommandObject modelOrCommandObject = new ModelOrCommandObject();
		modelOrCommandObject.setMessage("Hello world.");
		//put your command object in the model map.
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("modelOrCommandObject", modelOrCommandObject);
		//build your ModelAndView object.
		ModelAndView modelAndView = new ModelAndView();
		return modelAndView;
	 * One of the actions that your page is submits to.
	 * @param modelOrCommandObject
	 * @param result
	 * @param status
	 * @return
    public ModelAndView actionOne( 
                    @ModelAttribute("modelOrCommandObject") ModelOrCommandObject modelOrCommandObject, 
                    BindingResult result, 
                    SessionStatus status) {
		//do whatever you need to with your command or model object for this command
		return new ModelAndView();
	 * Another action that your page submits to.
	 * @param modelOrCommandObject
	 * @param result
	 * @param status
	 * @return
    public ModelAndView actionTwo( 
                    @ModelAttribute("modelOrCommandObject") ModelOrCommandObject modelOrCommandObject, 
                    BindingResult result, 
                    SessionStatus status) {
		//do whatever you need to with your command or model object.
		return new ModelAndView();

We’ll have the option in the view to map one action to the controller or multiple actions. Multiple actions is easy with a bit of javascript.

The jsp will contain code like this;

<form:form action="/myapp/one-action-to-call.do" method="POST" modelAttribute="command" method="POST">
<!– some form fields –>
<button onclick="this.form.action=’/myapp/one-action-to-call.do’;submit()">One action</button>
<button onclick="this.form.action=’/myapp/another-action-to-call.do’;submit()">Another action</button>

That’s been working well for me as a simple bridge between Spring MVC and *some* of the convenience and efficiency of grails.

I hope this keeps happening.

Now that my first Groovy/Grails project has wrapped up, I thought I’d share some things I learned. I am a big fan of the framework, which is a somewhat biased opinion, mostly given my background as a java developer. Things that I already knew and appreciated were made easier to use. That’s usually a good thing…

Scaffolding is cool, but…
The scaffolded code contains good examples, but scaffolding is not all that useful in the real world, save for very specific cases – mostly admin functions.

Drink the kool-aid.
Language and framework features can really save you a lot of time in writing clear and concise code. Remembering to use them is the trick. Keep your Refcardz handy. Don’t fight the framework. Keep it simple.

It doesn’t have to be a closure.
I found exceptions thrown from closures to be hard to trace. Just my opinion.

Don’t forget your past.
This is the greatness of the things you know (Spring, Struts 2, Spring MVC, Hibernate), minus all the xml. You’ll spend a lot more time writing code instead of configuring. You’re not going to want to go back, unless you have to of course.

This is still new.
Even though it’s been around for a few years, the framework still has bugs, and can still change in some pretty big ways from release to release. The cutting edge is cool. Be careful.

Plugging in?
Just because it’s in the plugin directory doesn’t mean it works. With the previous item in mind, and given the fact that the community is still growing, there are a lot of plugins available that are written for a specific version of Grails. Again, be careful.

Protecting Parameters in Groovy/Grails

Section 11.2 of the Grails Framework Reference Docs talks about how to protect parameters in a Groovy/Grails app. On my current project, on public facing pages, we’ve been obscuring ids using the base64 codec that comes with grails. Here is a quick example:

def encodedString = "test".encodeAsBase64()

println encodedString

//build your decoded string from the byte array returned from the decode method.
def decodedString = new String(encodedString.decodeBase64())

println decodedString

Obscure ids and keep those urls hard to guess!

Shiro/Grails Tips

The Shiro plugin page in the Grails plugin repository has great information. Here are a couple of additional items I picked up during an implementation on my current project:

1. Filter every action except ‘x’ on a given controller

	    myFilter(uri: '/myController/**') {
	      before = {
	        if (!controllerName || actionName == "anOpenAction" || actionName == "anotherOpenAction") return true

	        // Access control by convention.
	        if (!isErrorPage(controllerName, actionName)) {

In this case, we’re taking advantage of common properties in grails. Basically, we’re filtering actions on myController. The first ‘if’ clause (!controllerName) filters for direct/default controller views, ignoring direct views. The other clauses are saying ‘if we’ve hit this filter, but the actionName is ‘anOpenAction’ or ‘anotherOpenAction’, let the request through.

2. Simple landing pages – enhancing the ‘free’ Shiro AuthController

If there is no target URI on the user’s original request to login, meaning, if they weren’t challenged and instead clicked on a ‘login’ link, a simple way to control where they are directed (assuming the goal is not to direct them to ‘/’) is as simple as this (with source from the AuthController):

	// If the user came to the login page via redirect (security filter caught an attempt to
	            // go to a restricted area of the site), then send them back from whence they came.
		        def savedRequest = WebUtils.getSavedRequest(request)
		        if (savedRequest) {
		            targetUri = savedRequest.requestURI - request.contextPath
		            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
		            println "Target URI, from saved request: ${targetUri}"
		        else {
		            // If a controller redirected to this page, redirect back
			        // to it. Otherwise redirect to an appropriate URI depending on the
		            // role of the user who just logged in.
		        	if(params.targetUri) {
		        		targetUri = params.targetUri
		        	else {
		        		targetUri = //some bit of code that determine the URI from the current user, etc.

Where that last reference of ‘targetUri’ is somehow set to where you want your newly-authenticated user to land.

Strange Days, Indeed

On my current project, I was adding a closure to a taglib that displayed a link conditionally, based on the current logged-in user’s role. The taglib is referenced on every page of the application, as it is included in the main Sitemesh layout. For the purpose of this example, a user cannot have both of the roles mentioned below.

Originally, the code looked something like this:

	def user = User.findByUsername(SecurityUtils?.getSubject()?.getPrincipal())
	def roles = user?.roles
	roles.each { role->
		if(role.name == RoleNames.CUSTOMER) {
			out << " | ${link(controller:'customer', action:'showProfile'){'View Profile'}}"
		else if (role.name == RoleNames.SALES){
			out << " | ${link(controller:'agent', action:'showProfile'){'View Profile'}}"

The first issue I ran into was a LazyInitializationException while attempting to use the each closure on my list of roles. Apparently, there was a JIRA opened about this.

Since the taglib is part of the Sitemesh layout, it doesn’t keep the hibernate session alive long enough to provide support for lazy fetching of child objects. This is easily overcome with some eager fetching of the child objects – this case, roles.

Now, the code has turned into something like this:

	def user = User.createCriteria().list() {
		and {
		fetchMode('roles', FM.EAGER)

Obvious problem here – I’m expected a single result, but I’m using ‘list()’ instead of ‘get()’. Sorry. It took a minute to figure out. I’m using ‘list()’, I’ve learned my lesson, I’m getting back a result set, and it’s going to be some sort of a list. In other instances I’ve done the same thing, and since the result is not statically typed, I’m expecting I’ll just get whatever the first result is.

Simple enough.

But, something else happened here. In the each closure on roles, ‘role’ was also being interpreted as a list. The code above was failing.

It seems that when you’re eager fetching using ‘list()’, the parent object and all the children (even the singular instances accessed in the each closure) are treated as lists. To function correctly, the code had to be changed to this:

	roles.each { role->
		if(role[0].name == RoleNames.CUSTOMER) {
			out << " | ${link(controller:'customer', action:'showProfile'){'View Profile'}}"
		else if (role[0].name == RoleNames.SALES){
			out << " | ${link(controller:'agent', action:'showProfile'){'View Profile'}}"

That doesn’t seem as clear to me as it could be. A brief conversation with some co-workers, and changing:

		def user = User.createCriteria().list() {


		def user = User.createCriteria().get() {

got things back to normal for us. The comparisons then became:

	if(role.name == ... 

If anyone else has had a similar experience to the one above or an explanation of this behavior, I’d like to hear about it!