SlideShare a Scribd company logo
Demystifying By Mike Desjardins
Topics Installation Shock and Awe: Comparison with ant Project Object Model (POM) Inheritance and Modules Dependencies Build Configuration Whirlwind Tour of Plugins Lifecycles Build Profiles Sometimes Maven Lets You Down
About Me Developed Software professionally for about 15 years, the last 5 with Java Independent Contractor/Consultant Live in Portland, Maine For the past several years, primary focus has been on web services Wireless Telecommunications Financial Services Online Music Website:  http://mikedesjardins.us Twitter: @mdesjardins
Installation Requires JDK 1.4 Download Maven from  http://maven.apache.org/ Unzip the archive Add the M2_HOME environment variable and point it to your installation. Make sure JAVA_HOME is set and java is in your PATH. Make sure $M2_HOME/bin is in your PATH.
Ant vs. Maven Best illustrated by Example We will create a new trivial Hibernate Application that reads rows in a database table (shown below) and outputs them to the console. greeting_id greeting_text 1 Hello 2 Bon jour 3 Buenos dias 4 Kon ni chi wa
Example – Source Code First, we will need a class to represent a greeting: @Entity public   class  Greeting { @Id   @GeneratedValue (strategy=GenerationType. IDENTITY ) @Column (name= "greeting_id" ,nullable= false ,unique= true )  private  Integer  id ; @Column (name= "greeting_text" ) private  String  text ; @Column (name= "version" )  @Version private  Integer  version ; public  Integer getId() {  return   this . id ; } public   void  setId(Integer id) {  this . id  = id; } public  String getText() {  return   this . text ; } public   void  setText(String text) {  this . text  = text; } }
Example – Source Code Next, we will need a class with a static main method to actually do stuff...
Example – Source Code public   class  App { private   static  SessionFactory  sessionFactory ; static  { try  { sessionFactory  =  new  AnnotationConfiguration().configure().buildSessionFactory(); }  catch  (Throwable t) { System. out .println( &quot;Something terrible has happened.&quot; ); t.printStackTrace(); } } public   static  SessionFactory getSessionFactory() {  return  App. sessionFactory ; } public   void  run() { System. out .println( &quot;======================================================&quot; ); Criteria c = App. getSessionFactory ().openSession().createCriteria(Greeting. class ); List<Greeting> greetings =  c.list() ; for  (Greeting greeting : greetings) { System. out .println(greeting.getId() +  &quot;: &quot;  + greeting.getText()); } System. out .println( &quot;======================================================&quot; ); } public   static   void  main(String args[]) { App app =  new  App().run()); } }
Ant: Let's Get Started! First, let's create the directories for our project: Mac:~/_work$ mkdir demo-ant Mac:~/_work$ cd demo-ant Mac:~/_work/demo-ant$ mkdir src lib conf target Mac:~/_work/demo-ant$ cd src Mac:~/_work/demo-ant/src$ mkdir com Mac:~/_work/demo-ant/src$ cd com Mac:~/_work/demo-ant/src/com$ mkdir techmaine Mac:~/_work/demo-ant/src/com$ cd techmaine Mac:~/_work/demo-ant/src/com/techmaine$ mkdir antdemo Mac:~/_work/demo-ant/src/com/techmaine$
Ant: Let's Get Started! (If you’re more of a visual person)
Let's go get our jars! 1.) Visit the Hibernate Website, eventually find their download page…
Let's go get our jars! 2.) Download gigantic ZIP file ZZZZZZZZZ….
Let's go get our jars! 3.) Unpack the ZIP file 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/ 26428  09-10-08 12:21  hibernate-distribution-3.3.1.GA/lgpl.txt 1456  09-10-08 12:21  hibernate-distribution-3.3.1.GA/hibernate_logo.gif 152761  09-10-08 12:21  hibernate-distribution-3.3.1.GA/changelog.txt 2766130  09-10-08 12:27  hibernate-distribution-3.3.1.GA/hibernate3.jar 31493  09-10-08 12:22  hibernate-distribution-3.3.1.GA/hibernate-testing.jar 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/lib/ 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/lib/required/ 443432  06-13-08 12:09  hibernate-distribution-3.3.1.GA/lib/required/antlr-2.7.6.jar 559366  06-13-08 12:09  hibernate-distribution-3.3.1.GA/lib/required/commons-collections-3.1.jar 313898  06-13-08 12:09  hibernate-distribution-3.3.1.GA/lib/required/dom4j-1.6.1.jar 13236  06-13-08 12:09  hibernate-distribution-3.3.1.GA/lib/required/jta-1.1.jar 17384  08-19-08 19:40  hibernate-distribution-3.3.1.GA/lib/required/slf4j-api-1.5.2.jar 471005  06-13-08 12:10  hibernate-distribution-3.3.1.GA/lib/required/javassist-3.4.GA.jar 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/lib/optional/ 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/lib/optional/c3p0/ 608376  06-13-08 12:12  hibernate-distribution-3.3.1.GA/lib/optional/c3p0/c3p0-0.9.1.jar 0  09-10-08 12:27  hibernate-distribution-3.3.1.GA/lib/optional/proxool/ 475943  06-13-08 12:12  hibernate-distribution-3.3.1.GA/lib/optional/proxool/proxool-0.8.3.jar . . . . . . Holy Shnikeys! Do I really need  all  of this stuff?!?
Next Steps Copy the jar files to your lib directory Option 1: Copy Everything (Lazy) Option 2: Copy only what you need (Tedious) Create your build.xml file
Create the build.xml Start with an empty file <?xml version=&quot;1.0&quot;?> <project name=&quot;antdemo&quot; default=&quot;compile&quot; basedir=&quot;.&quot;> </project> Step 1
Create the build.xml Create some variables build.xml <!-- set global properties for this build --> <property name=&quot;lib&quot; value=&quot;lib&quot;/> <property name=&quot;src&quot; value=&quot;src&quot;/> <property name=&quot;conf&quot; value=&quot;conf&quot;/> <property name=&quot;target&quot; value=&quot;target&quot;/> <property name=&quot;classes&quot; value=&quot;${target}/classes&quot;/> Step 2
Create the build.xml Tell ant about all  of your libraries build.xml <fileset id=&quot;compile.libs&quot; dir=&quot;${lib}&quot;> <include name=&quot;antlr-2.7.6.jar&quot;/> <include name=&quot;asm.jar&quot;/> <include name=&quot;asm-attrs.jar&quot;/> <include name=&quot;cglib-2.1.3.jar&quot;/> <include name=&quot;commons-collections-3.2.jar&quot;/> <include name=&quot;commons-lang-2.3.jar&quot;/>  <include name=&quot;commons-logging-1.0.4.jar&quot;/> <include name=&quot;dom4j-1.6.1.jar&quot;/> <include name=&quot;ejb3-persistence.jar&quot;/> <include name=&quot;javassist.jar&quot;/> <include name=&quot;jboss-archive-browsing.jar&quot;/> <include name=&quot;jdbc2_0-stdext.jar&quot;/> <include name=&quot;jta.jar&quot;/> <include name=&quot;xml-apis.jar&quot;/> <include name=&quot;xercesImpl-2.6.2.jar&quot;/> <include name=&quot;hibernate3.jar&quot;/> <include name=&quot;hibernate-annotations.jar&quot;/> <include name=&quot;hibernate-commons-annotations.jar&quot;/> <include name=&quot;hibernate-entitymanager.jar&quot;/> </fileset> Step 3
Create the build.xml Tell ant about compiling build.xml <target name=&quot;init&quot;> <tstamp/> <mkdir dir=&quot;${classes}&quot;/> </target> <target name=&quot;compile&quot; depends=&quot;init&quot;> <mkdir dir=&quot;${basedir}/${classes}&quot;/> <javac srcdir=&quot;${basedir}/${src}&quot;    destdir=&quot;${basedir}/${classes}&quot;    debug=&quot;yes&quot;  target=&quot;1.5&quot;> <classpath> <fileset refid=&quot;compile.libs&quot;/> </classpath> </javac> <copy file=&quot;${basedir}/${conf}/hibernate.cfg.xml&quot;    todir=&quot;${basedir}/${classes}&quot;/> </target> <target name=&quot;clean&quot;> <delete quiet=&quot;yes&quot; dir=&quot;${basedir}/${target}&quot;/> <mkdir dir=&quot;${basedir}/${target}&quot;/> </target> Step 4
Create the build.xml Tell ant how to run the app build.xml <fileset id=&quot;runtime.libs&quot; dir=&quot;${lib}&quot;> <include name=&quot;postgresql-8.2-507.jdbc3.jar&quot;/> </fileset> <target name=&quot;run&quot; depends=&quot;compile&quot;> <java classname=&quot;com.techmaine.antdemo.App&quot;> <classpath> <fileset refid=&quot;compile.libs&quot;/> <fileset refid=&quot;runtime.libs&quot;/> <pathelement location=&quot;${basedir}/${classes}&quot;/> </classpath> </java> </target> Step 5
Recap We downloaded jars and dependencies ourselves We told ant The name of the jar file that we needed (Hibernate) All the dependent jar file names Where the jar files were located That it needed to compile java files Where the java files were located Where it should put the class files Where it should put the Hibernate configuration file How to run the application Where the jar and class files were located (again, this time for runtime) build.xml is 75 lines, but who’s counting?
Next: The way
Maven Terminology With maven, you execute  goals  in  plugins  over the different  phases  of the  build lifecycle , to generate  artifacts .  Examples of artifacts are jars, wars, and ears.  These artifacts have an  artifactId , a  groupId , and a  version . Together, these are called the artifact’s “ coordinates .”  The artifacts stored in  repositories .  Artifacts are  deployed  to remote repositories and  installed  into local repositories. A  POM  (Project Object Model) describes a project.
Create a Project Directory Maven has a command  for starting a project: mvn archetype:create \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \  -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Step 1
Create a Project Directory mvn  archetype :create \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \  -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Plugin Name Step 1
Create a Project Directory mvn archetype: create  \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \  -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Plugin Name Goal Step 1
Create a Project Directory Voila !  Look what maven has done for you: Step 1
Set up the dependencies Open pom.xml.  We need to tell maven that  we have a dependency on Hibernate: <project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0  http://maven.apache.org/maven-v4_0_0.xsd&quot;> <modelVersion>4.0.0</modelVersion> <groupId>com.techmaine</groupId> <artifactId>demo-mvn</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>demo-mvn</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> We’ll add the dependency here. Step 2
Set up the dependencies <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.1.ga</version> </dependency> This is all we need to add: We don’t need to tell Maven about any of the jars on which Hibernate depends; Maven takes care of all of the transitive dependencies for us! Step 2
Set up the compiler <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> Maven assumes a default source version of 1.3.  We need to tell it if we want 1.5.  Here’s a preview of plugin configuration: STUPIDITY ALERT! Step 3
Set up Hibernate Configuration Create a resources directory beneath the main (and, optionally, test) directory, and put the Hibernate configuration file there.  Files in the resources directory get copied to the root of the classpath when packaging occurs as part of the resource:resource goal (more on that later) The resources directories are automatically created for many of the archetypes, but not for the quickstart archetype that we used. Step 4
Package Next, package everything up before we run it. To do this, invoke maven thusly: mvn package   This is an alternate way to invoke maven.  Instead of specifying a plugin and goal, you specify a phase (in this case, package is the phase).  A phase is a sequenced set of goals.  The package phase compiles the java classes and copies the resources Step 5
Execute Next, use the exec plugin to run our application: mvn  exec:exec   \ -DmainClass=com.techmaine.mvndemo.App Step 6
Recap We told maven That we were making a “quickstart” project. That we depended on Hibernate Annotations. That we needed Java 1.5 pom.xml was 35 lines (would have been 22 if maven defaulted to Java 1.5 instead of 1.3)
Recap – Why Maven is Cool We downloaded jars and dependencies ourselves We told ant The name of the jar file that we needed (Hibernate) All the dependent jar file names Where the jar files were located That it needed to compile java files Where the java files were located Where it should put the class files Where it should put the Hibernate configuration file How to run the application Where the jar and class files were located (again, this time for runtime) build.xml is 75 lines, but who’s counting? We told maven That we were making a “quickstart” project. That we depended on Hibernate Annotations. That we needed Java 1.5 pom.xml was 35 lines (would have been 22 if maven defaulted to Java 1.5 instead of 1.3)
What can Maven do? When you first download it, almost nothing! Run goals Run phases (collections of goals) Download Dependencies* Download Plugins But... from where? * Actually, dependency downloads are done by a plugin, too.
Configuring Maven Settings Files (settings.xml) In ~/.m2 (per-user settings) and in Maven’s install directory, under conf (per-system settings) Alternate location for repository Proxy Configuration Per-server authentication settings Mirrors Download policies, for plugins and repositories; snapshots and releases.
Configuring Maven Project Object Model (pom.xml) Inherited – individual projects inherit POM attributes from parent projects, and ultimately inherit from the “Super POM” The Super POM is in Maven’s installation directory, embedded in the uber jar. The Super POM defines, among lots of other things, the default locations for the plugin and jar repositories, which is  http://repo1.maven.org/maven2
Repositories Local - in ~/.m2/repository Remote - e.g., http://repo1.maven.org/maven2 or another internal company repository (any directory reachable by sftp will do). Contains dependencies and plugins Can be managed by a “Repository Manager” like Nexus
The POM Describes the project, declaratively General Information - Project Coordinates (groupId, artifactId, Version) Build Settings – Configuration of the plugins Build Environment – We can configure different profiles that can be activated programatically POM Relationships – Dependencies on other projects
Anatomy of a POM File <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <packaging>jar</packaging> <version>1.0.0</version> <name>Super Duper Amazing Deluxe Project</name>  <modules> <!-- Sub-modules of this project --> </modules> <parent> <!-- Parent POM stuff if applicable --> </parent> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
General Information <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <modules> <!-- Sub-modules of this project --> </modules> <parent> <!-- Parent POM stuff if applicable --> </parent> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project> Coordinates
Project Inheritance <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
Project Inheritance What is inherited? Identifiers (groupId, artifactId, one must be different) Dependencies Plugin, Report Lists Plugin Configurations Why Inherit? Don’t repeat yourself, e.g., several projects use the same version of log4j. Enforce plugin version across projects
Multimodule Projects <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
Multimodule Projects Not the same thing as POM inheritance! A multimodule project builds submodules, but rarely produces an artifact itself Directory structure mimics module layout (e.g., if B is a submodule of A, then B will be a subdirectory of A).
Multimodule Projects <packaging>pom<packaging> <modules> <module>ejb</module> <module>ear</module> </modules> Depends on the EJB artifact Creates EJB jar
Multimodule: Reactor When Maven encounters a multimodule project, it pulls all of the POMs into the “Reactor”  The Reactor analyzes module inter-dependencies to ensure proper ordering. If no changes need to be made, the modules are executed in the order they are declared. Maven then runs the goals on each module in the order requested.
User-Defined Properties <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
User-Defined Properties User-Defined properties are like ant properties: <properties> <hibernate.version>3.3.0.ga</hibernate.version> </properties> ... <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifact> <version>${hibernate.version}</version> </dependency> </dependencies> Example from  Maven: The Definitive Guide,  Sonatype, O’Reilly p.266
Other Properties Maven Properties, project.*  ${project.version} Settings Properties, settings.* ${settings.interactiveMode} Environment Variables, env.* ${env.JAVA_HOME} Java System Properties ${java.version}, ${os.arch}, ${user.dir}
Dependencies <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
Dependencies Maven’s  pièce de résistance <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies>
Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> groupId and artifactId: must be unique
Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> 1.3.5  - prefer version 1.3.5, newer version is acceptable to resolve conflicts (1.3.4,1.3.9)  - Any version between 1.3.2 and 1.3.9, exclusive [1.3.4,1.3.9]  - Any version between 1.3.2 and 1.3.9, inclusive [,1.3.9]  - Any version up to, and including, 1.3.9 [1.3.5]  - Only version 1.3.5, do not use a newer version .
Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> compile  - default, packaged.  Available on compile-time and runtime CLASSPATH. provided  - you expect the JVM or app container to provide the library.  Available on compile-time CLASSPATH.  runtime  - needed to run, but not compilation (e.g., a JDBC driver) test  - only needed during test execution (e.g., JUnit)
Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> Prevents this dependency from being included as a transitive dependency if some other project depends on this project.
Transitive Dependencies A 1.0 B 1.0 C 1.0 E 1.0 D 1.0 Our project (Project “A”) depends on B and C.  Project C depends on projects D and E.  Thus, our project depends on B, C, D, and E, and Maven will fetch and use these artifacts appropriately.
Transitive Dependencies A 1.0 B 1.0 C 1.0 E 1.0 D 1.0 Now, let’s say project C has a dependency on project B, but requires version 1.1.  If project A’s POM doesn’t explicitly require version 1.0 or earlier, then Maven will choose version 1.1. B 1.1
Transitive Dependencies A 1.0 B [1.0] C 1.0 E 1.0 D 1.0 Uh oh.  Now Project A is saying that it must use version 1.0 of B, and only version 1.0, and project C needs version 1.1 of project B. B [1.1]
Dependency Exclusions One way to deal with conflicts is with exclusions <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>project-b</artifactId> <version>[1.0]</version> </dependency> <dependency> <groupId>com.techmaine</groupId> <artifactId>project-c</artifactId> <exclusions> <exclusion> <groupId>com.techmaine</groupId> <artifactId>project-b</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
Dependency Management Parent POM Child POM The  dependencyManagement  element allows you to specify version numbers of dependencies in child POMs without making all children dependent on a particular library. <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.5</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> </dependencies>
SNAPSHOT Versions SNAPSHOT is a literal string appended to a version number, e.g., 1.2.3-SNAPSHOT Indicates that a version is “under development” Use if you need Maven to keep checking for the latest version Maven replaces SNAPSHOT with a UTC time stamp before putting it into the repository.
Build Configuration <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
Build Configuration The build section of the POM, broken down further: <project> ... <build> <filters> <filter>filter/my.properties</filter> </filters> <resources> ... </resources> <plugins> ... </plugins> </build> ... </project>
Build Configuration  Filters <project> ... <build> <filters> <filter>filter/my.properties</filter> </filters> <resources> ... </resources> <plugins> ... </plugins> </build> ... </project> Path to a properties file (name=value).  When the resources are processed during packaging, maven will substitute any ${name} strings with the corresponding value from the properties file.
Build Configuration Resources The resources:resources goal copies files from the resources directory to the output directory Can process using filters Default location  src/main/resources Can be further configured: <resources> <resource> <directory>src/main/scripts</directory> <filtering>true</filtering> <targetPath>bin</targetPath> <includes> <include>run.bat</include> <include>run.sh</include> </includes> <resource> </resources>
Build Configuration Plugins All  work in Maven is performed by plugins Like Dependencies, are Downloaded from a repository Because they are shared, you often benefit from the fact that someone else has already built a plugin for whatever function you may need
Plugin Configuration The plugin section of the POM has a configuration element where you can customize plugin behavior: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.2</version> <configuration> <!-- Configuration details go here --> </configuration> </plugin> </plugins> </build>
Plugin Configuration: Example Below, we have configured the clean plugin to delete files ending in .txt from the tmp directory <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.2</version> <configuration> <filesets> <fileset> <directory>tmp</directory> <includes> <include>**/*.txt</include> </includes> <followSymlinks>false</followSymlinks> </fileset> </filesets> </configuration> </plugin> </plugins> </build>
Core Plugins clean  - has only one goal, clean.  Deletes the target directory, can be configured to delete other stuff compiler  - compiles sources, uses javac compiler by default.  Has a compile and testCompile goal. Can be configured to use any executable as the compiler deploy  - uploads artifacts to a remote repository Maven Plugin Whirlwind Tour
Core Plugins, cont. install  - installs the artifact  into the local repository. install goal, install this project’s artifact install-file goal, install a specific file into local repo (good for third-party stuff) surefire  - runs all of the unit tests in the test source directory, and generates reports. resources  - copies resources to be packaged Maven Plugin Whirlwind Tour
Packaging Plugins ear ,  ejb ,  jar ,  war assembly  - builds a binary distribution including runtime dependencies supports zip, tar.gz, tar.bz2, jar, dir, and war formats uses “assembly descriptors” to configure (although several pre-fab ones are available) one of the pre-fab descriptors builds executable jar files with all depenencies embedded Maven Plugin Whirlwind Tour
Utility Plugins archetype  - builds skeleton of a working project for many different frameworks Wicket, Tapestry 5, JSF, JPA, tons of others help  - even the help is a plugin!  Use the describe goal to learn what a plugin can do, e.g.,  mvn help:describe -Dplugin=compiler scm  - source control stuff Maven Plugin Whirlwind Tour
Build Lifecycle Usually, an artifact is built by executing a sequence of goals For example, to generate a WAR: Clean the build area Copy the resources Compile the code Copy the test resources Compile the test code Run the test Package the result
Maven’s Lifecycles Maven supports three standard lifecycles clean  - as you might expect, starts us fresh default  - the lifecycle that builds the code site  - a lifecycle for building other related artifacts (e.g.,  reports and documentation)
Clean Lifecycle The Clean Lifecycle has three phases: pre-clean clean post-clean Only clean is “bound” by default, to the clean goal of the clean plugin.  You can bind other tasks using executions.
Executions Let’s say you have a whizz-bang plugin named  mp3 , and it has a goal named  play  that lets you play an arbitrary audio clip, and you’d like to play a clip during pre-clean: <plugin> <groupId>com.techmaine</groupId> <artifactId>mp3</artifactId> <version>1.0</version> <executions> <execution> <phase>pre-clean</phase> <goals> <goal>play</goal> </goals> <configuration> <audioClipFile>toilet-flush.mp3</audioClipFile> </configuration> </execution> </executions> </plugin>
Maven’s Default Lifecycle Maven models the software build process with the 21 step “default lifecycle” validate generate-test-sources package generate-sources process-test-sources pre-integration-test process-sources generate-test-resources integration-test generate-resources process-test-resources post-integration-test process-resources test-compile verify compile test install process-classes prepare-package deploy
Package-Specific Lifecycles Maven automatically binds goals to the phases on the previous slide based on the packaging type.  E.g., for projects that package WARs: Lifecycle Phase Goal process-resources resources:resources compile compiler:compile process-test-resources resources:testResources test-compile compiler:testCompile test surefire:test package war:war install install:install deploy deploy:deploy
Build Profiles <project xmlns= http://maven.apache.org/POM/4.0.0  > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact>  <version>1.0.0</version>  <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration  --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
Profiles: Customized Builds Sometimes our artifacts need to be tweaked for different “customers” The Development version has different logging or database configuration than QA or Production There might be slight differences based on target OS or JDK version
How to declare a profile In the POM itself, in an external profiles.xml file, or even in settings.xml <project> ... <profiles> <profile> <id>appserverConfig-dev</id> <properties> <appserver.home>/path/to/dev/appserver</appserver.home> </properties> </profile> <profile> <id>appserverConfig-dev-2</id> <properties> <appserver.home>/path/to/another/dev/appserver2</appserver.home> </properties> </profile> </profiles> ... </project>
Build Configuration in a Profile You can even configure plugins based on a profile: <project> ... <profiles> <profile> <id>production</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <debug>false</debug> <optimize>true</optimize> </configuration> </plugin> </plugins> <appserver.home>/path/to/dev/appserver</appserver.home> </build> </profile> ... Example from  Maven: The Definitive Guide,  Sonatype, O’Reilly p.200
Activating a Profile On the command-line: mvn package -Pmyprofile1,myprofile2 In your settings.xml file: <settings> ... <activeProfiles> <activeProfile>dev</activeProfile> </activeProfiles> ... </settings> Activation elements
Activation Elements <project> … <profiles> <profile> <id>dev</id> <activation> <activeByDefault>false</activeByDefault> <jdk>1.5</jdk> <os> <name>Windows XP</name> <family>Windows</famliy> <arch>x86</arch> <version>5.1.2600</version> </os> <property> <name>mavenVersion</name> <value>2.0.9</value> </property> <file> <exists>file2.properties</exists> <missing>file1.properties</missing> </file> </activation> … </profile> </profiles> </project> Example from  Maven: The Definitive Guide,  Sonatype, O’Reilly p.204-205
Sometimes Maven Sucks … returns “about 128,000” results
Common Criticisms Poor Documentation - Lots of Maven’s online documentation is automatically generated and is generally pretty horrible Simple things are sometimes counterintuitive with Maven - E.g., copying a file Maven adds to the number of places you need to look when something breaks - both your source repository, and the maven repository Everything breaks if someone changes an artifactId or groupId Doesn’t work well if your network connectivity is unreliable or unavailable Gets tangled and confused if one of your transitive dependencies isn’t available in a maven repository
(FIN)
Ad

More Related Content

What's hot (20)

Hands On with Maven
Hands On with MavenHands On with Maven
Hands On with Maven
Sid Anand
 
Maven Basics - Explained
Maven Basics - ExplainedMaven Basics - Explained
Maven Basics - Explained
Smita Prasad
 
Maven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeMaven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafe
Holasz Kati
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
Dragos Balan
 
An Introduction to Maven Part 1
An Introduction to Maven Part 1An Introduction to Maven Part 1
An Introduction to Maven Part 1
MD Sayem Ahmed
 
Apache Maven In 10 Slides
Apache Maven In 10 SlidesApache Maven In 10 Slides
Apache Maven In 10 Slides
Robert Burrell Donkin
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
James Cellini
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 Overview
Mike Ensor
 
Apache maven 2 overview
Apache maven 2 overviewApache maven 2 overview
Apache maven 2 overview
Return on Intelligence
 
Maven basics
Maven basicsMaven basics
Maven basics
Vijay Krishnan Ramaswamy
 
Apache Maven
Apache MavenApache Maven
Apache Maven
Rahul Tanwani
 
Development Tools - Maven
Development Tools - MavenDevelopment Tools - Maven
Development Tools - Maven
Bert Koorengevel
 
Using Maven 2
Using Maven 2Using Maven 2
Using Maven 2
andyhot
 
Maven
MavenMaven
Maven
Марія Русин
 
Maven ppt
Maven pptMaven ppt
Maven ppt
natashasweety7
 
An introduction to Maven
An introduction to MavenAn introduction to Maven
An introduction to Maven
Joao Pereira
 
Introduction to maven
Introduction to mavenIntroduction to maven
Introduction to maven
Manos Georgopoulos
 
Maven 2 features
Maven 2 featuresMaven 2 features
Maven 2 features
Angel Ruiz
 
Maven tutorial for beginners
Maven tutorial for beginnersMaven tutorial for beginners
Maven tutorial for beginners
inTwentyEight Minutes
 
An Introduction to Maven
An Introduction to MavenAn Introduction to Maven
An Introduction to Maven
Vadym Lotar
 

Viewers also liked (20)

Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3
Matthew McCullough
 
Maven for Dummies
Maven for DummiesMaven for Dummies
Maven for Dummies
Tomer Gabel
 
Continuous delivery-with-maven
Continuous delivery-with-mavenContinuous delivery-with-maven
Continuous delivery-with-maven
John Ferguson Smart Limited
 
Maven and ANT
Maven and ANTMaven and ANT
Maven and ANT
Sun Technlogies
 
Automated Deployment with Maven - going the whole nine yards
Automated Deployment with Maven - going the whole nine yardsAutomated Deployment with Maven - going the whole nine yards
Automated Deployment with Maven - going the whole nine yards
John Ferguson Smart Limited
 
Maven 3 / Tycho
Maven 3 / TychoMaven 3 / Tycho
Maven 3 / Tycho
Karsten Thoms
 
Maven 3.0 at Øredev
Maven 3.0 at ØredevMaven 3.0 at Øredev
Maven 3.0 at Øredev
Matthew McCullough
 
Lorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - MavenLorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - Maven
Arnaud Héritier
 
Build Automation using Maven
Build Automation using Maven Build Automation using Maven
Build Automation using Maven
Ankit Gubrani
 
Continuous Delivery with Jenkins and Wildfly (2014)
Continuous Delivery with Jenkins and Wildfly (2014)Continuous Delivery with Jenkins and Wildfly (2014)
Continuous Delivery with Jenkins and Wildfly (2014)
Tracy Kennedy
 
Jenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated DeploymentJenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated Deployment
Dan Stine
 
Maven 2 in the real world
Maven 2 in the real worldMaven 2 in the real world
Maven 2 in the real world
Carlo Bonamico
 
Introduction to Apache Maven
Introduction to Apache MavenIntroduction to Apache Maven
Introduction to Apache Maven
juvenxu
 
Maven overview
Maven overviewMaven overview
Maven overview
Yukti Kaura
 
Tycho Tutorial (EclipseCon 2012)
Tycho Tutorial (EclipseCon 2012)Tycho Tutorial (EclipseCon 2012)
Tycho Tutorial (EclipseCon 2012)
jsievers
 
Análise de qualidade de código com Sonar - Fernando Boaglio
Análise de qualidade de código com Sonar - Fernando Boaglio Análise de qualidade de código com Sonar - Fernando Boaglio
Análise de qualidade de código com Sonar - Fernando Boaglio
Fernando Boaglio
 
Maven basic concept
Maven basic conceptMaven basic concept
Maven basic concept
Ming-Sian Lin
 
Continuous inspection with Sonar
Continuous inspection with SonarContinuous inspection with Sonar
Continuous inspection with Sonar
gaudol
 
Regla del Boy Scout y la Oxidación del Software
Regla del Boy Scout y la Oxidación del SoftwareRegla del Boy Scout y la Oxidación del Software
Regla del Boy Scout y la Oxidación del Software
Alejandro Pérez García
 
Maven
MavenMaven
Maven
feng lee
 
Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3
Matthew McCullough
 
Maven for Dummies
Maven for DummiesMaven for Dummies
Maven for Dummies
Tomer Gabel
 
Automated Deployment with Maven - going the whole nine yards
Automated Deployment with Maven - going the whole nine yardsAutomated Deployment with Maven - going the whole nine yards
Automated Deployment with Maven - going the whole nine yards
John Ferguson Smart Limited
 
Lorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - MavenLorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - Maven
Arnaud Héritier
 
Build Automation using Maven
Build Automation using Maven Build Automation using Maven
Build Automation using Maven
Ankit Gubrani
 
Continuous Delivery with Jenkins and Wildfly (2014)
Continuous Delivery with Jenkins and Wildfly (2014)Continuous Delivery with Jenkins and Wildfly (2014)
Continuous Delivery with Jenkins and Wildfly (2014)
Tracy Kennedy
 
Jenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated DeploymentJenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated Deployment
Dan Stine
 
Maven 2 in the real world
Maven 2 in the real worldMaven 2 in the real world
Maven 2 in the real world
Carlo Bonamico
 
Introduction to Apache Maven
Introduction to Apache MavenIntroduction to Apache Maven
Introduction to Apache Maven
juvenxu
 
Tycho Tutorial (EclipseCon 2012)
Tycho Tutorial (EclipseCon 2012)Tycho Tutorial (EclipseCon 2012)
Tycho Tutorial (EclipseCon 2012)
jsievers
 
Análise de qualidade de código com Sonar - Fernando Boaglio
Análise de qualidade de código com Sonar - Fernando Boaglio Análise de qualidade de código com Sonar - Fernando Boaglio
Análise de qualidade de código com Sonar - Fernando Boaglio
Fernando Boaglio
 
Continuous inspection with Sonar
Continuous inspection with SonarContinuous inspection with Sonar
Continuous inspection with Sonar
gaudol
 
Regla del Boy Scout y la Oxidación del Software
Regla del Boy Scout y la Oxidación del SoftwareRegla del Boy Scout y la Oxidación del Software
Regla del Boy Scout y la Oxidación del Software
Alejandro Pérez García
 
Ad

Similar to Demystifying Maven (20)

Apache Ant
Apache AntApache Ant
Apache Ant
hussulinux
 
Introduction To Ant
Introduction To AntIntroduction To Ant
Introduction To Ant
Rajesh Kumar
 
Ant - Another Neat Tool
Ant - Another Neat ToolAnt - Another Neat Tool
Ant - Another Neat Tool
Kanika2885
 
Ant - Another Neat Tool
Ant - Another Neat ToolAnt - Another Neat Tool
Ant - Another Neat Tool
Kanika2885
 
Apache ant
Apache antApache ant
Apache ant
K. M. Fazle Azim Babu
 
Ant User Guide
Ant User GuideAnt User Guide
Ant User Guide
Muthuselvam RS
 
Using Ant To Build J2 Ee Applications
Using Ant To Build J2 Ee ApplicationsUsing Ant To Build J2 Ee Applications
Using Ant To Build J2 Ee Applications
Rajesh Kumar
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
Brendan Sera-Shriar
 
Ant Build Tool
Ant Build ToolAnt Build Tool
Ant Build Tool
Rafael Mumme
 
Introduction To Ant1
Introduction To  Ant1Introduction To  Ant1
Introduction To Ant1
Rajesh Kumar
 
Deploy Flex with Apache Ant
Deploy Flex with Apache AntDeploy Flex with Apache Ant
Deploy Flex with Apache Ant
dctrl — studio for creativ technology
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Sbt, idea and eclipse
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipse
Mike Slinn
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
Clinton Dreisbach
 
Ant
Ant Ant
Ant
sundar22in
 
Ext 0523
Ext 0523Ext 0523
Ext 0523
littlebtc
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Adventurous Merb
Adventurous MerbAdventurous Merb
Adventurous Merb
Matt Todd
 
Optimizing Spring Boot apps for Docker
Optimizing Spring Boot apps for DockerOptimizing Spring Boot apps for Docker
Optimizing Spring Boot apps for Docker
Graham Charters
 
Rails 101
Rails 101Rails 101
Rails 101
The Active Network
 
Ad

Recently uploaded (20)

Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 

Demystifying Maven

  • 1. Demystifying By Mike Desjardins
  • 2. Topics Installation Shock and Awe: Comparison with ant Project Object Model (POM) Inheritance and Modules Dependencies Build Configuration Whirlwind Tour of Plugins Lifecycles Build Profiles Sometimes Maven Lets You Down
  • 3. About Me Developed Software professionally for about 15 years, the last 5 with Java Independent Contractor/Consultant Live in Portland, Maine For the past several years, primary focus has been on web services Wireless Telecommunications Financial Services Online Music Website: http://mikedesjardins.us Twitter: @mdesjardins
  • 4. Installation Requires JDK 1.4 Download Maven from http://maven.apache.org/ Unzip the archive Add the M2_HOME environment variable and point it to your installation. Make sure JAVA_HOME is set and java is in your PATH. Make sure $M2_HOME/bin is in your PATH.
  • 5. Ant vs. Maven Best illustrated by Example We will create a new trivial Hibernate Application that reads rows in a database table (shown below) and outputs them to the console. greeting_id greeting_text 1 Hello 2 Bon jour 3 Buenos dias 4 Kon ni chi wa
  • 6. Example – Source Code First, we will need a class to represent a greeting: @Entity public class Greeting { @Id @GeneratedValue (strategy=GenerationType. IDENTITY ) @Column (name= &quot;greeting_id&quot; ,nullable= false ,unique= true ) private Integer id ; @Column (name= &quot;greeting_text&quot; ) private String text ; @Column (name= &quot;version&quot; ) @Version private Integer version ; public Integer getId() { return this . id ; } public void setId(Integer id) { this . id = id; } public String getText() { return this . text ; } public void setText(String text) { this . text = text; } }
  • 7. Example – Source Code Next, we will need a class with a static main method to actually do stuff...
  • 8. Example – Source Code public class App { private static SessionFactory sessionFactory ; static { try { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable t) { System. out .println( &quot;Something terrible has happened.&quot; ); t.printStackTrace(); } } public static SessionFactory getSessionFactory() { return App. sessionFactory ; } public void run() { System. out .println( &quot;======================================================&quot; ); Criteria c = App. getSessionFactory ().openSession().createCriteria(Greeting. class ); List<Greeting> greetings = c.list() ; for (Greeting greeting : greetings) { System. out .println(greeting.getId() + &quot;: &quot; + greeting.getText()); } System. out .println( &quot;======================================================&quot; ); } public static void main(String args[]) { App app = new App().run()); } }
  • 9. Ant: Let's Get Started! First, let's create the directories for our project: Mac:~/_work$ mkdir demo-ant Mac:~/_work$ cd demo-ant Mac:~/_work/demo-ant$ mkdir src lib conf target Mac:~/_work/demo-ant$ cd src Mac:~/_work/demo-ant/src$ mkdir com Mac:~/_work/demo-ant/src$ cd com Mac:~/_work/demo-ant/src/com$ mkdir techmaine Mac:~/_work/demo-ant/src/com$ cd techmaine Mac:~/_work/demo-ant/src/com/techmaine$ mkdir antdemo Mac:~/_work/demo-ant/src/com/techmaine$
  • 10. Ant: Let's Get Started! (If you’re more of a visual person)
  • 11. Let's go get our jars! 1.) Visit the Hibernate Website, eventually find their download page…
  • 12. Let's go get our jars! 2.) Download gigantic ZIP file ZZZZZZZZZ….
  • 13. Let's go get our jars! 3.) Unpack the ZIP file 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/ 26428 09-10-08 12:21 hibernate-distribution-3.3.1.GA/lgpl.txt 1456 09-10-08 12:21 hibernate-distribution-3.3.1.GA/hibernate_logo.gif 152761 09-10-08 12:21 hibernate-distribution-3.3.1.GA/changelog.txt 2766130 09-10-08 12:27 hibernate-distribution-3.3.1.GA/hibernate3.jar 31493 09-10-08 12:22 hibernate-distribution-3.3.1.GA/hibernate-testing.jar 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/lib/ 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/lib/required/ 443432 06-13-08 12:09 hibernate-distribution-3.3.1.GA/lib/required/antlr-2.7.6.jar 559366 06-13-08 12:09 hibernate-distribution-3.3.1.GA/lib/required/commons-collections-3.1.jar 313898 06-13-08 12:09 hibernate-distribution-3.3.1.GA/lib/required/dom4j-1.6.1.jar 13236 06-13-08 12:09 hibernate-distribution-3.3.1.GA/lib/required/jta-1.1.jar 17384 08-19-08 19:40 hibernate-distribution-3.3.1.GA/lib/required/slf4j-api-1.5.2.jar 471005 06-13-08 12:10 hibernate-distribution-3.3.1.GA/lib/required/javassist-3.4.GA.jar 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/lib/optional/ 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/lib/optional/c3p0/ 608376 06-13-08 12:12 hibernate-distribution-3.3.1.GA/lib/optional/c3p0/c3p0-0.9.1.jar 0 09-10-08 12:27 hibernate-distribution-3.3.1.GA/lib/optional/proxool/ 475943 06-13-08 12:12 hibernate-distribution-3.3.1.GA/lib/optional/proxool/proxool-0.8.3.jar . . . . . . Holy Shnikeys! Do I really need all of this stuff?!?
  • 14. Next Steps Copy the jar files to your lib directory Option 1: Copy Everything (Lazy) Option 2: Copy only what you need (Tedious) Create your build.xml file
  • 15. Create the build.xml Start with an empty file <?xml version=&quot;1.0&quot;?> <project name=&quot;antdemo&quot; default=&quot;compile&quot; basedir=&quot;.&quot;> </project> Step 1
  • 16. Create the build.xml Create some variables build.xml <!-- set global properties for this build --> <property name=&quot;lib&quot; value=&quot;lib&quot;/> <property name=&quot;src&quot; value=&quot;src&quot;/> <property name=&quot;conf&quot; value=&quot;conf&quot;/> <property name=&quot;target&quot; value=&quot;target&quot;/> <property name=&quot;classes&quot; value=&quot;${target}/classes&quot;/> Step 2
  • 17. Create the build.xml Tell ant about all of your libraries build.xml <fileset id=&quot;compile.libs&quot; dir=&quot;${lib}&quot;> <include name=&quot;antlr-2.7.6.jar&quot;/> <include name=&quot;asm.jar&quot;/> <include name=&quot;asm-attrs.jar&quot;/> <include name=&quot;cglib-2.1.3.jar&quot;/> <include name=&quot;commons-collections-3.2.jar&quot;/> <include name=&quot;commons-lang-2.3.jar&quot;/> <include name=&quot;commons-logging-1.0.4.jar&quot;/> <include name=&quot;dom4j-1.6.1.jar&quot;/> <include name=&quot;ejb3-persistence.jar&quot;/> <include name=&quot;javassist.jar&quot;/> <include name=&quot;jboss-archive-browsing.jar&quot;/> <include name=&quot;jdbc2_0-stdext.jar&quot;/> <include name=&quot;jta.jar&quot;/> <include name=&quot;xml-apis.jar&quot;/> <include name=&quot;xercesImpl-2.6.2.jar&quot;/> <include name=&quot;hibernate3.jar&quot;/> <include name=&quot;hibernate-annotations.jar&quot;/> <include name=&quot;hibernate-commons-annotations.jar&quot;/> <include name=&quot;hibernate-entitymanager.jar&quot;/> </fileset> Step 3
  • 18. Create the build.xml Tell ant about compiling build.xml <target name=&quot;init&quot;> <tstamp/> <mkdir dir=&quot;${classes}&quot;/> </target> <target name=&quot;compile&quot; depends=&quot;init&quot;> <mkdir dir=&quot;${basedir}/${classes}&quot;/> <javac srcdir=&quot;${basedir}/${src}&quot; destdir=&quot;${basedir}/${classes}&quot; debug=&quot;yes&quot; target=&quot;1.5&quot;> <classpath> <fileset refid=&quot;compile.libs&quot;/> </classpath> </javac> <copy file=&quot;${basedir}/${conf}/hibernate.cfg.xml&quot; todir=&quot;${basedir}/${classes}&quot;/> </target> <target name=&quot;clean&quot;> <delete quiet=&quot;yes&quot; dir=&quot;${basedir}/${target}&quot;/> <mkdir dir=&quot;${basedir}/${target}&quot;/> </target> Step 4
  • 19. Create the build.xml Tell ant how to run the app build.xml <fileset id=&quot;runtime.libs&quot; dir=&quot;${lib}&quot;> <include name=&quot;postgresql-8.2-507.jdbc3.jar&quot;/> </fileset> <target name=&quot;run&quot; depends=&quot;compile&quot;> <java classname=&quot;com.techmaine.antdemo.App&quot;> <classpath> <fileset refid=&quot;compile.libs&quot;/> <fileset refid=&quot;runtime.libs&quot;/> <pathelement location=&quot;${basedir}/${classes}&quot;/> </classpath> </java> </target> Step 5
  • 20. Recap We downloaded jars and dependencies ourselves We told ant The name of the jar file that we needed (Hibernate) All the dependent jar file names Where the jar files were located That it needed to compile java files Where the java files were located Where it should put the class files Where it should put the Hibernate configuration file How to run the application Where the jar and class files were located (again, this time for runtime) build.xml is 75 lines, but who’s counting?
  • 22. Maven Terminology With maven, you execute goals in plugins over the different phases of the build lifecycle , to generate artifacts . Examples of artifacts are jars, wars, and ears. These artifacts have an artifactId , a groupId , and a version . Together, these are called the artifact’s “ coordinates .” The artifacts stored in repositories . Artifacts are deployed to remote repositories and installed into local repositories. A POM (Project Object Model) describes a project.
  • 23. Create a Project Directory Maven has a command for starting a project: mvn archetype:create \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \ -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Step 1
  • 24. Create a Project Directory mvn archetype :create \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \ -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Plugin Name Step 1
  • 25. Create a Project Directory mvn archetype: create \ -DgroupId=com.techmaine \ -DartifactId=demo-mvn \ -DpackageName=com.techmaine.mvndemo \ -Dversion=1.0 Plugin Name Goal Step 1
  • 26. Create a Project Directory Voila ! Look what maven has done for you: Step 1
  • 27. Set up the dependencies Open pom.xml. We need to tell maven that we have a dependency on Hibernate: <project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;> <modelVersion>4.0.0</modelVersion> <groupId>com.techmaine</groupId> <artifactId>demo-mvn</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>demo-mvn</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> We’ll add the dependency here. Step 2
  • 28. Set up the dependencies <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.1.ga</version> </dependency> This is all we need to add: We don’t need to tell Maven about any of the jars on which Hibernate depends; Maven takes care of all of the transitive dependencies for us! Step 2
  • 29. Set up the compiler <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> Maven assumes a default source version of 1.3. We need to tell it if we want 1.5. Here’s a preview of plugin configuration: STUPIDITY ALERT! Step 3
  • 30. Set up Hibernate Configuration Create a resources directory beneath the main (and, optionally, test) directory, and put the Hibernate configuration file there. Files in the resources directory get copied to the root of the classpath when packaging occurs as part of the resource:resource goal (more on that later) The resources directories are automatically created for many of the archetypes, but not for the quickstart archetype that we used. Step 4
  • 31. Package Next, package everything up before we run it. To do this, invoke maven thusly: mvn package This is an alternate way to invoke maven. Instead of specifying a plugin and goal, you specify a phase (in this case, package is the phase). A phase is a sequenced set of goals. The package phase compiles the java classes and copies the resources Step 5
  • 32. Execute Next, use the exec plugin to run our application: mvn exec:exec \ -DmainClass=com.techmaine.mvndemo.App Step 6
  • 33. Recap We told maven That we were making a “quickstart” project. That we depended on Hibernate Annotations. That we needed Java 1.5 pom.xml was 35 lines (would have been 22 if maven defaulted to Java 1.5 instead of 1.3)
  • 34. Recap – Why Maven is Cool We downloaded jars and dependencies ourselves We told ant The name of the jar file that we needed (Hibernate) All the dependent jar file names Where the jar files were located That it needed to compile java files Where the java files were located Where it should put the class files Where it should put the Hibernate configuration file How to run the application Where the jar and class files were located (again, this time for runtime) build.xml is 75 lines, but who’s counting? We told maven That we were making a “quickstart” project. That we depended on Hibernate Annotations. That we needed Java 1.5 pom.xml was 35 lines (would have been 22 if maven defaulted to Java 1.5 instead of 1.3)
  • 35. What can Maven do? When you first download it, almost nothing! Run goals Run phases (collections of goals) Download Dependencies* Download Plugins But... from where? * Actually, dependency downloads are done by a plugin, too.
  • 36. Configuring Maven Settings Files (settings.xml) In ~/.m2 (per-user settings) and in Maven’s install directory, under conf (per-system settings) Alternate location for repository Proxy Configuration Per-server authentication settings Mirrors Download policies, for plugins and repositories; snapshots and releases.
  • 37. Configuring Maven Project Object Model (pom.xml) Inherited – individual projects inherit POM attributes from parent projects, and ultimately inherit from the “Super POM” The Super POM is in Maven’s installation directory, embedded in the uber jar. The Super POM defines, among lots of other things, the default locations for the plugin and jar repositories, which is http://repo1.maven.org/maven2
  • 38. Repositories Local - in ~/.m2/repository Remote - e.g., http://repo1.maven.org/maven2 or another internal company repository (any directory reachable by sftp will do). Contains dependencies and plugins Can be managed by a “Repository Manager” like Nexus
  • 39. The POM Describes the project, declaratively General Information - Project Coordinates (groupId, artifactId, Version) Build Settings – Configuration of the plugins Build Environment – We can configure different profiles that can be activated programatically POM Relationships – Dependencies on other projects
  • 40. Anatomy of a POM File <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <packaging>jar</packaging> <version>1.0.0</version> <name>Super Duper Amazing Deluxe Project</name> <modules> <!-- Sub-modules of this project --> </modules> <parent> <!-- Parent POM stuff if applicable --> </parent> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 41. General Information <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <modules> <!-- Sub-modules of this project --> </modules> <parent> <!-- Parent POM stuff if applicable --> </parent> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project> Coordinates
  • 42. Project Inheritance <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 43. Project Inheritance What is inherited? Identifiers (groupId, artifactId, one must be different) Dependencies Plugin, Report Lists Plugin Configurations Why Inherit? Don’t repeat yourself, e.g., several projects use the same version of log4j. Enforce plugin version across projects
  • 44. Multimodule Projects <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 45. Multimodule Projects Not the same thing as POM inheritance! A multimodule project builds submodules, but rarely produces an artifact itself Directory structure mimics module layout (e.g., if B is a submodule of A, then B will be a subdirectory of A).
  • 46. Multimodule Projects <packaging>pom<packaging> <modules> <module>ejb</module> <module>ear</module> </modules> Depends on the EJB artifact Creates EJB jar
  • 47. Multimodule: Reactor When Maven encounters a multimodule project, it pulls all of the POMs into the “Reactor” The Reactor analyzes module inter-dependencies to ensure proper ordering. If no changes need to be made, the modules are executed in the order they are declared. Maven then runs the goals on each module in the order requested.
  • 48. User-Defined Properties <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 49. User-Defined Properties User-Defined properties are like ant properties: <properties> <hibernate.version>3.3.0.ga</hibernate.version> </properties> ... <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifact> <version>${hibernate.version}</version> </dependency> </dependencies> Example from Maven: The Definitive Guide, Sonatype, O’Reilly p.266
  • 50. Other Properties Maven Properties, project.* ${project.version} Settings Properties, settings.* ${settings.interactiveMode} Environment Variables, env.* ${env.JAVA_HOME} Java System Properties ${java.version}, ${os.arch}, ${user.dir}
  • 51. Dependencies <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 52. Dependencies Maven’s pièce de résistance <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies>
  • 53. Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> groupId and artifactId: must be unique
  • 54. Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> 1.3.5 - prefer version 1.3.5, newer version is acceptable to resolve conflicts (1.3.4,1.3.9) - Any version between 1.3.2 and 1.3.9, exclusive [1.3.4,1.3.9] - Any version between 1.3.2 and 1.3.9, inclusive [,1.3.9] - Any version up to, and including, 1.3.9 [1.3.5] - Only version 1.3.5, do not use a newer version .
  • 55. Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> compile - default, packaged. Available on compile-time and runtime CLASSPATH. provided - you expect the JVM or app container to provide the library. Available on compile-time CLASSPATH. runtime - needed to run, but not compilation (e.g., a JDBC driver) test - only needed during test execution (e.g., JUnit)
  • 56. Dependencies <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>awesome-lib</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>false</optional> </dependency> </dependencies> Prevents this dependency from being included as a transitive dependency if some other project depends on this project.
  • 57. Transitive Dependencies A 1.0 B 1.0 C 1.0 E 1.0 D 1.0 Our project (Project “A”) depends on B and C. Project C depends on projects D and E. Thus, our project depends on B, C, D, and E, and Maven will fetch and use these artifacts appropriately.
  • 58. Transitive Dependencies A 1.0 B 1.0 C 1.0 E 1.0 D 1.0 Now, let’s say project C has a dependency on project B, but requires version 1.1. If project A’s POM doesn’t explicitly require version 1.0 or earlier, then Maven will choose version 1.1. B 1.1
  • 59. Transitive Dependencies A 1.0 B [1.0] C 1.0 E 1.0 D 1.0 Uh oh. Now Project A is saying that it must use version 1.0 of B, and only version 1.0, and project C needs version 1.1 of project B. B [1.1]
  • 60. Dependency Exclusions One way to deal with conflicts is with exclusions <dependencies> <dependency> <groupId>com.techmaine</groupId> <artifactId>project-b</artifactId> <version>[1.0]</version> </dependency> <dependency> <groupId>com.techmaine</groupId> <artifactId>project-c</artifactId> <exclusions> <exclusion> <groupId>com.techmaine</groupId> <artifactId>project-b</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
  • 61. Dependency Management Parent POM Child POM The dependencyManagement element allows you to specify version numbers of dependencies in child POMs without making all children dependent on a particular library. <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.5</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> </dependencies>
  • 62. SNAPSHOT Versions SNAPSHOT is a literal string appended to a version number, e.g., 1.2.3-SNAPSHOT Indicates that a version is “under development” Use if you need Maven to keep checking for the latest version Maven replaces SNAPSHOT with a UTC time stamp before putting it into the repository.
  • 63. Build Configuration <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 64. Build Configuration The build section of the POM, broken down further: <project> ... <build> <filters> <filter>filter/my.properties</filter> </filters> <resources> ... </resources> <plugins> ... </plugins> </build> ... </project>
  • 65. Build Configuration Filters <project> ... <build> <filters> <filter>filter/my.properties</filter> </filters> <resources> ... </resources> <plugins> ... </plugins> </build> ... </project> Path to a properties file (name=value). When the resources are processed during packaging, maven will substitute any ${name} strings with the corresponding value from the properties file.
  • 66. Build Configuration Resources The resources:resources goal copies files from the resources directory to the output directory Can process using filters Default location src/main/resources Can be further configured: <resources> <resource> <directory>src/main/scripts</directory> <filtering>true</filtering> <targetPath>bin</targetPath> <includes> <include>run.bat</include> <include>run.sh</include> </includes> <resource> </resources>
  • 67. Build Configuration Plugins All work in Maven is performed by plugins Like Dependencies, are Downloaded from a repository Because they are shared, you often benefit from the fact that someone else has already built a plugin for whatever function you may need
  • 68. Plugin Configuration The plugin section of the POM has a configuration element where you can customize plugin behavior: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.2</version> <configuration> <!-- Configuration details go here --> </configuration> </plugin> </plugins> </build>
  • 69. Plugin Configuration: Example Below, we have configured the clean plugin to delete files ending in .txt from the tmp directory <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.2</version> <configuration> <filesets> <fileset> <directory>tmp</directory> <includes> <include>**/*.txt</include> </includes> <followSymlinks>false</followSymlinks> </fileset> </filesets> </configuration> </plugin> </plugins> </build>
  • 70. Core Plugins clean - has only one goal, clean. Deletes the target directory, can be configured to delete other stuff compiler - compiles sources, uses javac compiler by default. Has a compile and testCompile goal. Can be configured to use any executable as the compiler deploy - uploads artifacts to a remote repository Maven Plugin Whirlwind Tour
  • 71. Core Plugins, cont. install - installs the artifact into the local repository. install goal, install this project’s artifact install-file goal, install a specific file into local repo (good for third-party stuff) surefire - runs all of the unit tests in the test source directory, and generates reports. resources - copies resources to be packaged Maven Plugin Whirlwind Tour
  • 72. Packaging Plugins ear , ejb , jar , war assembly - builds a binary distribution including runtime dependencies supports zip, tar.gz, tar.bz2, jar, dir, and war formats uses “assembly descriptors” to configure (although several pre-fab ones are available) one of the pre-fab descriptors builds executable jar files with all depenencies embedded Maven Plugin Whirlwind Tour
  • 73. Utility Plugins archetype - builds skeleton of a working project for many different frameworks Wicket, Tapestry 5, JSF, JPA, tons of others help - even the help is a plugin! Use the describe goal to learn what a plugin can do, e.g., mvn help:describe -Dplugin=compiler scm - source control stuff Maven Plugin Whirlwind Tour
  • 74. Build Lifecycle Usually, an artifact is built by executing a sequence of goals For example, to generate a WAR: Clean the build area Copy the resources Compile the code Copy the test resources Compile the test code Run the test Package the result
  • 75. Maven’s Lifecycles Maven supports three standard lifecycles clean - as you might expect, starts us fresh default - the lifecycle that builds the code site - a lifecycle for building other related artifacts (e.g., reports and documentation)
  • 76. Clean Lifecycle The Clean Lifecycle has three phases: pre-clean clean post-clean Only clean is “bound” by default, to the clean goal of the clean plugin. You can bind other tasks using executions.
  • 77. Executions Let’s say you have a whizz-bang plugin named mp3 , and it has a goal named play that lets you play an arbitrary audio clip, and you’d like to play a clip during pre-clean: <plugin> <groupId>com.techmaine</groupId> <artifactId>mp3</artifactId> <version>1.0</version> <executions> <execution> <phase>pre-clean</phase> <goals> <goal>play</goal> </goals> <configuration> <audioClipFile>toilet-flush.mp3</audioClipFile> </configuration> </execution> </executions> </plugin>
  • 78. Maven’s Default Lifecycle Maven models the software build process with the 21 step “default lifecycle” validate generate-test-sources package generate-sources process-test-sources pre-integration-test process-sources generate-test-resources integration-test generate-resources process-test-resources post-integration-test process-resources test-compile verify compile test install process-classes prepare-package deploy
  • 79. Package-Specific Lifecycles Maven automatically binds goals to the phases on the previous slide based on the packaging type. E.g., for projects that package WARs: Lifecycle Phase Goal process-resources resources:resources compile compiler:compile process-test-resources resources:testResources test-compile compiler:testCompile test surefire:test package war:war install install:install deploy deploy:deploy
  • 80. Build Profiles <project xmlns= http://maven.apache.org/POM/4.0.0 > <modelVersion>4.0.0</modelVersion> <name>Super Duper Amazing Deluxe Project</name> <packaging>jar</packaging> <groupId>com.techmaine</groupId> <artifactId>superduper</artifact> <version>1.0.0</version> <parent> <!-- Parent POM stuff if applicable --> </parent> <modules> <!-- Sub-modules of this project --> </modules> <properties> <!-- Ad-hoc properties used in the build --> </properties> <dependencies> <!-- Dependency Stuff --> </dependencies> <build> <!-- Build Configuration --> <plugins> <!-- plugin configuration --> </plugins> </build> <profiles> <!-- build profiles --> </profiles> </project>
  • 81. Profiles: Customized Builds Sometimes our artifacts need to be tweaked for different “customers” The Development version has different logging or database configuration than QA or Production There might be slight differences based on target OS or JDK version
  • 82. How to declare a profile In the POM itself, in an external profiles.xml file, or even in settings.xml <project> ... <profiles> <profile> <id>appserverConfig-dev</id> <properties> <appserver.home>/path/to/dev/appserver</appserver.home> </properties> </profile> <profile> <id>appserverConfig-dev-2</id> <properties> <appserver.home>/path/to/another/dev/appserver2</appserver.home> </properties> </profile> </profiles> ... </project>
  • 83. Build Configuration in a Profile You can even configure plugins based on a profile: <project> ... <profiles> <profile> <id>production</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <debug>false</debug> <optimize>true</optimize> </configuration> </plugin> </plugins> <appserver.home>/path/to/dev/appserver</appserver.home> </build> </profile> ... Example from Maven: The Definitive Guide, Sonatype, O’Reilly p.200
  • 84. Activating a Profile On the command-line: mvn package -Pmyprofile1,myprofile2 In your settings.xml file: <settings> ... <activeProfiles> <activeProfile>dev</activeProfile> </activeProfiles> ... </settings> Activation elements
  • 85. Activation Elements <project> … <profiles> <profile> <id>dev</id> <activation> <activeByDefault>false</activeByDefault> <jdk>1.5</jdk> <os> <name>Windows XP</name> <family>Windows</famliy> <arch>x86</arch> <version>5.1.2600</version> </os> <property> <name>mavenVersion</name> <value>2.0.9</value> </property> <file> <exists>file2.properties</exists> <missing>file1.properties</missing> </file> </activation> … </profile> </profiles> </project> Example from Maven: The Definitive Guide, Sonatype, O’Reilly p.204-205
  • 86. Sometimes Maven Sucks … returns “about 128,000” results
  • 87. Common Criticisms Poor Documentation - Lots of Maven’s online documentation is automatically generated and is generally pretty horrible Simple things are sometimes counterintuitive with Maven - E.g., copying a file Maven adds to the number of places you need to look when something breaks - both your source repository, and the maven repository Everything breaks if someone changes an artifactId or groupId Doesn’t work well if your network connectivity is unreliable or unavailable Gets tangled and confused if one of your transitive dependencies isn’t available in a maven repository
  • 88. (FIN)