The Kaptain on … stuff

26 Jul, 2009

StreamingMarkupBuilder for Groovy-er xml

Posted by: TheKaptain In: Development

Been having an awful lot of fun lately playing with the Groovy StreamingMarkupBuilder. I’m not a big fan of xml in general, but it’s definitely got its uses(configuration and web service data interchange to name just a couple).

StreamingMarkBuilder makes it really very painless to create complex xml structures without a whole lot of hassle. There are some excellent examples out there already, but I couldn’t find one offhand that put all the pieces together.

This example demonstrates how to include the xml declaration, set the encoding, and incorporate namespaces. It also shows how to use iteration to create nodes in the Document. The (somewhat contrived) example code shows one possible way to template Facelet forms based on some simple parameters.

[groovy language=”true”]
import groovy.xml.StreamingMarkupBuilder

def inputs = [‘FirstName’, ‘LastName’, ‘Street’, ‘City’, ‘Country’]
def controller = ‘formController’
def bean = ‘formBean’

def builder = new StreamingMarkupBuilder()
builder.encoding = "UTF-8"
def doc = builder.bind {
mkp.xmlDeclaration()
mkp.declareNamespace(ui: "http://java.sun.com/jsf/facelets",
h: "http://java.sun.com/jsf/html")
‘ui:composition'(template: ‘/layout/main.xhtml’) {
‘h:form'(id: "${controller}_form") {
inputs.each {input ->
def inputId = input.toLowerCase().replaceAll(‘ ‘, ”)
‘h:outputLabel'(input, id: inputId, styleClass: ‘inputlabel’)
‘h:inputText'(id: "${inputId}_input", value: "${bean}_$inputId", styleClass: ‘inputText’)
}
}
‘h:commandButton'(id: "${controller}_submit", action: "#{${controller}.submit}", styleClass: "submitButton",
value: ‘Submit’)
}
}
[/groovy]

And the output looks like this.
[xml language=”true”]
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" template="/layout/main.xhtml" xmlns:h="http://java.sun.com/jsf/html">
<h:form id="formController_form">
<h:outputLabel id="firstname" styleClass="inputlabel">FirstName</h:outputLabel>
<h:inputText id="firstname_input" value="formBean_firstname" styleClass="inputText"/>
<h:outputLabel id="lastname" styleClass="inputlabel">LastName</h:outputLabel>
<h:inputText id="lastname_input" value="formBean_lastname" styleClass="inputText"/>
<h:outputLabel id="street" styleClass="inputlabel">Street</h:outputLabel>
<h:inputText id="street_input" value="formBean_street" styleClass="inputText"/>
<h:outputLabel id="city" styleClass="inputlabel">City</h:outputLabel>
<h:inputText id="city_input" value="formBean_city" styleClass="inputText"/>
<h:outputLabel id="country" styleClass="inputlabel">Country</h:outputLabel>
<h:inputText id="country_input" value="formBean_country" styleClass="inputText"/>
</h:form>
<h:commandButton id="formController_submit" action="#{formController.submit}" styleClass="submitButton" value="Submit"/>
</ui:composition>
[/xml]

Normally StreamingMarkupBuilder output is devoid of whitespace but for readability I rendered it using the very handy example provided here. Big thank you to Jeff Sheets for sharing that code!

22 Jul, 2009

I am a Procedural Programmer

Posted by: TheKaptain In: Development

I had occasion today to reflect on what I’ve learned in the last few years developing software and it occured to me, not much has really changed since I first struggled with Lisp and Scheme in university. I still don’t completely “get” functional programming! Wrapping my head around all those brackets in any derivative of Lisp felt like torture, but maybe that was just academia trying to punish me for my eventual release into a world of programming languages concieved AFTER 1979. Not that Iam in any position to be critical of such seminal ideas – which after all are at the root of the Groovy Closure I know and love. I do “get” Closures, fortunately.

🙂

In the last few years I’ve been exposed to a huge variety of different tools and frameworks, and have followed the transition of Java from 1.4 to 1.6(and beyond!) Past time to take a look at just what has changed, and perhaps why it doesn’t matter so much.

Build tools and dependency management – Ant, Maven, Ivy, Grape

I started off in my programming career with lots of  build.xml files and eventually made the (at times rough) transition from there to pom.xml. The best part of this: never having to hand-code a classpath again. Worth it right there. Maven adds enough dependency management magic to the build process to make it a nice alternative, and when you factor in the great IDE support available(I’m looking at you IntelliJ) it’s almost a no brainer. When you need to switch from one project to another, as has been pretty common in my career at least, being able to open a project at first sight and have your IDE correctly load up and run out of the box is a big plus.

Of late I’ve been getting more experience with Grape and Ivy. These dependency management tools bring some really elegant simplicity to the table, especially Grape; good-bye to complicated command line “java -cp …” calls when all you want to do is run a little snippet locally and import a jar. Now of course, this journey takes us all the way back to ant, since it is such a close(and apparently integral) part of Ivy. Which is all right in my book – ant has really stepped up to the challenge in recent history, in no small part due to the community. The Groovy AntBuilder and Gant enable many of the iterative style features so hard to express in xml mostly trivial, greatly simplifying usage of the powerful ant capabilities and making them easier to bring to bear. Now of course, the ability to run both Groovy and ant from with Maven kind of make it a moot point – if you really want to make your life easy, it pays to get to know all of these technologies and fit them into your build in the most effective way possible.

Dependency Injection – Spring, Maven, Seam, Guice

First time I saw dependency injection in action was with Spring. The IOC principle has since then become central to how I look at software. I mean, if you want to unit test effectively, it’s pretty much compulsory. And it encourages you away from ‘bad’ design patterns – static method only classes, shared instantiated utility classes, lack of interface abstraction, etc.

Maven and the Plexus container makes writing Maven plugins a breeze. Baking functionality into a maven build is really pretty trivial and I have had a lot of success with GMaven plugins for applying static analysis to a build: verifying that all properties in a resource bundle are actually referenced in a web application for instance. It’s an added bonus that you can easily test your plugin for Maven… with Maven.

The Seam framework also provides a very nice IOC container and it has been a real pleasure to leverage that power in a real-world application. It certainly facillitates testing – my preferred stack is TestNG with Unitils to add easy annotation support. It’s the simple things like @TestedObject to clearly specify intent and @InjectInto to mock out dependencies that make testing outside of the container as painless as possible. Not only does it ease testing, it encourages good modularization of functionality.

Guice is comparatively the new kid on the block, and the dependency injection framework I have the least experience with, but again the idea is sound, and having another implementation that can take advantage of history is a good thing. Webbeans aims to take the paradigm to the next level, and it will be interesting to see how that implementation evolves. Anyway you want to cut it, the picture is pretty clear – don’t hardcode your dependencies – inject them!

I am a… Functional Programmer?

Somehow, since I started writing code – I started to get it! Closures now make sense to me, currying does not sound like a cooking technique and I realized that however you code certain fundamentals apply.

  • write the code
  • test the hell out of the code
  • make sure the code gets USED, because this is the only way you’re going to find the bugs you didn’t think of in your tests(*see one line above). And no, you didn’t think of everything one line above.

The real point here is don’t discriminate – use the right tools for the job and get the most out of them you can, whether it’s functional VS procedural, Ant VS Maven, etc ad infinitum. Each tool brings a slightly different skillset to the table and if you want to make your programming life easier, it does pay to know which to use when (and how much). Beyond that, taking the time to pry and prod at the tools you use challenges your assumptions and gives you a greater appreciation of just exactly what is ‘going on’ when you hit the Big Green Go button on your build.
Not to mention that all of the tools/frameworks I’ve described here have LOTS of daily users AND represent some of the most executed(and IMO best written) code out there in the Java+ community. As a developer, you can’t help but benefit from digging into such code.
Whatever you do, don’t stay stuck in the past. It just doesn’t make a whole lot of sense when what you’re really after is to make your job as easy and painless as possible to do.

Reblog this post [with Zemanta]

16 Jul, 2009

Presenting a Groovy/Griffon talk

Posted by: TheKaptain In: Development

I’ve been asked by my friend and co-worker Manfred Moser to give a presentation at next month’s Vancouver Island Java user’s group meeting, and silly me I said yes before remembering that speaking in front of people always makes me feel quesy and light-headed. Thanks Manfred for the kind invitation; I’ll do my best to make it a good show.

No sooner had Manfred let loose a message on the Tweetosphere than Andres Almiray very graciously offered up some free copies of the upcoming book Griffon in Action to give away at the meeting. Thanks for that Andres!

The company I work for, Genologics, also gave me permission to publish a presentation that I gave recently at work as a Groovy primer for other members of the development staff. Thanks for that Cliff!

I demonstrated some code in SwingPad and created an application using a GMaven archetype to show off some of the sweetness that Groovy adds to the Java toolbox. It’s worth noting that even though that page doesn’t say it, GMaven recently released a 1.0 final verison(NICE!)

I’ve attached the presentation and some of the source code examples for anyone who might be interested, including the maven project that contains a variety of MOP, builder and GDK extension samples.

GroovyTalk

groovyDemo

SwingPad1

GroovyMailRoute

Prefusebuilder

SwingThreadingExample

Reblog this post [with Zemanta]

16 Jul, 2009

Going old school – Apache Camel mailing lists ftw!

Posted by: TheKaptain In: Development

I’ve been learning a lot about Apache Camel at work recently and am so very glad that I signed up for the mailing list a couple of weeks back.

Was scratching my head recently about why my headers were mysteriously disappearing from some messages and fortunately I read the mailing list before deep diving into the Camel source to find the problem. Somebody else came across this exact problem and pointed it out on the mailing list. In a beautiful display of same day service, a response was posted back to the forum by one of the developers. He filed a bug report and committed a fix within hours. Nice job Willen Jiang!

This is a great example of open source collaboration, as far as I’m concerned – and it saved me a lot of debugging thank-you-very-much!  This kind of care and attention in the community surrounding Camel makes me feel a lot more comfortable about leveraging it to solve some tricky integration problems at work. And the mailing list has been a wealth of knowledge in many other ways as well, guiding me to a lot of resources that I wouldn’t have otherwise known about.

If you’re a developer using Camel I highly recommend signing up for the mailing list.

Reblog this post [with Zemanta]

05 Jul, 2009

iPhone 3.0 and Bluetooth Stereo

Posted by: TheKaptain In: Cool Toys

One of the unexpected benefits of the recent 3.0 update to ithe Phone/iTouch operating system is the rebirth of my Motorola S9 bluetooth headset. I originally bought a pair of these on special from tigerdirect.ca ($19.99 as I recall) to use with a MacBook Pro and they were pretty hit and miss – I eventually gave up on them because everytime the connection dropped the laptop speakers would immediatley blare out whatever I was listening to.

I’d pretty much shelved them until I was reading over the list of new features and saw the new support for bluetooth stereo. Sure enough I dug the headset out of a box, charged it up and took the dogs for a walk – with beautiful wireless stereo sound piped out of my iPhone. The connection was very solid and the sound was at least comparable to the earbuds that come with the iPhone.

A quick test indicates that the microphone works great for phone calls as well, making these a great alternative to the earbuds. The lack of wires is a big bonus since the majority of the time when I’m listening to music from the iPhone it’s when I’m out with the dogs – and they do love to jump up and “accidentally” rip the earbuds off my head.

I thought I was doing pretty great with cut and paste and spotlight in the new feature set, and I get this added bonus for the same price as the rest: free :). Thanks Apple! I can even almost forgive you the $10 charge to update the iTouch OS(tsk tsk).

If you’re interested in a good headset for the iPhone, here’s a nice article with some alternatives. I’m also EXTREMELY glad to see that I seem to have gotten a good deal on the headset, since they’re still listed online at $49.95US and I paid less than half of that, including shipping and handling. Thanks tigerdirect.ca!

Motorola S9 bluetooth stereo headset

Reblog this post [with Zemanta]

Recently the company I work for has decided to make the move from an internally hosted Microsoft Exchange solution to a Google Apps hosted answer, and I couldn’t be happier. On a Mac, the Entourage client wasn’t entirely bad. But it did hog memory, disk space and processor and require at least one hard quit each and every day. Other than that it was just fine.

I’ve been a long time fan of GMail, and I have tried a bunch of the other ‘major players’ in the email game over the years: Netscape, Yahoo, .Mac, Hotmail and every silly @provider.com webmail account that they give you with your inet subscription. Those last have all been universally hideous pits where nothing but spam goes to die, BTW. GMail in general kicks them all. Put it together with Firefox and some of the excellent available extensions and you see where web apps can really shine. Enough touchy feely stuff, what I needed to know this week was how Google Apps could replace some of the key features I depended on from Exchange, and here’s what I came up with.

Feature Comparison

Feature Exchange Google Apps
Organize content Folders Labels, a superior alternative to folders in every way
Route incoming content Mail Rules applied to incoming email Filters to label and archive incoming emails
Search Form style criteria, simple and advanced Full text natural search and advanced syntax options – nobody beats Google for search
Conversations Replies only Nested ‘natural’ conversations – really shines for things like Crucible reviews or Wiki commentary
Startup time 60 seconds + Under 10 seconds
Tasks Good support, ‘My Day’ app kind of annoying Good support, but UI components were more than little ugly and overlaid other view components on initial try
Document support Download attachments to disk Online edit or view of all common document formats, including ability to share editing live
Storage capacity Regulated by Exchange server(less than a couple of GB is a guess in our particular deployment) 25 GB
Offline capability Never noticed a problem working offline. Then again I’m hardly ever offline. Gears, works for the majority if not all of Google Apps
Personalization None? Themes, browser adds-ons(Bless you LifeHacker!), lots of available configurability
Messaging None Browser based, jabber compatible – which means iChat compatible
Audio chat None Browser based, seamless and good quality with Macbook Pro built in speaker/mic
Video chat None
Browser based, seamless and good quality with Macbook Pro built in speaker/mic/iSight
Webclient Yes. Abysmal without any effective search capability First and foremost
Thick client Entourage, other clients available but less effective in my experience Lots, Mail.app preferred IMO
Mobile Never once had a problem using iPhone with exchange iPhone Google app covers the spectrum, Mail application integrates pretty seamlessly

OK, so I didn’t make a huge secret out of it with the blog title where I stand on this faceoff, but having managed to achieve in a few hours what it took me days and lots of Googling(irony intended) to do with Entourage is pretty compelling. I was able to transfer content, establish essentially the same organizational structure, and replace each and every Entourage/Exchange feature I care about with less than two hours of fiddling. Google Labs, Firefox extensions and just the general “hugeness” of the Google community promise me far better access to updates and enhancements than I could ever hope to get (at least for free) from the Microsoft alternative.

I will not say for one minute that Entourage and Exchange did not work for me. They did what they were meant to do, and in a lot of cases(especially on the iPhone) they did it very well. But even in just a pure browser environment, where a lot of the UI “bling” still doesn’t keep pace with a competing desktop application, the general functionality and usability of Google Apps just plain outshines Entourage – and a lot of other email clients as well. Exchange server VS Google for mail – well the one is only as good as the machine you host it on, and is subject to any availability problems that machine might have. Google is pretty much good everywhere, anytime.

Reblog this post [with Zemanta]