Devops 2
Devops 2
Introduction, Installation of Maven, POM files, Maven Build lifecycle, build phases (compile
build, test, package) Maven Profiles, Maven repositories (local, central, global), Maven
plugins, Maven create and build Artificats, Dependency management, Installation of
Gradle, understand build using Gradle.
Maven Lifecycle: Below is a representation of the default Maven lifecycle and its 8 steps:
Validate, Compile, Test, Package, Integration test, Verify, Install, and Deploy.
Validate: This step validates if the project structure is correct. For example – It checks if
all the dependencies have been downloaded and are available in the local repository.
Compile: It compiles the source code, converts the .java files to .class, and stores the
classes in the target/classes folder.
Test: It runs unit tests for the project.
Package: This step packages the compiled code in a distributable format like JAR or WAR.
Integration test: It runs the integration tests for the project.
Verify: This step runs checks to verify that the project is valid and meets the quality
standards.
Install: This step installs the packaged code to the local Maven repository.
Deploy: It copies the packaged code to the remote repository for sharing it with other
developers.
Maven follows a sequential order to execute the commands where if you run step n, all
steps preceding it (Step 1 to n-1) are also executed. For example – if we run the
Installation step (Step 7), it will validate, compile, package and verify the project along
with running unit and integration tests (Step 1 to 6) before installing the built package to
the local repository.
In Maven, goals and plugins play a crucial role in executing specific tasks and extending
the functionality of the build process.
Maven Goals:
● Goals are specific tasks that Maven can perform during the build lifecycle.
● Each phase of the lifecycle is associated with one or more goals.
● Maven provides default goals for each phase, but you can also define custom goals.
● Goals can be executed from the command line using the mvn command followed
by the goal name.
● Examples of common Maven goals include compile, test, package, and install.
Maven Plugins:
● Plugins are the building blocks of Maven’s functionality.
● They provide implementations for various goals and can be used to extend the
build process.
● Maven has a vast ecosystem of plugins that cover a wide range of tasks and
integrations.
● Plugins can be configured in the project’s POM file, specifying the desired version
and any custom configurations.
● Maven resolves and downloads plugins from remote repositories when needed.
● Examples of popular Maven plugins include the Maven Compiler Plugin, Surefire
Plugin for testing, and the Maven Assembly Plugin for creating custom
distributions.
Maven Commands:
mvn clean: Cleans the project and removes all files generated by the previous build.
mvn compile: Compiles source code of the project.
mvn test-compile: Compiles the test source code.
mvn test: Runs tests for the project.
mvn package: Creates JAR or WAR file for the project to convert it into a distributable
format.
mvn install: Deploys the packaged JAR/ WAR file to the local repository.
mvn site: generate the project documentation.
mvn validate: validate the project’s POM and configuration.
mvn idea:idea: generate project files for IntelliJ IDEA or Eclipse.
mvn release:perform: Performs a release build.
mvn deploy: Copies the packaged JAR/ WAR file to the remote repository after compiling,
running tests and building the project.
mvn archetype:generate: This command is used to generate a new project from an
archetype, which is a template for a project. This command is typically used to create new
projects based on a specific pattern or structure.
mvn dependency:tree: This command is used to display the dependencies of the project
in a tree format. This command is typically used to understand the dependencies of the
project and troubleshoot any issues.
Generally, when we run any of the above commands, we add the mvn clean step so that
the target folder generated from the previous build is removed before running a newer
build. This is how the command would look on integrating the clean step with install
phase:
mvn clean install
Similarly, if we want to run the step-in debug mode for more detailed build information
and logs, we will add -X to the actual command. Hence, the install step with debug mode
on will have the following command:
mvn -X install
Consider a scenario where we do not want to run the tests while packaging or installing
the Java project. In this case, we use -DskipTests along with the actual command. If we
need to run the install step by skipping the tests associated with the project, the command
would be:
mvn install -DskipTests
2. Maven Profile
A Build profile is a set of configuration values, which can be used to set or override default
values of Maven build. Using a build profile, you can customize build for different
environments such as Production v/s Development environments.
Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are
triggered in variety of ways. Profiles modify the POM at build time, and are used to give
parameters different target environments (for example, the path of the database server
in the development, testing, and production environments).
Profile Activation
A Maven Build Profile can be activated in various ways.
● Explicitly using command console input.
● Through maven settings.
● Based on environment variables (User/System variables).
● OS Settings (for example, Windows family).
● Present/missing files.
Now open the command console, go to the folder containing pom.xml and execute the
following mvn command. Pass the profile name as argument using -P option.
C:\MVN\project>mvn test -Ptest
Maven will start processing and displaying the result of test build profile.
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529
Now open the command console, go to the folder containing pom.xml and execute the
following mvn commands. Pass the profile names as argument using -P option.
Dependency management is one of the most difficult parts of developing software and
related products.
We have two options for dependency management:
1. Create your own.
2. Use Maven for dependency management.
Maven manages both aspects (build phases and dependencies) starting from a single file
called pom.xml.
Each step (represented by an arrow) moves the dependency from one point to the next.
A step is run by a phase execution.
Maven dependency management come from the pom.xml file, inside project’s root folder.
The dependencies list is written in the pom.xml.
This is a simple example:
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>
Dependencies list start with <dependencies> tag and end with </dependencies>.
A single dependency starts with <dependency> tag and end with </dependency> and is
uniquely identified by the three element <groupId>, <artifactId> e <version> both in
Maven Central Repository (or others external) and in the local repository (after the
download).
Compile phase
During compile phase, Maven downloads dependencies from Maven Central Repository
(or from other repositories written in the settings.xml files) into the local repository, the
/.m2 folder. This folder is created the first time Maven downloads a dependency. From
that moment all dependencies will be downloaded here. Usually /.m2 path has this
structure:
>C:\Users\User Name\.m2
For example, consider a Java project containing in its root folder the pom.xml file seen in
the above paragraph. From this folder, type the following maven command from cmd:
>mvn compile
This means that Maven is downloading the dependencies list written in the pom.xml,
from the Maven Central Repository (or from others external repositories) into the local
\.m2 repository.
Package Phase
The classes and the functions inside dependencies, are used both to compile correctly the
code (as shown in the previous paragraph), either to be executed during application runs.
For this purpose, during this phase, project’s dependencies are copied inside the final
package (that is the actual application which can be a .jar, .war, .ear), following the steps
below:
Builds and puts the final package inside the /target folder, which was created during the
Compile Phase.
Finally, dependencies are copied from the /.m2 repository, directly inside the final
package, so their code can be used by the application at runtime.
From the folder containing the example pom.xml, type the following maven command
from cmd:
>mvn package
The jar goal from the “package phase”, creates the “projec-1-0.jar” in the /targed folder
in project’s workspace. This is the final package, which contains the same dependecies
used for the compile phase. Now dependencies code can be used while application runs.
Install Phase
At this point, the builded package is copied from the /target folder into the /.m2
repository. In this way the package itself can be used as a dependency by other local
projects.
From the folder containing the example pom.xml, type the following maven command
from cmd:
>mvn install
Before adding dependencies in pom.xml, you need to fulfil some prerequisites first.
Prerequisites: -
⮚ Eclipse IDE
⮚ Active Internet Connection
⮚ Maven installed for Eclipse IDE
Now, create a Maven project or if you have already created it, then go to pom.xml file and
open it.
Once you open it a tab will open in Eclipse IDE, in the footer section of the tab there is an
option for adding dependencies.
Click on Dependencies and a panel will open where you can add the required
dependencies for your project. Click on add button.
Once you click on add button a new window will open and you need to enter the name of
the dependency which you want to add to your project. After providing the necessary
details it will start searching the dependency inside the repository.
After the search gets finished it will display the search results to you. You need to select
the dependency and click on OK button and it will be added to your project.
For Example, I am going to add the dependency for Apache poi libraries. First of all, I need
to search for it then select the desired one and then add that dependency to my project.
The second step is to select the required dependency. Once you select the required
dependency its Group Id, Artifact Id and version will get displayed in the related text
fields.
Finally, click on OK button and the required dependency will get added to your project.
This process is time taking and complex because you need to search your required
dependency among all the search results and then only you can add it to your project.
4. Introduction – Maven
Maven is a powerful project management tool that is based on POM (project object
model). It is used for projects build, dependency and documentation.
It simplifies the build process like ANT. But it is too much advanced than ANT.
There are many problems that we face during the project development. They are
discussed below:
1) Adding set of Jars in each project: In case of struts, spring, hibernate frameworks, we
need to add set of jar files in each project. It must include all the dependencies of jars also.
2) Creating the right project structure: We must create the right project structure in
servlet, struts etc, otherwise it will not be executed.
3) Building and Deploying the project: We must have to build and deploy the project so
that it may work.
Maven simplifies the above-mentioned problems. It does mainly the following tasks.
Build Tool:
A build tool takes care of everything for building a process. It does the following:
● Generates source code (if auto-generated code is used).
● Generates documentation from source code.
● Compiles source code.
● Packages compiled code into JAR of ZIP file.
● Installs the packaged code in local repository, server repository, or central
repository.
Ant and Maven both are build tools provided by Apache. The main purpose of these
technologies is to ease the build process of a project.
There are many differences between ant and maven that are given below:
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529
5. Maven Installation
We can download and install maven on windows, Linux and MAC OS platforms.
Download Maven
To install maven on windows, you need to download Apache maven first.
Download Maven latest Maven software from http://maven.apache.org/download.cgi
Here, we have installed JDK and its path is set by default, so we are going to append the
path of maven.
The path of maven should be %maven home%/bin. For example, E:\apache-maven-
3.1.1\bin.
4)Verify maven
To verify whether maven is installed or not, open the command prompt and write:
mvn −version
Now it will display the version of maven and jdk including the maven home and java
home.
6. Maven Repository
A maven repository is a directory of packaged JAR file with pom.xml file. Maven
searches for dependencies in the repositories. There are 3 types of maven repository:
1. Local Repository
2. Central Repository
3. Remote Repository
If dependency is not found in these repositories, maven stops processing and throws an
error.
...
</settings>
Now change the path to local repository. After changing the path of local repository, it
will look like this:
settings.xml
1. ...
2. <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.
apache.org/xsd/settings-1.0.0.xsd">
5. <localRepository>e:/mavenlocalrepository</localRepository>
6.
7. ...
8. </settings>
As you can see, now the path of local repository is e:/mavenlocalrepository.
Let's see the code to add the jUnit library in pom.xml file.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
You can search any repository from Maven official website mvnrepository.com.
Before maven 2, it was named as project.xml file. But, since maven 2 (also in maven 3), it
is renamed as pom.xml.
groupId It is the sub element of project. It specifies the id for the project
group.
artifactId It is the sub element of project. It specifies the id for the artifact
(project). An artifact is something that is either produced or used by
a project. Examples of artifacts produced by Maven for a project
include: JARs, source and binary distributions, and WARs.
version It is the sub element of project. It specifies the version of the artifact
under given group.
File: pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
Element Description
scope defines scope for this maven project. It can be compile, provided,
runtime, test and system.
File: pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies> <dependency>
<groupId>junit</groupId> <artifactId>junit</artifactId>
<version>4.8.2</version> <scope>test</scope>
</dependency> </dependencies> </project>
8. Maven Plugins
The maven plugins are central part of maven framework, it is used to perform specific
goal. According to Apache Maven, there are 2 types of maven plugins.
● Build Plugins
● Reporting Plugins
Build Plugins
These plugins are executed at the time of build. These plugins should be declared inside
the <build> element.
Reporting Plugins
These plugins are executed at the time of site generation. These plugins should be
declared inside the <reporting> element.
Plugin Description
resource copies the resources to the output directory for including in the JAR.
s
verifier verifies the existence of certain conditions. It is useful for integration tests.
To see the list of maven plugins, you may visit apache maven official website
http://repo.maven.apache.org/maven2/org/apache/maven/plugins/. Maven plugins
are also available outside the maven at codehaus.org and code.google.com.
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529
Now you will see a maven project with complete directory structure. All the files will be
created automatically such as Hello Java file, pom.xml file, test case file etc. The directory
structure of the maven project is shown in the below figure.
Now you can see the code of App.java file and run it. It will be like the given code:
package com.javatpoint;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{ System.out.println( "Hello World!" ); } }
If you right click on the project → Run As, you will see the maven options to build the
project.
Maven uses archetype plugins to create projects. To create a simple java application,
we'll use maven-archetype-quickstart plugin. In example below, we'll create a maven-
based java application project in C:\MVN folder.
Let's open the command console, go to the C:\MVN directory and execute the
following mvn command. Make sure that C:\MVN directory is empty before running the
command.
C:\MVN>mvn archetype:generate
-DgroupId = com.companyname.bank
-DartifactId = consumerBanking
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false
Maven will start processing and will create the complete java application project
structure.
C:\MVN>mvn archetype:generate -DgroupId=com.companyname.bank -
DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -
DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @
standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @
standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-
archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.companyname.bank
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529
C:\MVN>
Now go to C:/MVN directory. You'll see a java application project created, named
consumer Banking (as specified in artifactId). Maven uses a standard directory layout as
shown below −
Using the above example, we can understand the following key concepts −
Sr.No. Folder Structure & Description
consumerBanking
1
contains src folder and pom.xml
src/main/java
2
contains java code files under the package structure (com/companyName/bank).
src/main/test
3 contains test java code files under the package structure
(com/companyName/bank).
src/main/resources
4 it contains images/properties files (In above example, we need to create this
structure manually).
If you observe, you will find that Maven also created a sample Java Source file and Java
Test file. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank
folder, you will see App.java.
package com.companyname.bank;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ){
System.out.println( "Hello World!" ); }}
package com.companyname.bank;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName ) {
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp() {
assertTrue( true );
}}
Developers are required to place their files as mentioned in table above and Maven
handles all the build related complexities.
In Maven, you can create and build artifacts using the package phase of the build lifecycle.
The package phase is responsible for taking the compiled code and other project
resources and packaging them into a distributable format, such as a JAR (Java Archive),
WAR (Web Application Archive), or other custom formats.
Here are the steps to create and build artifacts using Maven:
Configure the Build Output: In your project's pom.xml file, you need to configure the
output of the build. This includes specifying the type of artifact you want to create (e.g.,
JAR, WAR) and any additional resources to include. You do this in the <build> section of
your pom.xml:
<build>
<finalName>my-artifact</finalName> <!-- Name of the artifact without the extension --
>
<plugins> <!-- Plugin configurations for creating the artifact -->
<!-- For example, maven-jar-plugin or maven-war-plugin -->
</plugins> </build>
Depending on your project type and requirements, you would use different plugins (e.g.,
maven-jar-plugin for JAR projects or maven-war-plugin for web applications).
Run the Build: To create and build the artifact, you run the Maven build command. Open
a command prompt or terminal in your project's directory and execute:
mvn clean package
clean: This goal removes the target directory, which contains the output of previous
builds. It ensures that you start with a clean slate.
package: This goal is responsible for creating the artifact as specified in your project's
pom.xml.
Review the Output: After running the Maven command, you'll find the built artifact in
the target directory within your project's root directory. The name of the artifact is
usually determined by the <finalName> configuration in your pom.xml file.
Deploy or Use the Artifact: Depending on your project's requirements, you can deploy
the generated artifact to a repository, use it in other projects, or distribute it as needed.
Remember that Maven is highly configurable, and you can customize the build process,
including artifact creation, to meet the specific needs of your project.