Tuesday, August 26, 2008

BGG takes top honors at CapJug Meeting!

Last week at the August meeting of the Capital Java User Group, we had several excellent books to give away. Apress had sent us a copy of Beginning Groovy and Grails: From Novice to Professional, which Shawn Hartsock has dubbed "BGG". The Pragmatic Programmers sent us several of their recent titles (special thanks to Jared Richardson, author of one of my favorites: Ship It!) and we had one left from an earlier supply from O'Reilly.

When we have this many books to give out we like to treat it like a poll. So, I'll describe each of the books and then start drawing names. Each winner can take their pick from the books remaining. I am happy to announce that Beginning Groovy and Grails was the first pick! Congratulations to Christopher, Joseph and James! The CapJug pick of the months is quite an honor. We still have another copy to give away next month so we'll see if they can hold the record for a second month.

It is great to see the growing interest and excitement in Groovy and Grails at our Java User Group and I know that ours is not unique. Java User Groups all over the world are beginning to embrace the next generation of Java!

Thursday, August 14, 2008

Out of the Box

I'm beginning to think that the term "out of the box" has jumped the shark.

Anyone involved in software development has heard, read and probably used this term at one time or another. If you are involved in Groovy and Grails development you probably hear it all the time. I think Scott Davis holds the record for most uses of the term in a single presentation. In the book "Beginning Groovy and Grails: From Novice to Professional" (an excellent book, by the way, which I am almost done poring over and will write a review on soon), this term appears about a dozen times. It's easy to understand why since Grails does come with so many features and so many things that just work right out of... well you know what I mean.

So, you ask, what's the big deal? It's just plain wrong, that's what. It's difficult these days to find software or software development tools that were ever in a box to begin with. This is especially true with open source tools like Groovy and Grails. And I am worried that using this kind of inaccurate term is going to affect the way others look at our profession. I mean, as programmers we're supposed to be at least somewhat intelligent, but what are people going to think when they hear us talking about features and benefits coming out of a box that never existed?

I think this is a serious problem and not an easy one to solve. How else can we express the magic of things like GORM without using so many words that we get jaw cramps. Nonetheless, it's a problem that must be solved. If we do not want people to start lumping us in with the likes of used car salesmen or, even worse, lawyers, we had better get started looking for another, more accurate, term.

I think we can do it if we all work together and if we're willing to think outside the box.

Saturday, August 2, 2008

No Fluff in Green Bay

Well, I guess there might be fluff in Green Bay, but not here at the Radisson Hotel and Conference Center where the Northern Wisconsin Software Symposium is being held. Here there is no fluff just stuff and good stuff at that. There's just a bit less of it than usual. Green Bay is not a big town so the NWSS is not a big conference. It's kind of like a No Fluffette.

But what it lacks in quantity it more than makes up for in quality! The speaker lineup, though limited, is top notch. Yesterday (Fri) Jeff Brown was extolling the goodness that is Groovy and Grails, Venkat Subramaniam was covering Agile development, mocking for unit testing, and testing our Java kung fu, and capping off the lineup was Mark Richards who gave a two-fer on Enterprise messaging with JMS followed by an SOA class.

Then after we'd all finished up our steak dinners Venkat treated us to a brand new keynote that was eye-opening, inspiring and hilarious all at the same time.

So far, so good. Now to head downstairs for day two. Today Jared Richardson, Brian Sletten and, local boy, John Carnell will be joining us. It'll be great as long as my head doesn't explode.

Tuesday, July 15, 2008

Grails and EJB 3 Session Beans

A while back I was working on a Grails project that needed to integrate with an EJB2 application via session beans. So, when my current project had a similar need I thought 'piece of cake!'. As it happens it was a piece of cake that wasn't that easy to get at.

The problem came about because we were working with EJB3 this time. I had heard that it should work the same but it doesn't. I eventually found that it is still extremely easy to do (this is Grails we're talking about after all) it's just different.

For starters the Spring class that we used to connect to an EJB2 session bean, SimpleRemoteStatelessSessionProxyFactoryBean (I wonder if there is a TinyURL! for class names) was not working with EJB3. Several people on the forums said that it should, but our application did not believe them. It turns out that there is a Spring class that does work with EJB3 and it even has a shorter name! The JndiObjectFactoryBean is a general purpose Factory for looking up JNDI objects and making them available to other beans. The JndiObjectFactoryBean will even use the JndiTemplate that I had setup before, though I'll show it again so you don't have to hunt it down.

So now we should be in business. Except that it didn't work. When using the SimpleRemoteStatelessSessionProxyFactoryBean we could just use the Session Bean's simple interface name, which was also its JNDI name. That was not working with the JndiObjectFactoryBean. This critter wanted a fully qualified, certified and USDA approved JNDI name. The bummer here is that this is vendor specific. So the rest of this will work for BEAORACLE WebLogic but it might be completely different for your app server.

First we have to make sure that the EJB3 session bean has the mappedName attribute in the @Stateless annotation. (In our case ...mappedName="CoverageSession") That makes up the first part of the JNDI name. Then we add a # symbol and top it off with the fully qualified name of the Remote Interface. So we ended up with something like this for our JNDI name: CoverageSession#org.blah.app.ejb.session.ICoverageSessionRemote Once we gave it that mouthful it was happy.

Here I'll show a slightly modified version of our resources.groovy file:


beans = {
ejbJndi(org.springframework.jndi.JndiTemplate){
environment = [
"java.naming.factory.initial" : "weblogic.jndi.WLInitialContextFactory",
"java.naming.provider.url" : "t3://some.enterprise.server:7001"
"java.naming.security.principal" : "dave",
"java.naming.security.credentials" : "1234" ]}

coverageSession(org.springframework.jndi.JndiObjectFactoryBean){
jndiName = "CoverageSession#org.blah.app.ejb.session.ICoverageSessionRemote"
jndiTemplate = ref("ejbJndi")
}
}


Now we can inject the session bean into a Grails Service and we can call its methods to retrieve and save EJB3 entities from that portion of the application that was written before we began using Grails and it all just works and I'm happy!

I'm still hoping to be able to convert the entire application to Grails before we go production but in case we can't the ability to integrate Grails with all of our existing Java technologies is a big help.

Wednesday, June 11, 2008

Grails to the Rescue

Everyone in software development knows what a death march is but not as many are familiar with a forlorn hope. The term comes from the time when wars were fought over fortresses or walled cities. Cannons were used to make a breach in the walls big enough to send troops into. Needless to say, the first troops to go into those breaches did not fare well. So, the first unit to be sent in became known as a forlorn hope. It was often a volunteer unit with the promise of fame, glory and military advancement for those that survived.

I've read and heard about death march software projects before but I had never experienced one until recently. About a month ago I was put in charge of a 2 1/2 year JSF/EJB project that had 8 months left and was less than half done. (By the way, that's my excuse for not blogging in a while. It's not as good as Glen Smith's excuse but it's all I've got) At first this was quite disheartening. I assessed the situation and made it clear that there was no way that we could meet the deadline but was told to just "do the best we could". So, I marched on...

Then, as I dug into the project more, I discovered that there were major pieces of the application that were isolated enough that they could be done in a different environment without impacting the overall system. Grails to the rescue. We are now using Grails for most of the remaining development and gaining momentum quickly. Two of the four of us on this team have Grails experience but the other two are coming up to speed very quickly and, I might add, enjoying their jobs more than they have for some time. One of the pleasant side effects of using Groovy and Grails is increased job satisfaction and motivation.

While there's still much to do and it is still unlikely that we will make that deadline, switching from JSF/EJB to Grails has turned this death march into a forlorn hope. In this case the reward won't be fame, glory and promotion but it just might be another IT shop standardizing on Groovy and Grails. Here's hoping!

Saturday, May 17, 2008

Introducing JugList.net

As part of a homeschool project and a way to try out their budding Groovy & Grails development skills, two of my sons, Zak and Ben, have been working on a website. Their creation is now up and running and you can see it at www.juglist.net

JugList.Net is a searchable directory of Java User Groups around the world.


You can search for a JUG (Java User Group) by name, city, state/province or country. If you still can't find a JUG in your area, there is a link to an article, by yours truly, that gives some tips on starting your own group.

Java User Groups are a valuable resource for honing your craft and building your career. They also provide a great way for experienced programmers to give a little back to the community. If you are not involved in a JUG yet, then check out juglist.net and find one near you.

Friday, May 16, 2008

Another way to use Groovy in the Enterprise

Another great way to incorporate Groovy into your enterprise Java projects is Groovy SQL. GSql makes JDBC access so easy and Groovy's seamless Java integration and dynamic nature provides for some interesting ways to take advantage of it.

In this example we'll build a utility class that will use convention to turn an SQL select statement into a List of data transfer objects.

Our goal here is to take an SQL statement and a Class, execute that statement and use the results to populate instances of the Class. We will assume the convention of camel case for object properties and underscores for database fields, so that a field called LAST_NAME would be mapped to a property called lastName. We will also assume that the select statement will only return fields that have a corresponding property in the Class.

So let's see what this might look like:

static Collection getData(String query, Class clazz, Connection con){
def field = ''
def result = []
def sql = new Sql(con)
sql.rows(query).each {row ->
def dto = clazz.newInstance()
row.keySet().each{
field = toCamelCase(it)
dto."${field}" = row."${it}"
}
result << dto
}
result
}


After defining a few variables, we create our groovy.sql.Sql object using the constructor that takes a Connection. This will allow us to use Connections provided by an application server such as WebLogic or WebSphere. We could easily change this method to take advantage of the other constructors.

Next we'll call the rows method of the Sql class, which will execute the SQL statement and return an ArrayList of GroovyRowResults. Now we'll iterate through this ArrayList and create a new instance of our DTO class for each row. GroovyRowResult implements the Map interface so we can loop through its keys with row.keySet().each. This will give us each of the fields in that row and we will turn them into property names with a call to the toCamelCase() method (which we'll look at shortly). Notice how we take advantage of GStrings to dynamically access properties of our DTO as well as keys of the row map. After we assign each of the fields in the row to properties of the DTO instance we add it to the result List. When the loop is done we just return the List. Obviously, more can be done to make this more robust and more flexible, but it's pretty amazing how easy it was to build a Groovy class that can replace tons of repetitive Java code.

Let's take a look at how we could use this class from a Java project:

...
Connection con = getConnectionFromPool();
String query = "SELECT FIRST_NAME, LAST_NAME, EMAIL FROM MEMBER";
Collection members = GroovyData.getData(query, MemberDTO.class, con);
...

That's all there is to it.

Now let's take a quick look at the toCamelCase() method we mentioned above. This doesn't directly have anything to do with the purpose of this post, but I am hoping that someone might see this and offer a groovier way to do the same thing. Basically the goal is to take a database field name such as LAST_NAME and turn it into a camelCase string like lastName. Here's how I did it:

static String toCamelCase(String val){
def sb = new StringBuffer()
Boolean newWord = false
val.toLowerCase().each{
if (it == '_')
newWord = true
else{
if (newWord){
newWord = false
sb << it.toUpperCase()
}
else
sb << it
}
}
sb.toString()
}

I was sure there was a groovier way to do this and, sure enough, Andres Almiray came up with this awesome improvement:

static String toCamelCase(String val){
def result = val.split("_").collect { word ->
word[0].toUpperCase() + word[1..-1].toLowerCase()
}.join("")
result[0].toLowerCase() + result[1..-1]
}

Thanks Andres! And if that wasn't groovy enough, Ted Naleid came up with this cool mix of regular expressions and meta-programming. Good stuff Ted!

def camelCaseConverter(orig) {
orig.toLowerCase().replaceAll(/_(\w)?/) { wholeMatch, firstLetter ->
firstLetter?.toUpperCase() ?: ""
}
}

String.metaClass.toCamelCase = {->
camelCaseConverter(delegate)
}