Gradle Bookmarks

Published: 2019-08-04, Updated: 2023-04-13

Links

Setar args da jvm no gradle.properties

org.gradle.jvmargs=-Xmx100m

Application plugin

Gerar binario sem zipar

./gradlew installDist

criar um pojeto gradle

criando um projeto nao executavel com libs java

$ gradle init --type java-library

criando um projeto nao executavel com libs java com a versao especifica do wrapper

$ gradle wrapper --gradle-version 4.1 init --type java-library

Pular testes

gradle -x test

gradle assemble sonarqube #### funcionou para mim

Pular uma task

gradle -x taskName

Problema de charset no gradle

setar o charset no gradle do projeto

compileJava.options.encoding = 'UTF-8'
compileJava.options.compilerArgs += ['--enable-preview']

compileTestJava.options.encoding = 'UTF-8'
compileTestJava.options.compilerArgs += ['--enable-preview']
compileJava {
	options.compilerArgs += ['--enable-preview']
	options.encoding = 'UTF-8'
}

compileTestJava {
	options.encoding = 'UTF-8'
	options.compilerArgs += ['--enable-preview']
}

se for multi-module

subprojects {

  prj ->

    compileJava.options.encoding = 'ISO-8859-1'
    tasks.withType(JavaCompile) {
        options.encoding = 'ISO-8859-1'
    }
}

Pular testes do junit

tasks.findByPath(':mobile-api-ibanking-tests:test').enabled = false

Exemplo de uma task

task hello {
  doLast {
    println 'Hello Gradle'
  }
} 

seria o mesmo que

task hello << {
  println 'Hello Gradle'
} 

Configurações do projeto

por default o gradle pega o nome da pasta como nome do projeto, para mudar essas configurações pode-se setar no settings.gradle

rootProject.name ='com.vogella.gradle.first' 

Mostar as informações do projeto

gradle project

Mostrar as tasks disponíveis

gradle tasks

Chamar commando do terminal

Setar variaveis globais no gradle

To set a global variable

project.ext.set("variableName", value)

To access it from anywhere in the project:

project.variableName

For instance:

project.ext.set("newVersionName", versionString)

and then...

println project.newVersionName

For more information see: http://www.gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html

EDIT: As commented by Dmitry, In new versions you can use the following shorthand:

project.ext.variableName = value

Pegar err e output do exec

def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"

Setar o classpath de cada estado, test, compile, runtime, etc

sourceSets {
  test {
    resources {
      srcDir "test"
    }
  }
}

sourceSets {
	main {
		java {
			srcDir 'src'
		}
		resources {
			srcDirs = ['src', 'filters', 'i18n', 'resources']
			filter {
				exclude '**/*.java'
			}
		}
	}
}

Mudar diretorio onde o gradle builda, buildir, buildDir

./gradlew build -Dorg.gradle.project.buildDir=/tmp/gradle-build

Remover arquivos do jar na hora do build

jar {
    exclude("**/tmp.properties")
}

Dependências

Colocar um projeto externo gradle como dependência

include ':app', ":libmodule"
project(':libmodule').projectDir = new File(settingsDir, '../MyLibraryDemo/libmodule')

Configurar entrega de dependencia no nexus

Instalar pacote como dependência repositório maven local (forma 1)

publishing {
  publications {
    maven(MavenPublication) {
      groupId = "com.acme.mylib"
      artifactId = project.findProperty("artifactId")
      version = project.findProperty("version")
      from components.java
    }
  }
}
 ./gradlew build publishToMavenLocal

Resvolendo dependencias localmente

adicionar dependência de uma pasta local

Referenciar jar como dependencia

dependencies {
	compile fileTree("${projectDir}/src/main/libs/") // local jars
}

Pointing to local dir as repo

repositories {
  flatDir {
    dirs 'lib'
  }
  flatDir {
    dirs 'lib1', 'lib2'
  }
}

Resolve from specific maven local repository

repositories {
	mavenCentral()
	mavenLocal()
	maven {
		url uri("${projectDir}/libs/maven")
	}
}

get root project dir - jars dentro de uma pasta

compile fileTree("${rootProject.projectDir}/libs/bin/")

OBS: também funciona no intellij

rodar o jar buildado de dentro de gradle (não testado)

task "server-start"(dependsOn:[jar]){
	ant.java(jar: jar.archivePath, fork:true){
		jvmarg("value": "-Dcom.sun.management.jmxremote")
		jvmarg("value": "-Dcom.sun.management.jmxremote.port=1617")
		jvmarg("value": "-Dcom.sun.management.jmxremote.authenticate=false")
		jvmarg("value": "-Dcom.sun.management.jmxremote.ssl=false")
	}
}

get depedencies tree

gradle dependencies

mostrar apenas dependencias de compilacao

./gradlew dependencies --configuration runtimeClasspath

Ver se uma dependencia existe no projeto

$ ./gradlew :mg-app:dependencyInsight --configuration compile --dependency org.postgresql:postgresql
> Task :mg-app:dependencyInsight
org.postgresql:postgresql:42.2.1
   variant "default" [
      org.gradle.status = release (not requested)
   ]

org.postgresql:postgresql:42.2.1
\--- project :mg-core
     \--- project :mg-backoffice
          \--- project :mg-web
               \--- compile

A web-based, searchable dependency report is available by adding the --scan option.

BUILD SUCCESSFUL in 8s
1 actionable task: 1 executed

exclude dependency

compile("org.springframework.boot:spring-boot-starter-web"){
	exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' //by both name and group
}

or from project

compile(project(':moduleXYZ')){
	exclude group: 'org.springframework.security'
}

or force exclude from everywhere

configurations {
	compile.exclude group: 'org.apache.log4j'
	compile.exclude group: 'log4j'
	compile.exclude module: 'slf4j-log4j12'
}

Excluir classe de dentro da dependencia

Force a specific dependency version

configurations.all {
	resolutionStrategy {
		force 'xml-apis:xml-apis:1.4.01'
	}
}

add module as dependency

dependencies {
  compile project(':drink-master')
...

add module as dependency for other modules from root project

allprojects {
    apply plugin: 'java'
    dependencies {
    	compile project(':drink-master')

create multimodule project

settings.gradle

include ':drink-master'

add dependency for all modules but not for one

allprojects{
 if(!project.name.equals("orbada-res")){
  // adding res module to all modules but not for yourself
      compile project(':orbada-res')
  }
}

add a task on the gradle build

build.doLast{
	println('hi')
}

Create custom binary jar on a custom task on build lifecycle

/**
 * generate the binary distribution file
 */
build.doLast {

	/**
	 * generate jar with only compiled sources
	 * (the default comes with resources)
	 */
	ant.jar(
		destfile: jar.archivePath,
		"keepcompression": "true"
	) {
		zipfileset("dir": sourceSets.main.output.classesDir)
	}

	/**
	 * the distribution zip file
	 */
	ant.zip(destfile: "${jar.archivePath}".replace(".jar", ".zip")){

		// get the generated jar above and put inside
		fileset("file": jar.archivePath)

		// adding resouces
		zipfileset("dir": sourceSets.main.output.resourcesDir)

		// adding dependencies
		configurations.compile.collect {
			zipfileset("file": it.absolutePath, fullpath: "lib/${it.name}")
		}
	}
}

Gradle events

run after each submodule build finish

subprojects {

	project.build.doLast{

run after all project be builded (or get error on build)

gradle.buildFinished { build
println("fim build com sucesso")
}

run after each project be loaded

gradle.afterProject {
    println("fim projet")
}

run after all projects be loaded

gradle.projectsEvaluated{
    println("projects evaluated")
}

run after all submodules be builded

project.evaluationDependsOnChildren();
build.doLast{
    println("fim build com sucesso")
}

copiar conteudo de um diretorio para o outro

ant.copy(
    todir: sourceSets.main.output.resourcesDir
){
    fileset(dir: project(":orbada-res").sourceSets.main.output.resourcesDir)
}

Copiar os resources e zipa-lo

/**
 * Copying static files
 */
ant.copy(
	todir: binFilePath
){
	fileset(dir: project.sourceSets.main.output.resourcesDir)
}

/**
 * Create a distribution file
 */
ant.zip(destfile: "${distPath}/${project.name}.zip"){
	zipfileset("dir": binFilePath)
}

exlude all current files and include only matches

jar {
	include("*.properties")
	include("**/res/**")
}

other existents on that folder WILL NOT be included

skip project tests on build.gradle

tasks.findByPath(':conciliation-component-tests:test').enabled = false

Debugar gradle no intellij

export GRADLE_OPTS='-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006'

No intellij adicione um debug remoto e passe a porta

Fazer refresh das dependencias

gradle build --refresh-dependencies

ou se for um gradle antigo

rm -rf $HOME/.gradle/caches/

Configurar o gradlew

gradle wrapper --gradle-version 2.0

Logger no gradle

build.gradle

logger.quiet('An info log message which is always logged.')
logger.error('An error log message.')
logger.warn('A warning log message.')
logger.lifecycle('A lifecycle info log message.')
logger.info('An info log message.')
logger.debug('A debug log message.')
logger.trace('A trace log message.')

Usando o escopo provided no gradle

apply plugin: 'maven'
apply plugin: 'java'
apply plugin: 'idea'
 
repositories {
    mavenCentral()
}
 
configurations {
    provided
}
 
sourceSets {
    main {
        compileClasspath += configurations.provided
        test.compileClasspath += configurations.provided
        test.runtimeClasspath += configurations.provided
    }
}
 
// if you use 'idea' plugin, otherwise fails with: Could not find method idea() for arguments...
idea {
    module {
        /*
         * If you omit [ ] around, it fails with: Cannot change configuration ':provided' after it has been resolved
         * This is due Gradle 2.x using Groovy 2.3 that does not allow += for single elements addition.
         * More: https://discuss.gradle.org/t/custom-provided-configuration-not-working-with-gradle-2-0-rc2-in-multi-project-mode/2459
         */
        scopes.PROVIDED.plus += [configurations.provided]
        downloadJavadoc = true
        downloadSources = true
    }
}
 
dependencies {
    compile 'com.google.guava:guava:17.0'
    provided 'javax:javaee-api:7.0'
}

pulando testes apenas no build

/**
 * Nao roda testes no build
 */
assemble << {
    tasks.findByPath(':atm-component-tests:test').enabled = false
}

Setando charset no gradle

nome comeco do `gradlew` existe a variável `DEFAULT_JVM_OPTS`, sete nela o que precisar

Jogar arquivos customizados no resources antes de gerar o pacote

processResources {
	doLast {
		def dep = project.configurations.compileOnly.filter { it.name.contains('hawtio-web') }.singleFile
		ant.unzip(src: dep, dest: new File(project.sourceSets.main.output.resourcesDir, "hawtio-static")){
			patternset(excludes: '**/WEB-INF/**,**/META-INF/**')
		}
	}
}

Setando a versão no /info do spring

Veja que no intellij isso nao vai funcionar, para que funcione terá que fazer o que esse link diz

processResources {
    outputs.upToDateWhen { false }
    doLast{
        println(">> adicionando a versao: ${rootProject.version} no properties do build")
        ant.echo(file: "${buildDir}/resources/main/application.properties",
                append: true, message: "\ninfo.version=${rootProject.version}"
        )
    }
}

ou

processResources {
    outputs.upToDateWhen { false }
    filesMatching('application.properties') {
        expand(project.properties)
    }
}

outro exemplo

build.gradle

processResources {
	filesMatching('application.properties') {
		expand(project.properties)
	}
}

application.properties

info.version=${version}

outro exemplo ainda mais especifico

processResources {
  filesMatching("**/application.properties") {
    expand version: version
  }
}

Usar classes de teste de outro projeto

funfa no eclipse e intellij tambem

No projeto que tem as classes de teste a serem compartilhadas:

configurations {
    testArtifacts
}
  task testJar (type: Jar) {
    baseName = "${project.name}-test"
    from sourceSets.test.output
}
  artifacts {
    testArtifacts testJar
}

No projeto que vai usar

testCompile project (path: ":some-project", configuration: 'testArtifacts')

Setar os args

Para rodar a aplicacao

apply plugin: 'application'
applicationDefaultJvmArgs = ["-Dgreeting.language=en"]

Para testar

test {
	exclude '**/*IntTest*'
	jvmArgs += ['--enable-preview']
}

Compilar modulo especifico

gradle :ABC:build

Setar variaveis de ambiente no gradle

use uma das duas abaixo

$JAVA_OPTS $GRADLE_OPTS

Exemplo

export JAVA_OPTS="-Xmx100m"; ./gradlew build

Referenciar as dependencias de teste de outro modulo

Modulo original

configurations {
  testArtifacts
}

Modulo que vai depender

compile project(path: ":atm-core", configuration: 'testArtifacts')

Excluir uma dependencia que está no compile do testCompile

compileTestJava {
	classpath = classpath.filter {
		it.name != "Abc.jar"
		println(it.name)
	}
}

Rodando projeto scala no intellij e no gradle

apply plugin: 'scala'
apply plugin: 'idea'
repositories{
    mavenCentral()
    mavenLocal()
}
dependencies{
    compile 'org.slf4j:slf4j-api:1.7.5'
    compile "org.scala-lang:scala-library:2.10.4"
    compile "org.scala-lang:scala-compiler:2.10.4"
    testCompile "junit:junit:4.11"
}
task run(type: JavaExec, dependsOn: classes) {
    main = 'Main'
    classpath sourceSets.main.runtimeClasspath
    classpath configurations.runtime
}

Como desabilitar o gradle daemon

echo 'org.gradle.daemon=false' >> $HOME/.gradle/gradle.properties

Pulas testes e criar task customizada de teste

/**
 * é desabilitada por padrão para que
 * não execute com o build geral de todos os projetos
 */
test {
    enabled = false
}

/**
 * foi criada para ser usada para quando se desejar rodar o testes
 * esta task nao roda em build
 */
task "cucumber-test"(type: Test){
    reports.junitXml.enabled = false;
    reports.html.enabled = false;
}

Rodar uma classe

task runClazz(type:JavaExec) {
	main = 'ps.cip.core.crypt.utils.SecurityUtils'
	classpath = sourceSets.main.runtimeClasspath
}

Herdar dependencias do modulo colocando nas dependencias

task myTestsJar(type: Jar) { 
  // pack whatever you need...
}

configurations {
  testArtifacts
}

artifacts {
   testArtifacts myTestsJar
}

apply plugin: 'java'
dependencies {
  compile project(':ProjectA')
  testCompile project(path: ':ProjectA', configuration: 'testArtifacts')
}

Iterar nas dependencias

final artifacts = Arrays.asList("org.apache.derby:derby", "org.apache.derby:derbynet")
project.configurations.compile.resolvedConfiguration.resolvedArtifacts.collect { dep ->
	def id = dep.moduleVersion.id
	def artifact = String.format("%s:%s", id.getGroup(), id.getName())
	println "> contains = ${artifacts.get(0).getClass()}, ${artifact.getClass()}, artificats = ${artifacts}, dep = ${artifact}, jars = ${dep.getFile()}"
	if(artifacts.contains(artifact)){
		println("action=copying, artifact=${artifact}")
		ant.copy(file: dep.getFile(), todir: "${distPath}/database/derby-server/lib")
	}
	// class org.gradle.api.internal.artifacts.DefaultResolvedArtifact
}

Pegar de onde está resolvendo as depdendencias

apply plugin: 'java'

repositories{
  mavenCentral()
}

dependencies{
  compile 'com.google.guava:guava:12.0'
}

task showMeCache << {
  configurations.compile.each { println it }
}

Ignorar warnings de javadoc

tasks.withType(Javadoc) {
	options.addStringOption('Xdoclint:none', '-quiet')
}

Arvore de dependencias

./gradlew mg-app:dependencies --configuration testCompile | tee log.log | less

Setar caminho da JDK

Two ways

  1. In gradle.properties in the .gradle directory in your HOME_DIRECTORY set org.gradle.java.home=/path_to_jdk_directory

  2. In your build.gradle

    compileJava.options.fork = true compileJava.options.forkOptions.executable = /path_to_javac

Ativar modulos do java

compileJava {
	doFirst {
		options.compilerArgs = [
			'--module-path', classpath.asPath,
			'--add-modules', 'jdk.compiler',
			'--add-modules', 'jdk.compiler/com.sun.source.util=ALL-UNNAMED',
			'--add-exports', 'jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED',
			'--add-exports', 'jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED',
			'--add-exports', 'jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED',
			'--add-exports', 'jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED'
		]
	}
}

Annotation Processor

allprojects {
	dependencies {
		compileOnly('com.mageddo:raw-string-literals:1.0.0')
		annotationProcessor('com.mageddo:raw-string-literals:1.0.0')
	}
}

Rodar task do gradle no build do intellij

buildscript {
	dependencies {
		classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:0.9.1"
		classpath "gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.9"
	}
}
allprojects {
	apply plugin: "com.commercehub.gradle.plugin.avro"
	apply plugin: "org.jetbrains.gradle.plugin.idea-ext"
}

idea.project.settings {
	taskTriggers {
		beforeBuild tasks.generateAvroJava
	}
}

Junit 5 / Junit5

dependencies {
	testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
	testImplementation("org.mockito:mockito-junit-jupiter:5.1.1")
}

test {
	useJUnitPlatform()
	testLogging {
		events "passed", "skipped", "failed"
	}
}

Task para rodar / debugar

task debug(type: JavaExec){
	debug = true
	classpath = sourceSets.main.runtimeClasspath
	main = className
}

task run(type: JavaExec){
	classpath = sourceSets.main.runtimeClasspath
	main = className
}

Criando plugins

Quando você quer que um projeto build depois do outro

tasks."compileJava".dependsOn project(":jvmti-native").tasks."assemble"

Dynamic Version

Configurar versão dinâmica

configurations.all {
  resolutionStrategy.cacheDynamicVersionsFor 3, 'minutes' // reduzindo a cache que é 24hrs por default para que nao corra o risco de pegar deps desatualizadas da máquina 
}

dependencies {
  api("com.acme:placebo-lib:0.10.+")
}

Configurar dependencia de uma url direta

https://stackoverflow.com/questions/23446233/compile-jar-from-url-in-gradle/38105112#38105112

def urlFile = { url, name ->
    File file = new File("$buildDir/download/${name}.jar")
    file.parentFile.mkdirs()
    if (!file.exists()) {
        new URL(url).withInputStream { downloadStream ->
            file.withOutputStream { fileOut ->
                fileOut << downloadStream
            }
        }
    }
    files(file.absolutePath)
}
dependencies { //example
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
}

Gerar binário jar-with-dependencies no gradle

task fatJar(type: Jar) {
  archiveBaseName = project.name + '-all'
  manifest {
    attributes(
      'Main-Class': className,
      'Class-Path': configurations.compileClasspath.collect { "lib/${it.name}" }.join(' ')
    )
  }
  from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
  with jar
}

você também pode colocar as configurações acima dentro da task jar para assim gerar o jar executável em tempo de build

gerar jar auto executável em tempo de build

jar{
	manifest {
		attributes 'Main-Class': 'com.mageddo.test.jmxhelloworld.bean.SimpleAgent'
	}
	from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

Ignorar o SSL no gradle

echo 'allowInsecureProtocol=true' > $HOME/.gradle/gradle.properties

Custom sourceset



sourceSets {
    main {
        java {
            srcDirs = ["$projectDir/src/"]
            include '**/*.java'
            exclude '**/main/**'
        }

        resources {
            srcDirs = ["$projectDir/src/main/resources"]
        }
    }

    test {
//        java { srcDir "$projectDir/unittest" } // tambem funciona mas vai adicionar o dir ao inves de subsituir pelo default
        java {
            srcDirs = ["$projectDir/unittest"]
        }
        resources {
            srcDir 'src/test/resources'
        }
    }
}

Task específica para testes com um padrão de nome

CompTest

test {
  useJUnitPlatform()
  exclude "**/*CompTest.class"
  testLogging {
    events "passed", "skipped", "failed"
  }
}

task compTest(type: Test) {
  useJUnitPlatform()
  include "**/*CompTest.class"
  failFast = true
  testLogging {
    events "passed", "skipped", "failed"
  }
}

Testes Manuais

test {
	exclude "**/*ManualTest.class"
}

task manualTest(type: Test) {
	include "**/*ManualTest.class"
	failFast = true
	jvmArgs += []
}

Parameterizable FAILFAST

task compTest(type: Test) {
  include '**/*CompTest.class'
  failFast = (project.findProperty("failFast") ?: System.getenv("FAILFAST")) == "1"
  outputs.upToDateWhen {
    false
  }
  useJUnitPlatform()
  testLogging {
    events "passed", "skipped", "failed"
  }
}

gradle examples, gradle commands, gradle bookmarks


Cheat Engine - Find Base Address Hello World Assembly

Comments