Wednesday, March 20, 2013

Java File Formatting using Maven via Eclipse settings


In below blog I am demonstrating an example of maven java formater, for java files. 

In my recent project multiple teams is working on a code base and most of them are fresher/associate level engineers.  Obviously they are not much aware of code standards and best practices to be followed while writing a code.  Check-style is one of the plugin comes with maven to cross check your code against all such standards to aware you about coding standards.

Few suggestions that checkstyle plugins imposes is:
  • Apply correct indentation (biggest plus point)
  • Lines should be wrapped after 80 characters
  • File must be UTF encoding
  • Tab characters in file must be replaced with spaces
  • And so on….

Although one can perform such all formatting using eclipse but when files are large in number and this happens repeatedly, it’s hard to maintain such coding standards.

  • Eclipse Juno
  • Java
  • Maven

The project is divided into multiple modules.  There is inter-dependency among maven sub-projects.  I made a change to parent most pom file structure for java file formatting so that all child and dependent project files get formatted as per the configuration file.

Configuration file!! What’s that??

Well, the goal here is to format all the project java files to meet most of the checkstyle rules/standards.  Most of the!! Yes, all the rules cannot be sufficed suggested by checkstyle as there are logical rules as well like making a method final etc.  All such rules require manual intervention.

Ok, so the very first step that you need to perform is open eclipse IDE.  Go to “Window -> Preferences”.  In the text box on top left type “format”.  A filtering would be applied; from available options select “Java -> Code Style -> Formatter” option.  Here you will find active profiles on right hand side screen like Java Conventions, Eclipse etc. 

Either selects one of those you want or create a new one using “New” option.  After that select “Edit option” and apply rules you want; such as converting tab character to 4 spaces etc.  See image below.

After making all desired changes as per your project structure and need, select “Apply” and using “Export” option save your present profile into XML file say for example you save it at location “C:/my-profile.xml”.

Now use this profile XML to format java files using maven.  Here we go.  Add java formatter plugin to your parent most pom.xml.
        … other plugins …

Now the maven command that you need to perform this operation is:
mvn java-formatter:format

And it’s done. 

You can find more details here about plugin.