Cool Groovy features 3 – ConfigSlurper

In Java configuration properties can only be key-value pairs e.g.
db_user="admin"
db_password="letmein"
Wouldn’t it be nice to be able to group configuration properties? This is exactly what you can do in Groovy using the ConfigSlurper class. It allows you to write config files like the following:
db {
    user="admin"
    password="letmein"
}

commands{
    setup="GET_DATABASE,GET_JBOSS_SERVER_FILES,CHECK_JBOSS_SERVER_FILES"
    refresh="GET_DATABASE"
    check="CHECK_JBOSS_SERVER_FILES,CHECK_APACHE_WORKER_PROPERTIES"
}
These properties are read in as a map of maps, and you can access each property by using the dot operator on the configuration object:
config = new ConfigSlurper().parse(new File("myApp.config").toURL())
dbUser = config.db.user
dbPassword = config.db.root
For more info, see: http://groovy.codehaus.org/ConfigSlurper
Posted in Groovy | Tagged | Leave a comment

Using group by without an aggregate function

It is interesting to find that in MySQL, you can write the following:
select * from orders o join order_tender ot on ot.order_id = o.id group by o.id
This doesn’t really make sense, since the purpose of “group by” is to group records when you are using an aggregate function, such as sum. e.g.
select o.id, sum(ot.value) from orders o join order_tender ot on 
ot.order_id = o.id group by o.id
If you want to read some ideas as to why the MySQL folks permit this, see: http://stackoverflow.com/questions/1225144/why-does-mysql-allow-group-by-queries-without-aggregate-functions
Posted in MySQL | Tagged | Leave a comment

Coffeescript – improved javascript

An interesting attempt to create a more powerful syntax for javascript:

http://jashkenas.github.com/coffee-script/

 

Posted in Javascript | Tagged | Leave a comment

Groovy – real life example

In my job we often have spreadsheets of data that we want to quickly turn into SQL scripts. (Yes, I know there are plenty of ways of importing spreadsheets into databases, but our DBAs want SQL scripts!) This is fairly simple task and could be done just by manually editing the CSV file and doing a few regular expression. However, one little annoyance is that you need to quote some of the columns in order to create a valid SQL script. Writing a Java program to do this would be quite time consuming, but with Groovy it is very quick. Here is the script I wrote:
File inputFile = new File("C:storestable.csv")
File outputFile = new File("C:storestable_quoted.csv")

// starts at 1
List columnsToQuote = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,23,24,25,27]

outputFile.delete()

inputFile.eachLine { line ->     
  String[] columns = line.split(",")    
  StringBuffer newLine = new StringBuffer()    
  // iterate over the columns and quote the ones that need it    
  columns.eachWithIndex{ column, i ->        
    if (columnsToQuote.contains(i+1)) {            
      newLine.append("'").append(column).append("'")        
    }        
    else {            
      newLine.append(column)        
    }        
    if (i != columns.length-1) {            
      newLine.append(",")        
    }    
  }    
  newLine.append("n")    
  // write the line into the output file    
  outputFile.append(newLine.toString())
}
You can see how much easier this is with Groovy – the files can be defined in a single line of code and you’re not forced to deal with lots of possible exceptions when doing the file IO. In addition, Groovy provides a very useful iteration closure – eachWithIndex – that allows you to iterate over a collection and be given both the object and its index on each iteration.
Posted in Groovy | Tagged | Leave a comment

Spring MVC versus Struts

This question is often asked, but tends to be answered by people who have a strong allegiance to Spring and tend to give a massive list of advantages, which often boil down to a much smaller list of actual advantages. I think the real advantages are:

1.       Based on interfaces, not classes, so easier for your classes to inherit from your own classes.

2.       Provides request interceptors that can do things to requests before or after your page controllers.

3.       No form objects. Binds directly to your Hibernate POJOs, so you don’t have to convert between ActionForms and Hibernate POJOs.

Posted in Spring | Tagged | Leave a comment

Cool Groovy features 2 – closures

A closure is a block of code (i.e. a function). In Java, to define a block of code, you would have to write a method or a class, but in Groovy you can write a closure and assign it to a variable, or simply declare it inline, when you want to use it. You can write methods to accept closures, which means you can write powerful and flexible APIs far more easily than with Java. In Java, if you want callers to be able to pass objects in to your API,  you would typically find yourself using the strategy pattern to define an interface that the classes of those objects must implement. Even if the caller only needs to write a couple of lines of code, this means that you have to write an interface, and they have to write an entire class, just to contain that code. By contrast, with Groovy, you can just write a method that declares that it accepts a closure. I’ll give a very simple example. I work in eCommerce, so let’s use the example of an eCommerce platform that uses a class called PromotionManager to deal with the promotions on the website. When writing this class, you don’t know all of the ways the rest of the platform might like to interact with the promotions. You need to provide a very flexible way of accessing the promotions, whilst still hiding the implementation details. With Groovy you could write a method like forEachPromo that iterates over all promotions and invokes a closure on each one:
class PromotionManager {
    Set<String> promos = new HashSet<String>()

    def PromotionManager() {
        promos.add "10% off"
        promos.add "Buy one get one free"
        promos.add "Free delivery"
    }

    def forEachPromo(Closure c) {
        for (String s : promos) {
            c(s)
        }
    }
}
So, for example, if a caller wanted to print out each promotion, they could call your API with:
PromotionManager pm = new PromotionManager()
 pm.forEachPromo {promo -> println promo }
For more details about closures, check out: http://groovy.codehaus.org/Closures+-+Informal+Guide
Posted in Groovy | Tagged | Leave a comment

Cool Groovy features 1 – no need for getters and setters

Consider the following Java code:

public class Customer{
private int id;
private String firstName;
private String lastName;
public void setId(int id){
this.id = id;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public int getId(){
return id;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return secondName;
}
}

In Groovy this would be defined as:

class Customer{
int id
String firstName
String lastName
}

In Groovy, if you don’t put an access modifier on an instance variable, it is assumed to be private,and Groovy generates public getters and setters for it. This means classes aren’t littered with getter and setter code, but just contain code that actually does stuff.

Posted in Groovy | Tagged | Leave a comment

Groovy

One of the technologies I’ve been playing around with recently is the Groovy language. It’s an interesting language as it offers a number of features not found in Java. Some of the these are features of the language itself, some are just additional libraries.

Some of the language features are:

  • No need for getters and setters.
  • Closures
  • Mixins
  • Native lists and maps
  • Native regular expressions
  • Native support for markup languages like HTML or XML
  • Native interaction with Java.

and some of the library features are:

  • Simplified file IO.
  • Simplified database and SQL usage.
  • Simplified XML parsing.
  • Better support for configuration files with the ConfigSlurper class.
  • Built in support for creating mocks and stubs for testing purposes.

If you haven’t already played around with Groovy, I’d strongly encourage you to take a look. The main website is:

http://groovy.codehaus.org

You can get the Eclipse plugin from:

http://groovy.codehaus.org/Eclipse+Plugin

Posted in Groovy | Tagged | Leave a comment

Hiding table columns with jQuery

A nice example of hiding a table column using jQuery is here:

http://www.devcurry.com/2009/07/hide-table-column-with-single-line-of.html

That example shows how to hide a single column. How might you do it if you have a row of tickboxes, one for each column? Here is one way:

    $(“input”).each( function(i) {
        $(this).change(function() {
            var columnId = i + 1;
            if (this.checked) {
                $(“td:nth-child(” + columnId + “)”).show();
            }
            else {
                $(“td:nth-child(” + columnId + “)”).hide();
            }
        });
    });

You need to add one to the iteration counter because the iteration starts from 0 but the nth-child selection starts from 1.

Posted in jQuery | Tagged , | Leave a comment

Printing Ant classpaths

Debugging Ant classpaths can be a bit of a pain, but the following link shows you how to print them out:

http://www.javalobby.org/java/forums/t71033.html

Even better, you can do a pretty version using:

http://blog.andrewbeacock.com/2005/08/pretty-printing-java-classpaths-using.html

Posted in Ant, Java | Tagged , | Leave a comment