SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
Introduction to Gradle
Andrey Adamovich
Aestas/IT
What is Gradle?
   Gradle is a general purpose build system
   It comes with a rich build description
    language (DSL) based on Groovy
   It supports ”build-by-convention” principle
   But it is very flexible and extensible
   It has built-in plug-ins for Java, Groovy,
    Scala, Web, OSGi
   It derives all the best and integrates well
    with Ivy, Ant and Maven
What’s in this presentation?
 Overview
 Basic features & principles
 Files and file collections
 Dependencies
 Multiple projects
 Plug-ins
 Reading material
 Questions
OVERVIEW
Gradle features I
 Declarative builds and build-by-
  convention
 Language for dependency based
  programming and many ways to
  manage dependencies
 Groovy as a base language allows
  imperative programming
Gradle features II
 Deep and rich API for managing
  projects, tasks, dependency
  artefacts and much more.
 State of the art support for multi-
  project builds
 Ease of integration and migration.
  Ant, Maven, Ivy are supported out-
  of-the-box
 Free and open source
Advanced features
 Parallel unit test execution
 Dependency build
 Incremental build support
 Dynamic tasks and task rules
 Gradle daemon
Who uses Gradle?
   Hibernate               Canoo
   Grails                  Carrier
   Groovy                  FCC
   Spring Integration      Zeppelin
   Spring Security         GPars
   Griffon                 Spock
   Gaelyk                  Aluminum
   Qi4j                    Gant
BASIC FEATURES &
PRINCIPLES
Hello, Gradle!
build.gradle:
task hello << {
  println ’Hello, World'
}            >gradle hello
                :hello
                Hello, World!

                BUILD SUCCESSFUL

                Total time: 2.401 secs


build.gradle:
task hello << {
  print ’Hello, '
}

task world(dependsOn: hello) << {
  println ’World!'
}             >gradle -q hello world
                Hello, World!

                >gradle -q world
                Hello, World!
Task configuration & execution
task hello

message = "What's up?"

hello {
  println "Configuring hello task."
  message = 'Hello, World!'
}

hello << {
  println message
                              >gradle hello
}                             Configuring hello task.
                              :hello
                              Hello, World!
hello << {                    What's up?
  println project.message
                              BUILD SUCCESSFUL
}
                              Total time: 1.958 secs
Gradle is Groovy, Groovy is Java
Java:

import java.io.File;
…
String parentDir = new File(”test.txt”)
                     .getAbsoluteFile()
                     .getParentPath();


Groovy:
def parentDir = new File(”test.txt”).absoluteFile.parentPath



Gradle:
parentDir = file(”test.txt”).absoluteFile.parentPath
Building Java project
apply plugin: 'java'


                       >gradle clean build
                       :clean
                       :compileJava
                       :processResources UP-TO-DATE
                       :classes
                       :jar
                       :assemble
                       :compileTestJava UP-TO-DATE
                       :processTestResources UP-TO-DATE
                       :testClasses UP-TO-DATE
                       :test
                       :check
                       :build

                       BUILD SUCCESSFUL

                       Total time: 7.6 secs
Java plug-in tasks
 compileJava         processResources                    clean


                            classes                     javadoc


compileTestJava    processTestResources                   jar


                          testClasses


                             test                      uploadArchives


                  check                     assemble



                                    build
Extending tasks
test {
  systemProperties ("net.sourceforge.cobertura.datafile": cobSerFile)
  cobSerFile = "${project.buildDir}/cobertura.ser"
}

test.doFirst {
  ant {
    delete(file: cobSerFile, failonerror: false)
    'cobertura-instrument'(datafile: cobSerFile) {
        fileset(dir: "${sourceSets.main.classesDir}", includes: "**/*.class") }
    }
  }
}

test.doLast {
  ant.'cobertura-report'(
        destdir: "${project.buildDirName}/test-results",
        format: 'xml',
        srcdir: "src/main/java",
        datafile: cobSerFile)
}
Ant is a first-class citizen

   All Ant tasks and types can be used
    inside Gradle script using Groovy
    syntax

   Whole Ant build script can be
    imported into Gradle and its targets
    can be called
Ant usage examples I
task hello << {
  String greeting = "hello from Ant"
  ant.echo(message: greeting)
}


task list << {
  def path = ant.path {
    fileset(dir: 'libs', includes: '*.jar')
  }
  path.list().each {
    println it
  }
}


task zip << {
  ant.zip(destfile: 'archive.zip') {
    fileset(dir: 'src') {
      include(name: '**.xml')
      exclude(name: '**.java')
    }
  }
}
Ant usage examples II
ant.taskdef(resource: 'checkstyletask.properties') {
  classpath {
    fileset(dir: 'libs/checkstyle', includes: '*.jar')
  }
}

ant.checkstyle(config: 'src/tools/sun_checks.xml') {
  fileset(dir: 'src')
}




<project>
  <target name="hello">
     <echo>Hello, from Ant</echo>
  </target>
</project>                                   >gradle hello
                                             :hello
                                             [ant:echo] Hello, from Ant

ant.importBuild 'build.xml'                  BUILD SUCCESSFUL

                                             Total time: 7.898 secs
Overriding conventions
version = 1.0
group = ’org.gradletutorials’


version = "1.0-${new Date().format('yyyyMMdd')}"


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

build.taskGraph.whenReady { taskGraph ->
  if (taskGraph.hasTask(':release')) {
    version = '1.0’
  } else {
    version = '1.0-SNAPSHOT’
  }
}



sourceSets.main.java.srcDirs += ["src/generated/java"]
sourceSets.main.resources.srcDirs += ["src/generated/resources"]
More examples
 Many source directory sets per
  project without a need of a plug-in
 Different dependencies per source
  directory
 Even different JDK per source
  directory
 Many artifacts per project
FILES AND FILE
COLLECTIONS
Referencing files & file collections
Groovy-like syntax:
// Using a relative path
File configFile = file('src/config.xml')

Create a file collection from a bunch of files:
FileCollection collection = files(
      'src/file1.txt',
      new File('src/file2.txt'),
      ['src/file3.txt', 'src/file4.txt'])

Create a files collection by referencing project properties:
collection = files { srcDir.listFiles() }

Operations on collections:
def union = collection + files('src/file4.txt')
def different = collection - files('src/file3.txt')}
Using file collections as input
Many objects in Gradle have properties, which accept a set of
input files. For example, the compile task has a source property,
which defines the source files to compile. You can set the value
of this property using any of the types supported by the files()
method:
// Use a File object to specify the source directory.
compile {
  source = file('src/main/java')
}

// Using a closure to specify the source files.
compile {
  source = {
    // Use the contents of each zip file in the src dir.
    file('src')
      .listFiles()
      .findAll { it.name.endsWith('.zip') }
      .collect { zipTree(it) }
    }
  }
}1
Copying files
Using Ant integration:
ant.copy(todir: 'javadoc') {
  fileset(dir: 'build/docs')
}


Using Gradle task type:

task copyTask(type: Copy) {
  from 'src/main/webapp‘
  into 'build/explodedWar‘
  include '**/*.jsp‘
  exclude { details ->
    details.file.name.endsWith('.html') &&
    details.file.text.contains('staging')
  }
}
DEPENDENCY
MANAGEMENT
Repository configuration
repositories {
  mavenCentral()
}


repositories {
  mavenCentral name: 'single-jar-repo', urls: "http://repo.mycompany.com/jars"
  mavenCentral name: 'multi-jar-repos', urls:
    ["http://repo.mycompany.com/jars1", "http://repo.mycompany.com/jars1"]
}


repositories {
  flatDir name: 'localRepository',
  dirs: 'lib' flatDir dirs: ['lib1', 'lib2']
}


repositories {
  add(new org.apache.ivy.plugins.resolver.FileSystemResolver()) {
    name = 'localRepository'
    latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy()
    addArtifactPattern(libDir +
      '/[organization]/[artifact]/[ext]s/[artifact]-[revision].[ext]')
  }
}
Referencing dependencies
dependencies {
  runtime files('libs/a.jar', 'libs/b.jar')
  runtime fileTree(dir: 'libs', includes: ['*.jar'])
}

dependencies {
  compile 'org.springframework:spring-webmvc:3.0.0.RELEASE'
  testCompile 'org.springframework:spring-test:3.0.0.RELEASE'
  testCompile 'junit:junit:4.7'
}


dependencies {
  runtime group: 'org.springframework', name: 'spring-core', version: '2.5'
  runtime 'org.springframework:spring-core:2.5',
          'org.springframework:spring-aop:2.5
}


List groovy = ["org.codehaus.groovy:groovy-all:1.5.4@jar",
               "commons-cli:commons-cli:1.0@jar",
               "org.apache.ant:ant:1.7.0@jar"]
List hibernate = ['org.hibernate:hibernate:3.0.5@jar',
                  'somegroup:someorg:1.0@jar']

dependencies {
  runtime groovy, hibernate
}
Transitive dependencies
configurations.compile.transitive = true

dependencies {
  compile 'org.springframework:spring-webmvc:3.0.0.RC2'
  runtime 'org.hibernate:hibernate:3.0.5'
}




dependencies {
  compile 'org.springframework:spring-webmvc:3.0.0.RC2'
  runtime('org.hibernate:hibernate:3.0.5') {
    transitive = true
  }
}
MULTI-PROJECT BUILDS
Directories & settings.gradle
settings.gradle:

include 'shared', 'api', ':service:service1', ':service:service2'




                                 You can have only one build file
                                  for the whole multi-project build
                                 All properties, settings, plug-ins,
                                  dependencies are derived without
                                  a need to duplicate information
                                 You can override almost all
                                  behaviour in child builds
All or something
allprojects {
  task build << {
    println "Building project: " + project.name
  }
}                                   >gradle build
                                     :build
subprojects {                        Building project: 90-multi-project
  task prebuild << {                 :api:prebuild
    println "It is subproject!"      It is subproject!
                                     :api:build
  }                                  Building project: api
  build.dependsOn prebuild           :service:prebuild
}                                    It is subproject!
                                     :service:build
                                     Building project: service
                                     :shared:prebuild
                                     It is subproject!
                                     :shared:build
                                     Building project: shared
                                     :service:service1:prebuild
                                     It is subproject!
                                     :service:service1:build
                                     Building project: service1
                                     :service:service2:prebuild
                                     It is subproject!
                                     :service:service2:build
                                     Building project: service2

                                     BUILD SUCCESSFUL

                                     Total time: 9.684 secs
Inter-project dependencies
subprojects {
  apply plugin: 'java'
  if (project.name.matches('^.*serviced+$')) {
    dependencies {
                                  >gradle clean build
      compile project(':api')
                                  :api:clean
      compile project(':shared') :service:clean
    }                             :shared:clean
  }                               :service:service1:clean
                                  :service:service2:clean
}                                                                        :service:service1:compileJava
                                     :shared:compileJava UP-TO-DATE      :service:service1:processResources UP-TO-DATE
                                     :shared:processResources UP-TO-DATE :service:service1:classes
project(':api') {                    :shared:classes UP-TO-DATE          :service:service1:jar
  dependencies {                     :shared:jar                         :service:service1:assemble
                                     :api:compileJava
    compile project(':shared')                                           :service:service1:compileTestJava
                                     :api:processResources UP-TO-DATE    :service:service1:processTestResources UP-TO-
  }                                  :api:classes                        DATE
}                                    :api:jar                            :service:service1:testClasses
                                     :api:assemble                       :service:service1:test
                                     :api:compileTestJava
dependsOnChildren()                                                      :service:service1:check
                                     :api:processTestResources UP-TO-DATE:service:service1:build
                                     :api:testClasses                    :service:service2:compileJava
                                     :api:test                           :service:service2:processResources UP-TO-DATE
                                     :api:check                          :service:service2:classes
                                     :api:build                          :service:service2:jar
                                     :service:compileJava UP-TO-DATE     :service:service2:assemble
                                     :service:processResources UP-TO-DATE:service:service2:compileTestJava
                                     :service:classes UP-TO-DATE         :service:service2:processTestResources UP-TO-
                                     :service:jar                        DATE
                                     :service:assemble                   :service:service2:testClasses
                                     :service:compileTestJava UP-TO-DATE :service:service2:test
                                     :service:processTestResources UP-TO-DATE
                                                                         :service:service2:check
                                     :service:testClasses UP-TO-DATE     :service:service2:build
                                     :service:test UP-TO-DATE
                                     :service:check UP-TO-DATE           BUILD SUCCESSFUL
                                     :service:build
                                     :shared:assemble                    Total time: 3.75 secs
                                     :shared:compileTestJava UP-TO-DATE
                                     :shared:processTestResources UP-TO-DATE
                                     :shared:testClasses UP-TO-DATE
                                     :shared:test UP-TO-DATE
                                     :shared:check UP-TO-DATE
                                     :shared:build
PLUGINS
Extending your build
Any Gradle script can be a plug-in:
apply from: 'otherScript.gradle'
apply from: 'http://mycomp.com/otherScript.gradle'



Use many of the standard or 3rd-party plug-ins:
apply   plugin:   'java'
apply   plugin:   'groovy'
apply   plugin:   'scala'
apply   plugin:   'war'


Configuration objects can be externalized:
task configure << {
  pos = new java.text.FieldPosition(10)
  // Apply the script.
  apply from: 'position.gradle', to: pos
  println pos.beginIndex
  println pos.endIndex
                                         position.gradle:
}
                                            beginIndex = 1;
                                            endIndex = 5;
Standard plug-ins
Plug-in ID                   Plug-in ID
base                         application (java, groovy)
java-base                    jetty (war)
groovy-base                  maven (java, war)
scala-base                   osgi (java-base, java)
reporting-base               war (java)
java (java-base)             code-quality (reporting-base, java,
                             groovy)

groovy (java, groovy-base)   eclipse (java, groovy, scala, war)
scala (java, scala-base)     idea (java)
antlr (java)                 project-report (reporting-base)
announce                     sonar
READING MATERIAL
Resources
   http://www.gradle.org
    ◦ /tutorials
    ◦ /current/docs/userguide/userguide.html
    ◦ /current/docs/dsl/index.html
   http://groovy.codehaus.org
    ◦ /gapi/
    ◦ /groovy-jdk/
    ◦ /User+Guide
   http://ant.apache.org/manual
Literature
                         “Build and test software written in Java and
                         many other languages with Gradle, the open
                         source project automation tool that’s getting
                         a lot of attention. This concise introduction
                         provides numerous code examples to help
                         you explore Gradle, both as a build tool and
                         as a complete solution for automating the
                         compilation, test, and release process of
                         simple and enterprise-level applications .”




 http://shop.oreilly.com/product/0636920019909.do
QUESTIONS?

Mais conteúdo relacionado

Mais procurados

Practical introduction to dev ops with chef
Practical introduction to dev ops with chefPractical introduction to dev ops with chef
Practical introduction to dev ops with chef
LeanDog
 

Mais procurados (20)

Ship your Scala code often and easy with Docker
Ship your Scala code often and easy with DockerShip your Scala code often and easy with Docker
Ship your Scala code often and easy with Docker
 
Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010
 
How and Why Prometheus' New Storage Engine Pushes the Limits of Time Series D...
How and Why Prometheus' New Storage Engine Pushes the Limits of Time Series D...How and Why Prometheus' New Storage Engine Pushes the Limits of Time Series D...
How and Why Prometheus' New Storage Engine Pushes the Limits of Time Series D...
 
Continous delivery with sbt
Continous delivery with sbtContinous delivery with sbt
Continous delivery with sbt
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
PuppetCamp SEA 1 - Use of Puppet
PuppetCamp SEA 1 - Use of PuppetPuppetCamp SEA 1 - Use of Puppet
PuppetCamp SEA 1 - Use of Puppet
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
Gradle in 45min
Gradle in 45minGradle in 45min
Gradle in 45min
 
Python virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutesPython virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutes
 
Practical introduction to dev ops with chef
Practical introduction to dev ops with chefPractical introduction to dev ops with chef
Practical introduction to dev ops with chef
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin Writing
 
Simple Build Tool
Simple Build ToolSimple Build Tool
Simple Build Tool
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
 
Get Gulping with Javascript Task Runners
Get Gulping with Javascript Task RunnersGet Gulping with Javascript Task Runners
Get Gulping with Javascript Task Runners
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
 
SBT Concepts, part 2
SBT Concepts, part 2SBT Concepts, part 2
SBT Concepts, part 2
 
The Gradle in Ratpack: Dissected
The Gradle in Ratpack: DissectedThe Gradle in Ratpack: Dissected
The Gradle in Ratpack: Dissected
 
SBT Crash Course
SBT Crash CourseSBT Crash Course
SBT Crash Course
 
Challenges of container configuration
Challenges of container configurationChallenges of container configuration
Challenges of container configuration
 

Destaque

Utilized Ant to do Windchill Deployment
Utilized Ant to do Windchill DeploymentUtilized Ant to do Windchill Deployment
Utilized Ant to do Windchill Deployment
Guo Albert
 
Grammaire Anglaise : BE ou HAVE
Grammaire Anglaise : BE ou HAVEGrammaire Anglaise : BE ou HAVE
Grammaire Anglaise : BE ou HAVE
Monique SEGOL
 
Vocabulaire anglais : les prepositions
Vocabulaire anglais : les prepositionsVocabulaire anglais : les prepositions
Vocabulaire anglais : les prepositions
Monique SEGOL
 
Prepositions de lieu
Prepositions de lieuPrepositions de lieu
Prepositions de lieu
lebaobabbleu
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
glassfish
 
Les pronoms & adjectifs personnels en anglais
Les pronoms & adjectifs personnels en anglaisLes pronoms & adjectifs personnels en anglais
Les pronoms & adjectifs personnels en anglais
Mr Quentin
 

Destaque (20)

Utilized Ant to do Windchill Deployment
Utilized Ant to do Windchill DeploymentUtilized Ant to do Windchill Deployment
Utilized Ant to do Windchill Deployment
 
PTC Windchill ESI 9.x Architecture
PTC Windchill ESI 9.x ArchitecturePTC Windchill ESI 9.x Architecture
PTC Windchill ESI 9.x Architecture
 
Whats Next for JCA?
Whats Next for JCA?Whats Next for JCA?
Whats Next for JCA?
 
Plm & windchill
Plm & windchillPlm & windchill
Plm & windchill
 
Grammaire Anglaise : BE ou HAVE
Grammaire Anglaise : BE ou HAVEGrammaire Anglaise : BE ou HAVE
Grammaire Anglaise : BE ou HAVE
 
Grammaire anglaise : les Temps Recap
Grammaire anglaise : les Temps RecapGrammaire anglaise : les Temps Recap
Grammaire anglaise : les Temps Recap
 
Vocabulaire anglais : les prepositions
Vocabulaire anglais : les prepositionsVocabulaire anglais : les prepositions
Vocabulaire anglais : les prepositions
 
Prepositions de lieu
Prepositions de lieuPrepositions de lieu
Prepositions de lieu
 
Support JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.YoussfiSupport JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.Youssfi
 
Grammaire anglaise : pronoms personnels - I, YOU, HE,...
Grammaire anglaise : pronoms personnels - I, YOU, HE,...Grammaire anglaise : pronoms personnels - I, YOU, HE,...
Grammaire anglaise : pronoms personnels - I, YOU, HE,...
 
Grammaire anglaise :les quantifieurs -SOME, ANY, A LOT OF, ...
Grammaire anglaise :les quantifieurs -SOME, ANY, A LOT OF, ...Grammaire anglaise :les quantifieurs -SOME, ANY, A LOT OF, ...
Grammaire anglaise :les quantifieurs -SOME, ANY, A LOT OF, ...
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 
Les pronoms & adjectifs personnels en anglais
Les pronoms & adjectifs personnels en anglaisLes pronoms & adjectifs personnels en anglais
Les pronoms & adjectifs personnels en anglais
 
Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...
 
Apprendre l'anglais gratuitement par Eric Lamidieu
Apprendre l'anglais gratuitement par Eric LamidieuApprendre l'anglais gratuitement par Eric Lamidieu
Apprendre l'anglais gratuitement par Eric Lamidieu
 
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
 
softCours design pattern m youssfi partie 9 creation des objets abstract fact...
softCours design pattern m youssfi partie 9 creation des objets abstract fact...softCours design pattern m youssfi partie 9 creation des objets abstract fact...
softCours design pattern m youssfi partie 9 creation des objets abstract fact...
 
Support de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfiSupport de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfi
 
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
 
Support de cours Spring M.youssfi
Support de cours Spring  M.youssfiSupport de cours Spring  M.youssfi
Support de cours Spring M.youssfi
 

Semelhante a Gradleintroduction 111010130329-phpapp01

Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
Igor Khotin
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
Ngoc Dao
 

Semelhante a Gradleintroduction 111010130329-phpapp01 (20)

Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
Gradle
GradleGradle
Gradle
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
 
Gradle - Build system evolved
Gradle - Build system evolvedGradle - Build system evolved
Gradle - Build system evolved
 
OpenCms Days 2012 - Developing OpenCms with Gradle
OpenCms Days 2012 - Developing OpenCms with GradleOpenCms Days 2012 - Developing OpenCms with Gradle
OpenCms Days 2012 - Developing OpenCms with Gradle
 
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!
Gradle: The Build System you have been waiting for!
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
DevOps Odessa #TechTalks 21.01.2020
DevOps Odessa #TechTalks 21.01.2020DevOps Odessa #TechTalks 21.01.2020
DevOps Odessa #TechTalks 21.01.2020
 
Programming language for the cloud infrastructure
Programming language for the cloud infrastructureProgramming language for the cloud infrastructure
Programming language for the cloud infrastructure
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java Developers
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Dev ops meetup
Dev ops meetupDev ops meetup
Dev ops meetup
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
 
Single Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle StorySingle Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle Story
 

Último

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Gradleintroduction 111010130329-phpapp01

  • 1. Introduction to Gradle Andrey Adamovich Aestas/IT
  • 2. What is Gradle?  Gradle is a general purpose build system  It comes with a rich build description language (DSL) based on Groovy  It supports ”build-by-convention” principle  But it is very flexible and extensible  It has built-in plug-ins for Java, Groovy, Scala, Web, OSGi  It derives all the best and integrates well with Ivy, Ant and Maven
  • 3. What’s in this presentation?  Overview  Basic features & principles  Files and file collections  Dependencies  Multiple projects  Plug-ins  Reading material  Questions
  • 5. Gradle features I  Declarative builds and build-by- convention  Language for dependency based programming and many ways to manage dependencies  Groovy as a base language allows imperative programming
  • 6. Gradle features II  Deep and rich API for managing projects, tasks, dependency artefacts and much more.  State of the art support for multi- project builds  Ease of integration and migration. Ant, Maven, Ivy are supported out- of-the-box  Free and open source
  • 7. Advanced features  Parallel unit test execution  Dependency build  Incremental build support  Dynamic tasks and task rules  Gradle daemon
  • 8. Who uses Gradle?  Hibernate  Canoo  Grails  Carrier  Groovy  FCC  Spring Integration  Zeppelin  Spring Security  GPars  Griffon  Spock  Gaelyk  Aluminum  Qi4j  Gant
  • 10. Hello, Gradle! build.gradle: task hello << { println ’Hello, World' } >gradle hello :hello Hello, World! BUILD SUCCESSFUL Total time: 2.401 secs build.gradle: task hello << { print ’Hello, ' } task world(dependsOn: hello) << { println ’World!' } >gradle -q hello world Hello, World! >gradle -q world Hello, World!
  • 11. Task configuration & execution task hello message = "What's up?" hello { println "Configuring hello task." message = 'Hello, World!' } hello << { println message >gradle hello } Configuring hello task. :hello Hello, World! hello << { What's up? println project.message BUILD SUCCESSFUL } Total time: 1.958 secs
  • 12. Gradle is Groovy, Groovy is Java Java: import java.io.File; … String parentDir = new File(”test.txt”) .getAbsoluteFile() .getParentPath(); Groovy: def parentDir = new File(”test.txt”).absoluteFile.parentPath Gradle: parentDir = file(”test.txt”).absoluteFile.parentPath
  • 13. Building Java project apply plugin: 'java' >gradle clean build :clean :compileJava :processResources UP-TO-DATE :classes :jar :assemble :compileTestJava UP-TO-DATE :processTestResources UP-TO-DATE :testClasses UP-TO-DATE :test :check :build BUILD SUCCESSFUL Total time: 7.6 secs
  • 14. Java plug-in tasks compileJava processResources clean classes javadoc compileTestJava processTestResources jar testClasses test uploadArchives check assemble build
  • 15. Extending tasks test { systemProperties ("net.sourceforge.cobertura.datafile": cobSerFile) cobSerFile = "${project.buildDir}/cobertura.ser" } test.doFirst { ant { delete(file: cobSerFile, failonerror: false) 'cobertura-instrument'(datafile: cobSerFile) { fileset(dir: "${sourceSets.main.classesDir}", includes: "**/*.class") } } } } test.doLast { ant.'cobertura-report'( destdir: "${project.buildDirName}/test-results", format: 'xml', srcdir: "src/main/java", datafile: cobSerFile) }
  • 16. Ant is a first-class citizen  All Ant tasks and types can be used inside Gradle script using Groovy syntax  Whole Ant build script can be imported into Gradle and its targets can be called
  • 17. Ant usage examples I task hello << { String greeting = "hello from Ant" ant.echo(message: greeting) } task list << { def path = ant.path { fileset(dir: 'libs', includes: '*.jar') } path.list().each { println it } } task zip << { ant.zip(destfile: 'archive.zip') { fileset(dir: 'src') { include(name: '**.xml') exclude(name: '**.java') } } }
  • 18. Ant usage examples II ant.taskdef(resource: 'checkstyletask.properties') { classpath { fileset(dir: 'libs/checkstyle', includes: '*.jar') } } ant.checkstyle(config: 'src/tools/sun_checks.xml') { fileset(dir: 'src') } <project> <target name="hello"> <echo>Hello, from Ant</echo> </target> </project> >gradle hello :hello [ant:echo] Hello, from Ant ant.importBuild 'build.xml' BUILD SUCCESSFUL Total time: 7.898 secs
  • 19. Overriding conventions version = 1.0 group = ’org.gradletutorials’ version = "1.0-${new Date().format('yyyyMMdd')}" task release(dependsOn: assemble) << { println 'We release now' } build.taskGraph.whenReady { taskGraph -> if (taskGraph.hasTask(':release')) { version = '1.0’ } else { version = '1.0-SNAPSHOT’ } } sourceSets.main.java.srcDirs += ["src/generated/java"] sourceSets.main.resources.srcDirs += ["src/generated/resources"]
  • 20. More examples  Many source directory sets per project without a need of a plug-in  Different dependencies per source directory  Even different JDK per source directory  Many artifacts per project
  • 22. Referencing files & file collections Groovy-like syntax: // Using a relative path File configFile = file('src/config.xml') Create a file collection from a bunch of files: FileCollection collection = files( 'src/file1.txt', new File('src/file2.txt'), ['src/file3.txt', 'src/file4.txt']) Create a files collection by referencing project properties: collection = files { srcDir.listFiles() } Operations on collections: def union = collection + files('src/file4.txt') def different = collection - files('src/file3.txt')}
  • 23. Using file collections as input Many objects in Gradle have properties, which accept a set of input files. For example, the compile task has a source property, which defines the source files to compile. You can set the value of this property using any of the types supported by the files() method: // Use a File object to specify the source directory. compile { source = file('src/main/java') } // Using a closure to specify the source files. compile { source = { // Use the contents of each zip file in the src dir. file('src') .listFiles() .findAll { it.name.endsWith('.zip') } .collect { zipTree(it) } } } }1
  • 24. Copying files Using Ant integration: ant.copy(todir: 'javadoc') { fileset(dir: 'build/docs') } Using Gradle task type: task copyTask(type: Copy) { from 'src/main/webapp‘ into 'build/explodedWar‘ include '**/*.jsp‘ exclude { details -> details.file.name.endsWith('.html') && details.file.text.contains('staging') } }
  • 26. Repository configuration repositories { mavenCentral() } repositories { mavenCentral name: 'single-jar-repo', urls: "http://repo.mycompany.com/jars" mavenCentral name: 'multi-jar-repos', urls: ["http://repo.mycompany.com/jars1", "http://repo.mycompany.com/jars1"] } repositories { flatDir name: 'localRepository', dirs: 'lib' flatDir dirs: ['lib1', 'lib2'] } repositories { add(new org.apache.ivy.plugins.resolver.FileSystemResolver()) { name = 'localRepository' latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy() addArtifactPattern(libDir + '/[organization]/[artifact]/[ext]s/[artifact]-[revision].[ext]') } }
  • 27. Referencing dependencies dependencies { runtime files('libs/a.jar', 'libs/b.jar') runtime fileTree(dir: 'libs', includes: ['*.jar']) } dependencies { compile 'org.springframework:spring-webmvc:3.0.0.RELEASE' testCompile 'org.springframework:spring-test:3.0.0.RELEASE' testCompile 'junit:junit:4.7' } dependencies { runtime group: 'org.springframework', name: 'spring-core', version: '2.5' runtime 'org.springframework:spring-core:2.5', 'org.springframework:spring-aop:2.5 } List groovy = ["org.codehaus.groovy:groovy-all:1.5.4@jar", "commons-cli:commons-cli:1.0@jar", "org.apache.ant:ant:1.7.0@jar"] List hibernate = ['org.hibernate:hibernate:3.0.5@jar', 'somegroup:someorg:1.0@jar'] dependencies { runtime groovy, hibernate }
  • 28. Transitive dependencies configurations.compile.transitive = true dependencies { compile 'org.springframework:spring-webmvc:3.0.0.RC2' runtime 'org.hibernate:hibernate:3.0.5' } dependencies { compile 'org.springframework:spring-webmvc:3.0.0.RC2' runtime('org.hibernate:hibernate:3.0.5') { transitive = true } }
  • 30. Directories & settings.gradle settings.gradle: include 'shared', 'api', ':service:service1', ':service:service2'  You can have only one build file for the whole multi-project build  All properties, settings, plug-ins, dependencies are derived without a need to duplicate information  You can override almost all behaviour in child builds
  • 31. All or something allprojects { task build << { println "Building project: " + project.name } } >gradle build :build subprojects { Building project: 90-multi-project task prebuild << { :api:prebuild println "It is subproject!" It is subproject! :api:build } Building project: api build.dependsOn prebuild :service:prebuild } It is subproject! :service:build Building project: service :shared:prebuild It is subproject! :shared:build Building project: shared :service:service1:prebuild It is subproject! :service:service1:build Building project: service1 :service:service2:prebuild It is subproject! :service:service2:build Building project: service2 BUILD SUCCESSFUL Total time: 9.684 secs
  • 32. Inter-project dependencies subprojects { apply plugin: 'java' if (project.name.matches('^.*serviced+$')) { dependencies { >gradle clean build compile project(':api') :api:clean compile project(':shared') :service:clean } :shared:clean } :service:service1:clean :service:service2:clean } :service:service1:compileJava :shared:compileJava UP-TO-DATE :service:service1:processResources UP-TO-DATE :shared:processResources UP-TO-DATE :service:service1:classes project(':api') { :shared:classes UP-TO-DATE :service:service1:jar dependencies { :shared:jar :service:service1:assemble :api:compileJava compile project(':shared') :service:service1:compileTestJava :api:processResources UP-TO-DATE :service:service1:processTestResources UP-TO- } :api:classes DATE } :api:jar :service:service1:testClasses :api:assemble :service:service1:test :api:compileTestJava dependsOnChildren() :service:service1:check :api:processTestResources UP-TO-DATE:service:service1:build :api:testClasses :service:service2:compileJava :api:test :service:service2:processResources UP-TO-DATE :api:check :service:service2:classes :api:build :service:service2:jar :service:compileJava UP-TO-DATE :service:service2:assemble :service:processResources UP-TO-DATE:service:service2:compileTestJava :service:classes UP-TO-DATE :service:service2:processTestResources UP-TO- :service:jar DATE :service:assemble :service:service2:testClasses :service:compileTestJava UP-TO-DATE :service:service2:test :service:processTestResources UP-TO-DATE :service:service2:check :service:testClasses UP-TO-DATE :service:service2:build :service:test UP-TO-DATE :service:check UP-TO-DATE BUILD SUCCESSFUL :service:build :shared:assemble Total time: 3.75 secs :shared:compileTestJava UP-TO-DATE :shared:processTestResources UP-TO-DATE :shared:testClasses UP-TO-DATE :shared:test UP-TO-DATE :shared:check UP-TO-DATE :shared:build
  • 34. Extending your build Any Gradle script can be a plug-in: apply from: 'otherScript.gradle' apply from: 'http://mycomp.com/otherScript.gradle' Use many of the standard or 3rd-party plug-ins: apply plugin: 'java' apply plugin: 'groovy' apply plugin: 'scala' apply plugin: 'war' Configuration objects can be externalized: task configure << { pos = new java.text.FieldPosition(10) // Apply the script. apply from: 'position.gradle', to: pos println pos.beginIndex println pos.endIndex position.gradle: } beginIndex = 1; endIndex = 5;
  • 35. Standard plug-ins Plug-in ID Plug-in ID base application (java, groovy) java-base jetty (war) groovy-base maven (java, war) scala-base osgi (java-base, java) reporting-base war (java) java (java-base) code-quality (reporting-base, java, groovy) groovy (java, groovy-base) eclipse (java, groovy, scala, war) scala (java, scala-base) idea (java) antlr (java) project-report (reporting-base) announce sonar
  • 37. Resources  http://www.gradle.org ◦ /tutorials ◦ /current/docs/userguide/userguide.html ◦ /current/docs/dsl/index.html  http://groovy.codehaus.org ◦ /gapi/ ◦ /groovy-jdk/ ◦ /User+Guide  http://ant.apache.org/manual
  • 38. Literature “Build and test software written in Java and many other languages with Gradle, the open source project automation tool that’s getting a lot of attention. This concise introduction provides numerous code examples to help you explore Gradle, both as a build tool and as a complete solution for automating the compilation, test, and release process of simple and enterprise-level applications .” http://shop.oreilly.com/product/0636920019909.do