Unit 2 - DO
Unit 2 - DO
                                                                                         1
 6. Maven encourages the use of a central repository of JARs and other dependencies.
    Maven comes with a mechanism that can be used to download any JARs required
    for building your project from a central JAR repository. This allows users of Maven
    to reuse JARs across projects and encourages communication between projects to
    ensure that backward compatibility issues are dealt with.
INSTALLATION OF MAVEN:
  Following steps are followed for installation of Maven
Prerequisite:
  Before installing the Maven, the Java must be installed on your system.
  The latest versions of Maven require JDK 8 or above installation.
Step 1: Download and extract Maven.
        Go to the site https://maven.apache.org/download.cgi. Based on the
operating system of your machine, choose the appropriate version.
        For installing Maven on Windows we need Binary Zip files.
                                                                                      2
      Click OK button.
Step 3: Open command prompt window and issue the command mvn --version at the
command prompt. It prompts the Version of the Apache Maven, Maven_Home directory
and Java Version. It is as shown below -
                                                                                       3
        artifactId: It is a sub element of project. This is generally refers to the name of
          the project. The artifact ID is also used as part of the name of the JAR, WAR or
          EAR file produced when building the project.
        version: This is the sub element of project which specifies the version of the
          project.
        packaging: It is used to define the packaging type such as jar, war etc.
     Release Vs. Snapshot artifact
        A release artifact indicates that the version is stable and can be used outside
          the development process. The outside development process can be testing,
          customer-qualification or preproduction.
        A snapshot artifact indicates that the project is under development. When we
          install or publish a component, Maven checks the version attribute. If it contains
          the string “SNAPSHOT”, Maven converts this keyinto a date and time value in
          UTC (Coordinated Universal Time) format.
CREATION OF MAVEN ARTIFACT USING COMMAND-LINE ARGUMENT:
Step 1: Create a folder in desktop (Example: Maven Project).
Step 2: Open command prompt and type cd <path name of folder created in desktop>.
        Check with screenshot below.
                                                                                Y
Step 3: Type mvn archetype:generate
        After a long compilation you will get a screen like this (shown below).
.
.
.
                                                                                          4
       Finally, it shows a groupId 2104: (Shown below).
Type any one of the version and press enter (Shown below).
         groupId is nothing but your company name (Example: psna.com, but you have
to type it as com.psna) (Shown below).
artifactId is nothing but your project name (Example: Demo) (Shown below).
It asked to define the package (Shown below). It asked to define the package
                                                                                      5
        Type com.psna package name (Shown below).
        Now you open the folder Maven Project in desktop, its shows the new folder
Demo.
BUILD PHASE:
Step 4: Type cd Demo.
                                                                                   6
Step 6: Compile the project.
        Type mvn compile
        If compilation is success then proceed to step 7.
        If compilation is error (Shown below).
                                                                                    7
        Now compilation process successfully executed.
Step 7: Test the project.
        Type mvn test
        After testing process successfully executed.
        The target files are created, check the folder in desktop.
        Then we have to create jar files. For that follow step 8.
                                                                     8
Step 8:Create package.
       Type mvn package
                          9
        After package successfully created.
        Then we have to verify that jar files are created. For that follow step 9.
Step 9: Verify jar files.
        Type mvn verify
                                                                                     10
RUNNING JAVA FILE:
Step 11: Type cd target (jar files are in target folder).
                                                                     11
POM FILES:
  POM stands for Project Object Model.
  It is XML file which is named as pom.xml.
  It is a fundamental building blocks for Maven project.
  It contains information related to the project and configuration information such as
      Dependencies
      Plugins
      Source directory
      Goals and so on
  Maven reads pom.xml file to accomplish its configuration and operations.
  The sample pom.xml is as follows
   <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
   https://maven.apache.org/xsd/maven-4.0.0.xsd”>
       <modelVersion>4.0.0</modelVersion>
       <groupld>com.myfirstproject</groupld>
       <artifactld>firstproject</artifactld>
       <version>0.0.1-SNAPSHOT </version>
       <build>
          <plugins>
             <plugin>
               <groupld>org.apachemaven.plugins</groupld>
               <artifactld> maven-compiler-plugin </artifactld>
               <version>3.8.1 </version>
               <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
               </configuration >
             </plugin>
          </plugins>
       </build>
   </project>
Elements of pom.xml File:
  project: It is a root element of the pom.xml file. This is the top level element.
  modelVersion: It Indicates the version model in which the current pom.xml is using.
   It is the sub element of project. It should be set to 4.0.0
  groupld: It is sub element of project. It specifies the id for the project group.
  artifactId: It is a sub element of project. This is generally refers to the name of the
   project. The artifact ID is also used as part of the name of the JAR, WAR or EAR file
   produced when building the project.
  version: This is the sub element of project which specifies the version of the project.
Additional Elements:
  packaging: It is used to define the packaging type such as jar, war etc.
  name: It is used to define the name of the maven project.
  url: It is used to define the url of the project.
                                                                                       12
  dependencies: The POM lists all the external libraries and dependencies that the
   project relies on during the build process and runtime. Maven uses this information
   to automatically download the required dependencies from remote repositories.
  dependency: It defines a dependency. I tis used inside dependencies.
  plugins: Maven allows developers to use various plugins to extend its functionality
   during the build process. The POM defines which plugins are applied to the project
   and their respective configurations.
  scope: It is used to define the scope for this maven project. It can be compile,
   provided, runtime, test and system.
MAVEN BUILD LIFECYCLE:
  Maven build lifecycle is a sequence of steps that need to be followed in order to build
   a project.
                                                                                       13
    3. Test Compile: In this phase, it tests the compiled source code and copies into
       the destination directory.
    4. Test: This phase tests code using a suitable unit testing method.
    5. Package: In this phase, all the compiled files are gathered and packaged in a
       specified format.
    6. Install: This phase installs the packages into the local repository.
    7. Deploy: In this phase, the final package is dep1oyed into a remote repository.
Maven Goals:
  In Maven, each phase is a sequence of goals.
  The purpose of each goal in Maven is to perform in specific task.
  When we build our Maven project, we need to specify the Goal
  The build phases are executed sequentially.
  Any maven build phases that come before the specified phase is also executed.
  For example, if we run mvn package then it will execute compile, test and package
   phases of the project.
Built-in Build Life Cycle Phases:
  Maven comes with 3 built-in build life cycles as shown below:
     1. Clean: In the Clean lifecycle phase, it performs the cleaning operation in which it
        deletes the build directory name target and its contents for a fresh build and
        deployment. To perform this operation, we use command mvn clean.
     2. Default: This phase handles the complete deployment of the project.
     3. Site: This phase handles the generating the java documentation of the project.
 1. Clean Phase:
      The purpose of clean phase is to clean up the project and make it ready for fresh
        compile and deployment.
      Clean lifecycle performs 3 types of clean operations -
                                                                                        14
                             Fig: Phases in “Default” lifecycle
Lifecycle phase                                 Description
                   Validates and ensures that the project is fine and perfect considering
Validate
                   all the required information is made available for the build.
Compile            Compilation of the project source code.
                   Executing the tests using some suitable test framework. Note: these
Test
                   test cases are not considered for packaging and deploying.
                   Packaging the successfully compiled and tested code to some
Package
                   distributable format - JAR, WAR, EAR.
                   Deploy the application to an environment where integration tests
Integration-test
                   can be run.
                   Performs action for a quality check and ensures the required criteria
Verify
                   being met.
                   Installing the application in the local repository. Any other project
Install
                   can use this as a dependency.
                   The final package will be copied to a remote repository, may be as a
Deploy
                   formal release.
 3. Site Phase:
      This phase performs a crucial task of Maven which is detailed documentation of
        the project and preparing reports about project.
      For Project documentation and site generation, in maven, we have a specific
        lifecycle dedicated for that, which has four phases and that are:
           Pre-Site: It executes the actions completed before the entire project site
             generation.
           Site: It generates the project‟s site documentation.
                                                                                       15
         Post-site: It performs post-site steps to complete site generation and set up
           site deployment.
         Site deploy: It distributes the site‟s documentation to the selected web
           server.
      When we execute this command “mvn site”, it will generate the Javadocs for the
       given Project.
Maven Profiles:
  Maven Profile is an important feature of Maven. Using Profile we can customize the
   build for different environments.
  Profiles are portable for different build environments. The build environment means
   a specific environment for production, testing or development environment
   instances. So in order to configure these instances Maven provides the various
   features for the build using profile.
  The profiles are specified in a pom.xml file. Hence using a single pom.xml file, it
   possible to work in different environments such as production or development with
   the help of profiles.
  By defining the profiles, it is possible to modify the pom.xml during the build time.
   That means we can configure separate environments for development and
   production instances. So, based on the parameters passed, the corresponding
   profiles are activated accordingly.
Different Types of Build Profiles:
There are three types of build profiles
 1. Per project: It is defined in pom.xml.
 2. Per User/Developer: It is defined in Maven settings.xml
    (%USER_HOME%/.m2/settings.xml)
 3. Global: It is defined in Maven global settings.xml (%M2_HOME%/conf/settings.xml)
Elements of Profile:
  The profiles element is in the pom.xml, it contains one or more profile elements.
   Since profiles override the default settings in a pom.xml, the profiles element is
   usually listed as the last element in a pom.xml.
  Each profile has to have an id element. This id element contains the name which is
   used to invoke this profile from the command-line. A profile is invoked by passing
   the -P <profile_id> command-line argument to Maven.
  A profile element can contain many of the elements which can appear under the
   project telement of a POM XML Document. In this example, we can override the
   behavior of the Compiler plugin and we have to override the plugin configuration
   which is normally enclosed in a build and a plugins element.
DEMO EXAMPLE:
  We will create a profile demo example with the help of Eclipse.
  Start Eclipse IDE.
Step 1: Click on New->Maven Project. Specify the Group Id. It will be given using
       com.name_of_company. I have given the name as com.mycompany. Then give
       the Artifact Id as a project name. I have given the name as profile demo. Then
       click on Finish button.
Step 2: Create a package inside src/main/java folder of the project. I have named it as
       com.profile. Inside this package I have created a App.java file as follows -
                                                                                     16
App.java
package com profiledemo;
public class App
{
   public static void main(String[] args)
   {
      System.out.println (“Simple Profile Demo Project”);
   }
}
Step 3: Edit the pom.xml file for adding the profiles for Test and Dev environment.
         For Test environment
         Id: TestEnv
         Compiler Plugin Version: 3.8.1
         JAR Plugin Version: 3.0.0
         For Dev environment
         Id: DevEnv
         Compiler Plugin Version: 3.10.1
         JAR Plugin Version: 3.2.0
         The sample pom.xml file is as follows -
pom.xml
<project xlns = “http://maven. apache.org/POM/4.0.0”
xmlns.xsi = “http://www.w3.0rg/2001/XMLSchema-instance”
xsi:schemaLocation = “http ://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd”>
   <modelVersion>4.0.0</modelVersion>
   <groupld>com.mycompany</groupld>
   <artifactld> profiled emo </artifactld>
   <version>0.0.1-SNAPSHOT </version >
   <profiles>
      <profile>
         <id>TestEnv</id>
         <build>
            <plugins>
               <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactid>maven-compiler-plugin </artifactld>
                 <version>3.8.1 </version >
                 <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                 </configuration>
               </plugin>
               <plugin>
                 <groupld>org.apache.maven.plugins</groupId>
                 <artifactld> maven-jar-plugin </artifactId>
                 <version>3.0.0</version>
               </plugin>
            </plugins>
                                                                                      17
       </build>
     </profile>
     <profile>
       <id>DevEnv</id>
       <build>
           <plugins>
             <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
             </plugin>
             <plugin>
                <groupId>org.apache.maven.plugins</groupld>
                <artifactId>maven-jar-plugin</artifactld>
                <version>3.2.0</version>
             </plugin>
            </plugins>
       </build>
     </profile>
  </profiles>
</project>
Advantages of using Profile:
  One of the major advantages of maven is creating profile based dependencies.
   Instead of creating separate POM.xml, we can create a profile and configure
   dependencies for that specific profile. This helps us to declare all the dependencies
   in one pom.xml.
  Multiple dependencies can be executed without replicating the code. Within the
   same working project, multiple dependencies can be tested at a time.
MAVEN REPOSITORIES:
  Maven repository is a directory where all the project jars, plugins, library jars or any
   other project related artifacts are stored and these can be accessed by Maven easily.
                                                                                        18
                                 Fig. Types of repository
   1. Local Repository:
        Maven local repository is located in developer‟s machine. When we execute
         any Maven project that requires dependencies, Maven downloads these
         dependencies from remote servers and stores them on developer‟s machine.
        By default, Maven creates local depository inside user‟s home directory i.e.
         C:/Users/m2 directory.
        We can change the location of local repository using the settings.xml file
         using localRepository tag.
         <settings>
            <localRepository> C:\M2 </localRepository>
         </settings>
   2. Central Repository:
        Maven Central can be accessed from
         https://repo.maven.apache.org/maven2/.
        Whenever we execute our Maven project then, required dependencies are first
         searched in the local repository, if those dependencies are not present in the
         local repository then those are downloaded from the central repository and are
         stored in the local repository for the future use.
   3. Remote Repository:
        Apart from central repository, we may need to deploy artifacts from remote
         locations. Such repositories are called as remote repositories.
        These Maven remote repository work exactly the same way as Maven‟s central
         repository.
        Whenever an artifact is needed from these repositories, itis first downloaded to
         the developer‟s local repository and then it is used.
MAVEN PLUGINS:
  Maven Plugin is a central part of Maven framework which is used to perform specific
   goal.
  There are two types of Maven plugins
    1. Build plugin: These plugins are declared inside <build> element. These plugins
       are executed at the time of build.
    2. Reporting plugin: These plugins are declared inside the element <reporting>.
       These plugins are executed at the time of site generation.
  Following is a list of some core plugins
                                                                                   19
        Clean: Clean up after the build.
        Compiler: Compiles Java sources.
        Deploy: Deploy the built artifact to the remote repository.
        Failsafe: Run the JUnit integration tests in an isolated class loader.
        Install: Install the built artifact into the local repository.
        Resources: Copy the resources to the output directory for including in the JAR.
        Site: Generate a site for the current project
        Surefire: Run the JUnit unit tests in an isolated class loader.
        Verifier: Useful for integration tests, it verifies the existence of certain
         conditions.
Dependency Management:
  In Maven, a dependency is just another archive-JAR, ZIP, and so on-which our
   current project needs in order to compile, build, test, and/or run.
  These project dependencies are collectively specified in the pom.xml file, inside of a
   <dependencies> tag.
  When we run a maven build or execute a maven goal, these dependencies are
   resolved and then loaded from the local repository.
  If these dependencies are not present in the local repository, then Maven will
   download them from a remote repository and cache them in the local repository.
  Dependency management is an important activity because to build a product we
   need several library files, plugins or some external dependencies. We have to be sure
   that all these components are compatible for building our product. This task can be
   taken care by dependency management.
Example of Dependency:
  Here is a dependency section of pom.xml file.
   <dependencies>
      <dependency>
        <groupld>junit</groupld>
        <artifactld>junit</artifactld>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupld>
        <artifactld>spring-core</artifactld>
        <version>4.3.5.RELEASE</version>
      </dependency>
   </dependencies>
  Inside the <dependencies> tag separate dependencies are specified by each
   <dependency> tag.
  Each dependency is supposed to have at least three main tags:
     groupId: It is a sub element of the project tag, indicates a unique identifier of a
       group the project is created. Typically, fully qualified domain name.
     artifactld: This element indicates a unique base name-primary artifact
       generated by a particular project.
     Version: This element specifies the version for the artifact under the given
       group.
                                                                                      20
Concept of Transitive Dependency:
  Transitive dependency means when library A depends upon library B and library B
   depends upon library C, and then A depends upon both B and C.
  In Maven using the command dependency:tree we can view all the transitive
   dependencies of our project. The command is
     $ mvn dependency:tree
Excluding Dependencies:
  There can be version mismatch issues (sometimes due to transitive dependencies)
   between the project artifacts and artifacts from the platform of deployments, such as
   Tomcat or another server.
  To resolve such version mismatch issues, maven provides <exclusion> tag, in order
   to break the transitive dependency.
For example:
<project>
…
  <dependencies>
     <dependency>
        <groupld>myprojects.ProjectA</groupld>
        <artifactld>Project-A</artifactld>
        <version> 1.0</version>
        <scope>compile</scope>
        <exclusions>
           <exclusion><!--declar e the exclusion here -->
              <groupId>myprojects.ProjectB</groupld>
              <artifactld>Project-B </artifactld>
           </exclusion>
        </exclusions>
     </dependency>
  </dependencies>
</project>
Disadvantages of Maven:
  Installation of Maven in each working system is required for executing the Maven
   based project.
  We cannot implement the dependency using Maven if Maven code for existing
   dependency is not available.
  Maven is slow in execution of project.
  It always need XML based file named pom.xml for configuration of the project.
INTRODUCTION TO GRADLE:
  Gradle is an Open Source build automation tool.
  The build automation tool is a tool that automates the creation of software build.
  Build automation is the process of automating the retrieval of source code, compiling
   it into binary code, executing automated tests and publishing it into a shared,
   centralized repository.
  It is launched in 2007 but the stable release came in 2009. Finally, Gradle came into
   picture in 2012 by overcoming the drawbacks of both ANT and Maven.
                                                                                     21
  Gradle tools takes the advantages of Ant and Maven. It removes the disadvantages of
   Ant and Maven.
  Gradle is written in Groovy language.
  Gradle is a general purpose build tool and its main focus is Java projects.
Features of Gradle:
 1. Free and Open Source: It is an open source tool.
 2. High Performance: Gradle finishes the tasks efficiently by considering the outputs
    from previous execution.
 3. Better Support: Gradle is popular for providing the support. The Gradle can provide
    support to build ANT projects. Tasks can be imported from ANT build projects and
    can be used in Gradle project.
 4. Scaling: Gradle can increase the productivity, from simple and single project to huge
    multi-project builds.
 5. Multi-Project Builds: Gradle supports the multi-project builds. It takes care of
    building all subprojects.
 6. IDE Support: Gradle has support for several IDEs. Gradle also generates the
    required solution files to load a project into Visual Studio.
INSTALLATION OF GRADLE:
  Gradle is a Java based Tool. Hence the Java 8 or higher version must be installed
   before installing the Gradle.
  If the Java is already installed or not is checked by issuing the command for Java
   version number at the command prompt
       $java --version
  The version number is displayed if the Java is already installed on your machine.
 Step 1: Visit official web page for Gradle https://gradle.org/install/
 Step 2: Select the Binary-Only option, and it will start downloading the .zip file on
 your machine.
 Step 3: Extract the file at the desired location.
 Step 4: Configure the Environment variable. Click on New tab of Environment
 variables for User variables.
                                                                                      22
Click Ok button.
Then click on path and click on Edit button. Click on New button. Then add the path
upto the bin folder. For example, C:\Program Files\gradle-8.2.I\bin. Then click Ok.
                                                                                 23
 Now we have successfully installed Gradle on our machine. The next step is
 initialization and verification.
 Step 5: Open command prompt and issue the command gradle --version. It will
 display the version of Gradle.
 If we issue the command gradle at the command prompt, then the gradle daemon will
 start.
Core Concepts:
  Project: Gradle project represents the application that can be deployed to the
   staging environment.
  Task: A task refers to a piece of work performed by a _build. For example - the task
   cane be creating a Jar file, compiling classes, or making JavaDoc
  Build Script: Gradle builds the build script for - 1. project 2. task. Every Gradle
   build represents one or more projects. The build script is written using the domain
   specification language called groovy. This script is saved as build.gradle
CREATING GRADLE PROJECT USING COMMAND-PROMPT:
Step 1: Create a folder in desktop (Example: Gradle Project).
Step 2: Open command prompt and type cd <path name of folder created in desktop>.
        Check with screenshot below.
Step 3: Create a gradle project using the command-line by issuing the following
command
     $ gradle init
                                                                                    24
       It will ask you to select type of project to generate, suppose you want to create an
application, and then enter 2 (shown below).
       Suppose you want to create an application in Java, and then enter 3 (shown
below).
       It will ask whether you need multiple subprojects for your application (shown
below).
       If you need multiple subprojects for your application, then select yes (shown
below).
Next, it will ask you to select build script DSL (shown below).
Suppose you want to build script DSL in Groovy, and then enter 2 (shown below).
If you want to choose your project name as Demo then type it (shown below).
Next, it will ask you to enter target version of Java (shown below).
       Suppose you want to enter target version of Java as 21, and then enter 21 (shown
below).
                                                                                        25
      It will ask whether you need to generate build using new APIs (shown below).
If you need want to generate build using new APIs, then type yes (shown below).
Step 5: Create a build of above application using the command-line by issuing the
following command
       $ gradle build
                                                                                        26
Step 6: Execute the application using the command-line by issuing the following
command
     $ gradle run
                                                                                       28
        Gradle Wrapper, also called wrapper in short.
        The wrapper contains some important files as describe below
          gradle-wrapper.jar contains code for downloading the Gradle distribution
            specified in the gradle-wrapper.properties file
          gradle-wrapper.properties contains wrapper runtime properties - most
            importantly, the version of the Gradle distribution that is compatible with
            the current project
          gradlew is the script that executes Gradle tasks with the wrapper on Linux
            and Mac OS machines.
          gradlew.bat is the gradlew equivalent batch script for windows machines
       The main benefits of wrapper are that we can build a project with wrapper on
         any machine without the need to install Gradle first.
       That means if on one machine if we create a gradle project and if we run that
         project on another machine then we need not have to install Gradle software
         on that machine.
       This is due to the gradle-wrapper file.
 3. settings.gradle
       The settings.gradle file is used to configure the global settings of gradle
         project.
MAVEN Vs GRADLE:
  S.No           Maven                                             Gradle
                                                 Gradle is a tool which can be used to
           Maven is a tool used form
   1                                             develop      domain-specific      language
           generating Java based projects.
                                                 projects.
                                                 It    uses    Groovy     based     Domain
           It is uses the XML (pom.xml) to
   2                                             Specification    Language       (DSL)   for
           create project structure.
                                                 creating the project structure.
           The purpose of the Maven tool-        The purpose set for Gradle based tool
   3       based project is to finish the        project    is    to    incorporate     new
           project within the given timeline.    functionality into the project.
           The     Java     compilation     is   The java compilation is not compulsory
   4
           compulsory for the Maven tool.        for the Gradle tool.
           It does not create local temporary    It performs better than maven as it
   5       files during software creation,       optimized for tracking only current
           and is hence slower.                  running task.
           It supports software development      It supports software development in
   6
           in Java, Scala, C#, and Ruby.         Java, C, C++, and Groovy.
29