I am trying to write a java program that takes a maven pom.xml file as input and does following:
- Downloads all dependencies
- Adds jars to classpath
- Executes java code (loaded from the jars)
Is it possible? any sample code to achieve #1 above will be greatly appreciated
If you absolutely have to do this embeded in a Java app:
The library Maven uses under the covers to do dependency resolution is called Aether. If you take a look at the documentation on the Sonatype site there’s an example of how to do step 1. Part of the dependency resolution process will give you access to a list of dependencies which you can then loop over to build your classpath.
For step 3 you could use a ProcessBuilder and launch the target Java app as a subprocess of the JVM that used Aether to build the classpath.
If you can use a shell script:
You can use
mvn dependency:get -Dartifact=[group]:[artifact]:[version]to download the artifacts to your local repo.Then you can use
mvn dependency:build-classpathto generate the classpath string.Then you can simply execute java with a -cp option. You’d have to also know what main class you want is, or you could compute the name of the primary jar from the artifact and version number and pass that to -jar.
If you’re able to get the pom.xml of the main project in your deployment environment:
You can just use
mvn exec:java -DmainClass=com.company.package.YourMainClass. This option is by far the simplest, but it does have the downside of executing within the maven JVM and as far as I’ve been able to find out there’s no option for forking a separate process. Also you need to have a full fledged pom to make this work which isn’t always convenient.