When you start programming, the main key to the success of your job is identified in the code. Its quality is certainly an essential element. A more professional approach, however, suggests the adoption of additional tools that increase the productivity of a programmer: development environments, a good debugger, version control systems but also build automation tools. In the latter category belongs Gradle, multiplatform and free software, among the most advanced currently available in the build automation.
In this article, we will introduce some basic concepts, common to all tools of this type, and then deepen the use of Gradle.
What is build automation
The software development phases are surrounded by a series of ancillary activities, sometimes preliminary, sometimes implemented retrospectively, often organized during development. Among these activities we can highlight the main ones:
- compilation: this is the process of transforming the sources (written by the programmer) into binary code (the format recognized by the machine);
- track packaging: the result of the compilation must take on a compact form and a clear connotation according to its purpose: executable, library to export, etc .;
- automated test execution: a true software cannot simply be “tested”. It is not enough to enter some random data with your own hands and feel satisfied with the results obtained. To avoid hidden bugs, it is necessary to carry out an experimental phase that demonstrates the reliability of the software in every facet, trying to verify its functionality in every possible situation. To follow a test strategy of this kind, a human being of goodwill is no longer enough, but a machine is necessary, a software specially designed to perform complete tests;
- solution deployment: once the software is ready and tested, it must be installed and configured on the systems for which it has been implemented;
- documentation of the project: the software products are often quite complex and live, through the published versions, a real evolution. Given the complexity of IT products, the preparation of appropriate documents explaining their use and functionality is essential. Obviously, the documentation will take the form most suited to the type of project and to the user target.
The build automation products are tools designed to automate all the steps just listed. Their importance is remarkable, to the point that they have populated the history of computing. If programmers have relied on Make for so many years , experts in the Java world have often compared themselves with Ant and Maven , both based on XML configuration files. Despite the differences that distinguish them, the build automation tools sometimes have common traits, such as:
- the build file : the operations that must be performed to transform the source project into the final solution are collected in a main file, which sometimes refers to or includes other secondary files;
- the task : is the concept that defines the single operation to be performed within the phases of the build process. Often the tasks are divided into micro-actions and are contextualized by assigning their precedence and dependencies to other tasks. In this way the flow of the entire build process is defined;
- the dependencies of software from other projects: a professional level, you do not start program “from scratch” but it is based on frameworks, libraries or other projects, which form the foundations of our work. Making sure that during the various build phases the project has everything necessary is a painful task for the programmer. A great merit of the tools of this category nowadays is to automate the fulfillment of the project dependencies automatically, through the network, making available the updated versions of the dependencies, or those better compatible with our needs.
Ultimately, an IT project comes to life thanks to a series of phases, sometimes complex, whose automation raises the programmer from considerable responsibility and reduces the possibility of errors of distraction or fatigue.
Gradle: let’s start using it
Build automation tools like Ant and Maven, rich in functionality and expandable, have often demonstrated a certain configuration rigidity due mostly to the use of the XML format. Gradle is proposed as one of the most advanced software management tools of the moment. It benefits from the use of configurations carried out in a declarative language: Groovy. It is a scripting language that was born within the Java technology. It belongs to object-oriented programming and its code is compiled on-the-fly and takes the form of bytecode for the Java Virtual Machine.
Gradle is a multiplatform project and can be downloaded from the reference site www.gradle.org. Following the download link you can download the sources, the binaries or a package that includes them both with the addition of documentation. We choose to download the version with the binaries and, once unzipped the archive in .zip format, we will get the content partially visible in the following figure.
Among the various folders, there are two of greater interest for our purposes:
- bin: contains the executables. They will be used to activate the command line program;
- lib: collects many jar archives that will allow Gradle to do its job. A quick look inside this directory points out some names that demonstrate on what solid bases rests Gradle and how deeply rooted in the Java world: ant, log4j, groovy, different commons of Apache and much more.
Once the .zip archive has been unpacked, Gradle is ready for use. To work, it requires nothing more than a properly configured JDK or JVM in the system. To test its functionality, we immediately use the command gradle, directly from the command line:
gradle -v
On Ubuntu, the output shown is as follows:
<pre class=”brush: php; html-script: true”>
————————————————————
Gradle 2.1
————————————————————
Build time: 2014-09-08 10:40:39 UTC
Build number: none
Revision: e6cf70745ac11fa943e19294d19a2c527a669a53
Groovy: 2.3.6
Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM: 1.7.0_21 (Oracle Corporation 23.21-b01)
OS: Linux 3.5.0-23-generic amd64
</pre>
As you can see, the command just typed shows the version of Gradle (2.1 in this case) and all the components it has available: JVM, groovy, ant and operating system.
The syntax
Since an important advantage of Gradle consists in the flexibility of the language used, let’s see it immediately at work. We create a build file, which we can call build.gradle , open it with a text editor and write the following code inside it:
import java.text.SimpleDateFormat SimpleDateFormat simple = new SimpleDateFormat ("HH: mm: ss") task let's tryGradle { for (int i = 1; i <20; i ++) if (i% 2 == 0) println i + "is even ..." println 'Operations terminated at' + simple.format (new Date ()) }
From the command line, type:
gradle proviamoGradle
obtaining the following output:
2 è pari... 4 è pari... 6 è pari... 8 è pari... 10 è pari... 12 è pari... 14 è pari... 16 è pari... 18 è pari... Operazioni terminate alle 12:33:35
In practice, we have created a program, whose heart is placed in the task called proviamoGradle , in which the even numbers between 1 and 20 are printed, followed by the hourly information of the end of the operations. The most interesting thing about this, though, is the fact that the code we used is nothing but Java .
The classes Dateand SimpleDateFormatwe used are exactly those belonging to the JDK, forand ifare the control constructs we know well and printlnis the instruction to request the printing of a single line console.
The example shows how the use of Groovy within Gradle not only gives flexibility to instructions, but all the richness of the functionality of the Java world.
Build automation: we compile a program in Java
Gradle can perform operations of any kind and can interact with all kinds of computer technology, although its functionality makes it particularly suitable for Java. For this reason, we will use it to build a Java program, a simple ‘Hello world’.
For all those sectors where the tool offers a large number of functionalities, the appropriate plugins are provided . For Java there is one that contains all the tasks that specify the most common needs: compilation, packaging in .jar , test, and so on. So we create a simple Hello.java file , with the most classic of the test contents:
public class Hello { public static void main (String [] args) { System.out.println ("Hello world!"); } }
At this point it is very important to follow Gradle’s conventions . Therefore we place the newly created file inside the src / main / java directory . The build.gradle file will be minimal, as it will only have to activate the ‘java’ plugin, without including any tasks:
apply plugin: 'java'
At this point, typing from the command line:
gradle build
Gradle will create, next to the src folder , the build folder , whose content will be as shown in the figure:
Those who know Java know that it is a complete compilation of our software: the .class file with the bytecode, a .jar and also a Manifest file. In practice, the plugin did what any Java programmer would have expected: it elaborated the sources, recognizing them by placing them in folders, and compiling them.
One last note: to make the .jar file usable , you need to set the Main-Class attribute in the Manifest. We can specify this other statement always in the build.gradle file:
apply plugin: 'java' jar { manifest { attributes 'Main-Class':'Hello' } }
Having done this and launched again the command gradle build we will get the same result, but this time the product .jar file will be executable from the command line with:
java -jar bin.jar
Integration on Android Studio.
Gradle has entered the world of Android programming, and it is interesting to investigate its use in Android Studio , an IDE published in May 2013 specifically to create Android apps. Rather than developing building skills within Android Studio, the use of Gradle has been integrated into it, which is connected to the IDE with a special plugin. The advantage of this choice consists in having a flexible and powerful system, but above all outside the IDE. This allows you to do command-line or automated scripting even on machines where Android Studio is not present.
Android Studio projects contain at least one mandatory form, which is called an app . Each module has its build.gradle file, structured like the following:
apply plugin: 'com.android.application' <font></font> android { compileSdkVersion 20 buildToolsVersion "20.0.0" <font></font> defaultConfig { applicationId "comexample.helloworld" minSdkVersion 14 targetSdkVersion 20 versionCode 1 versionName "1.0" } <font></font> buildTypes { release { runProguard false proguardFiles getDefaultProguardFile ('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree (dir: 'libs', include: ['* .jar']) }
After what was said about Gradle in this article, we can recognize the following elements:
- apply plugin loads the plugin containing tasks related to Android activities;
- the android element contains various configuration attributes of the project, such as the version number and reference API levels ( minSdkVersion and targetSdkVersion );
- dependencies specifies the dependencies of the project. What you see here is a local dependency , which allows you to have the classes available in the .jar files included in the libs directory . Very often remote dependencies are used , defined by Maven coordinates, such as:
compile ‘com.android.support:appcompat-v7:20.+’
which allows you to use classes contained in the appcompat7 support library.
The presence of Gradle in Android Studio also justifies the particular arrangement of Java sources and resources in the project, which follow the conventions previously mentioned, and which must be respected so that the build can be executed.
Another thing to remember is that, whenever the programmer makes changes to files build.gradle , Android Studio you must click on the button Sync Project Files With Gradle , recognizable by the following icon:
Conclusions
What is presented in this article is nothing but a drop in the sea of the features offered by Gradle. The official documentation of the project remains the best source of information. It is not uncommon to find programmers interested in understanding the topic, and not just in the context of Java. Gradle can be useful to anyone interested in a flexible scripting system to plan operations to be performed in the system, but also to all Android developers trying to get familiar with Android Studio.
It is also interesting to investigate the relationship between Gradle and his predecessors , Ant and Maven. Gradle is born in the sign of continuity and integration with both these excellent tools, to make sure that those who have already used them for years in build automation should not start all over again.