Tomcat & IntelliJ – Deploy war files outside webapps folder

At present I am working on developing an Android application that needs to be supported by a slew of REST services hosted in the cloud. I chose Google App Engine based on its support for Java, Groovy and most importantly Spring. I developed a Spring MVC based REST application and used ContentNegotiatingViewResolver to negotiate content based on request URL extensions. For example, an XML response will be returned if the request URL ends with .xml, a JSON response for .json and an HTML response if he URL doesn’t have any extension. Don’t get me started on Accept Header versus URL extension based content negotiation. That is a rant for another day.

I was attempting to Serialize a Map<Enum, List<Model>>. All was well and I was able to retrieve both HTML and JSON representations, but when I tested retrieving the XML representation, JAXB complained that it cannot handle a Map instance in the root although Jackson was totally cool about it. As usual, Googling revealed that JAXB expected a Container class at its root which I didn’t want to create. I didn’t want to give up either. So, I tried my luck using XStreamMarshaller. This time GAE complained that XStream used a restricted API. WTH?

Just out of curiosity, I wanted to check if XStreamMarshaller would work as expected when used outside of GAE. So, I created a Tomcat context file “myapp.xml” with the following definition and carefully placed it inside TOMCAT_HOME/conf/Catalina/localhost. I could have just started Tomcat from TOMCAT_HOME/bin/startup.bat to check if it works, but being an IDEA addict, I created a Run Configuration for the IDEA Tomcat plugin and started the server from inside IDEA. But the app refused to even be discovered, let alone be deployed. After a few frustrated attempts, I tried starting Tomcat directly outside IDEA. Thankfully the app got deployed successfully and to my surprise, the XStreamMarshaller skillfully streamed out the serialized XML. Problem Solved!

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="PATH_TO_MY_APP"
         reloadable="true"
         path="/myapp">
</Context>

But, why didn’t the app get deployed when I started Tomcat from inside IDEA? After all, I have linked IDEA to my local Tomcat installation and the script it executes is clearly in my TOMCAT_HOME/bin folder. Then, why why why in the world does the app refuse to be discovered? The solution came in the form of CATALINA_BASE. It seems that IDEA copies the contents of TOMCAT_HOME/conf folder into its HOME folder with some name like Unnamed_MyApp and sets this folder to be the CATALINA_BASE. That explains why “myapp.xml” is so totally ignored by Tomcat. Then, I navigated to “Tomcat Run Configuration -> Startup/Connection -> Environment Variables” and added CATALINA_BASE as an environment variable and pointed it to your local TOMCAT_HOME folder. After this configuration change IDEA started Tomcat as expected and my app was both discovered and deployed. Another Problem Solved!

But the real problem – JAXB complaining about Map and GAE rejecting XStreamMarshaller as restricted – is yet to be solved. Maybe I should try one of the CastorMarshaller, XmlBeansMarshaller or JibxMarshaller.

Any ideas?

Ceylon – Yet Another JVM Language (YAJL)

It is all too familiar, yet surprising; it is all too common, yet shocking; to see yet another JVM language created to scratch an itch that countless other languages are already trying to solve.

Of course Java is not expressive enough, it doesn’t have higher order functions, it doesn’t have modularity as a language feature, it doesn’t have clean way to do meta-programming, it does NOT have so many more features we love and does have so many more features we hate. These are most of what has frustrated Gavin King (the creator of Hibernate) as well and made him think about creating a new language – Ceylon. A few days ago, in his presentation at the QCon Beijing 2011 he gave a first glimpse of the language features and a few code snippets showing its beauty.

A lot of people have raised concerns and expressed strong opinions questioning a need for yet another language. Scala fans, the Groovy(++) camp, Gosu and Fantom hackers all think that Ceylon does not solve anything that is not solved already or could have been solved by just contributing to one of these modern languages. So, I am not going to be yet another anti Ceylon person but I am not a fan either.

I believe Ceylon is more of a strategic approach from RedHat than a language created out of true necessity. They would like to control a language and its followers like most other giant companies do today. Think about it. Oracle is controlling Java, Microsoft is controlling C# (VB, VC++, etc), Google is controlling Go (and Python?), Apple is controlling Objective C and VMWare is controlling Groovy. RedHat has just joined the party leaving only IBM out of the equation. I am sure they are not far behind. I just sincerely hope that they adopt an existing language (Scala?) instead of creating yet another one.

That said, the language itself looks cool, is very expressive and adds a lot of syntactic sweetness to say the least. I just wanted to highlight a few of them here…

String Interpolation:
In Java we use a “+” sign for string concatenation. There is no concept of string interpolation in either Java or Scala. In Groovy ${} construct is used while Ruby uses #{}. Ceylon’s syntax looks better than either of them though. It uses a “space” as the string interpolation operator and the result looks a lot cleaner. Don’t you think?

String name;
writeLine("Hello " name "!");

Getter:
In Java we use getXxx() methods to get a property value. This looks like a method and quacks like a method and does not give the feeling of accessing a property at all. In Ceylon, a very simple innovation has resulted in much more succinct getter methods. They have decided to get rid of paranthesis to both define and call getter methods. Look at the last line of the following snippet. Does it look like a method call? NO. Does it look like accessing a property? Of course it does !!!

class Counter() {
   variable Natural count := 0;
   shared Natural currentCount {
      return count;
   }
}
Counter c = new Counter();
writeLine(c.currentCount);

Constructor:
In Ceylon there is no separate constructor. The class definition itself acts as a constructor as shown below. Since, there is no concept of method or operator overloading in Ceylon there is no necessity to have a separate method and this syntax induces a “Why didn’t I think of this before ?” moment… The necessity for an overloaded method is handled by optional /defaulted parameters concept. So, you don’t have to worry too much about it…

class Customer (String cName, Natural cAge, Date cDob) {
   variable String name :=  cName;
   …
}

Builder:
With the support of named parameters and higher-order functions and quite a bit of thought, a syntactic structure as expressive as given below has been achieved in a general purpose and statically typed language like Ceylon.

Html hello {
   Head head { title = "Squares"; }
   Body body {
      Div {
         cssClass = "greeting";
         "Hello" name "!";
      }
   }

And then there is the rest of the now so common features like array like access to Sequences (equivalent of List in Java), higher-order functions, Closures, Currying, etc

It is not like I loved every single feature of Ceylon. I hated a few, but I am reserving that rant for another post…

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.

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()