Parsing Strings to DateTime (or LocalDate) using Joda time

November 27th, 2009

There’s no doubt that Joda time is now the defacto date time library for java. And a well written library it is. You get almost everything you can ever want to do with Date objects and best of all, almost all operations are dummy-proof. By dummy proof I mean that programmers making silly mistakes can’t really screw it up.

I recently had to parse a String into a LocalDate object using Joda time. I couldn’t find a parser in the docs or the very useful userguide but I knew it had to be possible, no one could overlook such a widely used operation. So I went in search of a parse.

It turns out that the parser and the formatter are one and the same thing in joda time, except with different methods ofcourse. Here’s how you construct a parser to parse a String in YYYYMMDD format :

DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().appendYear(4, 4).appendMonthOfYear(2)
            .appendDayOfMonth(2).toFormatter();

Read the rest of this entry »

Hibernate join tables for entity mapping – using them helps

November 22nd, 2009

Over the last couple of years I have had various discussions about this with my colleagues. I myself favoured foreign keys relationships rather than join tables till a little while ago. If you’re not aware of how to do one or the other, the eamples below should explain that.

Consider a very simple parent child relationship. Every parent can have multiple children. Using a join table and JPA annotations, the model classes look something like this for unidirectional relationships: (I have excluded all fields not required for this example)
With join table …

@Entity
class Parent {
    @OneToMany
    @JoinTable(
            name="parents_children",
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="child_id")
    )
    private Set<Child> children
}

@Entity
class Child {
    //nothing
}

Without join table …

@Entity
class Parent {
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="parent_id")
    private Set<Child> children;
}

@Entity
class Child {
    // nothing
}

Read the rest of this entry »

Difference between decorator and proxy patterns

November 18th, 2009

I had an interesting discussion with a colleague of mine regarding the differences between the proxy and the decorator pattern which made me give it some thought. To the untrained eye (that includes my eye!), they seem exactly the same. Infact you sometimes wonder, why the heck are there two names for the same pattern. As we’ll soon see, they are anything but the same.

I think we’re all aware that the decorator pattern is used to add behavior to existing code. This does not stop at one kind of behavior but any number of different things that we want to do. A proxy on the other hand simply delegates all calls to the underlying object delaying costly operations till they are absolutely neccessary. This basically means that what a proxy can do is decided at compile time and cannot be changed by the calling code after instantiation. Using the decorator pattern the behavior of the underlying object can be changed at runtime by adding multiple decorators to it. This behavior addition takes place at runtime depending on say user input. To put it simply, proxy is compile time, decorator is runtime.
Read the rest of this entry »

The usefulness of java.util.concurrent.TimeUnit

October 14th, 2009

I’m a bit ashamed to write this post. I have been working on Java 5 for well over two years and yet I was unaware of the power of the java.util.concurrent.TimeUnit class. While I have used almost all the other juc classes over this time and subsequently TimeUnit as well (in some of them), I never realized how powerful TimeUnit was on its own.

It all started with my obsession to remove all the checkstyle errors in a project that I have been working on. More than 50% of them turned out to be ‘magic number’ warnings. While some of them were my fault, most of them were due to laziness and then there were some due to Thread.sleep calls in the code. There must be an easy way to get rid of these without actually having to make private static final class members for every sleep value. I looked and looked and looked, nope, nothing.
Read the rest of this entry »

Creating a Seam project with eclipse and deploying it on tomcat tutorial

April 13th, 2009

What i’m about to show you is not really much of a tutorial but more of an example of one way of working with eclipse and deploying your seam based web app to tomcat. If you’re ok with JBoss, then go with it, nothing beats the support and ease of configuration that the JBoss AS provides for deploying seam applications. But since I was running JBoss on an old 5400 rpm hard disk with 25 other applications reading and writing data to it, it used to take 10+ minutes for it to startup (7m with reduced logging) and anywhere from 4 to 10 minutes for a hot redeploy of the application. Maybe I wasn’t doing it right but I decided to switch to tomcat for it’s ease of use and because i’m more familiar with its errors and pitfalls (configuring a ds comes to mind).

There are a few good tutorials out there if you want to work with JBoss and maybe one or two good ones for tomcat but nothing that works out of the box. One special tutorial is Read the rest of this entry »

Small java changes which should be in Java 7

April 8th, 2009

It’s ironic the stuff we get used to as developers. There’s so much we do repeatedly in every class or in every project or maybe even in every method yet we never realize that it’s probably best to add a new “feature” to java to make our life easier. While searching for some reading material on java’s handling of String (just to clear up some of my own personal doubts) I came across a very interesting OpenJDK sub-project, Coin. Coin, simply put, is a project to determine what small language changes should be added to JDK7. Wonderful, let’s see what people have come up with. And that’s just week 4 submissions.
Read the rest of this entry »

Simple concurrent In-memory cache for web application using Future

March 11th, 2009

In-memory cache’s can be extremely useful for small web applications where you don’t want to full-blown cache system like ehCache or simply can’t afford one. I recently had such a requirement and I must say that I kind of made a mess of it. The requirement was to cache User objects so that we didn’t have to make too many calls to the database. Let me just say outright that while such a cache is not the best idea in the world, it isn’t the worst either. When you simply need to cache a few objects to reduce the load on the db in a moderately loaded web-app, this implementation works just fine.

The service layer was my choice for the cache, I use the Controller -> Service -> DAO model in all my webapps mainly because it keeps the code clean and also because it makes it much easier to manage transactions across DAO’s. Read the rest of this entry »

Configuring DWR 3.0 with spring using annotations

February 21st, 2009

I’m a fan of the spring framework and I have recently become a fan of DWR as well. Both of them together are just unstoppable, they take ajax and bean exposure through javascript to a new level. I have written about my experiences integrating the two and about validating forms using ajax. I’d advise you to read at least the integration article before continuing.

Using annotations to configure the spring container is a very useful feature, a majority of developers prefer to use annotations rather than XML files. However, annotation driven configuration of DWR through spring was not possible in older versions of DWR. The new version however, allows such configuration and with ease I might add. You can now use DWR with spring with almost no configuration in your XML files(a little bit of configuration is required but it doesn’t go beyond 10 lines or so). The best part however is that you don’t need to configure a seperate servlet for DWR at all, all calls to dwr can be routed through the spring dispatcher servlet which helps cut down configuration even more. Read the rest of this entry »

Tracking logged in user’s using spring-security and HttpSessionListener in java web application

February 19th, 2009

If you haven’t already, please first read my article on configuring spring security and after that the article on writing a custom AuthenticationprocessingFilter. It is imperative that you know how to do both before you continue.

We always want to know who is on our website, how many users are logged in and how many visitors are present. Not only is the information useful, it also looks good. :) I tried looking for pluggable solutions to track users but couldn’t find any. Having implemented spring security in a few web apps, I decided to see if there was an easy way to do this. Read the rest of this entry »

Mapping many/all URL’s to a single spring controller using annotations

February 17th, 2009

Once in a while this kind of a question pops up on the spring forums. The requirement is almost always the same : Map many URLs to a single controller and/or map all URL’s without a defacto mapping to a default controller. Both have different solutions.

Let’s discuss the first one. The @RequestMapping annotation makes configuring spring controllers a breeze. The value param of the annotation accepts a string array of url’s, most of us miss this part. To map multiple URL’s to a single controller all you need to do is :

@Controller
@RequestMapping(value={"/changepassword.html","/admin/changepass.html"})
public class ChangePasswordForm {

// methods
}

You can also use ant-style regular expressions to map URL’s.

@Controller
@RequestMapping(value={"/changepassword.html","/admin/changepass.html", "/change*.html"})
public class ChangePasswordForm {

// methods
}

Now onto mapping ALL URL’s which do not have a default mapping to a particular controller. This is also quite simple, all you need to do is create a controller which maps to everything. The way spring-mvc works is that it looks for an absolute mapping to service every request, if it doesn’t find one, it then asks the best match to service the request. The controlller should look something like this :

@Controller
@RequestMapping("/*")
public class ChangePasswordForm {

// methods
}

Do leave a comment if you run into a scenario I haven’t covered here or if the post has been of help to you. :)

Custom AuthenticationProcessingFilter for spring security to perform actions on login

February 16th, 2009

Question like this one popup on the spring security forum all the time. The question is almost always the same. The system must perform some custom action after a user logs in or out of the system. And almost always this action has to be performed on the session like setting an attribute or removing one. Sometimes user’s also want to put their own User object in the session for later use in the application. All these actions can be performed by writing a custom AuthenticationProcessingFilter and replacing the default instance on the filter chain with your implementation.

Before I show you how to write your very own filter, Read the rest of this entry »

Registering PropertyEditors’s with spring for custom objects

February 14th, 2009

More often than not people come to the spring forums asking about PropertyEditor’s. PropertyEditors are needed when you want to convert a string value to an object. Say for example, your command object contains a reference to a User object and the list of user’s is shown in the jsp with the value of the option box serving as the id of the user. Once the form is submitted, unless you have a custom property editor for your user class, you will receive validation errors. Read the rest of this entry »

Pagination & sorting in jsp’s with the displaytag taglib & spring

February 13th, 2009

I hate writing pagination code. Infact I hate it so much, I try not to paginate my lists at all. ( I know, i know, very bad on my part) :) . Writing pagination code totally destroys the code reuse in an application, developers generally just copy paste the very same pagination code all over the place over and over again. Not to mention decorating such pagination displays is a pain in the ass as well. So while searching for a more concrete solution to my problem I stumbled upon displaytag.

Display tag is by far the most comprehensive pagination solution that I have ever come across. Not only is the library extremely stable, Read the rest of this entry »

Clearing formBackingObject data after spring form submit

February 13th, 2009

It’s all to common for beginners of spring to stumble upon what may look like odd spring problems. Most users think that these are bugs while more often than not they are expected spring behaviour. I myself have stumbled upon my fair share of such problems.

One such problem is clearing the data contained within the formBackingObject (or command object) after a successful Read the rest of this entry »

Method inlining with the final keyword in java

February 12th, 2009

I have noticed a lot of people on the internet asking about method inlining. The term generally arises whenever the final keyword is discussed. Basically, it is said that compilers inline methods which are declared final thereby avoiding the cost of putting them on the stack etc and thus improving performance drastically under heavy load conditions. The same is true for variables as well, their values are inlined thereby avoiding the cost of performing lookups at runtime. What nobody talks about is what exactly is inlining.

Consider the following class :

public class Inline {

	private int	i;

	public void methodA() {
		methodB();
	}

	public final void methodB() {
		i++;
                i--;
	}
}

methodB() is marked final in this case. It cannot be overriden. The compiler sees this and decides to alter the byte code of methodA() to instead look like this :

public void methodA() {
		i++;
		i--;
	}

methodB() has now been inlined into methodA() to save the cost of pushing a method onto the stack. This invocation will work faster than the earlier one although its almost impossible to determine how much faster without a proper production environment. It’s also important to note that java code is first compiled into byte code and then into runtime code by the JVM. This change of code takes place in the JVM and not during compilation. If you open your class file you will see nothing different in it from the source file.

final variables work in the same way except calls to them are replaced by their actual values because those are not going to change once they’re initialized.

It’s been said that the newer VM’s (ever since Hotspot) no longer provide benefits of marking methods and variables final as they deduce and mark them final on their own during runtime.