Groovy 2.0 released

Introduces the option for static type checking.

http://www.h-online.com/open/news/item/Groovy-2-0-introduces-static-type-checking-and-compiling-1628119.html

Posted in Uncategorized | Comments Off

Why isn’t Groovy/Grails more widespread among Java developers?

Recently I was following an interesting discussion in the LinkedIn Groovy Group which I decided to wrap up a bit in this article.

As you might know, the Groovy and Grails combo really is one of the best Java MVC solutions out there, adding a lot of nice features to the developer’s toolbox like dynamic typing, scripting styled speed of coding, metaclass programming, the convention over configuration paradigm, etc. From a Java point of view, integration couldn’t be better as Groovy is compiled together with Java and runs smoothly on the classic JVM. As a result, many products are already integrating and supporting their classes to be Groovy classes (Spring, Seam, Jasper, …) and more and more job adds appear mentioning these technologies. So, being the true Swiss army knife that Groovy/Grails is, where’s the catch?

A handful of reasons were collected in the thread, which basically narrow down to customer/management doubts, developer’s hesitation, the existence of several alternatives and in general the existence of several misconceptions.

Most customers and managers prefer to stay safe and sound, put their trust in proven technologies and aren’t too fond of change. Apart from policital and/or licensing issues, Java and Java solutions are mostly regarded as sufficient and reliable. Add to this the nice wealth of Spring/Hibernate resources out there, and its active, vibrant community. When it comes to adapting a new, dynamic language like Groovy (one of their bigger fears), a risk is introduced and hesitation follows.

Developers on the other hand cope with a different kind of fear. In a continuous, overwhelming stream of new technologies some of them become steering pioneers, but there’s an undeniable, biding herd that dreads change. True, Groovy initially requires you to walk the extra mile and do some studying, especially compared to Java which is more commonly taught and known. This explains why Groovy usually doesn’t attract newcomers. However, once you experience it, it’s almost incredible just how more efficient it is (Groovy’s XML handling and Grail’s scaffolding just to pick some examples). As such, architects play an important role and should get their teams acquainted, starting in Unit tests for example.

A third reason is the existence of other mature products. Spring/Hibernate has almost become the de facto standard, SpringRoo entices with its RAD feel while still being Java, Ruby/Rails convinces with all its power under the hood, and let’s not forget the JS market with GWT/Vaadin, Sencha, Dojo, all of them delivering amazing rich clients. In my opinion, developers shouldn’t think of Groovy as opposed, but juxtaposed to Java. As being mentioned before, integration with Java is almost seamless which is why developers should enrich themselves and their Java code with Groovy. The combination is perfect, and after all intended from day one. And finally, I can’t stress enough that the link between Groovy and Grails is not mandatory, which brings us to several misconceptions.

Some people think the Gr8 technologies are only useful in new development. However, Groovy & Grails are far from tightly coupled, which makes Groovy perfectly useful in legacy code. Furthermore, Groovy/Grails’ runtime performance isn’t awkward either. New Groovy/Grails releases improve performance constantly and while it is true that Groovy is somewhat slower, it is hardly noticeable unless doing really complex calculations (and even then you can still nest Java code to optimize). The LinkedIn thread shows several testimonials of successful high-end, multi-user, multi-hits per second projects written in Groovy/Grails, and you should really check out the link we tweeted earlier this week about Grails and heavy load.
Another misconception is that tooling and documentation are almost non-existent. Admitted, Eclipse and Netbeans have some catching up to do, but STS and IntelliJ offer really, really good Groovy & Grails support. Documentation with plenty of examples is available for both technologies on their websites and there are already several great, in-depth books out there (even this week, Manning did a mailing promoting the Gr8 technologies). There is also a nice, growing community sharing their expertise, innovations (and jokes) online. So if you want to get up & running in no time check out sites like Slideshare, etc. to find tons of shared presentations and I strongly advise using Twitter to stay up to date.

Conclusion:
Every new product needs time to convince people and get a decent following. As the introduction to this article already proved, Groovy/Grails IS being picked up by more and more people. So just be patient.

Finally, I picked these three interesting quotes:

Give Groovy and Grails a bit of a chance, it’s gaining traction amongst “serious” Java programmers who have refused to look at scripting languages in the past. I say time is the missing ingredient here, not lack of effort.
- Ewald Horn

I think the Groovy community doesn’t emphasize enough that Groovy is just a really good scripting language for all uses. Groovy should be pitched as a replacement for tasks that would otherwise have been written in Perl or Python.
-Uli Moszkowicz

There are reasons to use Java and we do have a mix.
-Joseph Nusairat

Posted in Grails, Groovy | 3 Comments

GPars – DataFlow Concurrency

Ever felt the need to do some parallel processing in your application? This is where GPars (Groovy Parallel Systems) comes to the rescue.

Although GPars offers a variety of concurrency models, I’d like to focus on DataFlow concurrency.
This is what the documentation has to say about DataFlow

“Dataflow concurrency offers an alternative concurrency model, which is inherently safe and robust. It puts emphasis on the data and their flow though your processes instead of the actual processes that manipulate the data. Dataflow algorithms relieve developers from dealing with live-locks, race-conditions and make dead-locks deterministic and thus 100% reproducible. If you don’t get dead-locks in tests you won’t get them in production.”

Let us consider the following problem; you need to build a customer object but the the data needed to do this comes from a bunch of different services. The code may look something like this:

def customer = new Customer()

customer.personal = someservice.getPersonalInfo(customerId)
customer.address = someservice.getAddressInfo(customerId)
customer.appleProducts = someservice.getAppleProducts(customerId)

println customer.toString()

Here the time to build the customer object is equal to the response times of the three service calls added together.

To fix this you probably want to launch the 3 services in separate threads and start writing a lot of code trying to get everything sorted out OR you could use DataFlow.

Using DataFlow the code above will look something like this:

def personal = new DataFlowVariable()
def address = new DataFlowVariable()
def appleProducts = new DataFlowVariable()

task {
    personal << someservice.getPersonalInfo(customerId)
}

task {
    address << someservice.getAddressInfo(customerId)
}

task {
    appleProducts << someservice.getAppleProducts(customerId)
}

def customer = new Customer()
customer.personal = personal.val
customer.address = address.val
customer.appleProducts = appleProducts.val

println customer.toString()

When the value of a DataFlowVariable is read it will block until the value is set (using <<).
In this case the time to build the customer object will be equal to the longest response time of a service call.

Only one issue remains; when one of the service calls throws an exception the value of the DataFlowVariable is never set so reading from it will result in a block!

To solve this issue I've created the following utility method

class DataFlowUtils {

    static public def handleExecution(def clojure) {
        def wrappedResult = null
        try {
            def clojureResult = clojure.call()
            wrappedResult = {clojureResult}
        } catch (all) {
            wrappedResult = {throw all}
        }

        wrappedResult
    }
}

And use it as follows

def personal = new DataFlowVariable()
def address = new DataFlowVariable()
def appleProducts = new DataFlowVariable()

task {
    personal << DataFlowUtils.handleExecution {
        someservice.getPersonalInfo(customerId)
    }
}

task {
    address << DataFlowUtils.handleExecution {
        someservice.getAddressInfo(customerId)
    }
}

task {
    appleProducts << DataFlowUtils.handleExecution {
        someservice.getAppleProducts(customerId)
    }
}

def customer = new Customer()
customer.personal = personal.val.call()
customer.address = address.val.call()
customer.appleProducts = appleProducts.val.call()

println customer.toString()

If an exception occurs the DataFlowVariable is set correctly, so reading them will not block the code anymore and the exception is thrown.

UPDATE: As Vaclav Pech pointed out, since the recent 0.12 version, DataFlow has build-in support for re-throwing the exception using the get() method

That's it, more info about gpars can be found here

Posted in Concurrency, Grails, Groovy | 2 Comments

Summer of Technology slides available

Here are the slides for the Groovy presentation I did for this year’s Contribute Summer of Technology. Feel free to leave feedback and suggest improvements. :)

SOT_Groovy

Posted in Groovy, Seminar | Leave a comment

The Builder Pattern

Quite recently, I had to prepare a presentation which a.o. covered the Builder pattern. I noticed that several developers couldn’t really identify the pattern, so I figured to explain it in short here.

As wikipedia states; “The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects.”

Now, this is quite interesting. The idea is to construct a complex object step by step, and implementing these steps separately. In true divide-et-impera style, we can first focus on these small steps which all together form a complex object and have some other class orchestrate these steps.

Speaking of wikipedia, it actually offers a great Java example which has an Orchestrator class – A Cook who can bake pizzas (the Object to be built). The cook knows in what order to create the dough, the topping, etc. For different kinds of pizza however, these small steps are different. Some pizzas require thick dough or foiled dough, some have or won’t have meat, etc. An abstract class PizzaBuilder is shown which sets the interface to follow for these different constructions of the pizza. From that point on specific PizzaBuilders are created;  the HawaianPizzaBuilder, the SpicyPizzaBuilder etc.
Check the example here.

Notice that Groovy offers this Builder pattern at syntax-level using Closures. Actually, Groovy takes it a bit further by providing specific Builders to create tree-based, markup-alike structures. But here again, the whole idea is that its construction is made out of small, specific steps.

For example, Groovy offers a MarkupBuilder which makes it easy to construct XML in code; XML elements are created by calling them as if they were methods, and attaching a closure that contains all children of an element. It’s obvious that this structure covers enough to build XML files, but also structures like HTML, Swing, Ant, etc.

Example:

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.records() {
  car(name:'HSV Maloo', make:'Holden', year:2006) {
    country('Australia')
    record(type:'speed', 'Production Pickup Truck with speed of 271kph')
  }
  car(name:'P50', make:'Peel', year:1962) {
    country('Isle of Man')
    record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight')
  }
  car(name:'Royale', make:'Bugatti', year:1931) {
    country('France')
    record(type:'price', 'Most Valuable Car at $15 million')
  }
}

This corresponds with the following XML:

    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>
      </car>
      <car name='P50' make='Peel' year='1962'>
        <country>Isle of Man</country>
        <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
      </car>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>

Not bad right?

By the way, another useful link I found to understand and explain Builders quickly is this one.

Posted in Groovy | Leave a comment

Git-shell

If you want to share your git repository on your server to start working on a project but you don’t want to mess with all the permissions, a thing you can do is creating users and making them log in with git-shell.

  1. Create a new user/password
  2. Add their public rsa key to your .ssh/authorized_keys
  3. sudo vi /etc/passwd
  4. Change /bin/sh for that user to /usr/bin/git-shell

Now the user can clone/push…  anything on your repository, but when he tries to login with a shell he will see:

$ ssh git@gitserver
fatal: What do you think I am? A shell?
Connection to gitserver closed.

Posted in Git | Leave a comment

The groovy stuff about groovy

The two presentations I attended about Groovy Guillaume Laforge showed how he could break down a Java class into a groovy class and still have the same behavior.

This is pretty nifty on itself, but another nice feature every programmer will appreciate is list accessors. Every Java programmer has to do stuff like this daily. For example a collection of objects of class Person which have a property firstname and you want to create a new collection of their firstnames.

So in Java we have to do something like this

List<String> firstNames = new ArrayList<String>();
for (Person person : people) {
    firstNames.add(person.getFirstname());
}
assert firstNames.size().equals(2);

In Groovy we can use an accessor on the list which will call the property on his containing objects creating a new collection. We don’t need to loop anywhere, he will do it implicitly because we say in which property we are interested inside the collection.

assert people.firstName.size() == 2 // The collection
assert people.firstName.join(', ') == 'jos, jef' // The additional printing with a convenience method join

This is only a small feature but it is a good example of boilerplate code I’ve written over and over again for which Groovy has a very gentle single-line solution.

Posted in Uncategorized | Leave a comment

Contribute Summer of Technology 2011

Contribute has, since its start in 2007, focused on the introduction and implementation of the newest ICT technology on the Belgian market.

By continuously investing in knowledge and experience we have become the technology partner of choice for many companies. We would like to share our experience in innovative technologies and are pleased to invite you to our Contribute Summer of Technology. We are proud to present 8 different Seminars during the months July, August and September 2011.

The goal of these seminars is to bring technology enthusiasts up to date with the latest products and standards. Each participant can bring his own powerful laptop, or get one from us during the day, and can get a day of hands-on experience in a variety of technologies. Each seminar is limited to 10 participants and one participant can register for a maximum of 2 sessions.

As a part of this program, Graviti will provide a Groovy/Grails session on September 6th. Groovy is an agile and dynamic language for the Java Virtual Machine, in combination with Grails you have your next Web 2.0 project done in weeks instead of months. Grails delivers a new age of Java web application productivity.

Register now!

Posted in Grails, Groovy, Seminar | 1 Comment

Graviti blog launched

Hello groovy world!

Welcome to the Graviti blog, a C4J (contribute4java) initiative to promote Groovy & Grails. We will try to actively provide information to acquaint you and hopefully get you going with Groovy & Grails. Going from basic tutorials with small use cases to the latest news about the Gr* world.

 

Posted in Grails, Groovy | Leave a comment