Monday, November 10, 2008

Happy Birthday Marines

233 years and counting......

Thursday, October 23, 2008

Creating RESTful services with Jersey and Groovy

It's been a while since I have put anything of substance on here, so I thought I would get back to it. I've been doing a lot of development with Groovy as of late, which I absolutely love. I wanted to combine that with another API that I really like, Jersey. Jersey is the open source JAX-RS (JSR 311) Reference Implementation for building RESTful Web services. So, for a simple service to create I decided on an Announcements service. This service when invoked would look for a file located in the User Home directory and create some HTML to return that would get rendered in the browser. This example also shows why I might want to use Groovy and Jersey together, as I will leverage Groovy's MarkupBuilder to generate the HTML that gets returned. I won't get into the details of how to setup Jersey as they have lots of samples that you can find here, and instead I'll just jump right in to what the source code would look like for my announcement service.


class AnnouncementService {
def announcements = "announcements.txt"
def errorReadingFileText = " - Error reading Announcements, Announcement File may not exist."
def noAnnouncementsText = " - No Announcements for Today"

@Produces (value=["text/html"])
String getHtmlResponse() {
// Return some cliched textual content
return getAnnouncements()

String getAnnouncements() {
def announcement = new File(System.getProperty("user.home") + File.separator + announcements)
def writer = new StringWriter()
def result = new groovy.xml.MarkupBuilder(writer);
result.html {
body {
h1(align: "center", "As of ${date()}")
table(width: "100%", height: "100%") {
td {
if (!announcement.exists()) {
} else if (announcement.text.length() <= 0) {
} else {
announcement?.eachLine {
tr(" - $it")
return writer.toString()

As you can see from the code above that we annotate our class with the @Path annotation. This basically defines your jersey resource. So if you wanted to invoke this resource you URL would be something like http://localhost:8080/sample/announcements where sample is the name of your war you deployed to your application server. In the code you can also see that our method getHtmlResponse() has been annotated with @GET which tells Jersey to call this method when the HTTP Request is a GET Request. So given the same URL noted above, you could type that into a browser and hit enter and it will invoke the announcement resource with a GET request and invoke our method. One other thing to note is the @Produces annotation. This annotation defines the mime type to return your result. In our case we want the result to render as html so we set the type to text/html. This annotation is one that I had to do a little diffrent with Groovy. In Java the annotation would look like @Produces("text/html"), whereas in Groovy I have to specifically call out the value property and enclose the value in brackets like this, @Produces (value=["text/html"]). If I didn't enclose the property in the proper way I got this error when compiling:

Annotation list attributes must use Groovy notation [el1, el2]

The good thing is my IDE (I was using Netbeans) caught this before compile time, and I refrenced this issue to figure out how to get around it.

So, as you can see from my source code that the bulk of the work is taking place in the getAnnouncements() method. This was the reason that I wanted to use Groovy, I could very easily read a file, and based on the content create some html markup that would be returned to the browser. Not much to discuss here, except that MarkupBuilder is very cool. Alright, I think that's it, Good Luck. One last thing is I used Jersey 1.0 and Groovy 1.5.6 to work this example.

Thursday, June 26, 2008

Rapid Web Application Prototypes with Maven and Groovy

Utilizing both Maven and Groovy you can rapidly prototype web apps, and in this blog I'll walk you through exactly how to do that. First we are going to create a simple Maven web app project using the Maven Web App Archetype. If you don't have Maven installed already, go ahead and install it. Now let's create a directory called sandbox, and cd into that directory. Now let's create our project by issuing the following command:

mvn archetype:generate

When prompted to choose a number enter 18 (The Java web application archetype) and hit enter. Next you will be prompted for the groupId, enter com.sample and hit enter, for the artifactId enter sample and hit enter, for the version enter 1.0 and hit enter, and for the package name enter com.sample and hit enter. Confirm you project by entering "Y" and hitting enter. Once finsihed you will have a maven project ready to go for deployment. You should see a sample diretory that was created in /sandbox with a pom.xml file. The pom.xml file is what we will look at next.

Next we need to add the dependency for Groovy to our pom, as well as the Maven Groovy Plugin. We do this by adding the following inside the <build> element in the parent pom:

Now that we have the Groovy Plugin added, lets add the Groovy dependency to the pom as well by adding it inside the <dependencies> element of the pom:

Ok, let's save all that and make sure we can build everything. From /sandbox/sample issue the following command:

mvn clean install

You should now have a successful build, and you could actually deploy the war that gets created (in /sandbox/sample/target you will have sample.war) to an application server such as JBoss. Ok, lets get onto the cool stuff. Groovy has a concept that lets you write normal Java servlets in Groovy, called Groovlets. Groovlets are really easy to work with and have some nice features like implicit variables (e.g. request and response which are bound to the ServletRequest and ServletResponse). So what we are going to do is configure our webapp so that it can handle Groovlets and then create our first Groovlet. We are first going to edit our web.xml which is located at /sandbox/sample/src/main/webapp/WEB-INF/, go ahead an open that up and add the following between the <web-app> elements:

This configures your webapp to compile your .groovy files to bytecode and execute your script when called. Next we need to create our Groovlet and then we are done. So, in /sandbox/sample/src/main/webapp create a file called Sample.groovy. We are going to create a simple Groovlet that accepts an HTTP GET request and has a parameter called username. We will process the request and just print out the response. So, go ahead and open up the Sample.groovy file you opened and add the following:

def username = request.getParameter("username")
println "Hello ${username}"
That's it. Rember that the request variable is implicit, meaning it's already bound to the ServletRequest and ready for use. Now we can compile our war, and deploy it to your favorite application server and you are ready to roll. Once deployed navigate to http://localhost:8080/sample/Sample.groovy?username=Chad in your web browser and you should see the print out "Hello Chad".

This is a really nice way to rapidly prototype webapps. I first started looking into this when I needed a servlet that could access the file system and return XML based off my lookup. Obiously using Groovy's nice features that have been added to the JDK for working with Files, and the MarkupBuilder, this task was trivial. Give it a spin and let me know what you think.

Monday, June 9, 2008

Deploying Jersey REST services to Weblogic

I recently had some trouble deploying a REST service using Jersey to Weblogic, specifically Weblogic 9.2. This had me stumped for quite a while as I could deploy my war to JBoss and Tomcat and it worked fine. Finally with an assist from the mailing list I was able to get past the problem and get the war to deploy. As Paul noted, the problem was that the default class scanning technique is not portable across servlet implmentations, so I needed to add the following to my web.xml (after the <servlet-class> element):

<param-value>*';' separated package names*</param-value>

This tells Jersey to use the package scanning instead of the class path scanning. Now all you have to do is insert your package names in the last param value (replace the *';' with your package name(s) seperated by ';').

For more detail on this issue see the issue that was filed with Jersey here.

Thursday, May 29, 2008

Groovy SQL - That was easy

I got the chance today to get my hands dirty with GSQL (Groovy's Built in support for SQL), and I must say that it was rather easy. What I needed to do was connect to an embedded Derby database, parse a file, and populate the table with the results. Not to hard right. So, here is what my data looked like in the file I needed to parse:


The best part about this was as I read each line in the file I added the data to the dataset for the table I was populating. The following shows a quick example of how to do this:

static parseData(path) {
println("parsing data for the following path: $path")
def loc = new File(path)

//Get an instance to the derby database
def sql = Sql.newInstance("jdbc:derby:dashboard;create=true", "org.apache.derby.jdbc.EmbeddedDriver")

//For Each line in the file, split the line based on the comma
loc.splitEachLine(',') {fields ->
def pid = fields[1]
def locResult = Double.parseDouble(fields[2])
def tloc = Double.parseDouble(fields[3])
def timeStamp = getDate(fields[0])

//Get the linesofcode dataset from the database
def ds = sql.dataSet("linesofcode")
//Add the properties from the current line in the file to the dataset.
println "Done Parsing Data"
So as you can see the first thing I do is get a new instance to my database:

def sql = Sql.newInstance("jdbc:derby:dashboard;create=true", "org.apache.derby.jdbc.EmbeddedDriver")

Next is the best part. I loop over each line in the file, splitting the line based of the "," and then dive right in poplulating my dataset with ds.add().

That was easy right? I thought so.

Thursday, May 8, 2008

JavaOne Day Two - All about SOA

As you can tell from my title I spent the bulk of my day attending sessions geared towards SOA. I have to say that the day started out fantastic when I attended the Integration Profile for Glassfish v3. This TS was given by Keith Babo and Andi Egloff of Sun and they did a phenomenal job of introducing us to Project Fuji, Sun's next generation integration runtime. I was pleasantly surprised to see when Keith gave the demo that they used a couple of the binding components that we, Gestalt, had developed. The good news is that Keith has put up a screencast of the demo he showed this morning that shows of Project Fuji, and also our RSS and XMPP components. Project Fuji and Glassfish ESB look very promising and I will be following them closely.

The rest of the day I spent my time going to various sessions on SOA. There is still a lot of talk about whether or not SCA is competing with JBI, or are they compliments. To be honest I'm still not sure my self, but we will see how it plays out.

I ended the day with the JBI 2.0 BOF. I really like the way the expert group is approaching this. They are doing a code first spec. What the heck does that mean? Basically what they are doing is going to be putting out code to the community implementing their ideas and gauges the communities feedback. Once they get the feedback they need then they will put it into the spec. I think this approach is better in that it will get the community involved in helping drive the specification, we just need to contribute and provide the expert group the feedback.

Well, that's a short and sweet for today, I'll try and get something up again tomorrow.

Wednesday, May 7, 2008

JavaOne - Day One

I know it's a day late, but I thought I would try and get this down for anyone who cares. JavaOne kicked off with a bang in the morning with the General Session in the morning. We were all greeted with some rockin music and dancers performing on stage. Half way through James Goosling graced us with his presence and launched T-Shirts into the crowd. Rich Green of Sun gave the talk and really focused on Java and how it runs everywhere with sample from Amazon, Sony Ericson, a very cool Facebook application, and concluded with a demo from Neil Young (Yeah, the rocker Neil Young). All in all, it was a very good start to JavaOne.

After the General Session I started hitting up some of the technical sessions. I hit up JRuby at first to see how that project is progressing. I must say, it's coming along really nice. The biggest take away was the IDE support that NetBeans is providing, it's really nice and improving every day.

I was also fortunate enough to get invited to listen in on the JBI expert group. I must say I was rather impressed with what was discussed. The biggest take away was make sure you keep track of JBI and keep an eye on it over the coming months, I know I will be watching very closely.

The next session I went to was upcoming Java language changes. Some of the highlights were the following:

  • Multi-catch statements
  • Safe re-throw
  • Modular programming
  • Annotations enhancement
The biggest focus was on the additional support for annotations.

Next up was secure mashups with OpenAjax. This was of particular interest to me since my team is current working on some mashup technologies. The stuff that OpenAjax is putting out is definitely worth keeping tabs on.

Finally to end the day I attended the Grails in depth session. I know that I have a particulair interest in Groovy and Grails, but I've got to say that Grails freaking rocks. If your team is doing Agile development and need to get quick rapid proof of concepts done, then you really need to take a good hard look at Grails. With its use of industry standards such as Hibernate and Spring, and the 40+ plugins that have been developed you'd be almost crazy to start from scratch and have to write all of that stuff yourself.

All in all it was a good first day, now I've got to get ready for day two. I'll try and get that up tonight or first thing tomorrow morning.

Tuesday, May 6, 2008

Pre JavaOne

Well, I'm fortunate enough to be in San Francisco for this years JavaOne confrence. I'm going to try and update my blog throughout the day on some of the highlights. Last night I went to the G2One meetup and listend to Guillaume Laforge give the state of the union on the Groovy and Grails community. There is a lot of excitement around booth of these communities and rightfully so. They are really cranking and getting a solid community behind them. Some interesting takeways from last night:

  • Groovy is going to be making several releases of the coming months, hoping to get to 2.0 by the end of the year.
  • Groovy has really been focusing on their performance and plans to improve it even more.
  • Grails has some really nice new features coming down the pipe for 1.1
Some other tidbids include
  • Look for support for Groovy/Grails in NetBeans 6.5
  • LinkedIn is using Grails to build one of their new services and been really happy with it and it's integration with their legacy systems.
  • Contegix has selected Grails as their platform of choice and talked about why.
It was a good start last night, and thanks to the G2One and NFJS folks for throwing a really nice function. More to come today on Day one at the concfrence.

Friday, April 25, 2008

Oh how I miss these days!!

I sometimes miss the days of being in the Military (Semper Fi), and being in the desert with nothing to do, here is a nice little video of what happens when bordem sets in.

Monday, April 21, 2008

Groovy XMLSlurper

If you know anything about Groovy, I'm sure you have seen the XML parsing features it brings to the table. Whether you have seen it or not it is definitely worth mentioning. I feel this is a great tool added to my Java tool chest.

Imagine you have the following XML:

<basketball team="Kansas" status="National Champions">
<name>Brandon Rush</name>
<position>Small Forward</position>
<name>Mario Chalmers</name>
<name>Sherron Collins</name>
<name>Darrel Arthur</name>
<position>Power Forward</position>
<name>Darnell Jackson</name>
<position>Power Forward</position>

Now that you have your XML you want to parse it and put it into a Player object. Let's go ahead and create our Player object:

class Player {
String name
String position
double ptsPerGame
double rebsPerGame

def String toString() {
return "Name: ${name}\r\nPosition: ${position}\r\nPoints Per Game: ${ptsPerGame}\r\nRebs Per Game${rebsPerGame}"

Now that we have our Player class created, lets create a class that will consume the XML create a Player for each Player in the XML:

class ParsePlayers {
private List players

ParsePlayers () {
players = new ArrayList()

def Player[] parsePlayers() {
def data = this.getClass().getResource("/players.xml").text
def xmlSlurper = new XmlSlurper()
def playersXml = xmlSlurper.parseText(data)

playersXml.player.each {
def player = new Player() =
player.position = it.position.text()
player.ptsPerGame = Double.parseDouble(it.'pts-per-game'.text().trim())
player.rebsPerGame = Double.parseDouble(it.'rebs-per-game'.text().trim())

return (Player[])players.toArray()

So, as you can see above that is a pretty simple way to parse XML using XMLSlurper from Groovy. I don't know about you, but that makes working with XML a little bit nicer.

Monday, February 25, 2008

Groovy Stub's

I've been getting the chance to use Groovy a lot more at work lately and it's allowed me to really dig deep into some of the features. One of those being the use of Stub's for Unit testing. This is a fantastic feature and really simple to use. Lets look at the following code below:

def Entries[] getFeed(feedUrl) {
def url = new URL(feedUrl)
def data = url.getText()

def xmlSlurper = new XmlSlurper()
def feed = xmlSlurper.parseText(data)

if (feedType.toLowerCase() == "rss") { { item ->
def rssItem = new Entries()
rssItem.title = item.title =
rssItem.description = item.description = item.pubDate
println (rssItem)
entries.add (rssItem)
} else {
feed.entry.each { entry ->
def atomEntry = new Entries()

atomEntry.title = entry.title =[0].@href
atomEntry.description = entry.content = entry.published
entries.add (atomEntry)
return (Entries[]) entries.toArray()

This code is pretty straight forward in that we are taking a URL for an RSS feed and going to read the feed and create an Entries object for each entry in the feed (this is a great example of how to use Groovy to consume rss feeds). The problem with unit testing this is the following section:

def url = new URL(feedUrl)
def data = url.getText()

I needed a way to stub this out so I could isolate this code at the unit level. Using Groovy's StubFor was the perfect way, the following is what my unit test looked like:

def void testAtomFeed() {
def block = new RssDataBlock()
block.engineURL = ""
block.feedType = "atom"
def urlStub = new StubFor(URL)
urlStub.demand.getText {
return "my mock data"
urlStub.use {
def entries = block.getFeed("")
assertEquals("", block.generateOutput(),
"Title:${title}\r\nDescription:${description}\r\nLink:${link}\r\nPublished Date: ${date}")

The import thing that is going on is we are creating a Stub for the URL class (new StubFor(URL)), and intercepting when the getText() method gets called we are going to return our sample data set. To use the stub you simply call urlStub.use and in the closure you execute your test. As you can see above, I call getFeed() with my bogus URL; and then I assert that the output I was expecting (generateOutput()pretty prints my output for me) is equal to what I actually got.

This is very powerful and makes my life a whole lot easier. The more I use Groovy, the more I'm impressed (I've even been able to convert some of my co-workers :) ). Stay tuned, I plan on posting about Groovlets next......

Monday, January 21, 2008

A Socket Client for Groovy

Groovy Rocks!! I needed a simple client that would write data to a socket to test this application I was working on so I wrote it in Java since I had done that before. My code looked like the following:

public static void main(String[] args) throws Exception {
String data = "test data";
InputStream is = new ByteArrayInputStream(data.getBytes());

Socket socket = new Socket("localhost", 8282);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader bw = new BufferedReader(new InputStreamReader(

BufferedReader br = new BufferedReader(new InputStreamReader(is));
String userInput;

if ((userInput = br.readLine()) != null) {

After I got done, I was curious how I could do this same sort of thing in Groovy. So, I spun up the Groovy Shell and away I went.....

s = new Socket("localhost", 8283)
s << "Groovy Rocks"

... I type go in my groovy shell and I'm done. Seriously, 3 lines of code and a quick shell to test it out. Groovy is awesome.