Cannot Set the Value of Read-only Property 'name' for Root Project ' of Type Org.gradle.api.project
This tutorial describes how to the Gradle build tool.
1. Introduction to the Gradle build system
1.ane. What is the Gradle build organization?
Gradle is a general purpose build management organization. Gradle supports the automatic download and configuration of dependencies or other libraries. It supports Maven and Ivy repositories for retrieving these dependencies.
Gradle supports multi-projection and multi-artifact builds.
1.2. Projects and tasks in Gradle
Gradle builds are described via a or multiple build.gradle files. At least ane build file is typically located in the root folder of the project. Each build file defines a projection and its tasks.
Projects can be something which should be built or something that should exist done.
Each project consists of tasks. A task represents a slice of work which a build performs, eastward.g., compile the source lawmaking or generate the Javadoc.
These build files are based on a Domain Specific Language (DSL). In this file you tin can use a combination of declarative and imperative statements. You can also write Groovy or Kotlin code, whenever y'all need it. Tasks can also be created and extended dynamically at runtime.
The following listing represents a very simple build file.
job how-do-you-do { doLast { println 'Hello Gradle' } }
To execute the hello
task in this build file, type gradle hello
on the command line in the directory of the build file. If the Gradle output should be suppressed, use the -q
(quiet) parameter.
gradle hello # alternative add the -q flag gradle -q hello
Y'all can use single and multiline comments in Gradle build files.
// Single line annotate /* Multi line comment */
1.4. Projection settings and description
By default, Gradle uses the directory name as projection proper name. Yous tin can change this by creating a settings.gradle file in the directory which specifies the project proper noun.
rootProject.name ='com.vogella.gradle.first'
You can too add a description to your project via the build.gradle file.
clarification = """ Case project for a Gradle build Projection proper noun: ${project.name} More detailed information here... """ task hello { doLast { println 'Howdy Gradle' } }
Use the gradle project
control to get information well-nigh your project. The following listing shows the output.
:projects ------------------------------------------------------------ Root project - Example project for a Gradle build Project name: com.vogella.gradle.first More detailed data here... ------------------------------------------------------------ Root project 'com.vogella.gradle.kickoff' - Case projection for a Gradle build Projection name: com.vogella.gradle.outset More than detailed data hither... No sub-projects To meet a listing of the tasks of a projection, run gradle <projection-path>:tasks For example, attempt running gradle :tasks BUILD SUCCESSFUL Total fourth dimension: ane.048 secs
ii. Gradle plug-ins
The Gradle build system uses plug-ins to extend its core functionality. A plug-in is an extension to Gradle which typically adds some preconfigured tasks. Gradle ships with a number of plug-ins, and you can develop custom plug-ins.
One example is the Java plug-in. This plug-in adds tasks to your project which allow compiling Java source code, run unit tests and to create a JAR file.
A plug-in is included in a build.gradle file with the utilize plugin: 'pluginname'
statement.
For example the entry utilise plugin: 'com.android.awarding'
makes the Android plug-in bachelor for a Gradle build.
2.ane. IDE back up for Gradle
The Gradleware company is developing Eclipse Gradle tutorial via the Eclipse Buildship project.
Other IDEs similar IntelliJ and Android Studio already include too good Gradle support.
three. Installing and configuring Gradle
The usage of Gradle requires an JDK (Java Evolution Kit) installation.
3.1. Download and excerpt Gradle
The latest version of Gradle tin be found on the Gradle Download page. Download the latest Complete distribution.
It is a gradle-${version}-all.zip, where ${version} is a placeholder for the current version.
Extract the contents of the downloaded nada file a new folder.
3.2. Installing Gradle on Windows
Add the binder to which you extracted Gradle to your PATH
environment variable.
By pressing Win + Interruption the system settings can be opened.
Get-go the Advanced Arrangement Settings take to be selected and and then the Environment Variables button needs to be pressed.
In the Surroundings Variables dialog the (1) GRADLE_HOME and JAVA_HOME user variables should be fix. Afterwards that the (2) Path entry in the arrangement variables is selected, the alter button can be pressed to add the bin folder of the Gradle installation to the Path.
3.3. Installing Gradle on Linux/Mac
three.3.1. Manual installation
The JAVA_HOME
variable must point to a proper jdk and $JAVA_HOME/bin
must be part of the PATH environment variable.
Add Gradle to the path past running export PATH=/usr/local/gradle/FOLDER_TO_WHICH_YOU_EXTRACTED_GRADLE/bin:$PATH
in a last.
3.three.two. Installation with SDKMAN!
SDKMAN! is a command-line tool that allows yous to install multiple Gradle versions and switch betwixt them. Information technology runs on any UNIX based operating system.
Installing SDKMAN!
You install it from the control-line. If you accept already installed SDKMAN! yous can skip this step.
curl -south "https://go.sdkman.io" | bash
After you've installed SDKMAN! yous take to restart you terminal before using it.
Installing Gradle and setting default version
sdk install gradle 3.two sdk default gradle 3.ii gradle -v
Switching Gradle version
sdk install gradle 2.xiii # utilize 2.13 for current terminal session sdk use gradle 2.13 gradle -5
3.3.3. Bank check if Gradle installation was successful
Open a control line and blazon gradle
, which will run Gradle'southward aid task by default.
iii.4. Using the Gradle daemon for improved startup fourth dimension
Gradle allows to start Gradle every bit daemon to avoid starting the Java virtual machine for every build. To configure that create a file called gradle.properties in the ${Habitation}/.gradle and add the following line to it:
Yous tin can also place the gradle.properties file to the root directory of your projection and commit it to your version control organization.
If Gradle is not used for a few hours, the daemon stops automatically.
Executing gradle with the --daemon
parameter on the command line starts the gradle daemon.
To stop the daemon interactively use the gradle --stop
control.
3.v. Specify custom JVM settings for Gradle
The GRADLE_OPTS environment variable offers the opportunity to set specific JVM options for Gradle.
In Using the Gradle daemon for improved startup time the performance for the JVM startup is improved, simply some other functioning killer for large builds can be a also small maximum heap space. Therefore it makes sense to increase it for Gradle.
export GRADLE_OPTS=-Xmx1024m
defines that Gradle tin use ane GB as maximum heap size.
On Windows OS environs variables are usually divers via the system property UI.
If you lot want to set JVM settings not globally but on a per project footing yous can identify them in <Your app binder>/gradle.properties
:
org.gradle.jvmargs=-Xms2g -Xmx4g -Twenty\:MaxHeapSize\=3g
3.6. Typical .gitignore file for Gradle projects
If you are using Git as version control arrangement, yous can use the following .gitignore file equally template for a Gradle projection.
# Android built artifacts *.apk *.ap_ *.dex # Java build artifacts form files *.course # other generated files bin/ gen/ build/ # local configuration file (for Android sdk path, etc) local.properties # OSX files .DS_Store # Eclipse project files .classpath .project # Android Studio *.iml .idea .gradle #NDK obj/
four. Exercise - Create a Java projection with Gradle command line
Gradle provides scaffolding support for creating Gradle based projects via the command line.
Create a new directory on your file system, switch to it and run the post-obit command.
gradle init -- type java - library -- test - framework junit - jupiter
This creates a new Gradle based Coffee project which uses JUnit Jupiter for unit testing.
You can run the build via
And the generated test via:
Gradle will generate a test written report in the `/build/reports/tests/test" folder.
five. Exercise: Configure Gradle properties
When using the gradle command the commencement fourth dimension a .gradle folder is created in the ${USER_HOME} directory.
On Linux this is normally /habitation/${yourUserName}/.gradle
On Windows this is normally C:\Users\${yourUserName}\.gradle
On Mac this is usually /Users/${yourUserName}/.gradle
Inside this .gradle folder a gradle.properties file with the following contents has to be created.
org.gradle.alert.mode = all
Now the default of the org.gradle.alarm.fashion property will be overridden. (Default is summary)
Common or secret properties can be ready or overridden here, e.m., Gradle defaults or access tokens for deployment. |
half dozen. Dependency management for Java projects
6.1. Managing dependencies with Gradle
Gradle allows managing the classpath of your projects. It tin can add JAR files, directories or other projects to the build path of your application. It too supports the automatic download of your Coffee library dependencies. Simply specify the dependency in your Gradle build file. This triggers Gradle to download the library including its transient dependencies during the build.
A Java library is identified past Gradle via its projection's groupId:artifactId:version
(also known equally GAV in Maven). This GAV uniquely identifies a library in a certain version. Yous tin utilize the Search Maven Website to search for the GAV of a library in Maven Central.
To add a dependency add together an entry to the dependency department in your build.gradle file every bit demonstrated past the following listing.
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.squareup.okhttp:okhttp:2.5.0' testCompile 'junit:junit:4.12' }
6.2. Specifying the repositories to search for dependencies
In your build file y'all specify the remote repositories to look for dependencies. Gradle supports Maven and Ivy repositories to search for dependencies. The following listing shows how to configure Maven central as dependency source.
repositories { mavenCentral() }
It is too possible to configure the target as a URL.
repositories { maven { url "http://repo.mycompany.com/maven2" } }
You can likewise specify other targets, for example Bintray equally Maven repository.
repositories { maven ("http://jcenter.bintray.com/") }
The next listing demonstrates how to define an Ivy dependency.
repositories { ivy { url "http://repo.mycompany.com/repo" } }
You can also add dissimilar repositories at once.
repositories { maven ("https://repository-achartengine.forge.cloudbees.com/snapshot/") jcenter { url "http://jcenter.bintray.com/" } }
You can besides reference artifacts from the file arrangement.
employ plugin: 'java' repositories { mavenCentral() } dependencies { compile group: 'commons-collections', name: 'commons-collections', version: '3.2' testCompile group: 'junit', proper name: 'junit', version: 'four.+' runtime files('libs/library1.jar', 'libs/library2.jar') runtime fileTree(dir: 'libs', include: '*.jar') compile fileTree(dir: "${System.properties['user.home']}/libs/cargo", include: '*.jar') } }
six.3. Show dependencies of a project (also transient dependencies) .
The post-obit command shows all transient dependencies of a Gradle project.
6.4. Gradle cache and deleting the enshroud
Yous tin refresh dependencies in your cache with the command line option --refresh-dependencies
. You can too delete the cached files under ~/.gradle/caches. With the next build Gradle attempts to download the dependencies once more.
6.5. Excluding transitive dependencies
Sometimes you have dependencies on packages that ascertain conflicting transitive dependencies. One solution is to exclude a dependency from a specific module:
compile 'org.springframework:leap-web:4.3.10.RELEASE' { exclude group: 'com.google.code.gson', module: 'gson' }
If you lot have multiple dependency that ascertain a dependency yous desire to exclude, you tin can practice so at the project level:
configurations.all { exclude grouping: 'com.google.code.gson', module: 'gson' }
Following the same approach nosotros can exclude a dependency only during runtime:
configurations.runtime { exclude grouping: 'com.google.code.gson', module: 'gson' }
half dozen.6. Forcing a specific version of a transitive dependency
It is possible to forcefulness gradle to option a specific version when information technology encounters conflicting transitive dependencies. Keep in listen that you might have to manually update this version when you are upgrading the packages that depend on it.
configurations.all { resolutionStrategy.force 'com.google.lawmaking.gson:gson:two.8.1' }
seven. Running a build
When starting a Gradle build via the command line, the gradle
control tool looks for a file called build.gradle
in the current directory.
Gradle also supports abbreviation of tasks, e.g,. to outset the task lars
using the gradle l
command is sufficient. The abbreviation must uniquely identify a task, otherwise Gradle gives you an mistake message, which tell that the abbreviation is ambiguous. CamelCase can also be used for an abbreviation, e.chiliad., the task gradle vogellaCompany
can also be called with the gradle vC
command.
A Gradle build can be triggered via the gradle
or gradle -q
command. The -q
or --quiet
parameter makes the execution of Gradle less verbose. A specific chore can be addressed like this: gradle -q other
, which runs the "other" task. You tin can of course likewise use the Gradle wrapper script, if that is avaiable.
To ascertain a different build file the -b buildFileName
choice can be used.
In scenarios where no network connexion is available the --offline
parameter can be used. This runs the Gradle build offline, which ways that Gradle does not endeavour to achieve resources from the network during a build. E.one thousand., for dependencies from an artifact repository like Maven Cardinal or Bintray.
To go a detailed output of what Gradle is doing you can specify the --info
parameter.
8. Gradle Tasks
8.1. Default Gradle tasks
Gradle also offers tasks for introspection of Gradle itself, and then a Gradle project can be analyzed by using Gradle's default tasks.
A good example is the tasks
chore, which shows the bachelor tasks of a project. When typing gradle -q tasks
, a list of tasks is shown. This command lists the base tasks even without an build.gradle
file.
Gradle as well tries to give some guidance for the usage of invoked tasks, as shown in the bottom of the console output. The gradle tasks --all
control would as well list dependent tasks, which are invoked before the actual task.
When running gradle tasks --all
the output looks quite similar to the i before, except of the init
chore, which depends on the wrapper
task.
8.2. Creating custom Gradle tasks
Yous already created a first minimalistic task in a build.gradle
file has been created.
task hello { doLast { println 'Howdy Gradle' } }
When running the gradle -q tasks
task with this build.gradle
file, the hullo
chore volition be listed under "Other tasks".
Tasks without a grouping are considered as private tasks. For example, the Gradle Job View of the Eclipse Gradle Plug-in does not show such tasks. Just they can exist shown past activating the right entry in the view's card.
Groups can be applied with the group
holding and a description can be applied past using the clarification
property. In case the group already exists the hello
task is added to it. If the group does not exist, it is created.
task howdy { grouping 'vogella' description 'The hello job greets Gradle by maxim "Howdy Gradle"' doFirst { println 'Hello Gradle' } doLast { println 'Bye bye Gradle' } }
eight.three. Task construction
Gradle has different phases, when working with tasks. Commencement of all in that location is a configuration phase, where the code, which is specified directly in a task'due south closure, is executed. The configuration block is executed for every available task and not only for those tasks, which are afterwards really executed.
After the configuration stage, the execution phase then runs the lawmaking inside the doFirst
or doLast
closures of those tasks, which are actually executed.
task onlySpecifiesCodeForConfigurationPhase { group 'vogella' clarification 'Configuration phase task example.' println 'I always get printed fifty-fifty though, I am non invoked' } chore anotherUnrelatedTask { doLast { println 'I am in the doLast execution phase' } }
When running gradle -q anotherUnrelatedTask
the post-obit is printed:
I always get printed fifty-fifty though, I am not invoked I am in the doLast execution stage
The showtime argument comes from the configuration phase in which the task definition of the onlySpecifiesCodeForConfigurationPhase
is evaluated.
8.four. Task dependencies
Gradle allows the definition of default tasks in the build file. These are executed, if no other tasks are specified. Tasks can likewise define their dependencies. Both settings are demonstrated in the following build file.
defaultTasks 'clean' , 'compile' task make clean { doLast { println 'Executing the make clean task' } } task compile { doLast { println 'Executing the compile task' } } task other ( dependsOn: 'compile' ) { doLast { println "I'm non a default job!" } } task cleanOther { doLast { println "I want to clean upwardly earlier running!" } } cleanOther . dependsOn make clean , compile
Hooking into predefined task executions for default tasks or tasks from plug-ins can also be done by using the dependsOn
method.
For case when certain things have to be done right subsequently the compilation of coffee code:
use plugin: 'java' task invokedAfterCompileJava ( dependsOn: 'compileJava' ) { doLast { println 'This volition be invoked right after the compileJava task is done' } }
An culling to creating a new task, which depends on the 'compileJava'
job, a new execution block can also be directly practical to an existing task, eastward.k., the 'compileJava'
chore.
utilise plugin: 'java' compileJava . doFirst { println 'Another action applied to the "compileJava" task' } compileJava . doLast { println 'Another doLast action is also applied' }
When running the javaCompile job all actions, which take been practical to the javaCompile task, are run ane by one according to the gild they have been practical to the task.
8.5. Skipping Tasks
Skipping tasks can be done by passing a predicate closure to the onlyIf
method of a task or by throwing a StopExecutionException
.
task eclipse { doLast { println 'Hullo Eclipse' } } // #1st arroyo - closure returning true, if the job should be executed, false if not. eclipse . onlyIf { projection . hasProperty ( 'usingEclipse' ) } // #2nd arroyo - alternatively throw an StopExecutionException() like this eclipse . doFirst { if (! usingEclipse ) { throw new StopExecutionException () } }
Tasks depending on the eclipse task will be run fifty-fifty, if a StopExecutionException is thrown. |
8.v.1. Accessing system variables like the user domicile directory
Y'all can access system variables. For example, to get the user abode directory use the following:
def homePath = System . backdrop [ 'user.dwelling' ]
9. Exercise: Gradle Tasks
nine.1. Using the tasks Gradle chore
The target of this exercise is to get an overview most the default tasks, which are delivered by default.
Open up a command line and execute the following control:
9.2. Using the help task
The target of this exercise is to make use of the help
task to become more data near other tasks, e.g., the init chore.
gradle - q assist -- task init
nine.3. Create a Groovy project
The previous do informed near the usage of the init task.
gradle - q init -- type swell - library
nine.4. Optional - Import the new bang-up project
Eclipse Buildship tin exist used to import the project into the Eclipse IDE.
ix.v. Using the dependencies job
In order to meet the project's dependencies (including the transitive ones) the dependencies chore has to exist invoked.
If the optional Buildship import practice has been done the dependencies
task can as well exist invoked using the Gradle Tasks view.
x. Using the Gradle wrapper
The Gradle wrapper allows that a user can run the build with a predefined version and settings of Gradle without a local Gradle installation. This wrapper is a batch script on Windows, and a beat out script for other operating systems. When yous start a Gradle build via the wrapper, the specified version of Gradle is automatically downloaded and used to run the build.
The wrapper is the preferred way of starting a Gradle build, as information technology make the execution of the build independent of the installed Gradle version. The wrapper script can be created via gradle wrapper
.
As a result you notice a gradlew for *nada based systems and gradlew.bat for window systems. These files can be used instead for the gradle
command, and if Gradle is not installed on the machine, Gradle is automatically downloaded and installed.
It is as well possible to ascertain a task which defines the version of the wrapper. If this task is executed, it creates the wrapper and downloads the right version of Gradle.
wrapper { gradleVersion = '4.9' }
The version of the Gradle Wrapper can too exist defined, when creating it via the command line.
gradle wrapper --gradle-version 4.nine
Without this explicit version parameter Gradle will automatically pick the latest version.
10.i. Configure GRADLE_OPTS for the Gradle wrapper
GRADLE_OPTS can also be defined inside the gradlew or gradlew.bat file.
# ! /usr/ bin / env bash ############################################################################## ## ## Gradle get-go up script for United nations * 10 ## ############################################################################## # Add default JVM options here . # You tin can as well apply JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script . DEFAULT_JVM_OPTS = "-Xmx1024m" # ... { more lines }
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%Bone%" == "Windows_NT" setlocal @rem Add together default JVM options here . You can also use JAVA_OPTS # and GRADLE_OPTS to laissez passer JVM options to this script . fix DEFAULT_JVM_OPTS =- Xmx1024m @rem ... { more than lines }
xi. Exercise: Configuring the Wrapper Task
Tasks like Gradle's Wrapper Task are available by default and certain properties of it, eastward.g., gradleVersion can be configured similar this:
wrapper { gradleVersion = '4.9' }
12. Exercise - Create Custom Gradle Tasks
12.i. Practice - How-do-you-do Gradle Task
Create a helloGradle task, which prints Hello Gradle with the group workshop and a proper description.
Then use the ./gradlew tasks
control to see your new helloGradle chore in the panel or use Buildship in the Eclipse IDE.
Then invoke the helloGradle task by calling ./gradlew hG
or again use Buildship in the Eclipse IDE.
12.2. Exercise - Dependencies between tasks
Create two new tasks chosen learnGroovy
, which prints Learn Groovy, and learnGradle
, which prints 'Learn Gradle'.
These tasks should have reasonable dependencies.
12.3. Exercise - doFirst activity for the tasks
Extend the learnGroovy
task so that it prints Install Eclipse IDE with Buildship earlier it prints Acquire Groovy.
thirteen. Practice: Creating a Re-create Task
New tasks tin can also be created and derived from another chore and specify certain backdrop.
The Copy
task type can exist used to specify such a task, which is able to copy files.
Create a new project with the following build.gradle file:
chore copyFile ( blazon: Re-create ) { from 'source' into 'destination' }
Create a source folder inside this projection and add a text file to this folder.
When running the copyFile
task it copies the text file to a new destination folder.
14. Exercise: Specifying a custom Task in some other gradle file
Create a new Gradle project, which contains the post-obit structure.
The CheckWebsite.groovy class looks similar this:
bundle com.example import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import java.io.IOException ; import org.jsoup.Jsoup ; import org.jsoup.nodes.Certificate ; class CheckWebsite extends DefaultTask { String url = 'http://world wide web.vogella.com' @TaskAction void checkWebsite () { // check the given website by using the url endeavour { Document doc = Jsoup . connect ( url ). get (); String championship = doc . title (); println title println url } catch ( IOException eastward ) { e . printStackTrace (); } } }
Since this grade has external dependencies to jsoup, a build.gradle file for this grade has to be created.
So the build.gradle inside the buildSrc folder, which is responsible for building the CheckWebsite
class, looks like this:
plugins { id 'groovy' } repositories { jcenter () } dependencies { compile 'org.jsoup:jsoup:1.8.3' }
Finally the main build.gradle file in the root folder makes use of the new com.case.CheckWebsite
task type.
task defaultWebsiteCheck ( type: com . example . CheckWebsite ) job checkGradleWebsite ( type: com . example . CheckWebsite ) { url = 'https://docs.gradle.org/' } wrapper { gradleVersion = 'four.9' }
xv. Practice: Trigger Gradle build from Java code
This exercise describes how to trigger a gradle build from Java code.
15.ane. Create new gradle projects
Create two new gradle projects with the names BaseProject (this project starts the gradle build) and TargetProject (this project is built by the BaseProject). Make sure the BaseProject applies the java plugin.
fifteen.2. Add dependencies
Add the post-obit dependency to the BaseProject.
compile 'org.gradle:gradle-tooling-api:4.0-rc-2'
fifteen.three. Build TargetProject
Create a class named Application with a static main method similar the following.
import java.io.File; import org.gradle.tooling.BuildLauncher; import org.gradle.tooling.GradleConnector; import org.gradle.tooling.ProjectConnection; public course Application { public static void main(Cord[] args) { ProjectConnection connexion = GradleConnector.newConnector().forProjectDirectory(new File("path/to/targetproject")).connect(); try { BuildLauncher build = connection.newBuild(); build.forTasks("build"); build.run(); } grab (Exception eastward) { e.printStackTrace(); } finally { connection.shut(); } } }
This method kickoff creates a ProjectConnection to the project that should exist build and connects to it. Make certain to replace path/to/targetproject with the path of the TargetProject. From the projection connexion, a new BuildLauncher can be obtained. With the assist of the method forTasks() you can specify the gradle tasks that should be executed. The BuildLauncher as well provides another methods to configure the build. You can, for example, set gradle build arguments or change the Java version to build the project with. By calling the run() method the build is finally executed. Brand certain to close the connection in the finally block.
xvi. Building Java projects
16.1. The Coffee plug-in
The Java plug-in provides tasks to compile Java source code, run unit of measurement tests, create Javadoc and create a JAR file.
16.2. Default projection layout of Java projects
This plug-ins assume a sure setup of your Java project (similar to Maven).
-
src/main/coffee contains the Java source code
-
src/test/java contains the Java tests
If you follow this setup, the following build file is sufficient to compile, test and bundle a Coffee projection.
To kickoff the build, type gradle build
on the command line.
SourceSets
can be used to specify a dissimilar project structure, e.g., the sources are stored in a src folder rather than in src/main/java.
apply plugin: 'java' sourceSets { main { java { srcDir 'src' } } test { coffee { srcDir 'test' } } }
16.3. Java project cosmos with the init task
Gradle does not however support multiple project templates (called archetypes) similar Maven. Simply it offers an init
task to create the structure of a new Gradle project. Without additional parameters, this chore creates a Gradle projection, which contains the gradle wrapper files, a build.gradle and settings.gradle file.
When adding the --blazon
parameter with 'java-library'
equally value, a java project construction is created and the build.gradle file contains a certain Java template with JUnit.
The build.gradle file will wait similar to this:
/* * ... deleted the generated text for brevity */ // Employ the coffee plugin to add support for Coffee utilize plugin: 'coffee' // In this section you declare where to find the dependencies of your project repositories { // Employ 'jcenter' for resolving your dependencies. // Y'all can declare whatever Maven/Ivy/file repository here. jcenter () } // In this section y'all declare the dependencies for your production and test code dependencies { // The production code uses the SLF4J logging API at compile time compile 'org.slf4j:slf4j-api:1.vii.12' // Declare the dependency for your favourite test framework you want to use // TestNG is also supported by the Gradle Test chore. Only change the // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add // 'test.useTestNG()' to your build script. testCompile 'junit:junit:4.12' }
A project hosted at Github Gradle-templates project provides more than templates beyond the init task. The Gradle team is also working on this archetype/template topic.
16.4. Specifying the Java version in your build file
Usually a Java project has a version and a target JRE on which information technology is compiled. The version
and sourceCompatibility
holding can exist set in the build.gradle file.
version = 0.1 . 0 sourceCompatibility = 1.8
When the version
property is gear up, the name of the resulting antiquity will be inverse accordingly, e.1000., {my-lib-name}-0.i.0.jar.
If the artifact is an executable java application the MANIFEST.MF file must exist aware of the class with the main method.
apply plugin: 'java' jar { manifest { attributes 'Main-Class' : 'com.example.principal.Application' } }
17. Building Groovy projects
17.1. The Groovy plug-in
The Groovy plug-in for Gradle extends the Java plug-in and provides tasks for Groovy programs.
apply plugin: 'groovy' repositories { mavenCentral () } dependencies { implementation 'org.codehaus.nifty:smashing-all:2.4.five' testImplementation 'junit:junit:4.12' }
To start the build, type gradle build
on the command line.
17.2. Default project layout of Bang-up projects
This plug-ins assume a certain setup of your Groovy projection.
-
src/chief/dandy contains the Smashing source lawmaking
-
src/exam/groovy contains the Groovy tests
-
src/master/java contains the Java source code
-
src/examination/java contains the Java tests
If you follow this setup, the following build file is sufficient to compile, test and parcel a Bully project.
19. Running JUnit 5 tests with Gradle
To apply Junit 5 for Java, add together the post-obit to your dependencies
closure in your 'build.gradle` file. Use at to the lowest degree Gradle 6.0 for this to avoid already stock-still issues.
dependencies { // more stuff testImplementation ( enforcedPlatform ( "org.junit:junit-bom:5.iv.0" )) // JUnit v BOM testImplementation ( "org.junit.jupiter:junit-jupiter" ) }
19.1. Test naming conventions for Gradle
The Gradle "examination" chore scans all compiled classes in the source folder of the project, e.g., /src/test/coffee or /src/test/groovy. JUnit classes are identified past:
-
Class or a super class extends TestCase or GroovyTestCase
-
Class or a super class is annotated with @RunWith
-
Class or a super class comprise a method annotated with @Test
You can set the scanForTestClasses
property to fake, if you exercise not want automated test grade detection. In this case, if no additional include / exclude patterns are specified, the default for included classes are /Tests.course", "/*Test.class" and the default excluded classes are "*/Abstract*.class".
xix.2. Include and Exclude particular Tests
The Test
course has a include
and exclude
method. These methods can be used to specify, which tests should actually be run.
Just run included tests:
test { include '**my.package.name/*' }
Skip excluded tests:
examination { exclude '**my.package.name/*' }
19.three. Evidence all test output in the terminal
By default Gradle doesn't impress the standard output of your tests to the last. To see all output of your tests add this to your build file:
test { testLogging . showStandardStreams = true }
20. Edifice multiple projects with Gradle
xx.1. Creating a multi projection build structure
A business awarding usually does not consist of just 1 unmarried project/module, merely has many projects, which should exist build.
Gradle has the concept of a root projection, which tin have many sub projects. The root project is specified by a build.gradle file, similar the single projects before. To specify, which projects belong to the build a settings.gradle file is used.
For instance there might be this project structure:
-
root_project
-
core
-
ui
-
util
-
-
settings.gradle
Having this projection construction the settings.gradle file would look like this:
include 'core' , 'ui' , 'util' # altenative way would be # include 'cadre' # include 'ui' # include 'util'
Besides the tasks
job Gradle likewise provides a projects
help task, which can be run in the root_project folder.
twenty.2. Specifying a general build configuration
In a build.gradle file in the root_project general configurations can be applied to all projects or just to the sub projects.
allprojects { group = 'com.example.gradle' version = '0.1.0' } subprojects { apply plugin: 'coffee' apply plugin: 'eclipse' }
This specifies a common com.example.gradle
group and the 0.ane.0
version to all projects.
The subprojects
closure applies mutual configurations for all sub projects, but not to the root project, like the allprojects
closure does.
20.3. Project specific configurations and dependencies
The core
, ui
and util
sub projects can also have their own build.gradle file. If they have specific needs, which are not already applied past the full general configuration of the root projection.
For case the ui project usually has a dependency to the core project. So the ui project needs its own build.gradle file to specify this dependency.
dependencies { compile project ( ':core' ) compile 'log4j:log4j:i.ii.17' }
Projection dependencies are specified with the projection method.
The |
Alternatively you can also define the dependencies of a projection in the root build.gradle file. Only it is considered good do to define the dependencies in the projection specific build.gradle files, hence the following approach is only included for demonstration purpose.
allprojects { apply plugin: 'java' repositories { mavenCentral () } } project ( ':com.case.core' ). dependencies { compile project ( ':com.example.model' ) compile 'log4j:log4j:1.2.17' }
21. Deployment with Gradle
21.2. Using the maven-publish plugin
The almost common way is to utilise the maven-publish
plugin, which is provided past Gradle by default.
// other plug-ins use plugin: 'maven-publish' publishing { publications { mavenJava ( MavenPublication ) { from components . java } } repositories { maven { url "$buildDir/repo" } } }
There are several publish options, when the coffee
and the maven-publish
plugin is applied.
The deployment to a remote repository can be washed like this:
utilise plugin: 'groovy' utilise plugin: 'maven-publish' group 'workshop' version = '1.0.0' publishing { publications { mavenJava ( MavenPublication ) { from components . coffee } } repositories { maven { // default credentials for a nexus repository manager credentials { username 'admin' countersign 'admin123' } // url to the releases maven repository url "http://localhost:8081/nexus/content/repositories/releases/" } } }
22. Integration with Emmet
Gradle supports running Ant tasks via the Peachy AntBuilder.
23. Convert Maven Projects to Gradle
Gradle provides an incubating init job, which helps with the creation of new Gradle projects. This chore tin also convert Apache Maven pom.xml files to Gradle build files, if all used Maven plug-ins are known to this task.
In this section the post-obit pom.xml maven configuration will be converted to a Gradle project.
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-case" xsi:schemaLocation= "http://maven.apache.org/POM/four.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion>four.0.0</modelVersion> <groupId>com.example.app</groupId> <artifactId>case-app</artifactId> <packaging>jar</packaging> <version>one.0.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>examination</telescopic> </dependency> </dependencies> </project>
Running the gradle init --blazon pom
control on the command line results in the following Gradle configuration.
The init task depends on the wrapper chore so that also a Gradle wrapper is created.
The resulting build.gradle file looks similar to this:
apply plugin: 'java' utilize plugin: 'maven' group = 'com.example.app' version = '1.0.0-SNAPSHOT' clarification = """""" sourceCompatibility = i.v targetCompatibility = one.5 repositories { maven { url "http://repo.maven.apache.org/maven2" } } dependencies { testImplementation group: 'junit' , name: 'junit' , version: '4.xi' }
24. Developing custom Gradle plug-ins
24.i. Why creating Gradle plug-ins
As a general rule, it is useful to have a build that is as much declarative equally possible as this simplifies futurity maintenance. Therefore information technology is advised to avert circuitous lawmaking in your Gradle build file. If yous demand custom logic you should place it into a custom Gradle plug-in.
24.ii. Gradle DSL
Each Gradle plug-in comes with a DSL. To see all properties of a Gradle object, you can employ the following lawmaking snippet:
println variants.properties .sort{information technology.central} .collect{information technology} .findAll{!filtered.contains(it.key)} .join('\northward')
For example to ascertain a tasks which show the properties of all android.applicationVariants
(in an Android project), apply:
chore showAndoidVariantsInformation { doLast { android.applicationVariants.all { variants -> println variants.properties .sort{it.central} .collect{it} .findAll{!filtered.contains(it.key)} .join('\northward') } } }
25. Exercise - Creating a simple Gradle plugin
The 'coffee-gradle-plugin' Gradle plug-in simplifies creating custom Gradle plug-ins. This plug-in is current incubating.
It does the following:
-
the gradleApi() dependency is automatically added
-
the gradleTestKit() dependency is automatically added
-
the necessary plug-in descriptor files automatically
25.1. Create a Gradle project
Select in Eclipse to create a new Gradle project. The com.vogella.gradleplugin as project name.
Stick to the defaults of the sorcerer and create the project.
25.2. Utilise the 'java-gradle-plugin' plug-in
Modify the build.gradle
file to the following:
plugins { id 'java-gradle-plugin' } gradlePlugin { plugins { vogellaPlugin { id = 'com.vogella.gradleplugin' implementationClass = 'com.vogella.gradleplugin.MyPlugin' } } } repositories { jcenter () } dependencies { // No need to add gradleApi() here, because it is applied past the 'java-gradle-plugin' plug-in // We want to merge and parse SpotBugs xml files with XSLT compile ( 'cyberspace.sf.saxon:Saxon-HE:ix.viii.0-12' ) // Use JUnit test framework testImplementation 'junit:junit:four.12' } wrapper { gradleVersion = 'iv.nine' }
In the /src/primary/coffee folder create the post-obit two classes.
packet com.vogella.gradleplugin ; import org.gradle.api.DefaultTask ; import org.gradle.api.tasks.TaskAction ; public course MyTask extends DefaultTask { @TaskAction public void myTask () { System . out . println ( "Hullo from vogella task" ); } }
bundle com.vogella.gradleplugin ; import org.gradle.api.Plugin ; import org.gradle.api.Project ; public course MyPlugin implements Plugin < Project > { @Override public void utilize ( Project project ) { project . getTasks (). create ( "myTask" , MyTask . class ); } }
Run the build job to build to plug-in and see next exercises on how to deploy and consume the plug-in.
26. Practise - Deploy your custom Gradle plug-in to your local Maven repository
Add the maven-publish Gradle plug-in and the publishing closure to the build.gradle file.
plugins { id 'java-gradle-plugin' id 'maven-publish' } grouping = 'com.vogella' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 // ... more code publishing { publications { mavenJava ( MavenPublication ) { from components . coffee } } }
Now boosted publishing tasks are available and the publishToMavenLocal chore tin be used to add the Gradle plug-in to the local Maven repository.
27. Exercise - Using the new plug-in
To use the new Gradle plug-in a dependency to it has to be divers. If you pushed your plug-in to your local Maven repository, Gradle should find it and brand it available.
buildscript { repositories { mavenLocal () } dependencies { classpath ' com . vogella : com . vogella . gradleplugin : 0.0 . 1 - SNAPSHOT ' } } apply plugin: ' com . vogella . gradleplugin '
Now the new job from the com.vogella.gradleplugin should be available:
./gradlew tasks ./gradlew myTask
28. Optional Do - Publishing the plug-in to the Gradle plug-in portal
To publish a Gradle plug-in in the Gradle Plug-in Portal the com.gradle.plugin-publish Gradle plug-in can be used.
The gradle.publish.cardinal and gradle.publish.secret properties accept to be added to the gradle.properties.
The gradle.properties file is normally located in the gradleHomeDir (unremarkably /${user.domicile}/.gradle) |
And so the build.gradle file needs to exist adjusted to be able to upload Gradle plug-ins.
plugins { id 'java-gradle-plugin' id 'maven-publish' id 'com.gradle.plugin-publish' version '0.9.x' } // more lawmaking ... pluginBundle { website = '${Spider web site for your plugin}' vcsUrl = 'https://github.com/${your-repo}' plugins { vogellaPlugin { id = 'com.vogella.gradleplugin' displayName = 'Vogella Sample Plug-in' description = 'Vogella Sample Plug-in for trying the ' tags = [ 'Vogella' , 'Preparation' , 'Gradle' , 'Sample' ] // Gradle's plug-in portal does not support SNAPSHOTs version = '0.0.1' } } }
The following task tin can then be used to upload the Gradle plug-in.
When the plug-in has been published the plugins closure can be used to make employ of the Gradle plug-in.
plugins { id "com.vogella.gradleplugin" version "0.0.1" }
And so the more than verbose buildscript
closure and the apply plugin
method from previous chapters can exist omitted.
29. Debugging Gradle Plug-ins
29.1. Actuate remote debugging
The following properties have to be specified in the gradle.properties file to enable remote debugging:
org.gradle.daemon = true org.gradle.jvmargs = -XX:+HeapDumpOnOutOfMemoryError -Xmx4g -agentlib:jdwp=transport=dt_socket,server=y,append=n,accost=5006
When running a Gradle build locally with these settings remote debugging can be accessed via localhost on port 5006.
The gradle.properties file is unremarkably located in the gradleHomeDir (normally /${user.home}/.gradle) |
29.two. Remote debugging in the Eclipse IDE
Yous should import a certain Gradle plug-in into the Eclipse IDE by using the Buildship tooling.
So break points can be added to the Gradle plug-in's source files.
Afterwards that open up the debug configuration and right click Remote Java Application to create a New Debug Configuration with the follwing settings:
Press the Debug button to run the remote debugger.
And then a Gradle build, which uses the desired Gradle plug-in, tin exist run by either using the Gradle Tasks View of the Buildship tooling inside the Eclipse IDE or invoke a Gradle build from command line.
When a interruption point is hit during the Gradle task processing the Eclipse IDE will stop at that signal.
30. Using code analysis tools
Gradle provides several plugins for analyzing the code base of a Gradle project.
Tool | Plugin | Description |
---|---|---|
Checkstyle | checkstyle | Validates checkstyle rules, which are practical for a project |
Jacoco | jacoco | Checks for test coverage of the lawmaking being congenital |
FindBugs | findbugs | Static Code Assay for Java |
CodeNarc | codenarc | Static Lawmaking Analysis for Keen |
PMD | pmd | Adds code quality checks for several programming languages to the build |
JDepend | jdepend | Another code analysis tool for analyzing dependencies in Coffee code |
30.i. Jacoco for Gradle projects
To use Jacoco for test coverage analysis the following code must be added to the height level build.gradle file
plugins { id 'jacoco' } jacocoTestReport { reports { xml . enabled true html . enabled true } }
If y'all have a multi projection Gradle project then you lot need to add together the jacocoTestReport and the jacoco plugin to the subprojects section of the top level build.gradle file.
plugins { id 'jacoco' } subprojects { use plugin: 'jacoco' jacocoTestReport { reports { xml . enabled true html . enabled true } } }
If yous would like to have a consolidated xml file for all the subprojects, e.k. to be used by SonarQube, yous tin create information technology with the following task in the top level build.gradle
task generateMergedReport ( type: JacocoReport ) { dependsOn = subprojects . test additionalSourceDirs . setFrom files ( subprojects . sourceSets . primary . allSource . srcDirs ) sourceDirectories . setFrom files ( subprojects . sourceSets . principal . allSource . srcDirs ) classDirectories . setFrom files ( subprojects . sourceSets . main . output ) executionData . setFrom project . fileTree ( dir: '.' , include: '**/build/jacoco/exam.exec' ) reports { xml . enabled true xml . destination file ( "../coverage-reports/coverage.xml" ) } }
This task volition save the consolidated xml file on the top level of the project under coverage-reports.
To finally create the consolidated xml file, run Gradle with the created task generateMergedReport.
./gradle make clean build generateMergedReport
Source: https://www.vogella.com/tutorials/GradleTutorial/article.html
Post a Comment for "Cannot Set the Value of Read-only Property 'name' for Root Project ' of Type Org.gradle.api.project"