December 19, 2015

India 2015 - The Deep South Part 1

What is this blog about?

It is about curiosity in understanding the nature of things.





It is about a happy journey.






  It is about a very short snapshot of life in India.

















Its basic theme is plurality.



Plurality is embedded in India. You can see it everywhere in India; from simple lives of millions to the overindulgence of the rich, from atheist to polytheistic views, and from genuine happiness to unbearable sadness. It implies that the distance between two extremes of a population is huge (statistically speaking) and we struggle with its implications. Neither extremes make much sense at the surface and this can force us to ask some basic questions. The rest of this series of blogs is about these questions and attempts to answers them.



November 19, 2015

India 2015 - Thirumal Nayak Palace Part 3

This is the last of the 3 part blog on the Thirumal Nayak Palace in Srivilliputtur.

The Audience Chamber
This is the grander chamber of the two. It has a pretty cool vaulted ceiling and a graded, rectangular-shaped dome.

The vaulted ceiling.
A symbol commemorating Queen Victoria is on the left side of this picture. See Part 1 for a full picture.
Looking up towards the ceiling in the audience chamber.

A picture depicting how the palace used to look.
The audience chamber is directly under the rectangular shaped roof.

In the center of the chamber there is a small prison and a witness box that were used by the British and Indian courts.

The witness box and prison. 
A farther view of the chamber showing the witness box and part of the prison.
 The chamber is supported by 10 pillars. Here is a view of the space in between the pillars and the wall.

This picture was taken just behind the prison.
I decided to write about this less-known palace in Srivilliputtur to show that buildings get repurposed and continuously evolve. In this particular case, the Archeological Society of India deemed this building to be a historically significant one back in the 1920s but because it was still being used by the courts, proper care and maintenance could not be done until the courts moved to a different location. I am glad that in a country as old as India there is still some importance to preserve history but I can only wonder how many such buildings have been ruined in a rush to the future.

November 17, 2015

India 2015 - Thirumal Nayak Palace Part 2

Continued...

King's residential chamber
As you enter the residential chamber, you see a replica stupa and some boards explaining the palace and the king in detail.

Residential chamber
I found the main attraction to be is its octagonal ceiling, which is covered with a colourful simple design, and lit by 16 windows.

Ceiling in residential chamber. The outer dome is circular.
The arches leading to the ceiling are simple yet pretty.

8 arches for 8 sides of the ceiling. The edge of the arches have stucco floral designs. 
The pillars surrounding the centre of the chamber.
Some of the original paintings can still be seen on the walls.

Some original wall paintings have been recovered, which is quite amazing given the fact that it was pretty much destroyed over 400 years. 
Painting of a dancing girl? I imagine some dye last longer than the others (looks like the red and black lasted).

Original painting





November 16, 2015

India 2015 - Thirumal Nayak's Palace Part 1

King Thirumal Nayak's Palace located on South Car street in Srivilliputtur is a hidden gem. It is a perfect example of how a building from 1600s underwent transition from a king's temporary residence to a functioning court house until 2007. It was renovated and is now open for public as a protected monument by the Archeological Society of India.  Here is the first part of a series about this palace and the King himself.

The palace as seen across the street. You can climb up a small house across the building to see the domes. There is a limit on the height of buildings in the vicinity. No one seems to care to follow this limit but most importantly there is no enforcement of this limit.

The palace as seen across the street. The verandah in the front was added later.
The palace from an angle. The Andal temple is to the left of this picture.
The palace was used by the king when he visited the deity in the nearby Andal temple. This palace is quite moderate compared to his palace in Madurai. It covers approximately 15,000 sq. ft.

Palace layout

Palace layout that shows to the chambers at the back while there is a large open entrance in the front. 
As you enter, you are greeted by these majestic pillars and arches.

The entrance. The logs in between the column of pillars of were added later to support the building.
The palace has two large chambers; one for the king and one for his audience.  The audience chamber has a vaulted roof and is supported by 10 pillars and arches.
The larger chamber was used to receive audience.
 The residential chamber is an octagonal structure supported by 8 arches.
The smaller chamber was used by the king. A replica of a stupa (in Meenakshi Amman temple in Madurai?) is placed in the centre of the chamber.
The palace was used a court at least since 1870 by the British and then by the Indian government after independence. The British modifications are very easy to spot:

The vaulted ceiling in the larger chamber that this inscribed to commemorate the reign of Queen Victoria, the Empress of India at the time.

Srivilliputtur also lost its sons for the distant great war in Europe. I imagine volunteers from here signed up mostly for the pay rather than out of patriotic duty.

A small structure built for the coronation of King and Emperor Edward VII (Queen Victoria's son) in 1903.
There was room with this title. No idea what it could have been.

November 9, 2015

India 2015 - Pennington Library

One of the oldest libraries around this area of Tamil Nadu is the Pennington Public Library in Srivilliputtur. It was founded in 1875 and named after then collector of Thirunelveli, Mr. Pennington. It currently contains about 75,000 books under English, Tamil, Reference, Children and Archives sections. This library is a must to see for its influence in education in this area.

Entrance is just right of this picture.

Entrance. The man on the right is like a guard. You must log in to register before entering.

Library committee members and Lydia

The library is not very big but historically important.

Right next to the library is this gorgeous school (The Hindu High School). There are two of these buildings on either side of the road. One for boys and another one for girls. This one is for boys. The girls' school hasn't been renovated yet.

The Hindu High School.

November 8, 2015

India 2015 - Bike Ride 1

Srivilliputtur lies on the foothills of the Western Ghats mountain range, which known to be a hotspot for biodiversity. It is close to a wildlife sanctuary for the endangered grizzled giant squirrel, which is locally known as Senpaga Thoppu. It is about 10k from my house.  On Aug 6th, Maven, Lydia and I went on a bicycle ride on the road that leads to this sanctuary. Within a kilometre of the ride, the intense noisy traffic disappears and you start to see rural life and wilderness. We rode about 2k before returning back. Lydia took all these photos.

Path to Senpaga Thoppu (as you leave Srivi). Notice how little traffic there is.

Cemetery. Lydia commented how even the cemeteries are crowded here.

A herd of goats. The herder said he has about 200 goats.
Stopped alongside a reservoir before heading back. This pool of water is a hotspot of bird watching, but don't be surprised if you see people using it as their public washroom.
The traffic on this road is mostly from people who work at the farms near by.

Returning back home (my street). My house is on the right closer to the temple on the middle of the road.

November 6, 2015

India 2015 - Arrival

Our trip preparation started a week before our departure and went quite smooth. We left Ottawa on Oct 30th for Chennai via Toronto and Frankfurt. The plane ride was as awesome as it could be with a toddler. We arrived in Chennai on Nov 1st and stayed there till the 3rd. Chennai was crazier than I thought it would be. It had grown exponentially for the past few decades and like all other cities in India, the infrastructure development lags quite a bit behind the commercial growth (and population). If you are a tourist, Chennai is a good place to start your exposure to India as you can get all the amenities, ranging from cushy toiler paper to mega shopping malls and over-the-top luxury. We are not tourists and our intent for a stopover in Chennai before heading to my hometown, Srivilliputtur (Srivi), was to reconnect with family and to rest. Indeed, we had a great time in Chennai but the crazy traffic was getting to us. We left Chennai for Srivi on the Pothigai Express train (overnight journey covering roughly 600km) on Nov 3rd.  We had reserved seats (+ beds) on coach A1 (AC, 2 tier). The train journey was rough as we had to share our narrow hard bed with a toddler, who was jet-lagged and over-stimulated. But one thing I love about Indian trains is the ability to open the door while moving and peek out to get some fresh air. So I did in the morning. It had rained. It was lush greenery and pools of water everywhere. It was quite awesome to experience cool morning breeze. We could taken a flight from Chennai to Madurai, which is about 80km from Srivi but you don't get experience a country over the air.

We reached Srivi at around 7 AM on Nov 4th. Here are some shots I took as we took an auto-rickshaw from the station to the our home.

Lydia is so excited to be here that you can't see how jet-lagged she is.
Road to my home in Srivi. You have no idea how crazy this road will be just an hour.

School kids starting their day

September 25, 2014

Executable Specifications

In my previous job, I was given the opportunity to use ScalaTest. It is a library to write and test software specifications. In other words, you can use it to write "executable specifications". Recently, I showed off ScalaTest at my current job. Here is the summary of it.

Suppose we have need table that has the following specification:
Creation:
 - first column must be "Col1"
Addition:
 - add a row (support variable row length)
 - can't add an empty row
...  etc
Retrieval:
 - error if you attempt to get values for a column that doesn't exist
 - empty array if no values for a column
... etc

Here is the ScalaTest code for the specification:

import org.scalatest._

class MyTableSpec extends FlatSpec with Matchers {
 
  behavior of "Addition"
 
  it should "allow you to add a row of values " in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 100, 100)

    myTable.getColumn("Col1") should be (Array(1))
    myTable.getColumn("Col2") should be (Array(100))
    myTable.getColumn("Col3") should be (Array(100))
  }
 
  it should "allow you to add a row of length less than the number of columns" in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 100)
  
    myTable.getColumn("Col1") should be (Array(1))
    myTable.getColumn("Col2") should be (Array(100))
  }
 
  it should "throw AssertionError if you attempt to add an empty row" in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
   
    a [AssertionError] should be thrownBy {
      myTable.add()
    }
  }
 
  behavior of "Retrieval"
 
  it should "give you a set of row values for time t" in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 100, 100)
   
    myTable.getRow(1) should be (Array(1,100,100))
  }
 
  it should "give you an empty array (of type Int) if you retrieve values for a column that doesn't have any" in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 10)
  
    myTable.getColumn("Col3") should be (Array.empty[Int])
  }
 
  it should "throw NoSuchElementException if you attempt to retrieve values for a column that does not exist" in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 10, 10)
   
    a [NoSuchElementException] should be thrownBy {
      myTable.getColumn("Col4")
    }
  }
 
  it should "throw AssertionError if you attempt to insert a row with a non-unique value for time " in {
    val myTable = new MyTable("Col1", "Col2", "Col3")
    myTable.add(1, 10, 10)
   
    a [AssertionError] should be thrownBy {
      myTable.add(1, 10, 10)
    }
  }
 
  behavior of "Creation"
 
  it should "throw AssertionError if the first column is not \"Col1\"" in {
    a [AssertionError] should be thrownBy {
      new MyTable("Col1")
    }
  }
 
}

 In addition to unit style testing, you can use ScalaTest to write clear, concise and descriptive tests (which leads to robust software).

At the core of ScalaTest is its Domain Specific Language (DSL) for testing software, and Scala, being flexible and extensible, is a natural fit.

If you are interested in the implementation of this table, contact me.

July 15, 2014

ArrayIndexOutOfException when creating a bean using Spring 3.0.5

I found a bug recently when using Spring 3.0.5, which appears to be fixed in 4.0.5. Here are the details.

If you have a class that has a parameterized constructor and also has a method that uses a lambda expression (introduced in Java 8), then a ArrayIndexOutOfException occurs when creating a bean for that class.

Here is the stack trace:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 17676
    at org.springframework.asm.ClassReader.readClass(Unknown Source)
    at org.springframework.asm.ClassReader.accept(Unknown Source)
    at org.springframework.asm.ClassReader.accept(Unknown Source)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:114)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at LambdaSpringTest.main(LambdaSpringTest.java:9)


Here are the reproduction steps:

1. A sample class

import java.util.List;

public class LambdaSpring
{
    public LambdaSpring(){}
   
    public LambdaSpring(String arg1, String arg2){}
   
    public void method(List<Object> list)
    {
        list.stream().forEach(t -> System.out.println(t));
    }
}


2. Spring Bean configuration

<bean id="lambdaspring" class="LambdaSpring">
 <constructor-arg value="blabla"></constructor-arg>
 <constructor-arg value="blabla2"></constructor-arg>
</bean>


3. Running this main method will result in ArrayIndexOutOfException

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LambdaSpringTest
{
    public static void main(String[] args)
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("lamdaspring.xml");
        LambdaSpring tmp = (LambdaSpring) context.getBean("lambdaspring");
    }
}


This issue appears to be fixed in Spring 4.0.5 (possibly earlier as well), but if you can't upgrade for some reasons, here are some workarounds:

I found that if you don't use the parameterized constructor, then you don't get this exception. Also, if you replace the lambda expression with the equivalent boilerplate code (i.e., implement Consumer interface), then you don't get this exception.


March 3, 2014

Properly handling equals method

Some time ago, I had to troubleshoot a nasty memory leak problem around connection pooling, where JVM heap space kept growing despite no incoming traffic. We were using the Apache Commons Pools library to manage the pool but we also extended to customize the validation of pooled object to ensure only pooled objects of less than certain age were kept. A ConcurrentHashMap instance was used to store the pooled object and its creation time, so when it was time to validate a pooled object, we would get the object from this hash map and check its age. A bug in this logic resulted in the hash map growing to heap space exhaustion. In particular, it was bug in equals method. In this blog, I summarize what I learnt:

Suppose:

You have an interface and a class that implements it;

    public interface SomeInterface{}

    public class ObjectP implements SomeInterface
    {
        public String str;
       
        public ObjectP(String str)
        {
            this.str = str;
        }
       
        @Override
        public String toString()
        {
            return str;
        }
       
        public String toUpperCase()
        {
            return str.toUpperCase();
        }
       
        @Override
        public boolean equals(Object o)
        {
            System.out.println("ObjectP.equals invoked");
            return str.equals(((ObjectP)o).str);
        }
    }


You have an TestInvocationHandler that acts a proxy to ObjectP:

       public class TestInvocationHandler<T> implements InvocationHandler 
   {
       
        T t = null;
       
        public TestInvocationHandler(T t)
        {
            this.t = t;
        }

        @Override
        public Object invoke(Object arg0, Method method, Object[] args)
                throws Throwable {
            if (method.getName().equals("equals")) {
               
                System.out.println("equals method invoked. args[0].getClass()=" + args[0].getClass());
                System.out.println("this object = "  + this);
              boolean result = this.equals(args[0]);
                System.out.println("equals method returned " + result);
                return result;
            } else if (method.getName().equals("hashCode")) {
                return this.hashCode();
            } else if (method.getName().equals("toString")) {
                return t.toString();
            } else {
                return invokeInternal(method, args);
            }
        }

        private Object invokeInternal(Method method, Object[] args) throws Exception, IllegalArgumentException, InvocationTargetException
        {
            return method.invoke(t, args);
        }
    }


You create a Proxy class as follows:
       
        TestInvocationHandler<ObjectP> h1 = new TestInvocationHandler<ObjectP>(new ObjectP("hello"));
        TestInvocationHandler<ObjectP> h2 = new TestInvocationHandler<ObjectP>(new ObjectP("world"));
               
        Proxy p1 = (Proxy) Proxy.newProxyInstance(ObjectP.class.getClassLoader(), new Class[] { SomeInterface.class }, h1);


What should p1.equals(p1) be? The answer is false. Here is the output of p1.equals(p1)

equals method invoked. args[0].getClass()=class com.sun.proxy.$Proxy0
this object = ProxyClassTest$TestInvocationHandler@1b16e52
equals method returned false



That is, this.equals(args[0])is equivalent of saying TestInvocationHandler.equals(Proxy) which always returns false.

This bug resulted in ConcurrentHashMap.remove(object) to do nothing which resulted in the hash map to grow till the heap space was full.

The fix was simple; args[0].equals(this) instead of this.equals(args[0]) so that we do  RetryingInvocationHandler.equals(RetryingInvocationHandler):

if (method.getName().equals("equals")){  
        System.out.println("equals method invoked. args[0].getClass()=" + args[0].getClass());
        System.out.println("this object = "  + this);
        boolean result = args[0].equals(this);
        System.out.println("equals method returned " + result);
        return result;
}
 





February 12, 2014

Useful logging mechanism: Log Markers

In my previous post, I showed a simple example about MDC. In this post, I discuss the use of log markers (http://logback.qos.ch/manual/filters.html). Like MDC filters, marker filters are also "turbo filters" in Logback. Both these filters get triggered after a log event is created but before the log appender(s) are invoked. So they are a good choice for high-performance logging. While MDC filters are ideal to trace the path of a request, log marker filters are good for logging certain use cases.

Suppose we want to log the stack trace for user authentication failures (incorrect userid, incorrect password, account locked, db failure, etc) . Typically, the stack traces are logged in DEBUG level so they don't fill your production logs. So what we want is the ability to log the stack trace only for user authentication failures.

Log markers come handy here. You can use a log marker (say LOG_STACKTRACE_USER_AUTH_FAILURE) like this:

Marker logMarker = MarkerFactory.getMarker(LOG_STACKTRACE_USER_AUTH_FAILURE);
log.debug(logMarker, exception);

And in your logback.xml:

 <turboFilter class="ch.qos.logback.classic.turbo.MarkerFilter">
    <Marker>LOG_STACKTRACE_USER_AUTH_FAILURE</Marker>
    <OnMatch>ACCEPT</OnMatch>
  </turboFilter>

Irrespective of the global logger level you may defined*, this will allow your software to log stack trace to an appender when a log event with a marker called "LOG_STACKTRACE_USER_AUTH_FAILURE" is created.

* This behaviour is particular to ch.qos.logback.classic.turbo.MarkerFilter implementation.

Here is a good stackoverflow discussion on uses for MDC and log markers: http://stackoverflow.com/questions/4165558/best-practices-for-using-markers-in-slf4j-logback



February 7, 2014

Useful logging mechanism: Mapped Diagnostic Context (MDC) in Logback

Quite often, enterprise-level web applications need to log sufficient information for troubleshooting problems but logging can be resource intensive and log analysis can be time consuming, especially if the application in question is deployed in production serving high volume of requests. Mapped Diagnostic Context (MDC)  in Logback is a useful logging mechanism that gives us the ability to select what to log. In this post, I describe a simple use case to demonstrate its usefulness.

If you are using Maven, you need the following dependencies in your pom.xml for this demo:

<dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.5</version>
</dependency>
<dependency>
 <groupId>ch.qos.logback</groupId>
 <artifactId>logback-core</artifactId>
 <version>1.0.13</version>
</dependency>
<dependency>
 <groupId>ch.qos.logback</groupId>
 <artifactId>logback-classic</artifactId>
 <version>1.0.13</version>

</dependency>

In the following example, we would like "Starting app" and "Finishing app" statements to be logged. We would also like to log "Hello Parthy" but not "Hello Fred", both of which are DEBUG-level log statements. 

Using MDC:

    public static void main( String[] args )
  {
        Logger logger = LoggerFactory.getLogger("personal.tests.logback");
        
        logger.info("Starting app.");

        String username = "Parthy";
        MDC.put("username",  username);
        logger.debug("Hello {}", username);
        MDC.remove("username");

        username = "Fred";
        MDC.put("username",  username);
        logger.debug("Hello {}", username);
        MDC.remove("username");
        
        logger.info("Finishing app.");
  }

logback.xml (using MDCFilter that is shipped with logback):

<configuration>
 <turboFilter class="ch.qos.logback.classic.turbo.MDCFilter">
  <MDCKey>username</MDCKey>
  <Value>parthy</Value>
  <OnMatch>ACCEPT</OnMatch>
 </turboFilter>

 <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
  <encoder>
   <pattern>%date [%thread] %-5level %logger - %msg%n</pattern>
  </encoder>
 </appender>

 <root level="INFO">
  <appender-ref ref="console" />
 </root>
</configuration>

Setting the OnMatch value in the turboFilter to DENY will prevent "Hello Parthy" getting logged. In this case, "Hello Fred" will also not be logged because the root logger level is INFO and "Hello Fred" is logged at DEBUG level.

To use MDC effectively, developers should put the customer support hat and ask how can I trace an individual request amidst tens or hundreds of thousands of request with minimal noise in the logs. Find out how requests are identified (request id, session id, user name etc) and use those as MDC keys. You might say that such filtering is CPU intensive. Actually, logback's turboFilter is intended for high performance.

Interested? Read more here: http://logback.qos.ch/manual/filters.html



May 22, 2013

Switzerland - Intro

We were looking for destinations for our honeymoon, and Switzerland came to our minds. Switzerland! At that time, I could only say the following about Switzerland:
  1. Used to be a great location for shooting songs for Indian romantic films
  2. Nice train stations, and vast green fields
  3. Swatch
I could not think of anything bad about Switzerland as such.

Switzerland also triggered the memory of a happy encounter with a Swiss couple on our engagement trip to India. My wife and I were returning from a short stay at a Jungle resort hotel near Ooty in India. We took the Nilgiri Passenger Train from Ooty to Mettupalayam in India. Boarding on a Indian train in the unreserved compartment is very chaotic, and seats in this train could not be reserved. While we were boarding the train, I saw two Caucasian tourists boarding as well. It interests me when I see a tourist in India because tourists to India are not your usual the trigger-happy ones. They are like the travelers we hear in the stories of the past, messengers from other cultures. Naturally, I try to make it a point to say hello to tourists in India, and force a conversation. They always something interesting to say about India. And luck would have it, this couple sat opposite us.

I looked at them, how they were dressed - loose cotton baggy pants. Their possessions indicated they have been travelling for a while. As I started analysing them, something yanked me out of the imaginary world of my mind to the real one - a tiff between some folks in our compartment. They were arguing (quite loudly) about who got to the seat first. Before boarding the train or bus, one of them threw a handkerchief on to a seat on the bus to signal seat reservation (this often happens in India). The other person denied that reservation. Thus, the arguments. More people joined in, and getting chaotic. I turned to my fellow tourists and said "Welcome to India!". They laughed, looked relieved (probably because they knew that they were not the only one to call the situation crazy). From then on, we had a natural flow of conversation. It turned out that they were from Switzerland. I thought about why a Swiss would come to see a culture that is its mirror image. By the time our train reached Mettupalayam, our "driver brother" was waiting outside the  station. Our new-found friends were looking for directions to go to the nearby city of Coimbatore, which was on our way to home. So we gave them a ride to Coimbatore. We reached Coimbatore, had dinner together, and as we dropped them off on really busy street, the power had gone. The usual Indian traffic chaos suddenly looked deadly. We quickly said our goodbyes, and they asked us to visit them in Switzerland. When I thought of Switzerland, I thought about them.

I remembered that an old friend of mine from high school in Mauritius, who now lives in Switzerland. I thought about meeting him, and see how life experiences has changed him after a 12 year gap. 

Along with my wife's excellent sales pitch to go to Switzerland, Switzerland was locked in as the destination for our honeymoon.

March 9, 2013

Getting code samples from Essential GWT book to work

I bought a book called 'Essential GWT' by Federico Kereki but did not receive a CD for the samples mentioned in the Essential GWT book. I downloaded the samples from here: http://www.informit.com/content/images/9780321705143/downloads/0321705149_Code.zip. Unfortunately, there was not much documentation about the samples or how to compile them. Here, I've noted some information which others find it useful. Note that you need to have GWT plugin for Eclipse installed.

After unzipping, there were these folders:

bookphp  mvpproject  stdserialize

The mvpproject seems to contains the bulk of samples that the book discusses. The source for the samples are contained in the folder 'src' and 'war' contains some web deployment info. To compile and deploy the samples:

1. Create a GWT Web Application Project. Call it 'mvpproject' and set the package name to be 'com.fkereki.mvpproject'. If these are not right, you can an error when you try to deploy saying that *.gwt.xml is not found.

2. Copy the source code that you downloaded to your project through Eclipse:

        BOOK_SOURCE/mvpproject/src/com/fkereki/mvpproject/*
        BOOK_SOURCE/mvpproject/src/com/fkereki/mvpproject/client/*
        BOOK_SOURCE/mvpproject/src/com/fkereki/mvpproject/server/*

4. The project requires the following external jars:

       gwt-ajaxloader.jar
       commons-fileupload-1.2.2.jar
       commons-lang3-3.1.jar           
       mysql-connector-java-5.1.23-bin.jar

5. Modify web.xml and appengine-web.xml in your project as follows:
    a. uncomment <sessions-enabled>true</sessions-enabled> in appengine- web.xml
    b. web.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- Servlets -->

    <servlet>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>com.fkereki.mvpproject.server.LoginServiceImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/mvpproject/login</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>worldServlet</servlet-name>
        <servlet-class>com.fkereki.mvpproject.server.WorldServiceImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>worldServlet</servlet-name>
        <url-pattern>/mvpproject/world</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>xhrProxyServlet</servlet-name>
        <servlet-class>com.fkereki.mvpproject.server.XhrProxyImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>xhrProxyServlet</servlet-name>
        <url-pattern>/mvpproject/xhrproxy</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>fileProcess</servlet-name>
        <servlet-class>com.fkereki.mvpproject.server.FileProcess</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>fileProcess</servlet-name>
        <url-pattern>/mvpproject/fileprocess</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>fileProduce</servlet-name>
        <servlet-class>com.fkereki.mvpproject.server.FileProduce</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>fileProduce</servlet-name>
        <url-pattern>/mvpproject/fileproduce</url-pattern>
    </servlet-mapping>

  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>Mvpproject.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>SystemServiceServlet</servlet-name>
    <servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
    <init-param>
      <param-name>services</param-name>
      <param-value/>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>SystemServiceServlet</servlet-name>
    <url-pattern>/_ah/spi/*</url-pattern>
  </servlet-mapping>

</web-app>

5. You need md5-min.js for some password hashing. It is in the downloaded folder (/BOOK_SOURCE/mvpproject/war/md5-min.js). Copy it to your war folder.

6. Modify your Mvpproject.html as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- The HTML 4.01 Transitional DOCTYPE declaration-->
<!-- above set at the top of the file will set     -->
<!-- the browser's rendering engine into           -->
<!-- "Quirks Mode". Replacing this declaration     -->
<!-- with a "Standards Mode" doctype is supported, -->
<!-- but may lead to some differences in layout.   -->

<html>
<head>
<!-- Note: charset=UTF-8 is required for international applications -->

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<!--                                                               -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!--                                                               -->
<link type="text/css" rel="stylesheet" href="Mvpproject.css">

<!--                                           -->
<!-- Any title is fine                         -->
<!--                                           -->
<title>MVP Project</title>

<!--                                           -->
<!-- This script loads your compiled module.   -->
<!-- If you add any GWT meta tags, they must   -->
<!-- be added before this line.                -->
<!--                                           -->
<script type="text/javascript" language="javascript" src="mvpproject/mvpproject.nocache.js"></script>
<!-- 
<script type="text/javascript" language="javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=aasJBXDV34FUcgc.WTwpYWlbhWme9l1xJtF8juZYjwZOTXEwawx5lbzAIKJtgII-"></script>
-->
<script type="text/javascript" language="javascript" src="md5-min.js"></script>
</head>

<!--                                           -->
<!-- The body can have arbitrary html, or      -->
<!-- you can leave the body empty if you want  -->
<!-- to create a completely dynamic UI.        -->
<!--                                           -->
<body>

<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1'
    style="position: absolute; width: 0; height: 0; border: 0"></iframe>

<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div
    style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled in order for this
application to display correctly.</div>
</noscript>
<div id="loading" style="top: 50%; left: 50%;"><img
    src="./ajax-loader.gif" /></div>
</body>
</html>


7. Since I used the new Apache Commans lang (version 3.x) which is different the author's, I modified /src/com/fkereki/mvpproject/server/Security.java to import org.apache.commons.lang3.RandomStringUtils rather than import org.apache.commons.lang.RandomStringUtils.

8. I also had to comment the File IO code in FileProcess.java to avoid this error:

java.io.FileOutputStream is not supported by Google App Engine's Java runtime environment

Et voila, your web application should start without errors (note I did do GWT compile first).