Fix code formatting

I have fixed the code formatting of these files so that they are finally consistent and much more readable.
I have also done minor minor refactoring to reduce code duplication by using some Java 7 features such as generic diamonds and multi-exception catch blocks. No real changes to the code behaviour!