46
Gradle: Build tool that rocks with DSL Rajmahendra Hegde JUGChennai Founder & Lead [email protected] tweet: @rajonjava

Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Embed Size (px)

DESCRIPTION

For the long time, we have used various build tools to package applications for new software releases or applying patches to existing applications etc. dependency management, version controlling, scalability, flexibility, single-multiple projects sup portability are some of the key areas that drove the selection of a build tool, This session focuses on Gradle as a successful build tool and looks into all the above areas and uses Groovy as a DSL. We will also look into how easy it is to use Gradle as compared to other open source build tools. Photos: https://plus.google.com/u/0/photos/105295086916869617504/albums/5739617166453582993 Gradle build tool that rocks with DSL By Rajmahendra Hegde at JavaOne Hyderabad, India on 4th May 2012

Citation preview

Page 1: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle: Build tool that rocks with DSL

Rajmahendra HegdeJUGChennai Founder & [email protected]

tweet: @rajonjava

Page 2: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

aboutMe {

name: 'Rajmahendra Hegde'

community: name: 'Java User Group – Chennai', role: 'Founder and Lead', url: 'http://jugchennai.in'

profession: company: 'Logica', designation: 'Project Lead'

javaDeveloperSince: 1999

contributions {

jcp: [jsrID: 354, name: 'Money and Currency API'],[jsrID: 357, 'Social Media']

communityProject: 'Agorava', 'VisageFX', 'Scalaxia.com', 'gradle-weaverfx-plugin'

}

interests: 'JUG Activities','JEE', 'Groovy', 'Scala', 'JavaFX', 'VisageFX', 'NetBeans', 'Gradle'

twitter: '@rajonjava'

email: '[email protected]'}

Page 3: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Agenda

• Build tools• Build tool basics• Gradle• Getting Started• Gradle Tasks• Gradle with Ant• Gradle with Maven• Plugins• Multi Project Support• Project Templates• IDEs Support

Page 4: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Automated Build Tool

Source Files,Resource Filesetc.

Jar

War

jpi

XYZ...

Build Tool

Page 5: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Build Tool

• Initialize• checkout• Compile• Check-style• Test• Code coverage • Jar• War• Ear• Deploy• etc...

• Generic build process• Dev, Test, Integ,

environment• Continuous Integration

Page 6: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Evolution of build tools

• Javac, Jar.. - Command based• IDEs – Application based

(a need for building application outside the IDEs!) (this is the age of onsite deployment and Continuous Integration)

• Ant – Task based - (XML)• Maven – Goal based (XML)• …• Gradle – A mix of good practices/tools(ant, maven,ivy etc.) with a flavor of

DSL

Page 7: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Build Tools

Page 8: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle is

• A general purpose Java build system• Platform independent• DSL based • Built for java based projects • Full support of Grooy, Ant and Maven• Task based system• Convention over configuration• Flexible, scalable, extensible• Plugins • Flexible multi-project support• Free and open source

Page 9: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Why

Core JavaNo

<XML>Use

@annotation

JVM LanguageNo

<XML>Use

DSL{}

Page 10: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

A domain-specific language (DSL) is a programming language or specification language dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique. - Wikipedia

Examples

Chess Notation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 1. P-K4 P-K4 2. N-KB3 N-QB3 3. B-B4 B-B4

Music Western Musical Notation – C, D, E, F, G, A, B, C Solfège syllables – Do, Re, Mi, Fa, Sol, La, Ti, Do. Carnatic Music Notation – Sa Re Ga Ma Pa Da Ne Sa Guitar Tab - 0 1 2 3 4 Harmonica Tab – 1b 1b 2d 2d

Rubik's Cube Notation - d', d2. f, f', f2, b, b', b2

Very popular in our own field SQL! SELECT * FROM MYTABLE WHERE MYFIELD = 4

And many...

DSL? Domain Specific Language

Page 11: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

DSLs in Action

By - Debasish GhoshForewords by: Jonas Bonér

December, 2010 | 376 pages ISBN: 9781935182450

DSLs in Action introduces the concepts you'll need to build high-quality domain-specific languages. It explores DSL implementation based on JVM languages like Java, Scala, Clojure, Ruby, and Groovy and contains fully explained code snippets that implement real-world DSL designs. For experienced developers, the book addresses the intricacies of DSL design without the pain of writing parsers by hand.

http://www.manning.com/ghosh/

Read about DSL

Page 12: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

• Download binary zip from gradle.org• Unzip in your favorite folder

• Set GRADLE_HOME Env. Variable • Add GRADLE_HOME[/ or \ ]bin to PATH

• To test $ gradle -v

• Build File name: – build.gradle– gradle.properties– settings.gradle

Getting Started$ gradle -v

--------------------------------------Gradle 1.0-rc-2--------------------------------------

Gradle build time: Tuesday, April 24, 2012 11:52:37 PM UTCGroovy: 1.8.6Ant: Apache Ant(TM) version 1.8.2 compiled on December 20 2010Ivy: 2.2.0JVM: 1.6.0_31 (Apple Inc. 20.6-b01-415)OS: Mac OS X 10.7.3 x86_64

Page 13: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

• Initializationl Initializes the scope of the buildl Identifies projects [multi-project env.] involvedl Creates Project instance

• Configurationl Executes buildscript{} for all its scopel Configures the project objects

• Executionl Determines the subset of the tasksl Runs the build

Build Lifecycle

Page 14: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task mytask << { println 'Hello World'}

mytask.doFirst { println 'The First'}

mytask.doLast { println 'The Last' }

mytask << {println 'Add more'

}

Gradle Tasks$ gradle mytask:mytaskThe FirstHello WorldThe LastAdd moreBUILD SUCCESSFUL

Page 15: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task mytask << {

String myString = 'Hello World'

def myMap = ['map1': '1', 'map2':'2']

println myString println myString.toUpperCase() println 'Map2: ' + myMap['map2']

5.times { if (it % 2 == 0) println (“Count $it”) } }

Gradle is Groovy$ gradle mytask:mytaskHello WorldHELLO WORLDMap2: 2Count 0Count 2Count 4

BUILD SUCCESSFUL

Page 16: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task task1(dependsOn: 'task2') << { println 'Task 1'}

task task2 (dependsOn: 'task3') << { println 'Task 2'}

task task4 << { println 'Task 4'}task task3 (dependsOn: task4) << { println 'Task 3'}

Gradle Task Dependencies $ gradle task1:task4Task 4:task3Task 3:task2Task 2:task1Task 1BUILD SUCCESSFUL

Page 17: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

defaultTasks 'task3', 'task1'

task task1 << { println 'Task 1'}

task task2 << { println 'Task 2'}

task task4 << { println 'Task 4'}

task task3 << { println 'Task 3'}

Gradle defaultTasks $ gradle:task3Task 3:task1Task 1BUILD SUCCESSFUL

Page 18: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task distribution << { println "We build the zip with version=$version"}

task release(dependsOn: 'distribution') << { println 'We release now'}

gradle.taskGraph.whenReady {taskGraph → if (taskGraph.hasTask(release)) {version = '1.0' } else { version = '1.0-SNAPSHOT' }}

Gradle DAG $ gradle distribution:distributionWe build the zip with version=1.0-SNAPSHOTBUILD SUCCESSFUL

$ gradle release:distributionWe build the zip with version=1.0:releaseWe release nowBUILD SUCCESSFUL

From Gradle Userguide

Page 19: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task copy(type: Zip) { from 'resources' into 'target' include('**/*.properties')}

// OR

task myCopy(type: Zip)myCopy.configure { from('source') into('target') include('**/*.properties')}

Configuring Tasks // ORtask myCopy(type: Zip)myCopy { from 'resources' into 'target' include( '**/*.properties')}

// OR

task(myCopy, type: Zip) .from('resources') .into('target') .include( '**/*.properties')

Page 20: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle with Ant

• Ant is first-class-citizen for Gradle• ant Builder • Available in all .gradle file

• Ant .xml• Directly import existing ant into Gradle build!• Ant targets can be called directly

Page 21: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task callAnt << { ant.echo (message: 'Hello Ant 1') ant.echo ('Hello Ant 2') ant.echo message: 'Hello Ant 3' ant.echo 'Hello Ant 4'}

task myCompile << {

ant.java(classname: 'com.my.classname',classpath: ${sourceSets.main.runtimeClasspath.asPath}")

}

Gradle with Ant...$ gradle callAnt:callAnt[ant:echo] Hello Ant 1[ant:echo] Hello Ant 2[ant:echo] Hello Ant 3[ant:echo] Hello Ant 4

BUILD SUCCESSFUL

Page 22: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

task runPMD << {

ant.taskdef(name: 'pmd', classname: 'net.sourceforge.pmd.ant.PMDTask',classpath: configurations.pmd.asPath) ant.pmd(shortFilenames: 'true', failonruleviolation: 'true', rulesetfiles: file('pmd-rules.xml').toURI().toString()) { formatter(type: 'text', toConsole: 'true') fileset(dir: 'src') }}

Gradle with Ant...

Page 23: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

<!-- build.xml --><project> <target name="antHello"> <echo>Hello, from Ant.</echo> </target></project>

// build.gradleant.importBuild 'build.xml'

Gradle calls Ant$ gradle antHello:antHello[ant:echo] Hello, from Ant.

BUILD SUCCESSFUL

Page 24: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

<!-- build.xml --><project> <target name="callAnt">

<echo>Hello, from Ant.</echo> </target></project>

// build.gradleant.importBuild 'build.xml'

callAnt << {println 'Gradle adds behaviour

to Ant task.'}

Gradle adds behaviour to Ant task$ gradle callAnt:callAnt[ant:echo] Hello, from Ant.Gradle adds behaviour to Ant task

BUILD SUCCESSFUL

Page 25: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle with Maven

• Ant Ivy• Gradle build on Ivy for dependency management

• Maven Repository• Gradle works with any Maven repository

• Maven Project Structure• By default Gradle uses Maven project structure

Page 26: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Maven Project Structure

Images: http://educloudsims.wordpress.com/

Page 27: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

repository {

mavenCentral() mavenLocal()

maven { url: “http://repo.myserver.come/m2”, “http://myserver.com/m2” }

ivy { url: “http://repo.myserver.come/m2”, “http://myserver.com/m2” url: “../repo” } mavenRepo url: "http://twitter4j.org/maven2", artifactUrls: ["http://oss.sonatype.org/content/repositories/snapshots/", "http://siasia.github.com/maven2", "http://typesafe.artifactoryonline.com/typesafe/ivy-releases", "http://twitter4j.org/maven2"]

}

Gradle repository

Page 28: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

dependencies {

compile group: 'org.springframework', name: 'spring-core', version: '2.0'

runtime 'org.springframework:spring-core:2.5'

runtime('org.hibernate:hibernate:3.0.5')

runtime "org.groovy:groovy:1.5.6"

compile project(':shared')

compile files('libs/a.jar', 'libs/b.jar')

runtime fileTree(dir: 'libs', include: '**/*.jar')

testCompile “junit:junit:4.5”

}

Gradle dependency

Page 29: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

repositories { flatDir { name "localrepo" dirs "../repo" }}

uploadArchives { repositories { add project.repositories.fileRepo ivy { credentials { username "username" password "password" } url "http://ivyrepo.mycompany.com/m2" } }}

Gradle Publish

Page 30: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Plugin Support

Page 31: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle Plugins

apply from: 'mybuild.gradle'

apply from: 'http://www.mycustomer.come/folders/mybuild.gradle'

apply plugin: 'java' apply plugin: 'war' apply plugin: 'jetty'

//Minimum gradle code to work with Java or War project:apply plugin: 'java' // ORapply plugin: 'war'apply plugin: 'jetty'

dependencies { testCompile “junit:junit:4.5”}

Page 32: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Java Pluginsapply plugin: 'java'

sourceCompatability = 1.7targetCompatability = 1.7

dependencies{ testCompile “junit:junit:4.5” }task "create-dirs" << { sourceSets*.java.srcDirs*.each { it.mkdirs() } sourceSets*.resources.srcDirs*.each { it.mkdirs() }}

src/main/java

src/main/resource

src/main/test

src/main/resource

Page 33: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

War Pluginsapply plugin: 'war'

src/main/webapp

Page 34: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Jetty Pluginsapply plugin: 'jetty'

Property Default Value

httpPort 8080

Page 35: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

• Android• AspectJ• CloudFactory• Cobertura• Ubuntu Packager• Emma• Exec• FindBug• Flex• Git• Eclipse• GWT• JAXB• ...

For more plugins : http://wiki.gradle.org/display/GRADLE/Plugins

Community Plugins

Page 36: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

apply plugin: SayHelloPlugin

sayhello.name = 'Raj'

class SayHelloPlugin implements Plugin<Project> {

void apply(Project project) {

project.extensions.create("sayhello", SayHelloPluginExtension)

project.task('sayHello') << {

println "Hello " + project.sayhello.name }

}}

class SayHelloPluginExtension { def String name = 'Default'

}

Writing Custom Plugin$ gradle sayHello:sayHelloHello Raj

BUILD SUCCESSFUL

//If we remove//sayhello.name = 'Raj'$ gradle sayHello:sayHelloHello Default

BUILD SUCCESSFUL

Page 37: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Multi Project Support

Page 38: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Multi Project Support//settings.gradle - defines the project participates in the buildinclude 'api', 'services', 'web'

allprojects {apply plugin: 'java'group = 'org.gradle.sample'version = '1.0 task omnipotenceTask { println 'You find me in all the project' }

}

subprojects { repositories {mavenCentral()} dependencies { compile "javax.servlet:servlet-api:2.5" }task callHoldMyBro (dependsOn: ':elderBro:compileJava') {}}

project(':war') {

apply plugin: 'java'

dependencies {compile "javax.servlet:servlet-api:2.5", project(':api') }}

Page 39: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle Project TemplatesA Gradle plugin which provides templates, and template methods like 'initGroovyProject' to users. This makes it easier to get up and running using Gradle as a build tool.

apply from: 'http://launchpad.net/gradle-templates/trunk/latest/+download/apply.groovy'

$ gradle createJavaProject

More Info: https://launchpad.net/gradle-templates

Page 40: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle Project Templates// Inside apply.gradlebuildscript {

repositories {ivy {

name = 'gradle_templates'artifactPattern "http://launchpad.net/[organization]/trunk/

[revision]/+download/[artifact]-[revision].jar"}

}dependencies {

classpath 'gradle-templates:templates:1.2'}

}// Check to make sure templates.TemplatesPlugin isn't already added.if (!project.plugins.findPlugin(templates.TemplatesPlugin)) {

project.apply(plugin: templates.TemplatesPlugin)}

Page 41: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle Wrapper// Write this code in your main Graldy build file.task wrapper(type: Wrapper) { gradleVersion = '1.0-rc-3'}

$ gradle wrapper

//Created files.myProject/ gradlew gradlew.bat gradle/wrapper/ gradle-wrapper.jar gradle-wrapper.properties

Page 42: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Gradle IDE Support

Page 43: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Reference • http://gradle.orga• http://gradle.org/overview• http://gradle.org/documentation• http://gradle.org/roadmap• http://docs.codehaus.org/display/GRADLE/Cookbook

http://www.gradle.org/toolinghttp://gradle.org/contribute

Page 44: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

Q & A

Page 45: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

User Group Events JUG-India

Java User Groups - India

Find your nearest JUG at

http://java.net/projects/jug-india

For JUG updates around india

[email protected]

May 5th JUGChennai - Chennai - Stephen Chin – http://jugchennai.in/javafxBOJUG – Bangalore - Simon Ritter, Chuk Munn Lee,Roger Brinkley and Terrence Barr PuneJUG – Pune - Arun Gupta

November 2nd & 3rd AIOUG Sangam '12 [Java Track] (Main Speaker as of now Arun Gupta)Call for Paper is open - http://www.aioug.org/sangamspeakers.php

JUGChennai

Java User Groups - Chennai

Main Website

http://jugchennai.inTweets: @jug_cG Group: jug-c

Page 46: Gradle build tool that rocks with DSL JavaOne India 4th May 2012

46

Rajmahendra [email protected]: @rajonjava