środa, 16 kwietnia 2014

Filtering java sources with maven to use with Gin

From time to time I get a need to use maven filtering capabilities to change properties depending on the maven build profile. It's nice thing I must admit. Recently, I also needed to do filtering on java source code (in Gin module to bind different constant to be injected to my GWT view), and it seems that standard filtering is not capable of doing it. So here is what I did...

If you google around, first posts on stackoverflow will tell you to do some magic with changing default source location of java files before the compilation. While it may work, it's not the best option. For such thing, a maven templating plugin was created.
Here's the example:
- in my Gin module description I needed to bind a boolean parameter to view depending on maven profile


        @Override
 protected void configure() {
  boolean isVerticalView = Boolean.parseBoolean("${isVerticalView}");
  bindConstant().annotatedWith(Names.named("isVerticalView ")).to(isVerticalView );
 }

As you can see, I put a parameter inside java code. Normal filtering will not subsitute this variable on build, so you have to use the templating plugin. To do so you have to:
  • move your class under src/main/java-templates/<original.package.name>/<filename>.java
  • add a isVerticalView property to your pom.xml (or pass it to maven any other way you want)
  • add templating plugin to your build plugins
<plugin>
   <groupid>org.codehaus.mojo</groupid>
   <artifactid>templating-maven-plugin</artifactid>
   <version>1.0-alpha-3</version>
   <executions>
 <execution>
  <id>filter-src</id>
  <goals>
   <goal>filter-sources</goal>
  </goals>
  <configuration>
    <!-- Note the two following parameters are the default one. These 
    are specified here just as a reminder. But as the Maven philosophy is strongly 
    about conventions, it's better to just not specify them. -->
     <sourcedirectory>${basedir}/src/main/java-templates</sourcedirectory>
     <outputdirectory>${project.build.directory}/generated-sources/java-templates</outputdirectory>
  </configuration>
 </execution>
   </executions>
</plugin>
Now you just need to compile the project- templating plugin will substitute the property and add generated-sources to build path :)

Brak komentarzy:

Prześlij komentarz