In Part 1 The Age Of Gradle, we go throw about Ant, Maven and Gradle.
I mentioned that we can use the combination of Maven and Gradle so I will share you how to do it.
The combination will be complex and depend on various use cases so I cannot cover all in one post. In this post, I just share Gradle script to import Maven dependencies from pom.xml file to gradle.build without any modification in pom.xml file.
This is my origin pom file.
Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <name>Ogirin Maven Project</name> <groupId>jp.btuan.express</groupId> <artifactId>sample</artifactId> <version>1.0</version> <packaging>jar</packaging> <properties> <version.jackson>2.8.8</version.jackson> <version.guava>23.0</version.guava> </properties> <dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${version.guava}</version> </dependency> </dependencies> </project>
And this is customized build.gradle file. You can see under dependencies block, I implemented script to read pom.xml file, get dependencies and version. Then load into gradle project.
Build.gradle
group 'jp.btuan.express' version '1.0' apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { // Load dependencies from old pom.xml file def pomXml = new XmlSlurper().parse('pom.xml') def pomDependencies = pomXml.dependencies.dependency pomDependencies.each { dependency -> // Get Dependency version def dependencyVersion = "${dependency.version}" if (dependencyVersion.matches("^\\\$\\{\\S*\\}\$")){ dependencyVersion = dependencyVersion.replaceAll("[\\\$\\{\\}]", ""); dependencyVersion = pomXml.properties."${dependencyVersion}" }else{ dependencyVersion = "${dependency.version}" } def dependencySpec = "${dependency.groupId}:${dependency.artifactId}:${dependencyVersion}" println dependencySpec switch (dependency.scope){ case 'test': dependencies.add 'testCompile', dependencySpec break; case 'runtime': dependencies.add 'runtime', dependencySpec break; default: dependencies.add 'compile', dependencySpec break; } } // Define dependencies with Gradle syntax compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2' }
Is it easy? Give me feedback if there are any to help it better.