org.gradle.jvmargs=-Xmx100m
Gerar binario sem zipar
./gradlew installDist
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
gradle -x test
gradle assemble sonarqube #### funcionou para mim
gradle -x taskName
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'
}
}
tasks.findByPath(':mobile-api-ibanking-tests:test').enabled = false
task hello {
doLast {
println 'Hello Gradle'
}
}
seria o mesmo que
task hello << {
println 'Hello Gradle'
}
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'
gradle project
gradle tasks
http://stackoverflow.com/a/159244/2979435
https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html
task hello { def p = ['curl', '-u', '"admin:password"', ""http://localhost:8081/api/storage/libs-release-local?list&deep=1""].execute() }
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
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
sourceSets {
test {
resources {
srcDir "test"
}
}
}
sourceSets {
main {
java {
srcDir 'src'
}
resources {
srcDirs = ['src', 'filters', 'i18n', 'resources']
filter {
exclude '**/*.java'
}
}
}
}
./gradlew build -Dorg.gradle.project.buildDir=/tmp/gradle-build
jar {
exclude("**/tmp.properties")
}
include ':app', ":libmodule"
project(':libmodule').projectDir = new File(settingsDir, '../MyLibraryDemo/libmodule')
publishing {
publications {
maven(MavenPublication) {
groupId = "com.acme.mylib"
artifactId = project.findProperty("artifactId")
version = project.findProperty("version")
from components.java
}
}
}
./gradlew build publishToMavenLocal
Referenciar jar como dependencia
dependencies {
compile fileTree("${projectDir}/src/main/libs/") // local jars
}
repositories {
flatDir {
dirs 'lib'
}
flatDir {
dirs 'lib1', 'lib2'
}
}
repositories {
mavenCentral()
mavenLocal()
maven {
url uri("${projectDir}/libs/maven")
}
}
compile fileTree("${rootProject.projectDir}/libs/bin/")
OBS: também funciona no intellij
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")
}
}
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
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
configurations.all {
resolutionStrategy {
force 'xml-apis:xml-apis:1.4.01'
}
}
dependencies {
compile project(':drink-master')
...
allprojects {
apply plugin: 'java'
dependencies {
compile project(':drink-master')
settings.gradle
include ':drink-master'
allprojects{
if(!project.name.equals("orbada-res")){
// adding res module to all modules but not for yourself
compile project(':orbada-res')
}
}
build.doLast{
println('hi')
}
/**
* 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}")
}
}
}
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")
}
ant.copy(
todir: sourceSets.main.output.resourcesDir
){
fileset(dir: project(":orbada-res").sourceSets.main.output.resourcesDir)
}
/**
* 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)
}
jar {
include("*.properties")
include("**/res/**")
}
other existents on that folder WILL NOT be included
tasks.findByPath(':conciliation-component-tests:test').enabled = false
export GRADLE_OPTS='-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006'
No intellij adicione um debug remoto e passe a porta
gradle build --refresh-dependencies
ou se for um gradle antigo
rm -rf $HOME/.gradle/caches/
gradle wrapper --gradle-version 2.0
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.')
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'
}
/**
* Nao roda testes no build
*/
assemble << {
tasks.findByPath(':atm-component-tests:test').enabled = false
}
nome comeco do `gradlew` existe a variável `DEFAULT_JVM_OPTS`, sete nela o que precisar
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/**')
}
}
}
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
}
}
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')
Para rodar a aplicacao
apply plugin: 'application'
applicationDefaultJvmArgs = ["-Dgreeting.language=en"]
Para testar
test {
exclude '**/*IntTest*'
jvmArgs += ['--enable-preview']
}
gradle :ABC:build
use uma das duas abaixo
$JAVA_OPTS $GRADLE_OPTS
Exemplo
export JAVA_OPTS="-Xmx100m"; ./gradlew build
Modulo original
configurations {
testArtifacts
}
Modulo que vai depender
compile project(path: ":atm-core", configuration: 'testArtifacts')
compile
do testCompile
compileTestJava {
classpath = classpath.filter {
it.name != "Abc.jar"
println(it.name)
}
}
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
}
echo 'org.gradle.daemon=false' >> $HOME/.gradle/gradle.properties
/**
* é 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;
}
task runClazz(type:JavaExec) {
main = 'ps.cip.core.crypt.utils.SecurityUtils'
classpath = sourceSets.main.runtimeClasspath
}
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')
}
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
}
apply plugin: 'java'
repositories{
mavenCentral()
}
dependencies{
compile 'com.google.guava:guava:12.0'
}
task showMeCache << {
configurations.compile.each { println it }
}
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
./gradlew mg-app:dependencies --configuration testCompile | tee log.log | less
Two ways
In gradle.properties
in the .gradle
directory in your HOME_DIRECTORY
set org.gradle.java.home=/path_to_jdk_directory
In your build.gradle
compileJava.options.fork = true compileJava.options.forkOptions.executable = /path_to_javac
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'
]
}
}
allprojects {
dependencies {
compileOnly('com.mageddo:raw-string-literals:1.0.0')
annotationProcessor('com.mageddo:raw-string-literals:1.0.0')
}
}
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
}
}
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 debug(type: JavaExec){
debug = true
classpath = sourceSets.main.runtimeClasspath
main = className
}
task run(type: JavaExec){
classpath = sourceSets.main.runtimeClasspath
main = className
}
tasks."compileJava".dependsOn project(":jvmti-native").tasks."assemble"
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.+")
}
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')
}
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
jar{
manifest {
attributes 'Main-Class': 'com.mageddo.test.jmxhelloworld.bean.SimpleAgent'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
echo 'allowInsecureProtocol=true' > $HOME/.gradle/gradle.properties
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'
}
}
}
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 += []
}
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