Maven Fetch JSON during building Jar

by GarciaPL on Monday 25 May 2015

My recent project was aimed to develop standalone application written in Swing with embedded database which was in form of JSON file. During building my Jar using Maven, I was faced with problem to replace this JSON file before final application will be produced. Before you will prepare such solution you should get familiar with Maven Build Lifecycle [1]. Below I listed those LifeCycle's :


  1. validate
  2. generate-sources
  3. process-sources
  4. generate-resources
  5. process-resources
  6. compile
  7. process-classes
  8. generate-test-sources
  9. process-test-sources
  10. generate-test-resources
  11. process-test-resources
  12. test-compile
  13. test
  14. prepare-package (maven 2.1+)
  15. package
  16. pre-integration-test
  17. integration-test
  18. post-integration-test
  19. verify
  20. install
  21. deploy
After you will decide in which phase you are going to run your custom Java class, which in my case was fetching JSON from server, you are going to use plugin called exec-maven-plugin developed by Codehaus [2].

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2</version>
                <executions>
                    <execution>
                        <id>fetchJSON</id>
                        <phase>prepare-package</phase>
                        <inherited>false</inherited>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>pl.avantis.iom.rest.DrupalQueriesImpl</mainClass>
                    <cleanupDaemonThreads>true</cleanupDaemonThreads>
                    <daemonThreadJoinTimeout>30000</daemonThreadJoinTimeout>
                </configuration>
            </plugin>

This plugin will run pl.avantis.iom.rest.DrupalQueriesImpl in phase prepare-package, this is a step just before package phase, so your Jar will contain the newest JSON file without downloading it manually .

Reference : [1] Maven Build Lifecycle [2] Codehaus - Exec Maven Plugin