Mastering GradleMaster the technique of developing, migrating,and building automation using GradleMainak MitraBIRMINGHAM - MUMBAI
Mastering GradleCopyright 2015 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrievalsystem, or transmitted in any form or by any means, without the prior writtenpermission of the publisher, except in the case of brief quotations embedded incritical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracyof the information presented. However, the information contained in this book issold without warranty, either express or implied. Neither the author, nor PacktPublishing, and its dealers and distributors will be held liable for any damagescaused or alleged to be caused directly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies 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 2015Production reference: 1280715Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirmingham B3 2PB, UK.ISBN 978-1-78398-136-6www.packtpub.com
CreditsAuthorMainak MitraReviewersAlexander BarnesProject CoordinatorMilton DsouzaProofreaderSafis EditingScott BattagliaMichael PuttersAndreas SchmidCommissioning EditorAmarabha BanerjeeAcquisition EditorNadeem N. BagbanContent Development EditorParita KhedekarTechnical EditorNamrata PatilCopy EditorsMario CecéreKausambhi MajumdarAngad SinghLaxmi SubramanianIndexerRekha NairGraphicsJason MonteiroProduction CoordinatorAparna BhagatCover WorkAparna Bhagat
About the AuthorMainak Mitra is a software developer who has rich experience in enterprisesoftware development and automation frameworks. He is an electrical engineer fromJadavpur University, Kolkata. He is currently working for an online gaming company.Prior to this, he worked for various product development companies, such as YahooInc., CA Technologies. He can be contacted at [email protected], I would like to thank the Gradle team for creating such arobust build automation tool. This book would not exist withoutthis open source tool.I would also like to thank the editors at Packt Publishing, whoinspired and helped me to write this book. The Packt Publishingteam, especially Parita and Namrata, provided insightful feedbackto help me.Before this book reached you, it was reviewed by many people atdifferent stages. Without their comments, feedback, and criticism,this book would not have been possible. I acknowledge the peopleinvolved here: Alexander Barnes, Scott Battaglia, Michael Putters,Andreas Schmid.Special thanks goes to my friend Abhinandan for his contribution tothis book and for compromising his weekends for me. He reviewedall the chapters in this book and guided me in writing most of thetopics. Without his expertise and support, this book would not havebeen possible.
About the ReviewersAlexander Barnes has been a professional software engineer for over 5 yearsafter graduating summa from the Texas A&M class of '09 with a BS in computerengineering 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 playeda leading role in developing the RESTful User Data Services (UDS) for theCallManager product and helped develop and maintain the administration anduser portals. He pioneered the transformation of his team's build system from Antto Gradle for the numerous project tools and utilities maintained by the team andbecame a subject-matter expert on Git, Gradle, and Linux in particular.Alex decided to move closer to his family, recently joining Novo Dia Group inAustin as a senior Java developer. He is an avid advocate of best software practicesand 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 developfreely, refactor to consistent design patterns as appropriate, and focus on reducingmutable states. Alex occasionally blogs about technologies and other interests on hiswebsite at http://toastedbits.com/.Alex enjoys pursuing other creative hobbies in his spare time; playing his guitar andlistening to a lot of rock, metal, and electronic music. He also wishes to pick up pianoand music production techniques to create his own electronic tracks in the future. Heis 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 theirlove and encouragement to achieve my dreams. Also, thanks tothe Electronic Frontier Foundation, GNU, and Apache SoftwareFoundation for making our software world a much more respectfulcommunity.
Andreas Schmid was born in 1985 and started working as a technology consultantin Munich in 2009 after an apprenticeship as an IT specialist and business informaticsstudies. His passion is creating software and solving difficult IT problems.In his career, he has participated in Java enterprise projects, contributing to databasemigrations, expediting the automation of various topics, as well as introducing andcoaching new software engineering techniques such as agile software developmentand test-driven development. It's been over 7 years since he started using it and therelies on continuous integration and delivery as much as possible.Further, he believes in the advantages of open source software and likes to immersehimself into these tools to get the most out of them. This deep understanding alsoenables him to contribute by providing patches and fixes in his spare time to furtherimprove these tools.While being a software engineer and doing things right, he also had the pleasure ofbeing 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 forshorter product development cycles.He likes to be where state-of-the-art software engineering practices and reality collide.
www.PacktPub.comSupport files, eBooks, discount offers, and moreFor 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 PDFand 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, signup for a range of free newsletters and receive exclusive discounts and offers onPackt books and ion/packtlibDo you need instant solutions to your IT questions? PacktLib is Packt's online digitalbook library. Here, you can search, access, and read Packt's entire library of books.Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browserFree access for Packt account holdersIf you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view 9 entirely free books. Simply use your login credentials forimmediate access.
Table of ContentsPrefaceChapter 1: Getting Started with Gradlevii1Understanding Build Automation SystemNeed for BASGradle overviewInstallation and quick startPre-requisitesGradle for WindowsGradle for Mac/LinuxThe Gradle JVM optionOur first scriptGradle command Line argumentsThe Gradle GUIStart up scriptBuild life cycleInitializationConfigurationExecutionCache managementCache locationChange Cache locationCache features234556777913151717181818191919Reduce the trafficDependency locationVersion integrationSwitching off remote checkingVersion conflicts1920202020[i]
Table of ContentsGradle with IDEInstalling the Gradle plugin in EclipseWorking with the Gradle project in IDESummaryChapter 2: Groovy Essentials for GradleOverviewMinimum codeSimpler I/O operationsIntegration with AntBuilder classesClosureGroovy script for Hello WorldData typesString2021222729293030303031313233Dynamic typing in Groovy34Classes, beans, and methodsControl structuresThe if-else conditionThe switch lderSummary36383839394040414243444849Chapter 3: Managing Task51Build script basicsTask configurationTask executionTask dependencyTask orderingTask operationsConditional executionBuild optimizationTask rules515556575861626466[ ii ]
Table of ContentsGradle's in-built tasksThe Copy TaskThe Rename TaskThe Zip taskCustom tasksUsing buildSrcThe standalone taskSummary6868686869717274Chapter 4: Plugin Management75The script pluginThe binary pluginGradle's in-built pluginsBuild and Test pluginsCode analysis pluginsIDE pluginsThe Java pluginConventionsConfigurationThe custom pluginThe build fileThe buildSrc directoryThe Standalone projectSummary7577777878787979848687889095Chapter 5: Dependency ManagementOverviewDependency configurationsDependency typesRepositoriesRepositories configurationDependency resolutionTransitive dependencyExclude transitivenessSelective excludeVersion conflictsDynamic dependencyCustomizing the dependencyDownload file other than JARDependency on files with classifiersReplacing transitive dependencies[ iii ]97979898100101103103104104105107107107108108
Table of ContentsCustom configuration for dependencyDependency reportsDependency-specific details108109112Publishing artifactsDefault artifactsCustom artifacts112113114Generate additional XML file along with your JAR fileGenerate an additional ZIP file along with your JAR fileCustom configurationThe maven-publish plugins114115116117Publishing to the local-hosted repositoryCustom POM120121Summary122Chapter 6: Working with Gradle123The War pluginThe Scala pluginLoggingFile managementReading filesWriting filesCreating files/directoriesFile operationsFilter filesDelete files and directoriesFileTreeProperty managementext closuregradle.propertiesThe command lineThe Custom properties fileMulti-project buildThe Multi-project structureThe Multi-project executionTask executionThe Flat hierarchyInterproject dependencyConfiguration-level dependencyTask-level dependencyLibrary 39140140142142144146148149149151152[ iv ]
Table of ContentsPartial buildsbuildDependentsbuildNeededTesting with GradleJUnit153153154155155Test configuration157TestNG162Execution based on groupExecution based on the TestNG suite file163164Summary165Chapter 7: Continuous IntegrationJenkins walk-throughJenkins installationJenkins configurationCreate jobExecute jobCheckstyle and PMD pluginsThe Sonar Runner pluginTeamCity hapter 8: Migration189Migration from AntImporting Ant file189190Accessing propertiesUpdate Ant tasks193194Using AntBuilder APIRewriting to Gradle195198Configuration201Migration from MavenBuild filename and project propertiesPropertiesDependency managementExclude transitive204205205206207Plugin declarationRepository configurationMulti-module declarationDefault valuesGradle init PluginSummary207208209210210212[v]
Table of ContentsChapter 9: Deployment213Role of Gradle in deploymentDocker overviewInstalling DockerDocker commandsHelp commandDownload imageThe list of imagesCreating a containerThe container listStart/stop containerConnecting to a containerDeleting a containerRemoving an imageCopying files to the containerContainer detailsUpdating DNS settingsCreating an image from a containerRunning an application in DockerBuild, Deployment, and Test pipelineSummaryChapter 10: Building Android Applications with GradleCreating Android project using Android StudioBuilding the Android project with GradlebuildTypesProGuard settingsBuild flavorsRunning the application on a device/emulatorSigning the release 252253255[ vi ]
PrefaceThis 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 applythe knowledge to real-life projects. Throughout the book, all the chapters aresupported by sufficient examples so that the reader can easily follow and absorb theconcepts. The book is divided into 10 chapters. The first six chapters are aimed atgaining knowledge about fundame