Introducing Maven A Build Tool for Today’s Java Developers — Second Edition — Balaji Varanasi www.allitebooks.com
Introducing Maven A Build Tool for Today’s Java Developers Second Edition Balaji Varanasi www.allitebooks.com
Introducing Maven: A Build Tool for Today's Java Developers ISBN-13 (pbk): 978-1-4842-5409-7 ISBN-13 (electronic): 978-1-4842-5410-3 https://doi.org/10.1007/978-1-4842-5410-3 Copyright © 2019 by Balaji Varanasi This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Steve Anglin Development Editor: Matthew Moodie Coordinating Editor: Mark Powers Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail editorial@apress.com; for reprint, paperback, or audio rights, please email bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers via the book’s product page, located at www.apress.com/978-1-4842-5409-7. For more detailed information, please visit http://www.apress.com/source-code. Printed on acid-free paper Balaji Varanasi Salt Lake City, UT, USA www.allitebooks.com
For my Vedha www.allitebooks.com
v About the Author ���������������������������������������������������������������������������������ix About the Technical Reviewer �������������������������������������������������������������xi Acknowledgments �����������������������������������������������������������������������������xiii Introduction ����������������������������������������������������������������������������������������xv Chapter 1: Getting Started with Maven ������������������������������������������������1 Standardized Directory Structure �������������������������������������������������������������������������2 Declarative Dependency Management �����������������������������������������������������������������2 Plug-ins �����������������������������������������������������������������������������������������������������������������3 Uniform Build Abstraction �������������������������������������������������������������������������������������3 Tools Support ��������������������������������������������������������������������������������������������������������3 Archetypes ������������������������������������������������������������������������������������������������������������4 Open Source����������������������������������������������������������������������������������������������������������4 Maven Alternatives �����������������������������������������������������������������������������������������������5 Ant + Ivy ����������������������������������������������������������������������������������������������������������5 Gradle ��������������������������������������������������������������������������������������������������������������7 Maven Components ����������������������������������������������������������������������������������������������9 Maven SCM �����������������������������������������������������������������������������������������������������9 Maven Wagon ��������������������������������������������������������������������������������������������������9 Maven Doxia ��������������������������������������������������������������������������������������������������10 Summary�������������������������������������������������������������������������������������������������������������10 Table of Contents www.allitebooks.com
vi Chapter 2: Setting Up Maven ��������������������������������������������������������������11 Installing on Windows �����������������������������������������������������������������������������������������13 Installing on Mac �������������������������������������������������������������������������������������������������13 Testing Installation ����������������������������������������������������������������������������������������������14 Getting Help ��������������������������������������������������������������������������������������������������������15 Additional Settings ����������������������������������������������������������������������������������������������16 Setting Up a Proxy �����������������������������������������������������������������������������������������������19 Securing Passwords ��������������������������������������������������������������������������������������20 IDE Support ���������������������������������������������������������������������������������������������������������21 Summary�������������������������������������������������������������������������������������������������������������21 Chapter 3: Maven Dependency Management �������������������������������������23 Using New Repositories ��������������������������������������������������������������������������������������26 Dependency Identification ����������������������������������������������������������������������������������28 Transitive Dependencies �������������������������������������������������������������������������������������29 Dependency Scope ���������������������������������������������������������������������������������������������32 Manual Dependency Installation �������������������������������������������������������������������������33 Summary�������������������������������������������������������������������������������������������������������������35 Chapter 4: Maven Project Basics ��������������������������������������������������������37 Basic Project Organization ����������������������������������������������������������������������������������37 Understanding the pom�xml File �������������������������������������������������������������������������40 Building a Project ������������������������������������������������������������������������������������������������42 Testing the Project ����������������������������������������������������������������������������������������������44 Properties in pom�xml �����������������������������������������������������������������������������������������49 Implicit Properties �����������������������������������������������������������������������������������������50 User-Defined Properties ��������������������������������������������������������������������������������50 Summary�������������������������������������������������������������������������������������������������������������51 Table of ConTenTs
vii Chapter 5: Maven Lifecycle ����������������������������������������������������������������53 Goals and Plug-ins ����������������������������������������������������������������������������������������������53 Lifecycle and Phases ������������������������������������������������������������������������������������������57 Plug-in Development �������������������������������������������������������������������������������������������61 Summary�������������������������������������������������������������������������������������������������������������68 Chapter 6: Maven Archetypes �������������������������������������������������������������69 Built-in Archetypes ����������������������������������������������������������������������������������������������69 Generating a Web Project ������������������������������������������������������������������������������������71 Multimodule Project ��������������������������������������������������������������������������������������������74 Creating an Archetype �����������������������������������������������������������������������������������������80 Using the Archetype ��������������������������������������������������������������������������������������������86 Summary�������������������������������������������������������������������������������������������������������������87 Chapter 7: Documentation and Reporting ������������������������������������������89 Using the Site Lifecycle ���������������������������������������������������������������������������������������89 Advanced Site Configuration �������������������������������������������������������������������������������94 Generating Javadoc Reports �������������������������������������������������������������������������������99 Generating Unit Test Reports�����������������������������������������������������������������������������101 Generating Code Coverage Reports ������������������������������������������������������������������102 Generating the SpotBugs Report �����������������������������������������������������������������������104 Summary�����������������������������������������������������������������������������������������������������������105 Chapter 8: Maven Release ����������������������������������������������������������������107 Integration with Nexus ��������������������������������������������������������������������������������������107 Project Release �������������������������������������������������������������������������������������������������113 Git Client Installation �����������������������������������������������������������������������������������������115 Creating a GitHub Repository ����������������������������������������������������������������������������115 Checking in Source Code ����������������������������������������������������������������������������������116 Table of ConTenTs
viii Maven Release ��������������������������������������������������������������������������������������������������118 Prepare Goal ������������������������������������������������������������������������������������������������118 Clean Goal ���������������������������������������������������������������������������������������������������123 Perform Goal ������������������������������������������������������������������������������������������������123 Summary�����������������������������������������������������������������������������������������������������������126 Chapter 9: Continuous Integration ����������������������������������������������������127 Installing Jenkins ����������������������������������������������������������������������������������������������128 Maven Project ���������������������������������������������������������������������������������������������������129 Configuring Jenkins ������������������������������������������������������������������������������������������130 Triggering Build Job ������������������������������������������������������������������������������������������133 Summary�����������������������������������������������������������������������������������������������������������135 Index �������������������������������������������������������������������������������������������������137 Table of ConTenTs
ix About the Author Balaji Varanasi is a seasoned technology leader, author, and speaker. He has over 18 years of experience managing, architecting, and delivering high-performance, scalable enterprise applications. During this period, he has worked in the areas of security, web accessibility, search, and enterprise portals. He has a master’s degree in computer science from Utah State University. He shares his insights and experiments at http://blog.inflinx.com.
xi About the Technical Reviewer Germán González-Morris is a polyglot software architect/engineer with 20+ years in the field, with knowledge in Java(EE), Spring, Haskell, C, Python, and Javascript, among others. He works with web distributed applications. Germán loves math puzzles (including reading Knuth) and swimming. He has tech-reviewed several books, including an application container book (WebLogic), as well as titles covering various programming languages (Haskell, TypeScript, WebAssembly, Math for coders, and regexp). You can find more details at his blog site (https://devwebcl. blogspot.com/) or twitter account (@devwebcl).
xiii Acknowledgments This book would not have been possible without the support of several people, and I take this opportunity to sincerely thank them. Thanks to the amazing folks at Apress: Steve Anglin, Mark Powers, Matthew Moodie, and many others. I also owe a huge thank you to Germán González-Morris for his technical review and for the valuable feedback he provided. Finally, I want to thank my wife, Sudha, for her constant support and encouragement. Thank you so much, dear!
xv Introducing Maven provides a concise introduction to Maven, the de facto standard for building, managing, and automating Java and JEE-based projects in enterprises throughout the world. The book starts by explaining the fundamental concepts of Maven and showing you how to set up and test Maven on your local machine. It then delves deeply into concepts such as dependency management, lifecycle phases, plug-ins, and goals. It also discusses project structure conventions, jump-starting project creation using archetypes, and documentation and report generation. Finally, it concludes with a discussion of Maven’s release process and integration with Jenkins. How This Book Is Structured Chapter 1 starts with a gentle introduction to Maven. It discusses reasons for adopting Maven, and it provides an overview of its two alternatives: Ant and Gradle. Chapter 2 focuses on setting up Maven on your machine and testing the installation. It also provides an overview of Maven’s settings. xml file, and it shows you how to run Maven in a HTTP proxy-enabled environment. Chapter 3 delves deeply into Maven’s dependency management. It then discusses the GAV coordinates Maven uses for uniquely identifying its artifacts. Finally, it covers transitive dependencies and the impact they have on builds. Introduction
xvi Chapter 4 discusses the organization of a basic Maven project and covers the important elements of a pom.xml file. Then you learn about testing the project using JUnit. Chapter 5 provides detailed coverage of Maven’s lifecycle, plug-ins, build phases, and goals. It then walks you through the process of creating and using a simple Maven plug-in. Chapter 6 introduces archetypes’ project templates that enable you to bootstrap new projects quickly. The built-in archetypes are used to generate a Java project, a web project, and a multimodule project. You will then create a custom archetype from scratch and use it to generate a new project. Chapter 7 covers the basics of site generation using Maven. It then discusses report generation and documentation such as Javadocs, test coverage reports, and SpotBugs reports and how to integrate them into a Maven site. Chapter 8 begins with a discussion of the Nexus repository manager and shows you how it can be integrated with Maven. It then provides complete coverage of Maven’s release process and its different phases. Chapter 9 introduces continuous integration (CI) concepts and discusses installation and configuration on Jenkins, an open source tool for continuous integration. Target Audience Introducing Maven is intended for developers and automation engineers who would like to get started quickly with Apache Maven. This book assumes basic knowledge of Java. No prior experience with Maven is required. InTroduCTIon
xvii Downloading the Source Code The source code for the examples in this book can be downloaded via the Download Source Code button located at www.apress.com/978-1- 4842- 5409-7. Once downloaded, unzip the code and place the contents in the C:\apress\gswm-book folder. The source code is organized by individual chapters. Where applicable, the chapter folders contain the gswm project with the bare minimum files to get you started on that chapter’s code listings. The chapter folders also contain a folder named final, which holds the expected end state of the project(s). Questions We welcome reader feedback. If you have any questions or suggestions, you can contact the author at Balaji@inflinx.com. InTroduCTIon
1© Balaji Varanasi 2019 B. Varanasi, Introducing Maven, https://doi.org/10.1007/978-1-4842-5410-3_1 CHAPTER 1 Getting Started with Maven Like other craftsmen, software developers rely on their tools to build applications. Developers’ integrated development environments (IDEs), bug-tracking tools, build tools, frameworks, containers, and debug tools, such as memory analyzers, play a vital role in day-to-day development and maintenance of quality software. This book will discuss and explore the features of Maven, which we know will become an important tool in your software development arsenal. Apache Maven is an open source, standards-based project management framework that simplifies the building, testing, reporting, and packaging of projects. Maven's initial roots were in the Apache Jakarta Alexandria project that took place in early 2000. It was subsequently used in the Apache Turbine project. Like many other Apache projects at that time, the Turbine project had several subprojects, each with its own Ant- based build system. Back then, there was a strong desire for developing a standard way to build projects and to share generated artifacts easily across projects. This desire gave birth to Maven. Maven version 1.0 was released in 2004, followed by version 2.0 in 2005 and version 3.0 in 2010. At the time of writing this book, 3.6.1 is the current version of Maven. Maven has become one of the most widely used open source software programs in enterprises around the world. Let's look at some of the reasons why Maven is so popular.
2 Standardized Directory Structure Often, when we start work on a new project, a considerable amount of time is spent deciding on the project layout and folder structure needed to store code and configuration files. These decisions can vary vastly across projects and teams, which can make it difficult for new developers to understand and adopt other teams' projects. It can also make it hard for existing developers to jump between projects and find what they are seeking. Maven addresses the preceding problems by standardizing the folder structure and organization of a project. Maven provides recommendations on where different parts of a project, such as source code, test code, and configuration files, should reside. For example, Maven suggests that all of the Java source code should be placed in the src\main\java folder. This makes it easier to understand and navigate any Maven project. Additionally, these conventions make it easy to switch to and start using a new IDE. Historically, IDEs varied with project structure and folder names. A dynamic web project in Eclipse might use the WebContent folder to store web assets, whereas IntelliJ IDEA might use web folder for the same purpose. With Maven, your projects follow a consistent structure and become IDE agnostic. Declarative Dependency Management Most Java projects rely on other projects and open source frameworks to function properly. It can be cumbersome to download these dependencies manually and keep track of their versions as you use them in your project. Maven provides a convenient way to declare these project dependencies in a separate, external pom.xml file. It then automatically downloads those dependencies and allows you to use them in your project. 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. Chapter 1 GettinG Started with Maven
3 The pom.xml file can also serve as a documentation tool, conveying your project dependencies and their versions. Plug-ins Maven follows a plug-in-based architecture, making it easy to augment and customize its functionality. These plug-ins encapsulate reusable build and task logic. Today, there are hundreds of Maven plug-ins available that can be used to carry out tasks ranging from code compilation to packaging to project documentation generation. Maven also makes it easy to create your own plug-ins, thereby enabling you to integrate tasks and workflows that are specific to your organization. Uniform Build Abstraction Maven provides a uniform interface for building projects. You can build a Maven project by using just a handful of commands. Once you become familiar with Maven's build process, you can easily figure out how to build other Maven projects. This frees developers from having to learn build idiosyncrasies so they can focus more on development. Tools Support Maven provides a powerful command-line interface to carry out different operations. All major IDEs today provide excellent tool support for Maven. Additionally, Maven is fully integrated with today's continuous integration products such as Jenkins and Bamboo. Chapter 1 GettinG Started with Maven
4 Archetypes As we already mentioned, Maven provides a standard directory layout for its projects. When the time comes to create a new Maven project, you need to build each directory manually, and this can easily become tedious. This is where Maven archetypes come to rescue. Maven archetypes are predefined project templates that can be used to generate new projects. Projects created using archetypes will contain all of the folders and files needed to get you going. Archetypes are also a valuable tool for bundling best practices and common assets that you will need in each of your projects. Consider a team that works heavily on Spring framework-based web applications. All Spring-based web projects share common dependencies and require a set of configuration files. It is also highly possible that all of these web projects have similar Log4j/Logback configuration files, CSS/Images, and Thymeleaf page layouts. Maven lets this team bundle these common assets into an archetype. When new projects get created using this archetype, they will automatically have the common assets included. No more copy and pastes of code or drag and drops of files required. Open Source Maven is open source and costs nothing to download and use. It comes with rich online documentation and the support of an active community. CONVENTION OVER CONFIGURATION Convention over configuration (CoC) or coding by convention is one of the key tenants of Maven. popularized by the ruby on rails community, CoC emphasizes sensible defaults, thereby reducing the number of decisions to be made. it saves time and also results in a simpler end product, as the amount of configuration required is drastically reduced. Chapter 1 GettinG Started with Maven
5 as part of its CoC adherence, Maven provides several sensible defaults for its projects. it lays out a standard directory structure and provides defaults for the generated artifacts. imagine looking at a Maven artifact with the name log4j-core-2.11.2.jar. at a glance, you can easily see that you are looking at a log4j-core Jar file, version 2.11.2. One drawback of Maven's CoC is the rigidness that end users experience when using it. to address this, you can customize most of Maven's defaults. For example, it is possible to change the location of the Java source code in your project. as a rule of thumb, however, such changes to defaults should be minimized. Maven Alternatives Although the emphasis of this book is on Maven, let's look at a couple of its alternatives: Ant + Ivy and Gradle. Ant + Ivy Apache Ant (http://ant.apache.org) is a popular open source tool for scripting builds. Ant is Java based, and it uses Extensible Markup Language (XML) for its configuration. The default configuration file for Ant is the build.xml file. Using Ant typically involves defining tasks and targets. As the name suggests, an Ant task is a unit of work that needs to be completed. Typical tasks involve creating a directory, running a test, compiling source code, building a web application archive (WAR) file, and so forth. A target is simply a set of tasks. It is possible for a target to depend on other targets. This dependency lets us sequence target execution. Listing 1-1 demonstrates a simple build.xml file with one target called compile. The compile target has two echo tasks and one javac task. Chapter 1 GettinG Started with Maven
6 Listing 1-1. Sample Ant build.xml File <project name="Sample Build File" default="compile" basedir="."> <target name="compile" description="Compile Source Code"> <echo message="Starting Code Compilation"/> <javac srcdir="src" destdir="dist"/> <echo message="Completed Code Compilation"/> </target> </project> Ant doesn't impose any conventions or restrictions on your project, and it is known to be extremely flexible. This flexibility has sometimes resulted in complex, hard-to-understand, and hard-to-maintain build. xml files. Apache Ivy (http://ant.apache.org/ivy/) provides automated dependency management, making Ant more joyful to use. With Ivy, you declare the dependencies in an XML file called ivy.xml, as shown in Listing 1-2. Integrating Ivy with Ant involves declaring new targets in the build.xml file to retrieve and resolve dependencies. Listing 1-2. Sample Ivy Listing <ivy-module version="2.0"> <info organisation="com.apress" module="gswm-ivy" /> <dependencies> < dependency org="org.apache.logging.log4j" name="log4j-api" rev="2.11.2" /> </dependencies> </ivy-module> Chapter 1 GettinG Started with Maven
Comments 0
Loading comments...
Reply to Comment
Edit Comment