Gradle Essentials - Abhinandan Maheshwari - E-Book

Gradle Essentials E-Book

Abhinandan Maheshwari

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Gradle is an advanced and modern build automation tool. It inherits the best elements of the past generation of build tools, but it also differs and innovates to bring terseness, elegance, simplicity, and the flexibility to build.

Right from installing Gradle and writing your first build file to creating a fully-fledged multi-module project build, this book will guide you through its topics in a step-by-step fashion.
You will get your hands dirty with a simple Java project built with Gradle and go on to build web applications that are run with Jetty or Tomcat. We take a unique approach towards explaining the DSL using the Gradle API, which makes the DSL more accessible and intuitive.
All in all, this book is a concise guide to help you decipher the Gradle build files, covering the essential topics that are most useful in real-world projects. With every chapter, you will learn a new topic and be able to readily implement your build files.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 188

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Gradle Essentials
Credits
About the Authors
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Running Your First Gradle Task
Installing Gradle
Installing manually
Installing on Mac OS X and Linux
Installing on Windows
Alternate methods of installing Gradle
Installing via OS-specific package managers
Mac OS X
Linux (Ubuntu)
Windows
Installing via SDKMAN
Verifying the installation
Setting JVM options
The Gradle command-line interface
The first Gradle build script
Task name abbreviation
Gradle Daemon
Gradle Wrapper
Generating wrapper files
Running a build via wrapper
Summary
2. Building Java Projects
Building a simple Java project
Creating a build file
Adding source files
Building the project
A brief introduction to plugins
Unit testing
Adding a unit test source
Adding the JUnit to the classpath
Running the test
Viewing test reports
Fitting tests in the workflow
Bundling an application distributable
Running the application with Gradle
Building the distribution archive
Generating IDE project files
Summary
3. Building a Web Application
Building a simple Java web project
Creating source files
Creating a build file
Building the artifact
Running the web application
Plugins to the rescue
References
Project dependencies
External libraries
The dynamic version
Transitive dependencies
Dependency configurations
Repositories
Summary
4. Demystifying Build Scripts
Groovy for Gradle build scripts
Why Groovy?
Groovy primer
Running Groovy code
Variables
Strings
Regular expressions
Closures
Data structures
List
Set
Map
Methods
Calling methods
Default values of parameters
Methods with map parameters/named parameters
Methods with varags
Methods with closure params
Classes
Constructors
Properties
Instance methods
Another look at applying plugins
Gradle – an object-oriented build tool
Build phases
Initialization
Configuration
Execution
Life cycle callbacks
Gradle Project API
Project methods
Project properties
Extra properties on a project
Tasks
Attaching actions to a task
Task flow control
dependsOn
finalizedBy
onlyIf
mustRunAfter and shouldRunAfter
Creating tasks dynamically
Setting default tasks
Task types
Using task types
Creating task types
References
Groovy
Gradle API and DSL used in this chapter
Summary
5. Multiprojects Build
The multiproject directory layout
The settings.gradle file
Organizing build logic in multiproject builds
Applying a build logic to all projects
Applying build logic to subprojects
Dependency on subprojects
Summary
6. The Real-world Project with Gradle
Migrating from an Ant-based project
Importing an Ant file
Using AntBuilder API
Rewriting Ant tasks to Gradle tasks
Migrating from a Maven project
Publishing artifacts
Continuous Integration
Generating documentation
Summary
7. Testing and Reporting with Gradle
Testing with TestNG
Integration testing
Code coverage
Code analysis reports
Summary
8. Organizing Build Logic and Plugins
Extracting build logic to buildSrc
The first plugin
Configuring plugins
Summary
9. Polyglot Projects
The polyglot application
Building Groovy projects
Building Scala projects
Joint compilation
References
Summary
Index

Gradle Essentials

Gradle Essentials

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 authors, 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: December 2015

Production reference: 1161215

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-236-3

www.packtpub.com

Credits

Authors

Kunal Dabir

Abhinandan

Reviewers

Eric Berry

André Burgaud

Michał Huniewicz

Fredrik Sandell

Commissioning Editor

Amarabha Banerjee

Acquisition Editors

Richard Brookes-Bland

Larissa Pinto

Content Development Editor

Rashmi Suvarna

Technical Editor

Madhunikita Sunil Chindarkar

Copy Editor

Trishya Hajare

Project Coordinator

Izzat Contractor

Proofreader

Safis Editing

Indexer

Hemangini Bari

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Authors

Kunal Dabir has over 10 years of experience working with clients ranging from Fortune 500 companies to startups. Currently, he works as a Lead Consultant at ThoughtWorks. He is a Java user group's co-organizer and speaks at various meet-ups and conferences.

While he is always eager to learn a new language, he usually codes in languages such as Groovy, Scala, JavaScript, CoffeeScript, Ruby, and Java. He frequently contributes to open source projects and also hosts his own projects on GitHub.

He has always been passionate about automating and scripting. From there, he got a knack for build tools. Apart from Gradle, he has spent a fair amount of time writing build scripts with tools such as Ant, Maven, Grunt, and Gulp. He was introduced to Gradle in 2011 while using Gaelyk. Since then, Gradle has become his tool of choice for build automation.

He can be found on Twitter and GitHub as @kdabir.

Acknowledgments

First and foremost, a big thanks to my loving wife, Smita, and adorable son, Nairit. Both of them patiently tolerated me spending countless hours in front of my Mac and never complained. I would like to thank my parents for always doing everything that they could so that I could do what I like. I dedicate this book to Smita, Nairit, Aai, and Baba.

This book would not have been possible without Packt's trust in me. I would like to thank the editors and coordinators from Packt, including Richard, Parita, Priyanka, Rashmi, Madhunikita, and many more. I would also like to thank Abhinandan for providing a helping hand with the project at the time it was required the most. Also, heartfelt thanks to all the reviewers, André Burgaud, Eric Berry, Fredrik Sandell, and Michał Huniewicz, for painstakingly reviewing all the chapters and providing detailed feedback.

I am grateful to ThoughtWorks for being such an amazing place where I learned so many things.

Last but not the least, this acknowledgement can not be complete without thanking the folks who made Gradle so awesome, those who built and maintained Groovy, and the Groovy community. Kudos to all for the hard work.

Abhinandan is a Java guy with an extensive experience in software design, architecture, and deployment and automation frameworks. He is passionate about providing solutions for different business needs. His other passions include hiking, reading, and travelling. You can contact him at <[email protected]>.

Like how a film cannot be made with just actors and directors—it requires lots of different team members' help, who support at different stages until the movie gets released— a book can't be written with just the effort of one person or the author. It requires lots of support from different people at different stages, without which it would not be possible to put the thoughts on paper and make it available to the audience.

First and foremost, I would like to thank my family for all the support they gave me throughout this book. They never complained about the weekends and vacations that I compromised while working on this book.

I would like to express my gratitude to the Packt Publishing team (Parita, Purav, and Rashmi), who provided support from the initiation of the idea until the publication of the book. I appreciate that they believed in me and provided me the opportunity to become the co-author of this book.

I would like to thank the reviewers who helped me to improve the quality of this book.

Thanks to Mainak for the quality input and comments, which helped to complete this book. I could not have done it without you.

About the Reviewers

Eric Berry is the co-founder and vice president of engineering at Keeply Inc. He graduated in 2003 from Cal Poly Pomona with a BS in computer science, and has more than 11 years of full-stack development experience working for Evite (http://www.evite.com/), eHarmony (http://www.eharmony.com/), and Chegg (http://www.chegg.com/). He was first introduced to Gradle in late 2010 while working at eHarmony, and created Chegg's middle-tier SOA using Gradle for all Java-based projects. As a supporter of open source software, he's the plugin release manager for the jEdit text editor and also the original author of the Gradle-release and Gradle-templates plugins.

He has worked as a senior software engineer at Evite specializing in full-stack, JSP, Servlet, Spring Framework, Hibernate, "web-2.0" JavaScript based frontend.

He has also worked as a senior software engineer at eHarmony specializing in full-stack, Java, Spring, Struts, Groovy, Spring Integration, Jersey.

He has worked as a lead software engineer at Chegg specializing in backend services, Java, Spring, Hibernate, Gradle, Jersey.

André Burgaud is a software engineer who is passionate about new technologies, programming languages in general, and Python in particular.

He started in law enforcement where he built up an interest in security. A career change led him to join the telecommunication department of the Gendarmerie headquarters in France; later, he implemented network management systems for Qwest broadband services in Minnesota, USA. He currently leads a software development department at Infinite Campus, focusing on the infrastructure for complex web applications.

During his spare time, he attempts to quench his thirst for technology by exploring programming languages, tools, operating systems, servers, or cloud services; also, he likes attending local meetups or online classes, listening to podcasts, and reading books.

Michał Huniewicz is a London-based professional software developer, amateur photo journalist, and one-time dervish. Currently, he is shifting his focus to big data challenges and has been involved in projects across a variety of industries, including banking, media, finance, telecoms, and government. He was also the head developer of an award-winning community portal. He holds an MSc degree in computer science from Adam Mickiewicz University. Learn more about him at http://www.m1key.me/.

He has also reviewed Gradle Effective Implementation Guide from Packt Publishing.

I would like to thank my friend, Bianca, for being such an amazing inspiration over the years—dziękuję.

Fredrik Sandell is a full-stack software developer with many years of experience developing Java-based web applications. He holds a MSc degree in networks and distributed systems from the Chalmers University of Technology and is currently based in Stockholm, Sweden.

Fredrik is employed at a fantastic company called Squeed AB.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

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.

Preface

When I first came across Gradle in 2011, it was a young yet powerful tool. If I remember correctly, the version was 0.9. It was difficult for me to get started despite Gradle having an adequate official documentation. What I missed the most was a guide that would just help me understand the core concepts first, without having to go through the entire documentation.

Gradle is a fantastic build tool. There is so much to learn about it that new users are often clueless about where to start. It is unwise to expect an application developer to go through the entire Gradle reference material just to understand the basics.

This book attempts to help a reader get started with Gradle by revealing the key concepts in a step-by-step manner. It introduces a more advanced topic succinctly. This book focuses on the practical usage of Gradle that a reader can immediately put to use on his or her project. This book strives to stay true to the spirit of 'essentials' by avoiding going into every possible feature and option that Gradle has to offer. Code samples for applications have been consciously kept very small in order to avoid distractions from application logic.

This book is a quick start guide for Gradle. If you are a Java developer already building your code with Ant or Maven and want to switch to Gradle, this book helps you to quickly understand the different concepts of Gradle. Even if you do not have exposure to other build tools such as Ant or Maven, you can start afresh on Gradle with the help of this book. It starts with the basics of Gradle and then gently moves to concepts such as multimodule projects, migration strategies, testing strategies, Continuous Integration, and code coverage with the help of Gradle.

What this book covers

This book can be roughly divided into three parts.

Section 1 includes Chapter 1, Running Your First Gradle Task, Chapter 2, Building Java Projects, and Chapter 3, Building a Web Application. This section introduces the basics of Gradle, with very simple examples, which helps readers to create build files for Java projects and Web applications. It gives a gentle start without involving any complex concepts.

Section 2 includes Chapter 4, Demystifying Build Scripts, and Chapter 5, Multiprojects Build. This section helps the reader to understand the underpinning of Gradle in more depth, still maintaining the 'essentials' aspect of this book. It also helps the reader to understand how to interpret and write scripts that conform to Gradle DSL.

Section 3 includes Chapter 6, The Real-world Project with Gradle, Chapter 7, Testing and Reporting with Gradle, Chapter 8, Organizing Build Logic and Plugins, and Chapter 9, Polyglot Projects. This section covers more real-world use cases that Gradle users come across. Some examples include migrating to Gradle from the existing build system, using Gradle on CI servers, maintaining code quality with Gradle, using Gradle to build project languages such as Groovy and Scala, and so on. These concepts mostly revolve around what various plugins have to offer and also allows the reader to create their own custom plugins.

Also, there are multiple places in all chapters where the reader can find tips, references, and other informative notes.

Chapter 1, Running Your First Gradle Task, starts with an introduction to Gradle and its installation, subsequently moving on to exploring the Gradle command-line interface, and finally running the first build file.

Chapter 2, Building Java Projects, explains topics such as building Java applications and libraries, unit testing with JUnit, reading test reports, and creating application distributions.

Chapter 3, Building a Web Application, deals with building and running Web applications. It also briefly introduces concepts such as dependencies, repositories, and configurations.

Chapter 4, Demystifying Build Scripts, starts with a primer to the Groovy syntax in the context of Gradle DSL. Then, it goes on to explain the backbone concepts of a Gradle build such as build phases, project API, and various topics related to Gradle tasks.

Chapter 5, Multiprojects Build, covers a few options to structure multiproject directories. Then, covers organization of a build logic, which is a multiproject build.

Chapter 6, The Real-world Project with Gradle, deals with one of the important problems faced by developers, that is, migrating their existing Ant and Maven scripts to Gradle. This chapter provides different strategies and examples, which guide developers to perform migration in a more simpler and manageable way. This chapter also gives an insight into the different ways of publishing artifacts with the help of Gradle and also how a developer can integrate Gradle with Continuous Integration workflow.

Chapter 7, Testing and Reporting with Gradle, deals with the integration of the TestNG framework with Gradle. Apart from unit testing with TestNG, it also deals with different strategies for integration testing, which the user can follow to execute integration tests separate from unit test cases. It also discusses about integrating Sonar with Gradle, which helps developers to analyze the quality of code on different parameters, and JaCoCo integration for code coverage analysis.

Chapter 8, Organizing Build Logic and Plugins, discusses one of the important building blocks of Gradle plugins, without which you will find this book incomplete. It discusses the needs of the plugin and the different ways in which developers can create a plugin based on the project size and complexities.

Chapter 9, Polyglot Projects, demonstrates how to use Gradle for projects that use languages apart from or in addition to Java; this chapter shows the examples of building Groovy and Scala projects.

What you need for this book

Your system must have the following software before executing the code mentioned in the book:

GradleJava 1.7 or above

For chapters 6-8, you need the following softwares:

JenkinsAnt 1.9.4Maven 3.2.2

Who this book is for

This book is for Java and other JVM-based language developers who want to use Gradle or who are already using Gradle on their projects.

No prior knowledge of Gradle is required, but some familiarity with build-related terminologies and an understanding of the Java language would help.

Conventions

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: "This class exposes just one method called greet which we can use to generate a greeting message."

A block of code is set as follows:

task helloWorld << { println "Hello, World!" }

Any command-line input or output is written as follows:

$ gradle --version

Or it may be written as follows:

> gradle --version

Whenever some output or code block is truncated it is denoted by an ellipsis (...) like this:

$ gradle tasks...Other tasks-----------helloWorld...

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: "Once the Submit button is pressed, we'll get the desired result."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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.

Customer support

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.

Downloading the example code

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.

Errata

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

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.

Questions

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.

Chapter 1. Running Your First Gradle Task

We are embarking on a fast-paced ride to learn the Gradle Essentials. To take a gentle start, we will first install Gradle. Then, we will get friendly with the Gradle's command-line interface by looking at the usage of the gradle command. Also, by the end of this chapter, we would have run our first Gradle build script.