Gradle in Action (Benjamin Muschko) (Z-Library)
Author: Benjamin Muschko
技术
Gradle in Action is a comprehensive guide to end-to-end project automation with Gradle. Starting with the basics, this practical, easy-to-read book discusses how to build a full-fledged, real-world project. Along the way, it touches on advanced topics like testing, continuous integration, and monitoring code quality. You'll also explore tasks like setting up your target environment and deploying your software.
📄 File Format:
PDF
💾 File Size:
16.0 MB
45
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
M A N N I N G Benjamin Muschko FOREWORD BY Hans Dockter IN ACTION www.it-ebooks.info
📄 Page
2
Gradle in Action BENJAMIN MUSCHKO M A N N I N GSHELTER ISLAND www.it-ebooks.info
📄 Page
3
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: orders@manning.com ©2014 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Jennifer Stout 20 Baldwin Road Copyeditor: Benjamin Berg PO Box 261 Proofreader: Melody Dolab Shelter Island, NY 11964 Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617291302 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 19 18 17 16 15 14 www.it-ebooks.info
📄 Page
4
brief contents PART 1 INTRODUCING GRADLE . ...............................................1 1 ■ Introduction to project automation 3 2 ■ Next-generation builds with Gradle 22 3 ■ Building a Gradle project by example 48 PART 2 MASTERING THE FUNDAMENTALS .................................73 4 ■ Build script essentials 75 5 ■ Dependency management 105 6 ■ Multiproject builds 133 7 ■ Testing with Gradle 157 8 ■ Extending Gradle 191 9 ■ Integration and migration 223 PART 3 FROM BUILD TO DEPLOYMENT ...................................247 10 ■ IDE support and tooling 249 11 ■ Building polyglot projects 282 12 ■ Code quality management and monitoring 310 13 ■ Continuous integration 337 14 ■ Artifact assembly and publishing 359iii 15 ■ Infrastructure provisioning and deployment 395 www.it-ebooks.info
📄 Page
5
www.it-ebooks.info
📄 Page
6
contents foreword xiii preface xv acknowledgments xvii about this book xix about the cover illustration xxiii PART 1 INTRODUCING GRADLE. ....................................1 1 Introduction to project automation 3 1.1 Life without project automation 4 1.2 Benefits of project automation 5 Prevents manual intervention 5 ■ Creates repeatable builds 5 Makes builds portable 6 1.3 Types of project automation 6 On-demand builds 6 ■ Triggered builds 7 Scheduled builds 7 1.4 Build tools 8 What’s a build tool? 9 ■ Anatomy of a build tool 10 1.5 Java build tools 12 Apache Ant 12 ■ Apache Maven 16 ■ Requirements for a next-generation build tool 19v 1.6 Summary 20 www.it-ebooks.info
📄 Page
7
CONTENTSvi 2 Next-generation builds with Gradle 22 2.1 Why Gradle? Why now? 23 Evolution of Java build tools 24 Why you should choose Gradle 26 2.2 Gradle’s compelling feature set 28 Expressive build language and deep API 29 Gradle is Groovy 30 ■ Flexible conventions 31 Robust and powerful dependency management 32 Scalable builds 33 ■ Effortless extendibility 34 Integration with other build tools 34 ■ Community-driven and company-backed 35 ■ Icing on the cake: additional features 35 2.3 The bigger picture: continuous delivery 36 Automating your project from build to deployment 36 2.4 Installing Gradle 38 2.5 Getting started with Gradle 40 2.6 Using the Command line 42 Listing available tasks of a project 42 ■ Task execution 43 Command-line options 45 ■ Gradle daemon 46 2.7 Summary 47 3 Building a Gradle project by example 48 3.1 Introducing the case study 49 The To Do application 49 ■ Task management use cases 49 Examining the component interaction 50 ■ Building the application’s functionality 51 3.2 Building a Java project 54 Using the Java plugin 54 ■ Customizing your project 58 Configuring and using external dependencies 59 3.3 Web development with Gradle 61 Adding web components 61 ■ Using the War and Jetty plugins 63 3.4 Gradle wrapper 68 Setting up the wrapper 69 ■ Using the wrapper 70 Customizing the wrapper 71 3.5 Summary 72www.it-ebooks.info
📄 Page
8
CONTENTS vii PART 2 MASTERING THE FUNDAMENTALS .....................73 4 Build script essentials 75 4.1 Building blocks 76 Projects 76 ■ Tasks 78 ■ Properties 79 4.2 Working with tasks 80 Managing the project version 80 ■ Declaring task actions 81 Accessing DefaultTask properties 82 ■ Defining task dependencies 83 ■ Finalizer tasks 84 ■ Adding arbitrary code 85 ■ Understanding task configuration 85 Declaring task inputs and outputs 88 ■ Writing and using a custom task 90 ■ Gradle’s built-in task types 92 Task rules 95 ■ Building code in buildSrc directory 98 4.3 Hooking into the build lifecycle 99 Hooking into the task execution graph 101 ■ Implementing a task execution graph listener 101 ■ Initializing the build environment 103 4.4 Summary 104 5 Dependency management 105 5.1 A quick overview of dependency management 106 Imperfect dependency management techniques 106 Importance of automated dependency management 107 Using automated dependency management 108 Challenges of automated dependency management 109 5.2 Learning dependency management by example 110 5.3 Dependency configurations 111 Understanding the configuration API representation 111 Defining a custom configuration 112 Accessing a configuration 113 5.4 Declaring dependencies 114 Understanding the dependency API representation 114 External module dependencies 115 ■ File dependencies 120 5.5 Using and configuring repositories 121 Understanding the repository API representation 121 Maven repositories 121 ■ Ivy repositories 124 Flat directory repositories 125www.it-ebooks.info
📄 Page
9
CONTENTSviii 5.6 Understanding the local dependency cache 126 Analyzing the cache structure 126 Notable caching features 127 5.7 Troubleshooting dependency problems 128 Responding to version conflicts 128 ■ Enforcing a specific version 129 ■ Using the dependency insight report 130 Refreshing the cache 130 5.8 Summary 131 6 Multiproject builds 133 6.1 Modularizing a project 134 Coupling and cohesion 134 ■ Identifying modules 135 Refactoring to modules 136 6.2 Assembling a multiproject build 137 Introducing the settings file 138 ■ Understanding the Settings API representation 139 ■ Settings execution 140 Settings file resolution 140 ■ Hierarchical versus flat layout 141 6.3 Configuring subprojects 142 Understanding the Project API representation 143 Defining specific behavior 144 ■ Declaring project dependencies 145 ■ Partial multiproject builds 147 Declaring cross-project task dependencies 149 Defining common behavior 151 6.4 Individual project files 152 Creating build files per project 153 ■ Defining the root project’s build code 153 ■ Defining the subprojects’ build code 153 6.5 Customizing projects 154 6.6 Summary 155 7 Testing with Gradle 157 7.1 Automated testing 158 Types of automated testing 158 ■ Test automation pyramid 159 7.2 Testing Java applications 159 Project layout 160 ■ Test configurations 161 Test tasks 161 ■ Automatic test detection 162 7.3 Unit testing 162 Using JUnit 162 ■ Using alternative unit testing frameworks 166 ■ Multiple unit testing frameworks in harmony 168 www.it-ebooks.info
📄 Page
10
CONTENTS ix 7.4 Configuring test execution 170 Command-line options 171 ■ Understanding the Test API representation 171 ■ Controlling runtime behavior 172 Controlling test logging 174 ■ Parallel test execution 175 Reacting to test lifecycle events 176 ■ Implementing a test listener 177 7.5 Integration testing 178 Introducing the case study 178 ■ Writing the test class 179 Supporting integration tests in the build 180 Establishing conventions for integration tests 181 Bootstrapping the test environment 183 7.6 Functional testing 184 Introducing the case study 184 ■ Supporting functional tests in the build 185 7.7 Summary 190 8 Extending Gradle 191 8.1 Introducing the plugin case study 192 Application management in the cloud with Gradle 192 Setting up the cloud environment 193 8.2 From zero to plugin 196 8.3 Writing a script plugin 197 Adding the CloudBees API library 197 Using the CloudBees API from tasks 198 8.4 Writing custom task classes 201 Custom task implementation options 202 Defining a custom task in buildSrc 202 8.5 Using and building object plugins 209 Applying object plugins 210 ■ Anatomy of an object plugin 212 Writing an object plugin 213 ■ Plugin extension mechanism 214 ■ Assigning a meaningful plugin name 217 Testing an object plugin 217 ■ Developing and consuming a standalone object plugin 218 8.6 Summary 221 9 Integration and migration 223 9.1 Ant and Gradle 224 Using Ant script functionality from Gradle 225 ■ Using standard Ant tasks from Gradle 231 ■ Migration strategies 233 www.it-ebooks.info
📄 Page
11
CONTENTSx 9.2 Maven and Gradle 236 Commonalities and differences 236 ■ Migration strategies 240 9.3 Comparing builds 243 9.4 Summary 245 PART 3 FROM BUILD TO DEPLOYMENT........................247 10 IDE support and tooling 249 10.1 Using IDE plugins to generate project files 250 Using the Eclipse plugins 251 ■ Using the IDEA plugin 258 Using the Sublime Text plugin 264 10.2 Managing Gradle projects in popular IDEs 267 Gradle support in SpringSource STS 268 ■ Gradle support in IntelliJ IDEA 271 ■ Gradle support in NetBeans IDE 274 10.3 Embedding Gradle with the tooling API 277 10.4 Summary 281 11 Building polyglot projects 282 11.1 Managing JavaScript with Gradle 283 Typical tasks when dealing with JavaScript 283 Using JavaScript in the To Do application 284 Dependency management for JavaScript libraries 285 Merging and minifying JavaScript using a third-party Ant task 287 ■ JavaScript optimization as part of the development workflow 289 ■ JavaScript code analysis using an external Java library 290 ■ Using a third-party Gradle JavaScript plugin 292 ■ Executing Grunt from Gradle 293 11.2 Building polyglot, JVM-based projects 296 Base capabilities of JVM language plugins 296 Building Groovy projects 298 ■ Building Scala projects 303 11.3 Other languages 307 11.4 Summary 308 12 Code quality management and monitoring 310 12.1 Integrating code analysis into your build 311 12.2 Measuring code coverage 312 Exploring code coverage tools 313 ■ Using the JaCoCo plugin 315 ■ Using the Cobertura plugin 317 www.it-ebooks.info
📄 Page
12
CONTENTS xi 12.3 Performing static code analysis 319 Exploring static code analysis tools 320 ■ Using the Checkstyle plugin 322 ■ Using the PMD plugin 324 Using the FindBugs plugin 326 ■ Using the JDepend plugin 327 12.4 Integrating with Sonar 328 Installing and running Sonar 330 ■ Analyzing a project with Sonar Runner 331 ■ Publishing code coverage metrics to Sonar 333 12.5 Summary 336 13 Continuous integration 337 13.1 Benefits of continuous integration 338 13.2 Setting up Git 340 Creating a GitHub account 340 ■ Forking the GitHub repository 341 ■ Installing and configuring Git 341 13.3 Building a project with Jenkins 342 Starting Jenkins 342 ■ Installing the Git and Gradle plugins 342 ■ Defining the build job 344 Executing the build job 347 ■ Adding test reporting 348 13.4 Exploring cloud-based solutions 351 13.5 Modeling a build pipeline with Jenkins 352 Challenges of building a pipeline 352 ■ Exploring essential Jenkins plugins 353 ■ Configuring the pipeline jobs 356 13.6 Summary 358 14 Artifact assembly and publishing 359 14.1 Building artifacts and distributions 360 Declaring additional artifacts 361 ■ Creating distributions 363 14.2 Publishing artifacts to a binary repository 366 Publishing to a Maven repository 366 ■ Old versus new publishing mechanisms 368 ■ Declaring a software component as a Maven publication 368 ■ Publishing a software component to the local Maven cache 369 ■ Declaring custom artifacts for publication 372 ■ Modifying the generated POM 373 Publishing to a local Maven repository 375 ■ Publishing to a remote Maven repository 377 14.3 Publishing to a public binary repository 379 Publishing to JFrog Bintray 380 ■ Publishing to Maven Central 383 www.it-ebooks.info
📄 Page
13
CONTENTSxii 14.4 Artifact assembly and publishing as part of the build pipeline 385 Build binaries once 385 ■ Publish once, reuse later 385 Picking an appropriate versioning scheme 387 Including build information in a deployable artifact 390 Publishing your To Do application WAR file 391 Extending the build pipeline 392 14.5 Summary 393 15 Infrastructure provisioning and deployment 395 15.1 Infrastructure provisioning 396 Infrastructure as code 396 ■ Creating a virtual machine with Vagrant and Puppet 397 ■ Executing Vagrant from Gradle 399 15.2 Targeting a deployment environment 401 Defining configuration in a Groovy script 401 ■ Reading the configuration with Groovy’s ConfigSlurper 403 ■ Using the configuration throughout the build 404 15.3 Automated deployments 405 Retrieving the artifact from the binary repository 405 Identifying necessary deployment steps 407 Deployment through SSH commands 407 15.4 Deployment tests 412 Verifying a successful deployment with smoke tests 412 Verifying application functionality with acceptance tests 415 15.5 Deployment as part of the build pipeline 416 Automatic deployment to test environment 417 Deployment tests 417 ■ On-demand deployment to UAT and production environment 418 15.6 Summary 419 appendix A Driving the command line 421 appendix B Groovy for Gradle users 429 index 440www.it-ebooks.info
📄 Page
14
foreword When you create a new technology like Gradle, one of the most critical stages of development has nothing to do with writing code. Once the initial versions of your project are used by thousands of developers and a community starts to assemble around it, the challenge becomes communicating with a much larger audience of users who will use the project and pass judgment on its merits, and growing the size of the community ten-fold or a thousand-fold. Gradle has already amassed a large audience, and we’ve seen tremendous growth over the last two years, but we’re getting ready for a still larger influx of end-users. Therefore, the importance of having a good book cannot be overstated. Devel- opers with a range of skills and abilities need to be able to pick up a book that’s easy to understand and which can impart both the syntax and the philosophy behind the tool. Only then will they be able to confidently grow the community that can educate itself using a single, authoritative reference for Gradle. Gradle in Action is that book. Additionally, this book gives new Gradle users a very good glimpse into how Gradle fits into a larger view of continuous delivery. Benjamin is the sort of expert that you hope emerges from an open source community. He has been a long term Gradle contributor and is the author of several popular Gradle plugins. He’s both a communicator and a developer. Ben- jamin has the rare ability to dive into the core details of a particularly challeng- ing development problem and then explain the tool to end-users. We’re happy that he has recently joined Gradleware and is now part of the Gradle develop- ment team.xiii www.it-ebooks.info
📄 Page
15
FOREWORDxiv I hope you enjoy the book as well as working with Gradle. May your software delivery process become both fun and efficient. HANS DOCKTER FOUNDER OF GRADLE AND GRADLEWAREwww.it-ebooks.info
📄 Page
16
preface When I started my career as a software developer, I was blissfully unaware of the need for project automation. My tool of choice was the IDE, which allowed me to run all tasks required to fully automate my software development cycle. In 2003 Rainer Sawitzki,1 an external consultant to the project I was working on, introduced me to Apache Ant. I thought it was the most amazing thing to be able to describe my auto- mation logic with the help of mostly pre-existing functionality and to execute it in a defined order. Despite the fact that the definition language was XML (these were the days when XML was still fashionable), I soon began to become more ambitious by cre- ating artifacts for different target platforms, writing deployment logic for web contain- ers, and setting up a continuous integration server. Automation requirements have changed significantly since then. My projects have grown in size and complexity. Deployment and delivery models have become far more sophisticated. And while I explored other build tool options to meet these needs over the years, I found that there was always a Catch-22. Many developers accepted the sta- tus quo in this space, which left them with painful experiences. Rarely is there a topic that’s discussed more religiously2 than the pros and cons of build tools and why peo- ple hate them so much. The purpose of this book isn’t necessarily to convince you to switch your current build to Gradle. If you’re happy with your setup (whatever you’re 1 Thanks again for the object-oriented mindset I picked up by working with you. You’ve been a great mentor to me.xv 2 This topic is on par with Windows versus Linux or the comparison of web application frameworks. www.it-ebooks.info
📄 Page
17
PREFACExvi using), by all means, stick to it. I will, however, talk about the massive innovation that Gradle brings to the table and compare it to existing solutions. I invite you to be your own judge. I started to write this book with a specific goal in mind: teach the core concepts of Gradle, but don’t stop there. In a world that embraces software development practices like continuous integration and delivery, you have to take into consideration the tool- ing ecosystem into which a build system must integrate. Hopefully, I’ve found the right balance in this book. If you have questions, comments, or ideas, I’d love to hear them. Your feedback might spark the urge to write a second edition or add-on con- tent. Feel free to send me an email or contact me on the book’s forum at Manning. As with all book projects, the page count is limited. To stick to the scope of this book, I had to leave out some of the content I initially planned to write. (This is my first book. With the naiveté of a virgin author, I thought I could fit it all in.) The source code repository of the book, found at https://github.com/bmuschko/gradle- in-action-source, expands on some of this material and lists references to other code examples and resources. I hope you enjoy reading the book as much as I enjoyed writing it.www.it-ebooks.info
📄 Page
18
acknowledgments When thinking about writing a book, you have no idea how much work it’s going to be. It’s safe to say that it literally controls your life for an extended period of time. After a while, the writing part becomes easier. The hard part is to start writing every day. This wouldn’t have been possible without the support, encouragement, and help of others. In 2010, I started to evaluate Gradle for the first time as a replacement for a Maven project for a previous employer. I probably wouldn’t have done that without the spike initiated by Jonathan Bodner, a long-term acquaintance, whom I deeply admire for his technical insight. He started me on my way to getting excited about Gradle, becoming deeply involved with its community, and writing plugins of my own. I’ve been a technical reviewer for books published by Manning for many years before writing my own. It started when I met Dan Allen, the author of Seam in Action (Manning, 2008), at one of the No Fluff Just Stuff conferences. After chatting with me for a while, he quickly got me excited about his endeavors and I offered to help him by reviewing his book. My engagement got me a first glimpse of what it means to write a book. I had always wanted to write a book, but never found the appropriate time or topic to jump on it. With Gradle, it just felt right. Thanks, Dan, for your enthusiasm that inspired me to carry on the torch and make it my own. One of the first things you do before writing a book is put together the outline and table of contents. The first person I showed the draft to was David James, the orga- nizer of the Washington DC–area Groovy user group. Thanks for your outside per- spective on the organization of the book, your meticulous attention to detail, and your strong encouragement to make the book a reality.xvii www.it-ebooks.info
📄 Page
19
ACKNOWLEDGMENTSxviii No commercial book is published without many people in the background. This goes out to everyone involved in the process at Manning Publications. Michael Stephens, who I talked to first, bought into the idea of this book and ultimately trusted me to do a good job. My gratitude also goes to Cynthia Kane, who helped me to find my writing style. I’d also like to thank Jennifer Stout, my development editor, who always tried to get the best out of me, made me think about whole text passages in a different way, and tolerated my impatience. You’ve been a great help. Thanks also to the whole Manning production and marketing team for guidance along the way and for making the book what it is now. I know you did a tremendous amount of work. I’d also like to thank the members of the Gradleware team, as well as the Gradle community, for creating Gradle and pushing the boundaries of build automation. Your continued effort and belief in a high-quality product improves the life of many disgruntled build masters around the globe. Special thanks go out to René Gröschke and Luke Daley for their technical insight and their review of the first third of the book. I am also grateful to Hans Dockter, the founder of Gradle, for contributing the foreword and endorsing this book in its early stages, and for the continued promotion through Gradleware. Thanks to the following reviewers of the manuscript who provided invaluable feed- back and gave me a different perspective on the content: Andy Keffalas, BJ Peter DeLaCruz, Chris Grijalva, Chris Nauroth, Dominik Helleberg, Eric Wendelin, Iain Starks, John Moses, Jon Bodner, Marcin Nowina-Krowicki, Mayur S. Patil, Mehrdad Karjoo, Mohd Suhaizal Md Kamari, Nacho Ormeño, Nick Watts, Pawel Dolega, Rob Bugh, Robin Percy, Samuel Brown, Scott Bennett-McLeish, Steve Dickson, Tarin Gamberini, Wellington R. Pinheiro, and Zekai Otles. Thanks also to Barry Kern for his careful technical proofread of the manuscript shortly before it went into production. Special thanks to Spencer Allain, Jonathan Keam, and Robert Wenner for thor- oughly reading every chapter of the book and providing me with line-by-line edits and comments at different stages of development; Michael McGarr and Samuel Brown for bouncing around ideas that involved content on continuous delivery and DevOps; and Baruch Sadogursky from JFrog for the technical review of chapter 14 and for pro- moting the book even before it was released. I also wish to thank the relentless Author Online forum participants for pushing the content to the next level. Writing a book requires making sacrifices and puts tremendous strain on personal relationships. I would like to thank my family and friends for being supportive, encouraging, and understanding while I’ve worked toward completing this ambitious goal. And, yes, there will be time for hanging out without me thinking about the con- tent of the current chapter. I’m deeply grateful to my wife Sarah for her unending support and optimism. You pushed me to believe in myself, made me take breaks from writing, and tolerated me falling asleep before 9:00 p.m. most days. Without you, the writing process would have been far more grueling than it was.www.it-ebooks.info
📄 Page
20
about this book Roadmap This book is divided into three parts. The first part gives an introduction to Gradle’s concepts and philosophy, explaining how it compares to other build tools and how to write scripts to automate simple tasks. Part two explores the tool’s building blocks and core techniques in greater depth. You should be able to use this knowledge to imple- ment complex, extendable, enterprise builds. The third part describes how Gradle can be used in the context of continuous deliver, focusing on topics like polyglot builds, code quality, artifact assembly, and deployment. The chapters in part 1, Introducing Gradle, are as follows: 1 Introduction to project automation—This chapter gives a gentle introduction into why it’s a good idea to automate your projects and how build tools can help get the job done. 2 Next generation builds with Gradle—How does Gradle compare to existing JVM- language build tools? This chapter covers Gradle’s extensive feature set and how it helps automate your software delivery process in the context of a Contin- uous Delivery deployment pipeline. As a first taste, you’ll write a simple build script and run it on the command line. 3 Building a Gradle project by example—This chapter introduces a Java-based web application as a vehicle to demonstrate some of Gradle’s core features. We’ll explore the use of the Java plugin for standardized and nonconventional use cases and examine productivity tools for fast development turnaround.xix www.it-ebooks.info
The above is a preview of the first 20 pages. Register to read the complete e-book.