You are on page 1of 42

Build Tools

Java Center of Excellence

Agenda
Introduction to Build Tools
Why required?

Apache Ant Introduction Installation Usage Hands on Apache Maven Introduction Installation Usage Hands on Feedback and Close

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Introduction
Imagine yourself working on a large Java project consisting many .java files. The classes in that are dependent on other classes and libraries, which are situated in multiple directories and the output files must go into multiple directories too and there are various project build routes for different applications and at the moment all of this is being done manually and so many hours are being spent changing directories compiling individual files and so on... Now, imagine if their was a tool that could alleviate the stress and hassle you are experiencing. So to alleviate the stress and hassle there are build tools like
ANT Maven

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Build Tools - Why required?


To perform common tasks like:
Compile code by executing common tasks like cleaning previous build files, copying resources files and generating class files Generate documentation from source code using JavaDoc Perform Unit testing using Use JUnit or TestNG Generate deployable like .jar file Deploy by coping runtime files to a server

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Apache Ant Apache Ant is a software tool for automating software build processes. It is implemented using the Java language, requires the Java platform, and is best suited to building Java projects but can be used for just about everything. Ant uses XML to describe the build process and its dependencies. By default the XML file is named build.xml. Ant is an Apache project. It is open source software, and is released under the Apache Software License.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Facts about Ant


Ant is the build tool used by most Java development projects. For example, most open source developers include build.xml files with their distribution. Ant made it trivial to integrate JUnit & TestNG tests with the build process. This has made it easy for willing developers to adopt test-driven development. The name ANT is an acronym for "Another Neat Tool".

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Ant Installation
Download the binaries from http://ant.apache.org/bindownload.cgi, unzip them to a suitable directory. Append path to ant bin to the PATH environment variable. Set JAVA_HOME to point to the location of the JDK installation on the machine that the software is being installed on.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Ant Basics
An Ant build file comes in the form of an XML document, all that is required is a simple text editor to edit the build file(s). An editor that provides XML syntax highlighting is preferable. The Ant installation comes with a JAXPCompliant XML parser, this means that the installation of an external XML parser is not necessary.
Basic build.xml Example

<?xml version="1.0"?> <project name=AntApp" default=Compile" basedir="."> <property name="src" value=src"/> <property name="build" value="build"/> <target name="init"> <mkdir dir="${build}"/> </target> <target name=Compile" depends="init"> <!-- Compile the java code --> <javac srcdir="${src}" destdir="${build}"/> </target> </project>

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Build.xml (contd.)
<?xml version="1.0"?>
Since Ant build files are XML files the document begins with an XML declaration which specifies which version of XML is in use, this is to allow for the possibility of automatic version recognition should it become necessary.

<project name=AntApp" default=Compile" basedir=".">


The root element of an Ant build file is the project element, it has three attributes.
name: The name of the project, it can be any combination of alphanumeric characters that constitute valid XML. default: The default target to use when no target is specified, out of these three attributes default is the only required attribute. basedir: The base directory from which any relative directories used within the Ant build file are referenced from. If this is omitted the parent directory of the build file will be used.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

Build.xml (contd.)
<property name="src" value=src"/> <property name="build" value="build"/>
The property element allows the declaration of properties which are like user-definable variables available for use within an Ant build file. The name attribute specifies the name of the property and the value attribute specifies the desired value of the property. The name and value values are subject to standard XML constraints.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

10

Build.xml (contd.)
<target name="init"> <mkdir dir="${build}"/> </target>

The target element is used as a wrapper for a sequences of actions. A target has a name, so that it can be referenced from elsewhere, either externally from the command line, or internally via the depends keyword, or through a direct call. The target in the example is called "init" (initiate), it makes a directory using the mkdir element with the name specified by the build property defined in three. The target element has a number of possible attributes, unless otherwise specified, these are optional:
name: The name of the target is used to reference it from elsewhere, it is subject to the constraints of XML well formedness. This is the only required attribute for the target element. depends: This is a comma separated list of all the targets on which this target depends,depends contains the list of the targets that must be executed prior to executing this target. description: This is a short description of the target.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

11

Build.xml (contd.)
<target name="compile" depends="init"> <!- - Compile the java code - -> <javac srcdir="${src}" destdir="${build}"/> </target>
The javac element, as used above, is a task, tasks are performed in the body of a target, in this case, the source directory is specified by referencing the src property and the destination directory is specified by referencing the build property. The example above causes javac to be executed, compiling all the .java files in the directory specified by the src property and placing the resultant .class files in the directory specified by the build property.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

12

Executing targets in Ant


To execute target init in the build.xml discussed
Navigate to project folder on command prompt Execute command ant init This will execute the tasks defined under init

To execute target compile


Execute command ant as compile is the default target it will be execute else you can execute ant compile as well This will first execute target init as compile depends on init and then execute tasks defined under compile

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

13

Frequently used Ant tasks


Task java:Javac - Compiles Java source files Task java:Java - Launcher for Java applications Task java:Javadoc - Generates Javadoc documentation for a collection of source code Task filesystem:Copy - Copies a file or directory to a new file or directory Task filesystem:Delete - Deletes a file or directory, or set of files defined by a fileset Task packaging:Jar - Creates a JAR archive Task packaging:War - Creates a WAR archive Task packaging:Zip - Create a Zip file Task filesystem:Mkdir - Creates a given directory

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

14

Exercise
To get a hands-on on ant we would be building an application which will return sum of two integers passed as arguments to application. In the duration of building this application we will learn how to compile, build and clean this application using ant.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

15

Create application structure


Create a folder AntExample. Create folder src. Create package structure com.uhc.ant under src.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

16

Create main class


Create a main class AntExample.java under src/com/uhc/ant folder.

package com.uhc.ant; public class AntExample { public static void main(String args[]) { AntExampleService aeService = new AntExampleService(); //Prints the sum of two integers passed in the arguments System.out.println("The sum of two integers is :"+ aeService.getSum(Integer.parseInt(args[0]),Integer.parseInt(args[1]))); } }

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

17

Create service class


Create a service class AntExampleService.java under src/com/uhc/ant folder.
package com.uhc.ant; public class AntExampleService { /** * *This method returns the sum of two integers. */ public int getSum(int a, int b) { return a+b; } }

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

18

Add build.xml
Add project build.xml in base folder
<?xml version="1.0"?> <project name="AntExample" default="compile" basedir="."> <property name="src" value=src"/> <property name="build" value="build"/> <target name="init"> <mkdir dir="${build}"/> </target> <target name="compile" depends="init"> <!-- Compile the java code --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="clean" description="Removes previous build"> <delete verbose="true"> <fileset dir="${build}"/> </delete> </target> </project>

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

19

Init & Compile Execution


Navigate to project folder on command prompt. Execute command ant init. On successful build execution
New directory structure build would be created under base directory

Now execute command ant compile. On successful build execution


Two classes AntExample.class and AntExampleService.class would be created under build\com\uhc\ant directory

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

20

Clean Execution
Execute command ant clean. On successful build execution
Classes AntExample.class and AntExampleService.class would be deleted from build\com\uhc\ant directory

Now execute command ant. On successful build execution


The default target compile will be executed.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

21

Apache Maven Maven is a project management tool which encompasses


A project object model (POM) A set of standards A project lifecycle A dependency management system Logic for executing plugin goals at defined phases in a lifecycle

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

22

Maven Installation Download the binaries from http://maven.apache.org/download.html, unzip them to a suitable directory. Add an environment variable M2_HOME and add the path to maven installation as value. Append path to maven bin to the PATH environment variable. Set JAVA_HOME to point to the location of the JDK installation on the machine that the software is being installed on. Test the maven installation by running mvn v on command prompt.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

23

Project Object Model (POM)


The POM contains four categories of description and configuration
General project information

This includes a projects name, the URL for a project, the sponsoring organization, and a list of developers and contributors along with the license for a project. The behavior of the default Maven build is customized under this section. The location of source and tests can be changed, new plugins can be added and plugin goals can be attached to lifecycle. The build environment consists of profiles that can be activated for use in different environments.

Build settings

Build environment

POM relationships

A project rarely stands alone; it depends on other projects, inherits POM settings from parent projects, defines its own coordinates, and may include submodules.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

24

Sample pom.xml
<project xmlns=http://maven.apache.org/POM/4.0.0 xmlns:xsi=http://www.w3.org/2001/XMLSchemainstance xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/mavenv4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.uhc.maven</groupId> <artifactId>MavenExample</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>5.5</version> <classifier>jdk15</classifier> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.4</version> </plugin> </plugins> </build> </project>
Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

25

The Build Lifecycle


A Maven lifecycle consists of a sequence of named phases: validate, compile, package, and install among other. There is phase that captures compilation and a phase that captures packaging. There are pre- and post- phases which can be used to register goals which must run prior to compilation, or tasks which must be run after a particular phase. When you tell Maven to build a project, you are telling Maven to step through a defined sequence of phases and execute any goals which may have been registered with each phase. A build lifecycle is an organized sequence of phases that exist to give order to a set of goals.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

26

Default Lifecycle (default)


It is a general model of a build process for a software application. The first phase is validate and the last phase is deploy Maven Lifecycle Phases Lifecycle Phase Description
validate Validate the project is correct and all necessary information is available to complete a build
Compile the source code of the project

Command
mvn validate

compile

mvn compile

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

27

Maven Lifecycle Phases (contd.)


Lifecycle Phase
test-compile

Description
Compile the test source code into the test destination directory Run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR Install the package into the local repository, for use as a dependency in other projects locally Copies the final package to the remote repository for sharing with other developers and projects.

Command
mvn test-compile

test

mvn test

package

mvn package

install

mvn install

deploy

mvn deploy

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

28

Clean Lifecycle (clean)


Running mvn clean invokes the clean lifecycle which consists of three lifecycle phases:
pre-clean clean post-clean

The interesting phase in the clean lifecycle is the clean phase. The Clean plugin's clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. The clean:clean goal deletes the output of a build by deleting the build directory. If you haven't customized the location of the build directory it will be the ${basedir}/target directory. Executing the clean phase gives Maven an opportunity to execute any other goals which may be bound to the preclean phase.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

29

Build Profiles
Profiles allow for the ability to customize a particular build for a particular environment; profiles enable portability between different build environments. Maven allows to define any number of build environments (build profiles) which can override any of the settings in the pom.xml. You could configure your application to read from your local, development instance of a database in your "development" profile, and you can configure it to read from the production database in the "production" profile. Profiles can be defined under <profiles> tag in pom.xml or profiles.xml placed under projects base directory. Each profile is identified by the value given in <id> tag e.g <id>development</id> denotes development profile. To execute mvn install under the development profile, you need to pass the Pdevelopment argument on the command-line.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

30

Exercise
To get a hands-on on maven we would be building an application which will return sum of two integers passed as arguments to application. In the duration of building this application we will learn how to compile, test, install and clean this application using maven.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

31

Create application structure


Create a folder MavenExample. Create folders src\main\java, src\test\java, src\main\resources & src\test\resources under MavenExample. Create package structure com.uhc.maven under src\main\java and src\test\java.

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

32

Create main class


Create a main class MavenExample.java under src/main/java/com/uhc/maven folder. package com.uhc.maven;

public class MavenExample {


public static void main(String args[]) { MavenExampleService meService = new MavenExampleService(); //Prints the sum of two integers passed in the arguments System.out.println("The sum of two integers is :"+ meService.getSum(Integer.parseInt(args[0]),Integer.parseInt(args[1]))); } }

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

33

Create service class


Create a service class MavenExampleService.java under src/main/java/com/uhc/maven folder.

package com.uhc.maven; public class MavenExampleService { /** * *This method returns the sum of two integers. */ public int getSum(int a, int b) {

return a+b;
} }

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

34

Create test class


Create a test class MavenExampleServiceTest.java under src/test/java/com/uhc/maven folder. package com.uhc.maven; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * Unit test for MavenExampleService. */ public class MavenExampleServiceTest { @Test public void getSumTest() { MavenExampleService meService = new MavenExampleService(); assertEquals(5,meService.getSum(2,3)); } }

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

35

Add testng.xml
Add testng.xml under src/test/resources folder.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Maven Example Test Suite"> <test name="Maven example"> <classes> <class name="com.uhc.maven.MavenExampleServiceTest" /> </classes> </test> </suite>

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

36

Add pom.xml
Add project pom.xml in base folder
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.uhc.maven</groupId> <artifactId>MavenExample</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>5.5</version> <classifier>jdk15</classifier> <scope>test</scope> </dependency> </dependencies> Contd.
Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

37

pom.xml (contd.)
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.4</version> <configuration> <suiteXmlFiles> <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> </project>

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

38

Compile & Clean Execution


Navigate to project folder on command prompt. Execute command mvn compile. On successful build execution
New directory structure target\classes\com\uhc\maven would be created under base directory Two classes MavenExample.class and MavenExampleService.class would be present under the above directory

Now execute command mvn clean. On successful build execution


The directory target under base directory will be deleted

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

39

Test Execution
Now execute command mvn test. On successful build execution
New directory structures target\classes\com\uhc\maven & target\test-classes\com\uhc\maven would be created under base directory Two classes MavenExample.class and MavenExampleService.class would be present under target\classes\com\uhc\maven and MavenExampleServiceTest.class would be present under target\test-classes\com\uhc\maven The command prompt will show the number of test run, failures, errors and skipped

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

40

Install Execution
Now execute command mvn install. On successful build execution
New directory structures target\classes\com\uhc\maven & target\test-classes\com\uhc\maven would be created under base directory Two classes MavenExample.class and MavenExampleService.class would be present under target\classes\com\uhc\maven and MavenExampleServiceTest.class would be present under target\test-classes\com\uhc\maven The command prompt will show the number of test run, failures, errors and skipped

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

41

Questions

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited.

42