A project object model
ou may be wondering, what is Apache Maven? Apache Maven, is a software projectmanagement, and comprehension tool, based on the concept of a project object model, orPOM. Maven can manage a project's build, reporting, and documentation from a centralpiece of information. This is a quote directly from the Apache Maven project website. A morecomprehensive definition of Apache Maven, is that Maven is a project managementtool, which encompasses a project object model.
It follows a set of standards, it includes a project life cycle, a dependency managementsystem, and logic for executing plugin goals at defined phases in a life cycle. Maven isdesigned to provide a simple project setup, that uses best practices as a guide. With Maven,your projects follow a consistent structure. Projects become IDE agnostic, by enforcing a
consistent structure, it makes modifications easier in the future, when new developers areintroduced to the project.
It also ensures that programmers always get the most recent version of compilers, etcetera. Most Java projects rely on other projects, and open source frameworks, to functionproperly. It can be cumbersome to download these dependents manually, and keep track oftheir versions, as you use them in your project. Maven provides a convenient way todeclare these project dependencies, in a separate, external, POM.XML file. It thenautomatically downloads these dependencies and allows you to use them in yourproject. This simplifies project dependency management greatly.
It is important to note, that in the POM.XML file, you specify the what, and not the how. ThePOM.XML file, can also serve as documentation tool, conveying your project dependenciesand their versions. Software developers refer to Maven, as a build tool. Since it is used tobuild deployable artifacts from source code. On the other hand, if you asked a projectmanager they might call it a project management tool, since it follows a development lifecycle. In reality, it is both.
Installation in Maven
To get started using Apache Maven, start by downloading Maven fromthe maven.apache.org website. From this page we can either use the link on the left thatsays Download, or we can just use the link in the middle where it says Use Download. Mavenis currently at version 3.3.9 at the time of this series. Always make sure you download thelatest version. Let's look quickly at the system requirements. Probably one of the mostimportant ones is that it requires Java Development Kit or JDK 1.7 or higher.
There is no minimum memory requirement, and as far as disk space goes, you needapproximately 10 MB for the Maven installation itself, but in addition to that, additional spacewill be needed for your local Maven repository. The size might vary depending on yourusage, but expect at least 500 MB, and there's no minimum requirement for your operatingsystem. Let's scroll down and take a look at the files. One of the nice things is underFiles, there is a link in the first paragraph there that takes you to installation instructions.
We'll take a look at that in a minute, but for right now, under the link we have Binary tar file, aBinary zip file, and two source files. I'm gonna go ahead and download theapache-maven-3.3.9-bin.zip file. It doesn't take long to download and you can see it's only8.2 MB. Let's switch over to the installation instructions next. It's always a good idea tocheck the installation instructions in case something has changed from the time of thisvideo.
The first thing we need to do is extract the archive file that I just download, so I'm gonna godown to my archive, and I'm gonna click on it and I'm going to click on Extract, and I'mgonna say Extract all. The Maven website recommends that you extract the file to theProgram Files directory on your C: drive so I'm gonna do that. I'm gonna click onBrowse, I'm gonna go into my C: drive, to my Program Files, and I'm going to go ahead andsay Select Folder, and I'm gonna say Extract.
It is important to understand you'll need Administrative Access in order to copy the file toyour Program Files so I'm gonna click Continue. Now I have a folder calledapache-maven-3.3.9, and if I open it up, I'll see there's a bin folder, a boot folder, a conffolder, and a lib folder. At this point, I've completed my download. The instructions for usingMaven depends on whether you're running a Windows machine or a Mac OS or Linuxmachine.
Install Maven on Windows
Now that we have the Maven file downloaded and extracted into our program filesdirectory, we can go ahead and install Maven on our Windows machine. As I statedearlier, the Maven download is not very large. That's because Maven's power is includedin its plugins which are located and retrieved from a central repository on an as-neededbasis and allowing for greater code reuse. Before the installation we must verify our Javaversion from the command line using java -version.
Remember it must be 1.7 or higher. I'm going to open up a command window. I'm going totype cmd and hit enter. Now, I'm going to type, java -version and hit enter. The version onmy machine is 1.8.0_91. That's higher than 1.7, so I'm good to go. To make life easier, weneed to update our environment variables. We can do that using either the commandwindow, but, if you use the command window you're going to have to update them everytime, or, we can go to the control panel.
For now, let's use the control panel. I'm going to go back to start again and type "controlpanel". From here, I'm going to go to System and Security. I want to go to System. Now, Ineed to go to my Advanced system settings. Then you'll see at the bottom it saysEnvironment variables. Let's click on Environment variables. The top half of the screen arespecific user variables for the producer profile. The second half, the bottom half, is mysystem variables.
What we want to do here is we want to add a variable to indicate where the Java homeis. This is where we stored our JDK. In my case, mine is located on my C drive, in myprogram files directory. Let me show you. I'm going to open up File Explorer. I'll go to my Cdrive. I'll go to Program Files, Java, and there it is, jdk1.8.0_91.
It's probably in the same location for you. Go ahead and find the path for your JDK file. Let'sadd a new system variable. We're going to click on new and we're going to call itjava_home. The value for the variable will be the path that takes me to my JDK file. In ourcase it's going to be c:\program files\java\jdk, mine was 1.8.0_91 and I'm going to click OK.
Now you'll see it's added to your list of system variables. The next thing we need to do is weneed to add our new Apache Maven directory, which is also in my program files. Let's goback and take a look. If I go to my C drive, to Program Files, the very first folder is ApacheMaven 3.3.9. Inside there is the bin folder. That's what I need, I need to know that path. Letme close that. What I want you to do is to click on the path variable that already exists andsay "edit".
We're going to add a new variable. It's going to say, c:\programfiles\apache-maven-3.3.9 this time I also want to include, \bin. Now, my environment knows
where to find the Maven commands. I'm going to click OK. I'm going to click OK, again, andOK again, and I'll close my control panel.
Now, we do need to open a new command prompt. If you have any command promptwindows open, go ahead and close them and start a new window so it will pick up thoseenvironment changes that we just made. Now, from the command prompt, I'm going to typemvn -v and hit enter. We can see that this is Apache Maven 3.3.9. It tells me my Mavenhome folder. It gives me the Java version that we're using, the Java home, as well as thedefault local and operating system name.
At this point I'm ready to get started using Maven on my Windows machine.]
IDE integration
aven's popularity has grown, and many of the integrated development environments usedwith Java have started to integrate Maven with their product. For example, Maven is alreadyset up to integrate with NetBeans, Eclipse, and IntelliJ, just to name a few. Starting with theNetBeans version 6.7 and higher, there is full Maven support. You can even use theNetBeans IDE to create Maven projects from archetypes using the new project wizard.
Finally, the IDE also includes a Maven repository browser that enables you to view localrepository and register external Maven repositories. If you happen to be running NetBeans6.5 or lower, you can add Maven by adding the necessary plugin. Under Tools, Plugins,choose Available Plugins, from there choose Maven, click Install, then Close. There is alsogood documentation on the NetBeans Wiki site for using NetBeans with Maven.
Let's take a look at the Wiki site. From the Wiki page, definitely take notice of thetutorials, tips, and tricks for using Maven. If you are accustomed to using Eclipse, then youwanna use the Eclipse version M2Eclipse, which is specifically designed for Mavenintegration. This version of Eclipse includes the ability to launch Maven builds, handledependency management based on Maven's pom.xml file, automatic download of requireddependencies, and wizards for creating new project and search capabilities for Mavenremote repositories.
Here is the homepage for this version of the M2Eclipse website. As you can see, this versionof Eclipse is designed specifically for integration of Apache Maven. Maven integration isalready included in the IntelliJ IDEA platform. Programmers can start using IntelliJ to importexisting Maven projects, create new projects, run Maven goals, and more. It has full editingsupport for the pom.xml files, and similar to NetBeans, JetBrains IntelliJ IDEA also hasdetailed documentation for the integration with Maven.
Here's another good place to start. So no matter which IDE you're using, chances are Mavensupport is already included.
Project Object Model (POM)
As I've stated, Maven use of the concept of a Project Object Model, or POM. This model hasa a set of standards, a project lifecycle, a dependency management system, and logic forexecuting plugin goals at certain phases in the lifecycle process. One of the things thatmakes Maven so powerful is that it relies on the concept that projects are set up with defaultbehaviors. For example, the pom.xml file is always located in the base directory.
The source code must be in a certain directory. Resources necessary for the project are in aanother folder or directory. Test cases are in a specifically named folder. And a target folderis always created that's used for the final JAR file. Let's take a look at the folder structure
created by Maven for a calculator program. As you can see the base directory is calledcalculator. Inside calculator we have our src folder, as well as our target folder, and ourpom.xml file.
Inside the source folder is where we'll find our main Java programs and our source code, aswell as any needed resources. And, the test folder, which contains again, the Java testprograms. And any resources needed for that. Finally, the JAR file will be stored in the targetfolder. This folder structure is an important example of how Maven has adopted conventionover configuration. By always using a standard folder structure, it allows developers toconcentrate on coding. Once the code and resources are placed in the correctdirectories, and the POM file is updated.
Maven handles the rest. A project model includes: A project description, a unique set ofcoordinates, project attributes, the project's license information. The project version, anyauthors or contributors to the project, and a list of project dependencies. Before we gofurther, let's take a look at a sample POM file. This is the file for the calculator project. ThePOM file is stored as an XML file. XML files use tags similar to HTML.
Except for the names inside the tags are different. In the case of Maven, we have tags suchas group ID, artifact ID, packaging, version, etc. The artifact ID is used for the name of theprogram. In our case, calculator. Since it's a Java program, the packaging is going to be tocreate a JAR file. And the version in this case is 1.0. The description, name, and URL are alloptional. Below that are the dependencies. When you create a sample program usingMaven, it automatically adds a j unit dependency to allow us to do unit testing for our Javaprogram.
You might have noticed the three red asterisks next to the three fields: group ID, artifactID, and version. That's because these three fields together, make up what we call thecoordinates of the project, and they must be a unique combination. So, if I wanted tocreate a second version of my calculator project. I'd have to change the version number from1.0 to 2.0, or 1.1,
or something, to make it unique. Features that are enabled by using the POM includedependency management, access to remote repositories, universal reuse of build logic, toolportability and integration, allowing IDEs such as Eclipse, NetBeans, and IntelliJ, to have acommon place to find information about a project.
And, easy searching and filtering of project artifacts. The Project Object Model, the POM,and the POM file are the heart of Maven projects. And provide key information about theproject.
Maven lifecycle
When using Maven it's important to understand the Maven life cycle. Let's take a look at ahigh level overview of the flow when using Maven. Maven starts by generating a project. Aproject consists of a POM or Project Object Model and source code that's assembled in the
Maven standard directory layout. Next, we execute Maven with a life cycle phase as anargument that prompted Maven to execute a series of plugin goals. After that, we can installa Maven artifact into our local Maven repository.
And finally, we can run the app. Let's take a closer look at the default life cycle phases. Oneof the phases is
Validate. Validate is used to validate the project to make sure it is correct and all necessaryinformation is available. Another phase is
Compile. We compile the source code of the project.
Test. Test compiles the source code using a suitable unit testing framework. These tests
should not require the code be packaged or deployed just yet.
Package,
take thecompiledcode andpackage it initsdistributable
format. For example, a Java program will be packaged as a Java file or a Java archive file.
Integration-test. Process and deploy the package if necessary into an environment whereintegration tests can be run.
Verify runs any checks to verify the package is valid and meets quality criteria.
Install.
Install the package into the local repository for use as a dependency in other projects locally.
And finally, Deploy. This is done in an integration or release environment. It copies the finalpackage to the remote repository for sharing with other developers and projects. Plugingoals can be attached to each lifecycle phase. As Maven moves through the phases in alifecycle it will execute the goals attached to each particular phase. Each phase may havezero or more goals bound to it. For example, when we run mvn install we will see that morethan one goal is executed.
In the package phase it'll automatically execute the JAR goal in the JAR plugin. Let's run anmvn install on an existing project and we can see the different goals that are executed. I'venavigated to my directory for Hello World. If I run mvn install, which is a lifecycle phase,
we can see what goals are executed. At the top you'll see Maven resources-plugin 2.6resources.
So the resources plugin was executed. Next, the compile was executed. There was nothingto compile because all classes were up to date. Next is the test resources,
the test compile, and finally using the surefire plugin it ran a test. The result of the test arelisted below. It said the number of tests run was one. Zero failures and zero errors. Soeverything worked according to our specifications. The last plugin that you'll see here is theJAR plugin.
The JAR plugin again is used to create a Java archive file or a JAR file. After the JAR file iscreated the install then moves the JAR file to local Maven repository. You can see here itsays that the installing of the Hello World to
c:/users/producer/ .m2/repository/com/lynda/hello world, the version number1.0/helloworld1.0.jar.
It also installed the POM file into that same repository. That repository is automaticallycreated by Maven and that's where all our local programs are stored.
Maven Repository
One of the big benefits of using Maven is you now have access to the Mavenrepository. There's actually two repositories that we're gonna talk about. The first one is thecentral Maven repository that contains a large collection of Java and other open-sourcecomponents. Again, the power of Maven is that these open-source components are availableto you but they will not be downloaded unless you need them. That enforces that you havethe most recent version of each component. The second repository is a local repositorythat Maven creates on your computer.
It's usually located on your home drive in a folder called .m2. This directory contains yourMaven repository. When you download a dependency from a remote Maven
repository, Maven stores a copy of the dependency in your local repository. In addition, italso places a copy of your jar file and the pom.xml file for each installed project. Let's take alook at both of these. Let's start by looking at a website that allows you to browse the centralrepository. You can find this at http://search.maven.org As you can see, you can enter in anycomponent that you want to search for and it does have an advanced search feature andeven a browse feature.
Let's just try searching for junit, which is one of the components that we use to do unittesting within Java. As you can see, there's several versions of the artifact ID, junit, that wecan use in our program. Now, let's take a look at the local Maven repository. As you can see,my .m2 folder is located under Users, Producer. So yours might be located in a differentplace but you can find it by searching .m2. Inside the local repository, you'll see an indexfolder and a repository folder.
Let's open the repository and you'll see, since I've compiled and installed several Mavenprojects, it's already downloaded a lot of different components that I needed, includingjunit. I also created a project called HelloWorld and I installed the HelloWorld. Let's look atthe installation for that. Since all my project so far, I've actually installed inside a packagecalled com dot lynda. I need to go there and you'll see, there's HelloWorld.
Inside HelloWorld, there is a version 1.0 and inside 1.0 is a copy of my POM file, as well asmy executable jar file. So all of your projects should be available inside your local repository.
Maven's dependency management
Another feature of Maven is the way it handles Dependency Management. As a programmer,we often take advantage of code reuse, especially in the realm of open-sourceprogramming. For example, in Java, we use APIs that contain libraries of softwarecomponents that we can use instead of recreating the source code from scratch. Almost allJava programmers have, at some time, used the Math functions or the String functions intheir coding. These functions include math.pow to find the value of a number raised to apower, or math.min to find the smallest of two numbers.
Some of the String functions include the .length command, the .substring, two lower, twoupper. These are just a few examples of what it means to reuse existing code. Maven alsoallows us to reuse existing components and plugins using the dependency section of ourPOM file, our Project Object Model file. For example, a common dependency when workingwith Java is the junit component. We define dependencies inside a project's POM file usingit's Maven coordinates.
Remember, the coordinates include the group ID, artifact ID and version. Let's refer back tothe POM file we saw earlier. As you can see, there's a tag called dependencies, and insidethese, there is one dependency called junit. The three tags groupID, artifactId, and
version are the coordinates that make this particular dependency unique. The scopeidentifies what part of the life cycle this dependency is going to be used in.
In this case, it's the test phase. It is easy to add additional project dependencies by updatingthis pom.xml file. By adding a list of dependencies here in one place, it is also easy forsomeone to identify what dependencies are required for this particular project. Finally, byincluding the dependencies in this external file, it is easy to update the version numbers inone place as dependencies might change.
POM categories and configuration
[Instructor] The Project Object Model or POM Categories and Configuration. The POM filecontains all the information about a project. The file is stored with an .XML extension. Here'san example of POM.XML file that has the minimum amount of information required. As youcan see, it has a groupId, an artifactId, and a version. Remember those three things make upthe Maven coordinates and are required for all projects. Although this is not a comprehensivelist, some of the most common categories that are usually included in POM file include theproject coordinates, which we just saw, the project's license information, a list of developersand contributors to the project, a list of project dependencies, the name of the project, theURL associated with this project, the packaging type, the scope of the element listed, andeven information about inheritance.
Each of these categories has its own XML tag. For example, the scope tag would be the lessthan sign, the word scope, and the greater than sign.
Although these are not all the categories that you can use in a POM file, these are the onesthat you'll see most often.
POM syntax
The Project Object Model Syntax. The Project Object Model, or POM, is documented in anXML file, where XML stands for Extensible Markup Language, which is always located in thebase directory of your project. The syntax for XML looks similar to HTML, using the anglebrackets to indicate the beginning and end of an element. The difference is that the elementsdo not follow any standard list of keywords. Instead they are descriptive of the content insidethe tags.
Every open XML tag must have a corresponding closing tag. And tags can be nested oneinside the other. The file can start with an XML declaration,
but that is optional. All values in the file are declared as XML elements. All projects extendthe super Project Object Model, or POM, automatically. And the specific project POMcontains all pertinent information for that project. Here is an example of a pom.xml file thatincludes the XML declaration, and the required maven coordinates.
As you can see, the XML declaration takes up the first four lines. Below that, we have themodelVersion and then the maven coordinates, the groupID, the artifactID, and theversion number.
The POM file contain many more XML tags depending on the complexityof your project.
Project dependencies
Project Dependencies. As a programmer, we often rely on other components available tous. Maven provides support for both internal and external dependencies. One of the mostcommon dependencies is the junit dependency.This is used for testing a Javaprogram. Other examples include log4j and jaxen, just to name a few. Here is some sample
code. As you can see, I am only displaying two of the dependencies for this project, butmore can be added using the XML tag dependency.