Tomcat 5.5 and above doesn’t need the JDK

Most of us who install Tomcat on our development machines wouldn’t have noticed that Tomcat versions before 5.5 required the full blown Java Development Kit (JDK) to be installed on the machine. Just installing the Java Runtime Environment (JRE) wasn’t enough. The JDK is meant for developers to be able to compile Java programs, and has the development tools such as the compiler, debugger and other development libraries. Tomcat versions prior to 5.5 used the Java compiler that comes with the JDK to compile JSP pages at runtime and consequently required a full blown JDK.

Tomcat versions 5.5 and above have a Java compiler (the Eclipse JDT Java compiler) packaged along with it. Now, this is used to compile the JSP pages dynamically instead of the JDK compiler. Hence, it is enough if we just install JRE starting from Tomcat version 5.5 and above.

Groovy: List Operations

Anybody who has programmed in Java for sometime would attest to how frustrated they could get while operating on the Collection API. Even simple operations demand unnecessary lines of code increasing the LOC and reducing expressiveness of the intended logic. Fortunately, Java has noticed the pain and has been adding utility classes to the Collections API to improve readability of the code since Java 5. Even better, there are a couple of libraries, Lambdaj and op4j, that implement the powerful Fluent interface that takes readability to the next higher plane.

Libraries and utilities are good for Java, but we are still bound by the constraints of the language itself. Isn’t it? That is where Groovy steps in. Groovy is in a totally different league when it comes to expressiveness of code. It was designed with the “Principle of least surprise” in mind. Best of all, Groovy source compiles to java byte-code thereby only adding a jar file as a dependency to your projects.

To whet your appetite, here are a few code snippets for list operations in Groovy that will make you smile…

Create lists in groovy: Keeping the literal notation the same, you can define different implementations of the collections framework

// Returns an ArrayList by default
def personalities = ["Steve", "Bill", "Larry"]

// Returns a LinkedList
def personalities = ["Steve", "Bill", "Larry"] as LinkedList

// Returns a String array
def personalities = ["Steve", "Bill", "Larry"] as String[]

Basic list operations: There are many more operations. But this gives you a feel for how easy it is to add, remove and retrieve elements off of the list

// Defines a list of strings
def personalities = ["Steve", "Bill", "Larry"]

// Retrieving an element
assert "Larry" == personalities[2]

// Retrieving a range of elements
assert ["Bill", "Larry"] == personalities [1..2]

// Adding an element
assert ["Steve","Bill","Larry","Scott"] == (personalities< <"Scott")

// Removing an element
assert ["Steve", "Bill", "Larry"] == (personalities -= ["Scott"])

Other cool operations: These are some operations that you typically don't find in Java. Correct usage of these operations will lead you towards strong and idiomatic Groovy programming.

// Transforming one list into another
assert [2,4,6] == [1,2,3].collect{ it*2 }

// Finding every element matching the closure
assert [1,3] == [1,2,3].findAll{ it % 2 == 1 }

// Print each element of the list
[1,2,3].each{ println it }

// Spread Dot operator operates on every element of the list
assert [1,2,3] == ["a", "bb", "ccc"]*.size()   

// Spread operator is used to pass a list as method parameters
def add(a, b, c) { return a+b+c }
assert 6 == add(*[1,2,3])

There are many many more features that support the Collections framework. To list it all is not the intention of this post, rather this post is intended to give a quick feel for how easy it is to write Groovy code when dealing with a Collection of objects.

Groovy: No-arg constructor is always there

Do you usually write a no-arg constructor for your Java classes? You don’t have to – unless you need to initialize something in that constructor. Behind the scenes, the Java compiler adds the no-arg constructor directly into the byte-code if none is provided. But when one or more overloaded constructors are provided for that class, the compiler doesn’t add the default no-arg constructor to the byte-code. This has been part of Java since the beginning.

Fast forward to today. I was doing some work with Groovy. All of a sudden, i realized that i forgot to add a no-arg constructor inspite of adding multiple constructors to a class and the code was still working without errors. That is when I found out that the Groovy compiler adds the no-arg constructor to the byte-code regardless of other overloaded constructors. I just thought I should share this learning with the world and hence this blog!

Does JRuby, Jython, Scala and other JVM languages do it too? Will have to check…

Don’t get me started on why i should use overloaded constructors when Groovy provides dynamic constructors out of the box. The short answer is “API Requirement” from the client.

Hibernate never stops surprising me

I have a simple form in my web application where a user can fill in his personal details and address details. User specific fields include firstName, middleName and lastName while Address specific fields include street, city and zip. On the server side, I have POJOs for User and Address. Finally I use Hibernate to map these POJOs to the database. Since, the Address will not be used outside the context of the User, I decided to map it as a Component of the User class.

The User class and its corresponding mapping is given below:

@Entity @Table(name = "user")
public class User {

     @Column(name = "first_name")
     private String firstName;
     
     @Column(name = "middle_name")
     private String middleName;
     
     @Column(name = "last_name")
     private String lastName;
    
     @Embedded
     private Address homeAddress;

     ... Getters and Setters
}

The Address class is mapped to User as a component. You can see the specifics of the mapping below.

@Embeddable
public class Address {
     @Column(name = "address_street")
     private String street;
     
     @Column(name = "address_city")
     private String city;
     
     @Column(name = "address_state")
     private String state;

     ... Getters and Setters
}

As you may already know, mapping components using hibernate is a very useful feature. This feature and support for nested components and components referring to other entities are the primary source of support for rich and fine grained domain model in hibernate. But while i was using Component mapping, I recently stepped on an interesting Feature (or it could be an Issue) and I was happily surprised by it.

Want to know the surprise? Keep reading…

In this case you map an Address as a value type using @Embedded annotation in the “homeAddress” field of the User class. The Address class itself is declared to be @Emeddable. This is the standard Hibernate/JPA way to map value types. The Address class has street, city and zip and it gets stored into the same table as the User class’s table. Now, when you insert an instance of User into the database, while specifying all null values for Address‘s fields maybe because the user didn’t give his address, then what would you expect in return at some point in time when you retrieve this User back from the database.

I for one expected user.getAddress() will return an Address instance. Then address.getStreet() will return null. But that is not what happened. user.getAddress() returned null by itself. That was interesting and even helped me in my case because, if the user hasn’t given any details for his home address, then it probably means that his address itself is not there in the system. So, returning null for getAddress() is semantically the right thing to do. I was surprised and when i checked the hibernate documentation it was even mentioned there that if all properties of a component are null, then the component itself is considered null.

In another situation this could have been bad, I don’t know, but for my purpose I was happily surprised with this nice touch from hibernate. These kind of small things is what differentiates a great product from a good product. Ain’t it?

Final Modifier for method arguments. What do you think?

The IT industry today is sodden with TLAs like SOA, ESB… and FLAs like AJAX, SOAP and JUNK. i was thinking about refreshing myself with some fundamentals again. Blogging about a basic concept may not be cool, but refreshing – don’t you think? I know what you are thinking. You are thinking that i am digressing too much. Ok, lets cut to the chase.

One of the best practices i follow religiously is to use final modifiers for method arguments where applicable. This is “supposedly” a best-practice written by somebody somewhere. Regardless of whether it is documented as a best-practice or not it is an important concept to understand and use. I have 2 valid reasons to use them for my method arguments.

First, final variables cannot be modified. Come on, everybody knows that. Maybe, but its use is significantly enhanced when it is a method argument and more importantly when you are in a big team environment.

Lets assume that a method takes List as its argument. Typically, the intention of that method is to work with the List – add to it, remove elements from it, use its elements in some way, sort it and what not. Consequently when the method returns, the caller can investigate the passed List and work with the modifications the callee introduced. But the caller will be on for a big surprise if the callee changes the instance that reference points to itself.

We know that java uses “Pass by copy of reference”. If the callee points the received reference to a different List and then modifies this List, the caller will not be able to see any change at all. This is because the copy of the reference held by the caller still points to the same old List. More often than not this is done by mistake and is not intentional. If such a behavior is intentional, final modifier is not required. In all other cases since this leads to bugs in code, it is a good practice to use final modifier for method arguments.

Second, if the method uses the infamous anonymous inner-class syntax to do something, and that inner class wants to use the methods arguments, java requires those arguments to be declared final. This is more of a rule than a valid reason.

Are there more valid reasons? I will be glad to receive information from you guys.

Hibernate: Why should I Force Discriminator?

Hibernate is an ambitious project that aims to be a complete solution to the problem of managing persistent data in java. Even with such an arduous task before them, the hibernate team tries very hard to expose a simple API for developers like us. Still, the complexity behind the API shows its ugly face time and again and I believe it is unavoidable as long as the mismatch between Object and Relational world exists.

That said, although I have worked with hibernate for many years and have been its advocate in all my organizations, I keep facing newer issues and keep finding newer ways to work with it efficiently and effectively. Recently, when I was working for nboomi.com, I faced an issue when mapping a OneToMany relationship to the sub-classes of “Single Table Inheritance” strategy. After a frustrating couple of hours of debugging I finally landed on the correct solution. So, I thought other developers who will travel this path could get benefited and started writing this blog post.

Let me explain the issue I faced with an example. Assume you have a normal User Entity with the typical id, version and loginId properties. Assume this User can have many AboutUs sections and many Service sections. You don’t need to be an architect to model them as OneToMany relationships from User. So, I modelled UserAboutSection and UserServiceSection entities and created a OneToMany relationship between User and these entities. Looking at the commonality between these two, I decided to factor out the common fields into a superclass called UserSection. Now, both UserAboutSection and UserServiceSection extends UserSection. I chose to map this Inheritance hierarchy using “Single Table Inheritance” strategy to keep it simple and since most of the fields were common and only a few were specific.

The User entity is given below. Notice the List<UserAboutSection> and a List<UserServiceSection> mapped using OneToMany relationship.

The getters, setters, adders, imports and static imports are omitted for brevity.

@Entity @Table(name = "user")
public class User extends BaseEntity {

    @Column(name = "login_id")
    private String loginId;

    @Column(name = "password")
    private String password;

    ...

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserAboutSection> aboutUs;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserServiceSection> services;

    ... Getters, Setters and Adders
}

Here goes the UserSection entity that acts as the base class in this “Single Table Inheritance” strategy. Hibernate uses the @DiscriminatorColumn annotation to distinguish between sub-classes.

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Here goes the UserAboutSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("ABOUT")
public class UserAboutSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserAboutSection
}

Here goes the UserServiceSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("SERVICE")
public class UserServiceSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserServiceSection
}

Pretty straightforward… huh! When you try to retrieve an instance of User along with its aboutUs and services collections eagerly (or lazily – doesn’t matter), what do you expect?

I expected an instance of User with the aboutUs collection filled with only UserAboutSection instances and the services collection filled with only UserServiceSection instances corresponding to only the rows they represent in the database. And I believe this expectation is valid, because that is what the mapping looks like and hibernate also has all the information it needs to make this work.

But I got something different. Both the aboutUs and services collections had all the UserSection rows that belong to this User. I mean, aboutUs collection had all the UserSection instances including UserAboutSection and UserServiceSection instances. This was surprising because hibernate has all the information it needs to populate the right instances.

After quite a bit of debugging, googling and RTFM-ing I landed upon @ForceDiscriminator annotation. This annotation has to be applied to the base class in the Inheritance hierarchy for “Single Table Inheritance” strategy. In my case, I had to apply it to UserSection entity. The UserSection entity after applying this annotation is given below…

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
@ForceDiscriminator
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Once I ask hibernate to Force Discriminiator, it is happy and populates the aboutUs and services collections with its respective instances.

Ok, Problem Solved! But why did I have to tell hibernate to Force Discriminator. Shouldn’t that be the default behaviour. Is it a bug in hibernate or is it a feature? Am I missing something? If any one of you hibernate fans have walked this path and know the answer, please feel free to drop in a comment. I sincerely hope this post will be a valuable time-saver for other hibernate developers who step on this Bug/Feature.

Groovy: Private is not private

If I have to name one language that I thoroughly enjoy programming in, it has got to be Groovy. I work with it almost on a daily basis although the platform for my day job doesn’t require it. Personally, I love groovy for the obvious reasons and also for the not so obvious reason – It has some sentimental value to me since I have been following this language since its inception.

That said, one of the things that surprised me while using groovy was its Private modifier. It seems groovy completely ignores its mere presence. I am used to the unavailability of privates in javascript for a pretty long time and so I religiously follow naming conventions to separate private from public assets. I have never used similar naming conventions for groovy because I thought the concept of private existed. Unfortunately, I was wrong. Let us dive into a few short examples to see what I mean…

class User {
   String firstName;
}

def user = new User()
user.firstName = "John"
println user.firstName

This is a typical POGO. firstName is private by default. Public Setters and Getters are generated automatically at compile time. When the caller uses this property, he will actually be using the public Setter or Getter instead of directly accessing the field. Typical groovy stuff…

On the flip side, if you don’t want groovy to generate the Getters and Setters at compile time, then you should modify the field using a private keyword as shown in the snippet below.

class User {
   private String firstName;
}

def user = new User()
user.firstName = "John"
println user.firstName

Now, groovy won’t generate the Getters and Setters for firstName. But if you run the above code, you will be surprised to see that the field is still accessible. The caller is able to set and get the firstName.

I thought maybe groovy is probably not suppressing the Getter and Setter generation due to some bug and that is the reason why this field is still accessible. But that is not the case, as you can see in the next example. In this snippet, you can see that I use groovy’s “.@” syntax to access the field directly and the field is still accessible.

class User {
   private String firstName;
}

def user = new User()
user.@firstName = "John"
println user.@firstName

Then I tried private methods. No surprise there, since I got used to the surprise by now. Yes, the private methods are also directly accessible.

class User {
   private String firstName;
   private String name() {
      firstName;
   }
}

def user = new User()
user.@firstName = "John"
println user.name()

Thank god though. There was some silver lining. Java classes aren’t able to access all of these private fields, properties and methods. It is only the other groovy scripts that are able to access it. The example below will demonstrate the same.

class User {
   private String firstName;
}

class UserTest {
   public static void main(String args[]) {
      User user = new User();
      System.out.println(user.firstName); // compile error
      System.out.println(user.getFirstName()); // compile error
      System.out.println(user.name()); // compile error
   }
}

After some googling, I found a few jira issues here, here and here.

After going through these links, it looks like this was a bug in groovy from the beginning, but nobody bothered to fix it because for such a dynamically and reflectively capable language private is just a documentation anyways.

Groovy – Syntax sugar for map keys

Groovy keeps putting a smile on my face again and again. This time it is for a cool syntax sugar that i found useful as well as clean. Lets get to the chase without too much of chit-chat.

Let’s create a Map of people and their ages in groovy using literal syntax. You could write it this way…

Map people = [
   "John" : 24,
   "Steve" : 30,
   "Cathy" : 25 
];

Pretty straight-forward! But don’t you think the double quote around each name looks like unnecessary clutter. I thought so and I guess groovy developers thought so too. So, they made it easy on us and allowed us to just ignore the quotes. So, the same map can be written as shown below, without the quotes and groovy still understands what you mean. In this case, groovy considers the key to be of String data type. If you used numeric literals for keys, groovy would consider them as their appropriate numeric type.

Map people = [
   John : 24,
   Steve : 30,
   Cathy : 25 
];

You may ask that this is well and good, but then how will i use my variables as keys? It so happens that many a times when we create a map using literal syntax we use only string literals or numeric literals as keys and not a variable reference. So, this syntax covers for most of the cases. But, if you definitely need to use your variables as keys, then you have two options.

The first option is to not use literal syntax. Instead you could just use normal map.put() syntax to get the job done. But this doesn’t look groovy.

Map people;
people.put(name1, 24)
people.put(name2, 30)
people.put(name3, 25)

The second option is to wrap the keys with parenthesis as shown below. This way you are explicitly telling groovy to consider them as variable references.

Map people = [
   (name1) : 24,
   (name2) : 30,
   (name3) : 25 
];

Ok, now this syntax is more cluttered than the original one with quotes wrapped around them. I agree. But, considering the frequency with which this is going to be used, I think this is a better alternative.

Groovy – Add Static & Instance methods dynamically

Like Ruby and other dynamic languages in its Genre, groovy also allows us to add methods to a class dynamically at runtime. You need not restrict yourself to adding instance methods alone. Even static methods are supported.

To showcase this, let’s create a class called User with name and email properties.

class User {
  String name, email
}

Now, let’s add a static newInstance() method to create a new instance of this class. Technically speaking this is not a method; it is a closure. This example is contrived, but I hope you get the idea.

User.metaClass.static.newInstance = {name, email ->
  new User(name: name, email: email)
}

Now, let’s add an instance method to update the “name” property of User. Here, the “delegate” references the “this” pointer. Remember, this is not a method; it is a closure.

User.metaClass.updateName = { name ->
  delegate.name = name
}

The very next line you can start creating a new instance of user using this dynamically added static method and instance method as shown below.

User user = User.newInstance('ganesh', 'g@e.com')
assert 'ganesh' == user.name

user.updateName ("ganeshji")
assert "ganeshji" == user.name

It is not necessary that you add these new methods right below the class. You can add it anywhere in your code. As long as you call these methods after the lines that define these new methods are executed you should be fine.

Groovy – Java keyword as a method name

Java, like any other language has reserved words. We are not allowed to use these words as method names or variable names. Most of the times that is fine, but sometimes we may find that these reserved words form the best name for a method. Helplessly, with just a sigh, we name the method with its synonym instead.

Groovy, being a JVM language, has the same set of restrictions. But since it is completely dynamic in nature, it handles this scenario a bit differently from within and allows us to use reserved words as method names. All you have to do is wrap the method name within quotes during method definition as shown below and you are done. Cool isn’t it?

class User {
  String name

  String "delete"() {
    name = ""
  }
}
def user = new User(name: "ganesh")
assert "" == user.delete()