Java Builds with Maven and Ant

Post on 30-Aug-2014

7.283 views 6 download

Tags:

description

Overview of Maven and Ant for Java builds, with some comparison and contrast.

Transcript of Java Builds with Maven and Ant

Java BuildsJava Buildswith Ant & Mavenwith Ant & MavenFeb 23, 2009Feb 23, 2009

David Noblednoble@g2ix.com

Pasadena Java Users Grouppasadenajug.org

About MeAbout Me

David Noble

Sr Solutions Architect

Exist Global / G2iX

About YouAbout You

Ant users? Ivy? Maven users? Continuous integration?

Build ToolBuild Tool

Collect inputs Process inputs Generate final outputs

Build Tool - InputsBuild Tool - Inputs

Source code Java, SQL

Resources Properties, XML

Dependencies Libraries, components, frameworks

Build Tool - ProcessingBuild Tool - Processing

Compile Run tests Copy files Replace keywords Package Install / deploy

Build Tool - OutputsBuild Tool - Outputs

JAR / WAR / EAR files Zip files Reports

AntAntProcedural1. Set path2. Compile jars3. Run unit tests4. Create reports5. Copy files6. Assemble WAR

MavenMavenDeclarative1. Define name & version2. Define as WAR project3. Specify dependencies4. Specify unit test plugin

AntAnt

“make for java” Properties, paths, and filesets Targets Target dependencies Tasks

Ant InstallationAnt Installation

Download Unzip Add to PATH Set ANT_HOME env variable Extend by adding jars to lib/ Customize by modifying XSL in etc/

Ant Project DefinitionAnt Project Definition

build.xml Project name Property variables Paths Tasks Targets

Ant PropertiesAnt Properties

<property name="lib.dir" value="lib"/> From command line In build.xml From external XML From external property files From environment

Ant PathsAnt Paths<path id="classpath">

<fileset dir="${lib.dir}" includes="**/*.jar"/>

</path>

<target name="compile">

<mkdir dir="${classes.dir}"/>

<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>

</target>

Ant TargetsAnt Targets

Name Description Dependencies Conditionals (if, unless) <antcall> task

Ant TasksAnt Tasks

Core tasks Optional tasks Custom tasks

Third party Write your own

Selected Core TasksSelected Core TasksAnt AntCall Apply Basename BuildNumber Checksum

Chmod Concat Condition Copy Cvs Delete DependSet

Dirname Ear Echo EchoXML Exec Fail Filter FixCRLF Get

Import Input Jar Java Javac Javadoc Length LoadFile

LoadProperties LoadResource MakeURL Mail MacroDef

Manifest ManifestClassPath Mkdir Move Nice Parallel

Patch PathConvert PreSetDef Property Record Replace

ResourceCount Retry Rmic Sequential SignJar Sleep Sql

Subant Sync Tar Taskdef Tempfile Touch Truncate TStamp

Typedef Unjar Untar Unwar Unzip Uptodate Waitfor

WhichResource War XmlProperty XSLT Zip

Ant Multi-Project BuildsAnt Multi-Project Builds

Option 1 – Master build.xml Option 2 – Cascading build.xml's

Ant ScriptingAnt Scripting

<macrodef> task <script> task

Ivy for DependenciesIvy for Dependenciesbuild.xml

<project xmlns:ivy="antlib:org.apache.ivy.ant"

name="hello-ivy" default="run">

<target name="resolve">

<ivy:retrieve />

</target>

</project>

Ivy for DependenciesIvy for Dependenciesivy.xml

<ivy-module version="2.0">

<info organisation="apache" module="hello-ivy"/>

<dependencies>

<dependency org="commons-lang"

name="commons-lang" rev="2.0"/>

<dependency org="commons-cli"

name="commons-cli" rev="1.0"/>

</dependencies>

</ivy-module>

Ivy RepositoriesIvy Repositories

Maven artifact repositories Build your own

Ivy ReportsIvy Reports

Ant EcosystemAnt Ecosystem

IDE plugins Custom tasks

More AntMore Ant

Ant http://ant.apache.org/

Core tasks http://ant.apache.org/manual/coretasklist.html

External tools http://ant.apache.org/external.html

IVY http://ant.apache.org/ivy/

MavenMaven

Project and artifact-based build platform

Uses repositories to manage artifacts and third party libraries

Customized by modifying the behavior of the life-cycle via plugins.

MavenMaven

Maven ArtifactsMaven Artifacts

Output of the build process JARs, WARs, EARs, zip files Stored in repositories Published and consumed by Maven One per project

Maven DependenciesMaven Dependencies

Items needed during build process Managed as artifacts and metadata

within remote repositories Usually created and published by

other Maven builds Though not necessarily

Maven DependenciesMaven Dependencies<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.2</version>

<scope>test</scope>

</dependency>

Maven Directory StructureMaven Directory Structure

pom.xml src/ target/

Maven Directory StructureMaven Directory Structure

src main

com/example/app/App.java test

com/example/app/AppTest.java

Maven Directory StructureMaven Directory Structure target

classes/ generated-classes/ site/ surefire-reports/ test-classes/ webdemo-1.0-SNAPSHOT.war

Maven Project Object ModelMaven Project Object Model

“POM” Fundamental unit of work in Maven Build components inherit from best

practices and common base

Maven Build Life-CycleMaven Build Life-Cycle

Consistent pattern Portable process knowledge Modify build with plugins

Extensible in decoupled way

Large number of phases, not all required Compile, test, package, install, deploy

Default Lifecycle PhasesDefault Lifecycle Phases validate, initialize

generate-sources, process-sources

generate-resources, process-resources

compile, process-classes

generate-test-sources, process-test-sources

generate-test-resources, process-test-resources

test-compile, process-test-classes

test

prepare-package, package

pre-integration-test, integration-test, post-integration-test

verify, install, deploy

Site Lifecycle PhasesSite Lifecycle Phases

Pre-site: executes processes Site: generates documentation Post-site: executes processes Site-deploy: copies files

Clean Lifecycle PhasesClean Lifecycle Phases

Pre-clean: executes processes Clean: removes files Post-clean: executes processes

Phases have GoalsPhases have Goals

generate-resources ear:generateApplicationXml

process-resources resources:resources

package ear:ear

install install:install

deploy deploy:deploy

Maven SettingsMaven Settings

Two setting files Installation settings:

conf/settings.xml in install directory User settings: ~/.m2/settings.xml

C:\Users\username on Windows Vista C:\Documents and Settings\username on XP

Maven SettingsMaven Settings

Separate installation and user settings User settings are things you don't share

server usernames and passwords, local paths, etc.

Installation settings are things that should be the same on all Maven installations can distribute various ways: check out Maven install

from SCM, provide a re-bundled Maven, etc.

Maven ArchetypesMaven Archetypes

POJO jar Web applications

AppFuse, Wicket, MyFaces, etc Groovy

Maven ArchetypesMaven Archetypes

mvn archetype:generate Application structure Code generation Plugin Distributed in repositories

Maven ResourcesMaven Resources

Accessed by code at runtime Not required for compilation Packaged within the artifact Can be filtered with custom values

Maven PluginsMaven Plugins Reusable pieces of build functionality Perform a clearly defined task based on a set of

input configuration Maven takes responsibility for orchestrating their

execution Primarily written in Java, but can be written in a

number of scripting languages Are also stored and downloaded from repositories

Maven RepositoriesMaven Repositories Repositories are a storage location for artifacts Maven has two types:

Remote repository - repository accessible over HTTP, FTP, filesystem, etc that contains artifacts to consume and as a place to publish build artifacts

Local repository - a cache of artifacts on your machine, downloaded from several remote repositories

Maven is pre-configured to use the Central Repository for dependencies

A large collection of open source and re-distributable artifacts, primarily for Java

Can establish and manage your own remote repositories Can be used by build systems other than Maven

Repository ServersRepository Servers

Archiva Artifactory Nexus

ArchivaArchiva

Helps to manage Maven repositories Control your environment for your

team Can be run personally for offline

cache

ArchivaArchiva A repository management server

manages Maven remote repositories and the artifacts inside them

Used by a group or team for an “internal” remote repository deploy your own build artifacts

control content from external sources

on demand downloading of artifacts

CI server companion

Can be used as a personal server make it easier to clean your local repository without downloading remotely again

must be careful about introducing build inconsistencies localized to your environment, however

Installing ArchivaInstalling Archiva Two choices

Existing servlet container or application server

Standalone

pre-configured instance of Jetty 6, Java Service Wrapper, Apache Derby

Configuration files APP_BASE/conf/jetty.xml - server port, outgoing mail server and databases

standalone only, configure using container settings for others

APP_BASE/conf/archiva.xml - maintained by the application applies to both choices

Two databases – users and repository statistics

When using standalone, recommend a separate conf directory set ARCHIVA_BASE environment variable to point to a copy of the conf directory

makes upgrading easier

Configuring Maven For ArchivaConfiguring Maven For Archiva

There are a number of alternatives for configuring Maven to use a repository manager: add to the POM

used in addition to central, but always checked first

add to Maven settings

as above, but applies to all projects

override or mirror central

never use the central repository, everything else the same

override or mirror all repositories given

Could add the repositories to the POM what if the parent POM is in the repository, not the check out?

use the POM if users must build using that repository without configuring settings

Use Maven settings instead generally prefer the mirror all repositories

MavenMaven Archetypes Artifacts POM – Project Object Model Dependencies Directory structure Plugins (testing, reporting, deploying, etc) Repositories

Maven EcosystemMaven Ecosystem

IDE support Artifact repositories Plugins Continuous integration

Maven CompaniesMaven Companies

Maven LinksMaven Links

Maven http://maven.apache.org/

Archiva http://archiva.apache.org/

Artifacts http://mvnrepository.com/

Free Books http://www.exist.com/better-build-maven/

http://www.sonatype.com/book

CreditsCredits

Special thanks to Carlos Sanchez and Brett Porter

for their inputs and material from their training slides

Thanks!Thanks!

David Noble

dnoble@g2ix.com

www.dnoble.org