35,99 €
If you are a developer with some experience in build tool and want to become an expert in build tool, then this book is for you. Basic knowledge of Gradle or any other build tool is essential.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 292
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2015
Production reference: 1280715
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-136-6
www.packtpub.com
Author
Mainak Mitra
Reviewers
Alexander Barnes
Scott Battaglia
Michael Putters
Andreas Schmid
Commissioning Editor
Amarabha Banerjee
Acquisition Editor
Nadeem N. Bagban
Content Development Editor
Parita Khedekar
Technical Editor
Namrata Patil
Copy Editors
Mario Cecére
Kausambhi Majumdar
Angad Singh
Laxmi Subramanian
Project Coordinator
Milton Dsouza
Proofreader
Safis Editing
Indexer
Rekha Nair
Graphics
Jason Monteiro
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Mainak Mitra is a software developer who has rich experience in enterprise software development and automation frameworks. He is an electrical engineer from Jadavpur University, Kolkata. He is currently working for an online gaming company. Prior to this, he worked for various product development companies, such as Yahoo Inc., CA Technologies. He can be contacted at <[email protected]>.
First, I would like to thank the Gradle team for creating such a robust build automation tool. This book would not exist without this open source tool.
I would also like to thank the editors at Packt Publishing, who inspired and helped me to write this book. The Packt Publishing team, especially Parita and Namrata, provided insightful feedback to help me.
Before this book reached you, it was reviewed by many people at different stages. Without their comments, feedback, and criticism, this book would not have been possible. I acknowledge the people involved here: Alexander Barnes, Scott Battaglia, Michael Putters, Andreas Schmid.
Special thanks goes to my friend Abhinandan for his contribution to this book and for compromising his weekends for me. He reviewed all the chapters in this book and guided me in writing most of the topics. Without his expertise and support, this book would not have been possible.
Alexander Barnes has been a professional software engineer for over 5 years after graduating summa from the Texas A&M class of '09 with a BS in computer engineering and a minor in mathematics. He started his career at Cisco Systems, working with a variety of Java web technologies and tools. At Cisco, he played a leading role in developing the RESTful User Data Services (UDS) for the CallManager product and helped develop and maintain the administration and user portals. He pioneered the transformation of his team's build system from Ant to Gradle for the numerous project tools and utilities maintained by the team and became a subject-matter expert on Git, Gradle, and Linux in particular.
Alex decided to move closer to his family, recently joining Novo Dia Group in Austin as a senior Java developer. He is an avid advocate of best software practices and the usage of the right tools for the job. Some of his favorite tools include Git, Gerrit, Jenkins, Sonar, Gradle, Java, and Linux. He strives to design and develop freely, refactor to consistent design patterns as appropriate, and focus on reducing mutable states. Alex occasionally blogs about technologies and other interests on his website at http://toastedbits.com/.
Alex enjoys pursuing other creative hobbies in his spare time; playing his guitar and listening to a lot of rock, metal, and electronic music. He also wishes to pick up piano and music production techniques to create his own electronic tracks in the future. He is also an enthusiast of craft beers and playing board games and poker with friends.
I would like to thank my friends and family for giving me their love and encouragement to achieve my dreams. Also, thanks to the Electronic Frontier Foundation, GNU, and Apache Software Foundation for making our software world a much more respectful community.
Scott Battaglia is a senior software development engineer for Audible Inc. (an Amazon.com, Inc. company), the leading provider of premium digital spoken audio information. He currently leads the shared Android platform team and coaches on a variety of topics, including open source, interviewing, and scrum. Prior to this, he was an identity management architect and senior application developer with Rutgers, the State University of New Jersey.
He has actively contributed to various open source projects, including Apereo Central Authentication Service and Inspektr, and has previously contributed to Spring Security, Apereo OpenRegistry, and Apereo uPortal. He has spoken at a variety of conferences, including Jasig, EDUCAUSE, and Spring Forward on topics such as CAS, Identity Management, Spring Security, and software development practices.
Michael Putters has been working with various technologies for the past 15 years, from low-level assembler projects to Angular websites, his main interests being compiler and graphics development. More recently, he's been involved with the Gradle project as it is the only build system capable of handling any type of project, Java-based applications, native C++ software, mobile applications on iOS and Android, and even JavaScript and TypeScript websites. Currently, he's acting as the CTO at a number of tech companies in Paris, France.
Andreas Schmid was born in 1985 and started working as a technology consultant in Munich in 2009 after an apprenticeship as an IT specialist and business informatics studies. His passion is creating software and solving difficult IT problems.
In his career, he has participated in Java enterprise projects, contributing to database migrations, expediting the automation of various topics, as well as introducing and coaching new software engineering techniques such as agile software development and test-driven development. It's been over 7 years since he started using it and the relies on continuous integration and delivery as much as possible.
Further, he believes in the advantages of open source software and likes to immerse himself into these tools to get the most out of them. This deep understanding also enables him to contribute by providing patches and fixes in his spare time to further improve these tools.
While being a software engineer and doing things right, he also had the pleasure of being a product owner. In this area, the important question he had to answer was, "Do we do the right things?" So, he also gets his teeth into validated learning for shorter product development cycles.
He likes to be where state-of-the-art software engineering practices and reality collide.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
This book is a practical guide to learning enterprise build systems with Gradle. This book helps you to master the core concepts of the tool and to quickly apply the knowledge to real-life projects. Throughout the book, all the chapters are supported by sufficient examples so that the reader can easily follow and absorb the concepts. The book is divided into 10 chapters. The first six chapters are aimed at gaining knowledge about fundamental topics such as Task, Plugins, Dependency Management, various in-built plugins, and a lot more. The next few chapters cover diverse topics such as Continuous Integration, Migration, and Deployment, which enables readers to learn concepts that are very useful for agile software development. The last chapter of the book focuses on the Android build system with Gradle, which will be useful for mobile developers.
Chapter 1, Getting Started with Gradle, discusses briefly about the build automation system, its needs, and how Gradle can help developers to automate the build and deployment process. Along with the Gradle installation, configuration, and features, this chapter also talks about some important concepts such as the initialization script, the Gradle GUI interface, and the Gradle command-line options.
Chapter 2, Groovy Essentials for Gradle, talks about the fundamental concepts of Groovy programming language. This chapter also discusses the classes, beans, and collection frameworks. This chapter gives the reader a heads up on Groovy, which is required for Gradle.
Chapter 3, Managing Task, discusses Tasks in detail, which is the basic unit of action in Gradle. Developers learn about different flavors of Tasks such as in-built tasks and custom tasks. This chapter also discusses task configurations, task ordering, and task dependencies.
Chapter 4, Plugin Management, talks about one of the important building blocks of Gradle, plugins. The reader will learn to create simple plugins and custom plugins. Also, the user will be able to configure plugins as per his/her needs. This chapter also discusses one of the most usable plugins, the Java plugin, in detail. The user will learn about different conventions supported and how to customize the standard conventions as per the project's/organization's requirements.
Chapter 5, Dependency Management, discusses one of the other important features of Gradle, dependency management, in detail. It discusses the dependency resolution, dependency configuration, and dependency customization. It also discusses repository management. It provides a deep insight of how the user can configure different external repositories, internal repositories, as well as use the local filesystem as a repository.
Chapter 6, Working with Gradle, discusses two additional plugins, War and Scala. It also discusses various topics such as property management, multi-project build, and the logging features. The user will learn about different I/O operations, as well as unit testing features using JUnit and TestNG in Gradle.
Chapter 7, Continuous Integration, talks about the continuous integration concepts and tools such as Jenkins and TeamCity, and their integration with Gradle. It also discusses different code quality plugin (Checkstyle, PMD, and Sonar) integrations with Gradle.
Chapter 8, Migration, fulfills one of the critical requirements of users who are already using other build tools such as Ant or Maven and want to migrate to Gradle. It talks about different migration strategies to convert the existing Ant and Maven scripts to Gradle.
Chapter 9, Deployment, explains the deployment aspect of software engineering. How smoothly the user can automate the deployment process, which saves lots of developer as well as operation team time and efforts. It discusses container-based deployment automation processes and tools; Docker. It gives details about Docker installation, useful Docker commands, and how to integrate Docker with continuous integration tools and Gradle to create a build-deploy-test workflow.
Chapter 10, Building Android Applications with Gradle, talks about mobile application development and deployment. Gradle is an official build tool for Android. This chapter focuses on sample Android application development and different deployment strategies such as deploying the debug version, the release version, deployment on different configurations, and so on.
Your system must have the following software before executing the code mentioned in the book:
If you are a Java developer with some experience in Gradle and want to become an expert, then this book is for you. Basic knowledge of Gradle is essential.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Gradle shares the same JVM options set by the environment variable JAVA_OPTS."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click on OK to add the repository."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Consider a typical IT company development center scenario. Different teams are working together on one enterprise project with many components. Teams are working on server-side technologies, frontend technologies, the messaging layer, mobile development and there may be a separate team responsible for Quality Assurance. Every team is working as per their schedule, developing their own component(s), unit testing and committing code, and this cycle is repeated in multiple iterations. So far, everybody is happy as they are able to meet the deadlines as per the software release dates. Then comes the integration phase, when teams have to build the complete project and deploy the software (which could be WAR, JAR, or any service) to the integration/staging environment. And then the nightmare starts.
Although every team has successfully followed many best practices of software engineering such as committing code on a daily basis, unit testing of code and verifying the working software on a developer's test environment, but in the integration or staging environment the situation has suddenly changed. The team is stuck with configuration and interoperation issues, localization issues, environmental issues, and so on.
This might be a very common scenario for any project and the situation will become worse if they are not using any automated solution for the build and deployment process. Hence the need for an automated process or we can call a Build Automation System (BAS), which automates the manual task of building the project seamlessly and delivers the software in a repeatable, reliable, and portable fashion. BAS doesn't claim that there will be absolutely no issues or errors, but with BAS, the software can be managed in a better way, minimizing the probability of repeating the same error again and again.
Gradle is one of the advanced build automation tools available in the market. In the next 10 chapters, we will explore how to mitigate these problems with Gradle and with other related technologies. However, before we start learning Gradle, we need to understand what a BAS is and why we need it.
The most common processes in building any software include compiling the source files, packaging the compiled output to a compressed format (ZIP, JAR or any other format), and adding the required resource files and configuration files to the packaging. Along with this, it may also include some other activities such as running static code analysis on the source code to provide feedback on the design and coding patterns, and another important area is Quality Assurance, which involves unit testing, integration testing, regression testing, and so on.
A BAS is part of the software life cycle, which automates the build and deployment phases of the software. The first phase is building the software, which is the process of creating the binaries or executables. The second phase is the deployment phase, wherein we need to install the software at a particular location. This phase also includes various other activities such as unpacking the bundle, localization of the software, configuring the software as per the environment and setting the environment-specific properties required to execute the software. The next important step is functional testing to check the behavior of the software. Once everything is fine, it makes a happy and smiley ending for you.
So, as a developer, writing the code and test cases is just one of the major tasks in Software Development Life Cycle (SDLC). Build and deployment is also considered as another important phase in any software life cycle. If it is not managed properly, it could lead to major downtime and client dissatisfaction.
Build automation allows us to automate the manual steps in the build process. It also helps to eliminate the redundant tasks, mitigates the risks of manual intervention, keeps the history of the builds, and saves the cost and time spent in the manual process. The goal here is to create reproducible assets every time you run the build script, which will not be the case, if you manually execute the steps every time.
Many developers relate the build automation with Continuous Integration (CI). Do not get confused. The CI allows executing the build process, performing deployment activities, and many more activities. It helps to create a workflow for build and deployment automation. It also helps to schedule the builds and provides on-demand execution of builds. The schedule could be once in every hour, once in four hours, nightly builds or on every user commit. Some of the well known CI tools are Jenkins, TeamCity, Bamboo, Hudson, Cruise Control, and so on, which are totally different from Build tools, such as Ant, Maven, and Gradle.
Imagine that all the preceding mentioned steps in building a software need to be done manually, and every developer has to perform steps on different machines. Now you can realize the amount of effort wasted in figuring out problems with build issues rather than focusing on the actual business requirements. That's one of the reasons why we need a BAS. Following are some of the major activities, which we automate for the build system:
Another reason to have a BAS is to reduce the operational complexities. If a new member joins the team and he has to perform the manual build of the software, it could be a nightmare for him, if there is no automation. Rather than concentrating on the business requirement, most of his time will be wasted on how to compile it, how to run unit tests, how to execute integration tests, and so on.
Actually, what he needs to know is where to commit the source code, where to put the resources, and what commands to execute to perform the build process. The build process should automatically perform all the tasks of compiling, packaging, running tests, uploading asserts and so on.
The more automated the build and deployment process, the faster you will get the deliverables to the client. It also helps with business continuity. In case of any system crash or network failure, you can rebuild and deploy the software on back up infrastructure in much less time.
Some developers believe that project automation is a waste of time and why should they put in extra effort as their IDE performs this job. They can build the JAR, WAR, or any other deliverable unit with the help of IDE and deploy the same. Since they can build, and test it quickly, it works very well on their local system. The problem starts when integration happens. Thus, an automated system is required to avoid any manual intervention (unless it is the only option left), and to make builds portable, predictable and efficient.
Before getting into the details of Gradle, we need to understand some of the terminologies related to the build system.
There are two types of build tools, namely imperative build tools and declarative build tools. An imperative build tool tells the system what to do and how to do it. In other words, it provides a set of action statements or commands, which the system executes in the same order and performs those actions. You can take Ant as an example of the imperative build system.
Whereas, a declarative build tool instructs the system, telling it what you would like to achieve, and system will figure out how to interpret it. With a declarative approach, the user only needs to determine the what, not the how. This is one of the key innovations Maven brought to the build world, after Ant achieved some popularity, where we don't need to write each and every step of an action, and end up creating a very large and verbose build script. With Maven we need to write some configuration parameters for the build and the build system itself decides how to interpret it. Internally, the declarative layer is based on a powerful imperative layer, which can be accessed directly as required. Ant and Maven are very good and reliable build systems. They are innovative in all the areas for which they were designed and built. Each of them has introduced key innovations into the build space.
Gradle combines the good parts of both tools and provides additional features and uses Groovy as a Domain Specific Language (DSL). It has power and flexibility of Ant tool with Maven features such as build life cycle and ease of use.
Gradle is a general purpose, declarative build tool. It is general purpose because it can be used to build pretty much anything you care to implement in the build script. It is declarative, since you don't want to see lots of code in the build file, which is not readable and less maintainable. So, while Gradle provides the idea of conventions and a simple and declarative build, it also makes the tool adaptable and developers the ability to extend. It also provides an easy way to customize the default behavior and different hooks to add any third-party features.
Primarily, Gradle is a JVM-language build tool, but it also supports C, C++, Android, and so on. You will find more information about this at https://docs.gradle.org/current/userguide/nativeBinaries.html.
It provides automation for the different phases required in a Java project, such as compile, package, execute test cases, and so on. It has grouped its similar automation tasks into plugins. When you import any plugin to a Gradle script file, they always come with a set of predefined tasks. To get started with Gradle, you need to have basic knowledge of Java. It uses Groovy as its scripting language, which is another JVM language. We will discuss Groovy in the next chapter. As the build script is written in Groovy, it tends to be much shorter, expressive, and clearer than those written in Ant or Maven. The amount of boilerplate code is much less in Gradle with use of Groovy DSL. It also leverages Maven conventions for familiarity, while making it easy to customize to the needs of your project. Developers can add new functionality or extend the existing features at any time. They can override the existing tasks or plugins to provide the new functionality.
In the last section, we learned how to install Gradle. Now it's time create our very first Gradle script. This script will print Hello Gradle- This is your first script on the console. Just open a text editor, type in the following three lines, and save the file as build.gradle.
Then execute the gradle helloGradle command as follows:
So, what have we done here?