An Introduction to Gradle for Java Developers

Kostas Saidis
Kostas SaidisSoftware and Data Architect
An Introduction to Gradle for Java
Developers
Kostas Saidis
www.niovity.com
Java Hellenic User Group Meetup
April 2, 2016
About Me
Kostas Saidis
saiko@niovity.com
Software & Data
Architect
Twitter:
@saikos
Linkedin:
http://gr.linkedin.com/in/saiko
Academia
BSc @ cs.unipi.gr (2001)
MSc @ di.uoa.gr (2004)
PhD @ di.uoa.gr (2011)
Industry
Freelance consultant, developer &
instructor since 1999
Enterpreneur since 2011 (niovity)
Java
Early Java enthusiast (1997)
Groovyist since 2011
Using Gradle
Building software with Gradle
Since version 0.9
Fifteen real-life projects with team sizes ranging from 2 to 10
members
Custom plugin authoring
Target audience
Java developers
with little or no experience
in Gradle or another build tool.
Build tools
www.ayorkshirehome.com
Software build tools
Tools for managing and automating
the software build process.
Software what?
Building
software
sucks!
(big time)
Software build process
Develop
Test
Assemble
Deploy
Integrate
Repeat
Again and again and again
What is Gradle?
Gradle is one of the finest software
build tools out there
Makes the software build process easier to setup, extend and maintain
In this presentation
We focus on understanding Gradle
Gradle is a superb piece of software
What makes it so great?
No flame wars
No feature comparison with other tools
At a glance
Gradle
Open source: Apache License v2
First release 2009, latest release March 2016 (2.12)
Backed by Gradleware... ooops, I mean Gradle Inc
Used by: Android, Spring IO, Linkedin, Netflix, Twitter and more...
At a glance
Gradle
Combines the best of Ant, Ivy and Maven
Cross-platform file management
Dependency management
Conventions
In a smart and extensible way
Deep API
Groovy DSL
Easy-to-write plugins
Ultimately offering
Clean and elegant builds
Plenty of new features
Better build management
Features
Non exhaustive list
Full-fledged programmability
Both declarative and imperative
Convention over configuration
Transitive dependency management
Multi-project builds
Polyglot (not only Java)
Numerous plugins and integrations
Incremental and parallel execution
Reporting and analytics
Embeddable
Great documentation
The most distinct features
IMHO
1. Its superb design and technical sophistication.
2. The exposure and manipulation of its “internal” Java APIs
through Groovy (aka the Groovy DSL).
A simple example
A simple Java project
1 apply plugin: ”java”
2 group = ”org.foo.something”
3 version = ”1.0−SNAPSHOT”
4 repositories {
5 mavenCentral()
6 }
7 dependencies {
8 compile ”commons−io:commons−io:2.4”
9 testCompile ”junit:junit:4.11”
10 runtime files(”lib/foo.jar”, ”lib/bar.jar”)
11 }
The contents of build.gradle (aka the build script), placed in the root folder of the
project.
Core Concepts
Build script: a build configuration script supporting one or more
projects.
Project: a component that needs to be built. It is made up of
one or more tasks.
Task: a distinct step required to perform the build. Each
task/step is atomic (either succeeds or fails).
Publication: the artifact produced by the build process.
Dependency Resolution
Dependencies: tasks and projects depending on each other (internal)
or on third-party artifacts (external).
Transitive dependencies: the dependencies of a project may
themselves have dependencies.
Repositories: the “places” that hold external dependencies
(Maven/Ivy repos, local folders).
DAG: the directed acyclic graph of dependencies (what
depends on what).
Dependency configurations : named sets (groups) of dependencies
(e.g. per task).
Plugins
A plugin applies a set of extensions to the build process.
Add taks to a project.
Pre-configure these tasks with reasonable defaults.
Add dependency configurations.
Add new properties and methods to existing objects.
Plugins implement the “build-by-convention” principle in a flexible
way.
The Build Lifecycle
1. Initialization: initialization of the project.
2. Configuration: configuration of the project (computes the DAG).
3. Execution: executes the sequence of build tasks.
The simple example
1 apply plugin: ”java”
2 //Introduces a set of Maven−style conventions
3 //(tasks, source locations, dependency configurations, etc)
4 group = ”org.foo.something”
5 version = ”1.0−SNAPSHOT”
6 repositories {
7 //resolve all external dependencies via Maven central
8 mavenCentral()
9 }
10 dependencies {
11 //each name (compile, testCompile, etc) refers to
12 //a configuration introduced by the java plugin
13 compile ”commons−io:commons−io:2.4”
14 testCompile ”junit:junit:4.11”
15 runtime files(”lib/foo.jar”, ”lib/bar.jar”)
16 }
Invoking gradle
Run a build task
> gradle test
Compiles the sources and runs the tests
> gradle tasks
clean, assemble, build, classes, testClasses, test, jar, etc
Never invoke gradle directly but always use the gradle wrapper: a
mechanism to execute gradle without manually installing it
beforehand (not covered here).
A more complex example
Ant integration, custom tasks
1 apply plugin:’java’
2 task generateFiles(type: JavaExec) {
3 main = ’some.class.name’
4 classpath = sourceSets.main.runtimeClasspath
5 args = [ projectDir, ’path/to/gen/files’ ]
6 }
7 test {
8 dependsOn generateFiles
9 doLast {
10 ant.copy(toDir:’build/test−classes’){
11 fileset dir:’path/to/gen/files’
12 }
13 }
14 }
15 import org.apache.commons.io.FileUtils
16 clean.doFirst {
17 FileUtils.deleteQuietly(new File(’path/to/gen/files’))
18 }
Hmmm
What’s going on here?
Let’s have a closer look
1 //apply the java plugin as before
2 apply plugin:’java’
3 //introduce a new task (that invokes a java process)
4 task generateFiles(type: JavaExec) {
5 main = ’some.class.name’
6 classpath = sourceSets.main.runtimeClasspath
7 args = [ projectDir, ’path/to/gen/files’ ]
8 }
9 //customize the test task
10 test {
11 dependsOn generateFiles
12 doLast {
13 ant.copy(toDir:’build/test−classes’){
14 fileset dir:’path/to/gen/files’
15 }
16 }
17 }
18 //import a class required by this build script
19 //some necessary classpath definitions are not shown for brevity
20 import org.apache.commons.io.FileUtils
21 //customize the clean task
22 clean.doFirst {
23 FileUtils.deleteQuietly(new File(’path/to/gen/files’))
24 }
Hmmm
What’s that strange syntax?
It’s Groovy!
groovy-lang.org
The Gradle DSL
Gradle’s power lies in its Groovy-based DSL
What you need to know about Groovy to start using Gradle in its full
potential
For more Groovy magic, have a look at:
An Introduction to Groovy for Java Developers
What is Groovy?
Groovy is a feature-rich, Java-friendly language for the JVM
A super version of Java
Augments Java with additional features
Designed as a companion language for Java
seamless integration with Java → an additional jar at runtime!
syntactically aligned with Java → syntactically correct Java will
work in Groovy (with some gotchas)!
compiles into JVM bytecode and preserves Java semantics → call
Groovy from Java == call Java from Java!
the 2nd language targeting the Java platform (JSR-241) →
Java was the first!
Groovy Scripts
Java
1 public class Booh {
2 public static void main(String[] args) {
3 System.out.println(”Booh booh”);
4 }
5 }
Compile and run it.
Groovy
1 println(”Booh booh”)
Run it directy.
POJOs vs POGOs
Java
1 public class Foo {
2 private String message;
3 public void setMessage(String message) {
4 this.message = message;
5 }
6 public String getMessage() {
7 return message;
8 }
9 }
Groovy
1 class Foo {
2 String message
3 }
Groovy Map Syntax
Java
1 Map<String, String> pairs = new HashMap();
2 pairs.put(”one”, ”1”);
3 pairs.put(”two”, ”2”);
Groovy
1 Map<String, String> pairs = [one:’1’, two:”2”]
Groovy Operator Overloading
1 import java.util.concurrent.*
2 class Tasks {
3 List<Callable> taskList = []
4 void execute() {
5 for(Callable t: taskList) {
6 t.run()
7 }
8 }
9 void leftShift(Tasks tasks) {
10 taskList.addAll(tasks.taskList)
11 }
12 }
13 Tasks t1 = new Tasks()
14 ...
15 Tasks t2 = new Tasks()
16 ...
17 t1 << t2
Groovy Closures
A closure is an anonymous function together with a referencing
environment.
may accept parameters or return a value,
can be assigned to variables,
can be passed as argument,
captures the variables of its surrounding lexical scope.
Example
1 class Test {
2 long x = 3
3 //a block of code assigned to a variable
4 Closure<Long> times = { long l −> l * x }
5 //x is the free variable
6 }
7 Test test = new Test()
8 assert test.times(3) == 9
9 test.x = 4
10 assert test.times(3) == 12
11 class Test2 {
12 long x = 0
13 }
14 test.times.resolveStrategy = Closure.DELEGATE_FIRST
15 test.times.delegate = new Test2()
16 assert test.times(3) == 0
Groovy method invocation syntax
1 //omit parentheses
2 println(”booh booh”)
3 println ”booh booh”
4 method ”one”, 2
5 //omit map’s braces
6 method([one:1, two: 2])
7 method(one:1, two:2)
8 method one:1, two:2
9 //The closure as last argument pattern
10 Closure clos = { int x, int y −> x + y }
11 method(”one”, 2, clos)
12 method ”one”, 2, clos
13 method(”one”, 2) { int x, int y −>
14 x + y
15 }
Back to Gradle
Behind the scenes
Gradle build scripts are Groovy scripts.
Such Groovy scripts operate in the context of Gradle’s domain
objects (DSL objects).
The main DSL object is a org.gradle.api.Project instance.
There is one-to-one relationship between a Projet object and a
build.gradle file.
Each DSL object exposes its own properties and methods.
Have a look at: Gradle DSL Reference
Putting it all together
Epiphany
1 //a groovy script with a Project object as the context
2 apply plugin: ”java”
3 //invocation of Project.apply(Map) method
4 group = ”org.foo.something”
5 version = ”1.0−SNAPSHOT”
6 //update of project.group, project.version properties
7 repositories {
8 mavenCentral()
9 }
10 //invocation of the Project.repositories(Closure) method
11 //From the docs: the closure has a RepositoryHandler object
12 //as its delegate
13 dependencies {
14 compile ”commons−io:commons−io:2.4”
15 testCompile ”junit:junit:4.11”
16 runtime files(”lib/foo.jar”, ”lib/bar.jar”)
17 }
18 //here?
Quiz
And here?
1 apply plugin:’java’
2 task generateFiles(type: JavaExec) {
3 main = ’some.class.name’
4 classpath = sourceSets.main.runtimeClasspath
5 args = [ projectDir, ’path/to/gen/files’ ]
6 }
7 test {
8 dependsOn generateFiles
9 doLast {
10 ant.copy(toDir:’build/test−classes’){
11 fileset dir:’path/to/gen/files’
12 }
13 }
14 }
15 import org.apache.commons.io.FileUtils
16 clean.doFirst {
17 FileUtils.deleteQuietly(new File(’path/to/gen/files’))
18 }
Build lifecycle
Configuration vs Execution Phase
1 test {//closure runs at configuration phase
2 dependsOn generateFiles
3 doLast { //at execution phase
4 ant.copy(toDir:’build/test−classes’){
5 fileset dir:’path/to/gen/files’
6 }
7 }
8 }
9 test.doLast { //at execution phase
10 ant.copy...
11 }
12 task test << { //at execution phase
13 ant.copy...
14 }
15 test { //at configuration phase
16 ant.copy...
17 }
18 task test { //at configuration phase
19 ant.copy...
20 }
Thank you
Questions?
Proudly powered by:
LATEX
Using the Beamer class &
the Wronki theme (slightly modified).
1 of 39

Recommended

Gradle by
GradleGradle
GradleJadson Santos
7.1K views88 slides
Gradle - the Enterprise Automation Tool by
Gradle  - the Enterprise Automation ToolGradle  - the Enterprise Automation Tool
Gradle - the Enterprise Automation ToolIzzet Mustafaiev
3.9K views96 slides
Gradle Introduction by
Gradle IntroductionGradle Introduction
Gradle IntroductionDmitry Buzdin
7.8K views39 slides
Introduction to gradle by
Introduction to gradleIntroduction to gradle
Introduction to gradleNexThoughts Technologies
574 views22 slides
Exploring the power of Gradle in android studio - Basics & Beyond by
Exploring the power of Gradle in android studio - Basics & BeyondExploring the power of Gradle in android studio - Basics & Beyond
Exploring the power of Gradle in android studio - Basics & BeyondKaushal Dhruw
1.4K views62 slides
Hands on the Gradle by
Hands on the GradleHands on the Gradle
Hands on the GradleMatthias Käppler
5.8K views24 slides

More Related Content

What's hot

Maven by
MavenMaven
MavenEmprovise
1.2K views27 slides
Java 10 New Features by
Java 10 New FeaturesJava 10 New Features
Java 10 New FeaturesAli BAKAN
350 views30 slides
Introducing GitLab (September 2018) by
Introducing GitLab (September 2018)Introducing GitLab (September 2018)
Introducing GitLab (September 2018)Noa Harel
1.3K views44 slides
GraalVM by
GraalVMGraalVM
GraalVMNexThoughts Technologies
927 views15 slides
Version Control with Git by
Version Control with GitVersion Control with Git
Version Control with GitLuigi De Russis
1.1K views62 slides
BitBucket presentation by
BitBucket presentationBitBucket presentation
BitBucket presentationJonathan Lawerh
10.3K views18 slides

What's hot(20)

Maven by Emprovise
MavenMaven
Maven
Emprovise1.2K views
Java 10 New Features by Ali BAKAN
Java 10 New FeaturesJava 10 New Features
Java 10 New Features
Ali BAKAN350 views
Introducing GitLab (September 2018) by Noa Harel
Introducing GitLab (September 2018)Introducing GitLab (September 2018)
Introducing GitLab (September 2018)
Noa Harel1.3K views
Introduction to Gitlab | Gitlab 101 | Training Session by Anwarul Islam
Introduction to Gitlab | Gitlab 101 | Training SessionIntroduction to Gitlab | Gitlab 101 | Training Session
Introduction to Gitlab | Gitlab 101 | Training Session
Anwarul Islam1.9K views
Source Code Management systems by xSawyer
Source Code Management systemsSource Code Management systems
Source Code Management systems
xSawyer8.4K views
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017 by Hardik Trivedi
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi1.8K views
What is Kotlin Multiplaform? Why & How? by Shady Selim
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How?
Shady Selim2.4K views
Closures in Javascript by David Semeria
Closures in JavascriptClosures in Javascript
Closures in Javascript
David Semeria3.7K views
Maven Overview by FastConnect
Maven OverviewMaven Overview
Maven Overview
FastConnect8.5K views
Ansible presentation by Suresh Kumar
Ansible presentationAnsible presentation
Ansible presentation
Suresh Kumar7.1K views
An Introduction to Maven by Vadym Lotar
An Introduction to MavenAn Introduction to Maven
An Introduction to Maven
Vadym Lotar13.9K views

Viewers also liked

Gradle by Example by
Gradle by ExampleGradle by Example
Gradle by ExampleEric Wendelin
1.6K views21 slides
Gradle by
GradleGradle
GradleReturn on Intelligence
6K views26 slides
Gradle - time for a new build by
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new buildIgor Khotin
6.2K views69 slides
Gradle: The Build System you have been waiting for! by
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Corneil du Plessis
1.2K views21 slides
Building with Gradle by
Building with GradleBuilding with Gradle
Building with GradleKaunas Java User Group
1.7K views17 slides
Javaone - Gradle: Harder, Better, Stronger, Faster by
Javaone - Gradle: Harder, Better, Stronger, Faster Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster Andres Almiray
2.2K views32 slides

Viewers also liked(20)

Gradle - time for a new build by Igor Khotin
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
Igor Khotin6.2K views
Gradle: The Build System you have been waiting for! by Corneil du Plessis
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!
Corneil du Plessis1.2K views
Javaone - Gradle: Harder, Better, Stronger, Faster by Andres Almiray
Javaone - Gradle: Harder, Better, Stronger, Faster Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster
Andres Almiray2.2K views
Gradle enabled android project by Shaka Huang
Gradle enabled android projectGradle enabled android project
Gradle enabled android project
Shaka Huang8.1K views
Gradle 2.Breaking stereotypes by Strannik_2013
Gradle 2.Breaking stereotypesGradle 2.Breaking stereotypes
Gradle 2.Breaking stereotypes
Strannik_2013569 views
Gradle 2.Write once, builde everywhere by Strannik_2013
Gradle 2.Write once, builde everywhereGradle 2.Write once, builde everywhere
Gradle 2.Write once, builde everywhere
Strannik_2013613 views
Top 10 reasons to migrate to Gradle by Strannik_2013
Top 10 reasons to migrate to GradleTop 10 reasons to migrate to Gradle
Top 10 reasons to migrate to Gradle
Strannik_20132.5K views
Git.From thorns to the stars by Strannik_2013
Git.From thorns to the starsGit.From thorns to the stars
Git.From thorns to the stars
Strannik_20131.1K views
Gradle by thoraage
GradleGradle
Gradle
thoraage1.1K views
Android Gradle about using flavor by Ted Liang
Android Gradle about using flavorAndroid Gradle about using flavor
Android Gradle about using flavor
Ted Liang487 views
4. arteria carotida externa by anatogral
4. arteria carotida externa4. arteria carotida externa
4. arteria carotida externa
anatogral1K views
Predicting the Future as a Service with Azure ML and R by Barbara Fusinska
Predicting the Future as a Service with Azure ML and R Predicting the Future as a Service with Azure ML and R
Predicting the Future as a Service with Azure ML and R
Barbara Fusinska674 views
남동구 라선거구 최승원 by 승원 최
남동구 라선거구 최승원남동구 라선거구 최승원
남동구 라선거구 최승원
승원 최266 views
5. arteria carotida int. by anatogral
5. arteria carotida int.5. arteria carotida int.
5. arteria carotida int.
anatogral441 views

Similar to An Introduction to Gradle for Java Developers

In the Brain of Hans Dockter: Gradle by
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
1.5K views57 slides
Oscon Java Testing on the Fast Lane by
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
3.9K views39 slides
Apache Groovy: the language and the ecosystem by
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemKostas Saidis
2.8K views118 slides
What's New in Groovy 1.6? by
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?Guillaume Laforge
697 views45 slides
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge by
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
694 views53 slides
Using the Groovy Ecosystem for Rapid JVM Development by
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentSchalk Cronjé
895 views79 slides

Similar to An Introduction to Gradle for Java Developers(20)

In the Brain of Hans Dockter: Gradle by Skills Matter
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
Skills Matter1.5K views
Oscon Java Testing on the Fast Lane by Andres Almiray
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray3.9K views
Apache Groovy: the language and the ecosystem by Kostas Saidis
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
Kostas Saidis2.8K views
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge by GR8Conf
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf694 views
Using the Groovy Ecosystem for Rapid JVM Development by Schalk Cronjé
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
Schalk Cronjé895 views
Gradleintroduction 111010130329-phpapp01 by Tino Isnich
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich364 views
Boosting Your Testing Productivity with Groovy by James Williams
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
James Williams1.2K views
Javaone2008 Bof 5101 Groovytesting by Andres Almiray
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
Andres Almiray960 views
10 Cool Facts about Gradle by Evgeny Goldin
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
Evgeny Goldin6.8K views
Gradle - Build system evolved by Bhagwat Kumar
Gradle - Build system evolvedGradle - Build system evolved
Gradle - Build system evolved
Bhagwat Kumar922 views
淺談 Groovy 與 AWS 雲端應用開發整合 by Kyle Lin
淺談 Groovy 與 AWS 雲端應用開發整合淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合
Kyle Lin12.6K views
Java 9 features by shrinath97
Java 9 featuresJava 9 features
Java 9 features
shrinath97121 views
GTAC Boosting your Testing Productivity with Groovy by Andres Almiray
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
Andres Almiray1.3K views
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge by Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Guillaume Laforge3.8K views
Gradle in 45min - JBCN2-16 version by Schalk Cronjé
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
Schalk Cronjé868 views
Groovy a Scripting Language for Java by Charles Anderson
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
Charles Anderson1.1K views
Taming Functional Web Testing with Spock and Geb by C4Media
Taming Functional Web Testing with Spock and GebTaming Functional Web Testing with Spock and Geb
Taming Functional Web Testing with Spock and Geb
C4Media8.3K views
Gradle in a Polyglot World by Schalk Cronjé
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
Schalk Cronjé1.6K views

Recently uploaded

What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueShapeBlue
222 views23 slides
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineShapeBlue
181 views19 slides
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...ShapeBlue
138 views18 slides
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...ShapeBlue
120 views13 slides
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...ShapeBlue
88 views13 slides
Cencora Executive Symposium by
Cencora Executive SymposiumCencora Executive Symposium
Cencora Executive Symposiummarketingcommunicati21
139 views14 slides

Recently uploaded(20)

What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue222 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue181 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue138 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue120 views
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by ShapeBlue
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
ShapeBlue88 views
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue117 views
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ... by ShapeBlue
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
ShapeBlue146 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue93 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue210 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue132 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue197 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue112 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue176 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue94 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue163 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue140 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue79 views

An Introduction to Gradle for Java Developers

  • 1. An Introduction to Gradle for Java Developers Kostas Saidis www.niovity.com Java Hellenic User Group Meetup April 2, 2016
  • 2. About Me Kostas Saidis saiko@niovity.com Software & Data Architect Twitter: @saikos Linkedin: http://gr.linkedin.com/in/saiko Academia BSc @ cs.unipi.gr (2001) MSc @ di.uoa.gr (2004) PhD @ di.uoa.gr (2011) Industry Freelance consultant, developer & instructor since 1999 Enterpreneur since 2011 (niovity) Java Early Java enthusiast (1997) Groovyist since 2011
  • 3. Using Gradle Building software with Gradle Since version 0.9 Fifteen real-life projects with team sizes ranging from 2 to 10 members Custom plugin authoring
  • 4. Target audience Java developers with little or no experience in Gradle or another build tool.
  • 6. Software build tools Tools for managing and automating the software build process.
  • 7. Software what? Building software sucks! (big time) Software build process Develop Test Assemble Deploy Integrate Repeat Again and again and again
  • 8. What is Gradle? Gradle is one of the finest software build tools out there Makes the software build process easier to setup, extend and maintain
  • 9. In this presentation We focus on understanding Gradle Gradle is a superb piece of software What makes it so great? No flame wars No feature comparison with other tools
  • 10. At a glance Gradle Open source: Apache License v2 First release 2009, latest release March 2016 (2.12) Backed by Gradleware... ooops, I mean Gradle Inc Used by: Android, Spring IO, Linkedin, Netflix, Twitter and more...
  • 11. At a glance Gradle Combines the best of Ant, Ivy and Maven Cross-platform file management Dependency management Conventions In a smart and extensible way Deep API Groovy DSL Easy-to-write plugins Ultimately offering Clean and elegant builds Plenty of new features Better build management
  • 12. Features Non exhaustive list Full-fledged programmability Both declarative and imperative Convention over configuration Transitive dependency management Multi-project builds Polyglot (not only Java) Numerous plugins and integrations Incremental and parallel execution Reporting and analytics Embeddable Great documentation
  • 13. The most distinct features IMHO 1. Its superb design and technical sophistication. 2. The exposure and manipulation of its “internal” Java APIs through Groovy (aka the Groovy DSL).
  • 14. A simple example A simple Java project 1 apply plugin: ”java” 2 group = ”org.foo.something” 3 version = ”1.0−SNAPSHOT” 4 repositories { 5 mavenCentral() 6 } 7 dependencies { 8 compile ”commons−io:commons−io:2.4” 9 testCompile ”junit:junit:4.11” 10 runtime files(”lib/foo.jar”, ”lib/bar.jar”) 11 } The contents of build.gradle (aka the build script), placed in the root folder of the project.
  • 15. Core Concepts Build script: a build configuration script supporting one or more projects. Project: a component that needs to be built. It is made up of one or more tasks. Task: a distinct step required to perform the build. Each task/step is atomic (either succeeds or fails). Publication: the artifact produced by the build process.
  • 16. Dependency Resolution Dependencies: tasks and projects depending on each other (internal) or on third-party artifacts (external). Transitive dependencies: the dependencies of a project may themselves have dependencies. Repositories: the “places” that hold external dependencies (Maven/Ivy repos, local folders). DAG: the directed acyclic graph of dependencies (what depends on what). Dependency configurations : named sets (groups) of dependencies (e.g. per task).
  • 17. Plugins A plugin applies a set of extensions to the build process. Add taks to a project. Pre-configure these tasks with reasonable defaults. Add dependency configurations. Add new properties and methods to existing objects. Plugins implement the “build-by-convention” principle in a flexible way.
  • 18. The Build Lifecycle 1. Initialization: initialization of the project. 2. Configuration: configuration of the project (computes the DAG). 3. Execution: executes the sequence of build tasks.
  • 19. The simple example 1 apply plugin: ”java” 2 //Introduces a set of Maven−style conventions 3 //(tasks, source locations, dependency configurations, etc) 4 group = ”org.foo.something” 5 version = ”1.0−SNAPSHOT” 6 repositories { 7 //resolve all external dependencies via Maven central 8 mavenCentral() 9 } 10 dependencies { 11 //each name (compile, testCompile, etc) refers to 12 //a configuration introduced by the java plugin 13 compile ”commons−io:commons−io:2.4” 14 testCompile ”junit:junit:4.11” 15 runtime files(”lib/foo.jar”, ”lib/bar.jar”) 16 }
  • 20. Invoking gradle Run a build task > gradle test Compiles the sources and runs the tests > gradle tasks clean, assemble, build, classes, testClasses, test, jar, etc Never invoke gradle directly but always use the gradle wrapper: a mechanism to execute gradle without manually installing it beforehand (not covered here).
  • 21. A more complex example Ant integration, custom tasks 1 apply plugin:’java’ 2 task generateFiles(type: JavaExec) { 3 main = ’some.class.name’ 4 classpath = sourceSets.main.runtimeClasspath 5 args = [ projectDir, ’path/to/gen/files’ ] 6 } 7 test { 8 dependsOn generateFiles 9 doLast { 10 ant.copy(toDir:’build/test−classes’){ 11 fileset dir:’path/to/gen/files’ 12 } 13 } 14 } 15 import org.apache.commons.io.FileUtils 16 clean.doFirst { 17 FileUtils.deleteQuietly(new File(’path/to/gen/files’)) 18 }
  • 23. Let’s have a closer look 1 //apply the java plugin as before 2 apply plugin:’java’ 3 //introduce a new task (that invokes a java process) 4 task generateFiles(type: JavaExec) { 5 main = ’some.class.name’ 6 classpath = sourceSets.main.runtimeClasspath 7 args = [ projectDir, ’path/to/gen/files’ ] 8 } 9 //customize the test task 10 test { 11 dependsOn generateFiles 12 doLast { 13 ant.copy(toDir:’build/test−classes’){ 14 fileset dir:’path/to/gen/files’ 15 } 16 } 17 } 18 //import a class required by this build script 19 //some necessary classpath definitions are not shown for brevity 20 import org.apache.commons.io.FileUtils 21 //customize the clean task 22 clean.doFirst { 23 FileUtils.deleteQuietly(new File(’path/to/gen/files’)) 24 }
  • 26. The Gradle DSL Gradle’s power lies in its Groovy-based DSL What you need to know about Groovy to start using Gradle in its full potential For more Groovy magic, have a look at: An Introduction to Groovy for Java Developers
  • 27. What is Groovy? Groovy is a feature-rich, Java-friendly language for the JVM A super version of Java Augments Java with additional features Designed as a companion language for Java seamless integration with Java → an additional jar at runtime! syntactically aligned with Java → syntactically correct Java will work in Groovy (with some gotchas)! compiles into JVM bytecode and preserves Java semantics → call Groovy from Java == call Java from Java! the 2nd language targeting the Java platform (JSR-241) → Java was the first!
  • 28. Groovy Scripts Java 1 public class Booh { 2 public static void main(String[] args) { 3 System.out.println(”Booh booh”); 4 } 5 } Compile and run it. Groovy 1 println(”Booh booh”) Run it directy.
  • 29. POJOs vs POGOs Java 1 public class Foo { 2 private String message; 3 public void setMessage(String message) { 4 this.message = message; 5 } 6 public String getMessage() { 7 return message; 8 } 9 } Groovy 1 class Foo { 2 String message 3 }
  • 30. Groovy Map Syntax Java 1 Map<String, String> pairs = new HashMap(); 2 pairs.put(”one”, ”1”); 3 pairs.put(”two”, ”2”); Groovy 1 Map<String, String> pairs = [one:’1’, two:”2”]
  • 31. Groovy Operator Overloading 1 import java.util.concurrent.* 2 class Tasks { 3 List<Callable> taskList = [] 4 void execute() { 5 for(Callable t: taskList) { 6 t.run() 7 } 8 } 9 void leftShift(Tasks tasks) { 10 taskList.addAll(tasks.taskList) 11 } 12 } 13 Tasks t1 = new Tasks() 14 ... 15 Tasks t2 = new Tasks() 16 ... 17 t1 << t2
  • 32. Groovy Closures A closure is an anonymous function together with a referencing environment. may accept parameters or return a value, can be assigned to variables, can be passed as argument, captures the variables of its surrounding lexical scope.
  • 33. Example 1 class Test { 2 long x = 3 3 //a block of code assigned to a variable 4 Closure<Long> times = { long l −> l * x } 5 //x is the free variable 6 } 7 Test test = new Test() 8 assert test.times(3) == 9 9 test.x = 4 10 assert test.times(3) == 12 11 class Test2 { 12 long x = 0 13 } 14 test.times.resolveStrategy = Closure.DELEGATE_FIRST 15 test.times.delegate = new Test2() 16 assert test.times(3) == 0
  • 34. Groovy method invocation syntax 1 //omit parentheses 2 println(”booh booh”) 3 println ”booh booh” 4 method ”one”, 2 5 //omit map’s braces 6 method([one:1, two: 2]) 7 method(one:1, two:2) 8 method one:1, two:2 9 //The closure as last argument pattern 10 Closure clos = { int x, int y −> x + y } 11 method(”one”, 2, clos) 12 method ”one”, 2, clos 13 method(”one”, 2) { int x, int y −> 14 x + y 15 }
  • 35. Back to Gradle Behind the scenes Gradle build scripts are Groovy scripts. Such Groovy scripts operate in the context of Gradle’s domain objects (DSL objects). The main DSL object is a org.gradle.api.Project instance. There is one-to-one relationship between a Projet object and a build.gradle file. Each DSL object exposes its own properties and methods. Have a look at: Gradle DSL Reference
  • 36. Putting it all together Epiphany 1 //a groovy script with a Project object as the context 2 apply plugin: ”java” 3 //invocation of Project.apply(Map) method 4 group = ”org.foo.something” 5 version = ”1.0−SNAPSHOT” 6 //update of project.group, project.version properties 7 repositories { 8 mavenCentral() 9 } 10 //invocation of the Project.repositories(Closure) method 11 //From the docs: the closure has a RepositoryHandler object 12 //as its delegate 13 dependencies { 14 compile ”commons−io:commons−io:2.4” 15 testCompile ”junit:junit:4.11” 16 runtime files(”lib/foo.jar”, ”lib/bar.jar”) 17 } 18 //here?
  • 37. Quiz And here? 1 apply plugin:’java’ 2 task generateFiles(type: JavaExec) { 3 main = ’some.class.name’ 4 classpath = sourceSets.main.runtimeClasspath 5 args = [ projectDir, ’path/to/gen/files’ ] 6 } 7 test { 8 dependsOn generateFiles 9 doLast { 10 ant.copy(toDir:’build/test−classes’){ 11 fileset dir:’path/to/gen/files’ 12 } 13 } 14 } 15 import org.apache.commons.io.FileUtils 16 clean.doFirst { 17 FileUtils.deleteQuietly(new File(’path/to/gen/files’)) 18 }
  • 38. Build lifecycle Configuration vs Execution Phase 1 test {//closure runs at configuration phase 2 dependsOn generateFiles 3 doLast { //at execution phase 4 ant.copy(toDir:’build/test−classes’){ 5 fileset dir:’path/to/gen/files’ 6 } 7 } 8 } 9 test.doLast { //at execution phase 10 ant.copy... 11 } 12 task test << { //at execution phase 13 ant.copy... 14 } 15 test { //at configuration phase 16 ant.copy... 17 } 18 task test { //at configuration phase 19 ant.copy... 20 }
  • 39. Thank you Questions? Proudly powered by: LATEX Using the Beamer class & the Wronki theme (slightly modified).