Groovy Programming An Introduction for Java Developers 1st Edition Kenneth Barclay instant download
Groovy Programming An Introduction for Java Developers 1st Edition Kenneth Barclay instant download
https://ebookname.com/product/groovy-programming-an-introduction-
for-java-developers-1st-edition-kenneth-barclay/
https://ebookname.com/product/programming-groovy-dynamic-
productivity-for-the-java-developer-1st-edition-venkat-
subramaniam/
https://ebookname.com/product/programming-groovy-2-dynamic-
productivity-for-the-java-developer-2nd-edition-venkat-
subramaniam/
https://ebookname.com/product/java-an-introduction-to-problem-
solving-and-programming-6th-edition-walter-savitch/
https://ebookname.com/product/ethics-in-engineering-practice-and-
research-2nd-edition-caroline-whitbeck/
Epidemics and Enslavement Biological Catastrophe in the
Native Southeast 1492 1715 Indians of the Southeast
Paul Kelton
https://ebookname.com/product/epidemics-and-enslavement-
biological-catastrophe-in-the-native-southeast-1492-1715-indians-
of-the-southeast-paul-kelton/
Great Land Rush and the Making of the Modern World 1650
1900 1st Edition John C. Weaver
https://ebookname.com/product/great-land-rush-and-the-making-of-
the-modern-world-1650-1900-1st-edition-john-c-weaver/
https://ebookname.com/product/track-field-1-print-edition-
gabrielle-vanderhoof/
https://ebookname.com/product/european-union-law-for-
international-business-1st-edition-bernard-bishop/
https://ebookname.com/product/systems-biology-and-livestock-
science-1st-edition-marinus-te-pas/
The Mongols and the Islamic World From Conquest to
Conversion 1st Edition Peter Jackson
https://ebookname.com/product/the-mongols-and-the-islamic-world-
from-conquest-to-conversion-1st-edition-peter-jackson/
Barclay FM.qxd 6/11/06 1:50 PM Page 1
groovy programming
This page intentionally left blank
Barclay FM.qxd 6/11/06 1:50 PM Page 3
groovy programming
an introduction for
java developers
Kenneth Barclay
John Savage
To Irene
–K.B.
To Salwa
–J.S.
This page intentionally left blank
Barclay FM.qxd 6/11/06 1:50 PM Page 7
contents
Foreword xiv
Preface xvi
About the Authors xix
1 Groovy 1
1.1 Why Scripting? 1
1.2 Why Groovy? 3
2 Numbers and Expressions 5
2.1 Numbers 6
2.2 Expressions 6
2.3 Operator Precedence 8
2.4 Assignment 9
2.5 Increment and Decrement Operators 10
2.6 Object References 11
2.7 Relational and Equality Operators 12
2.8 Exercises 14
3 Strings and Regular Expressions 17
3.1 String Literals 17
3.2 String Indexing and Slicing 18
3.3 Basic Operations 19
3.4 String Methods 19
3.5 String Comparison 23
3.6 Regular Expressions 23
3.7 Exercises 25
vii
Barclay FM.qxd 6/11/06 1:50 PM Page 8
viii Contents
Contents ix
10 Files 103
10.1 Command Line Arguments 103
10.2 File Class 104
10.3 Exercises 111
11 Case Study: A Library Application (Methods,
Closures) 113
11.1 Iteration 1: Specification and Map Implementation 113
11.2 Iteration 2: Implementation of a Text-Based User Interface 119
11.3 Iteration 3: Implementation with Closures 122
11.4 Exercises 125
12 Classes 127
12.1 Classes 127
12.2 Composition 135
12.3 Exercises 137
13 Case Study: A Library Application (Objects) 139
13.1 Specification 139
13.2 Iteration 1: An Initial Model 140
13.3 Iteration 2: Augment the Model 142
13.4 Iteration 3: Reinstate the User Interface 147
13.5 Exercises 153
14 Inheritance 157
14.1 Inheritance 157
14.2 Inherited Methods 160
14.3 Redefined Methods 162
14.4 Polymorphism 163
14.5 The Abstract Class 166
14.6 The Interface Class 169
14.7 Exercises 173
15 Unit Testing ( JUnit) 179
15.1 Unit Testing 179
15.2 The GroovyTestCase and JUnit TestCase Classes 181
15.3 The GroovyTestSuite and JUnit TestSuite Classes 186
15.4 The Role of Unit Testing 189
15.5 Exercises 193
Barclay FM.qxd 6/11/06 1:50 PM Page 10
x Contents
Contents xi
22 Case Study: A Library Application (GUI) 303
22.1 Iteration 1: Prototype the GUI 303
22.2 Iteration 2: Implement the Handlers 306
22.3 Exercises 313
23 Server-Side Programming 315
23.1 Servlets 315
23.2 Groovlets 316
23.3 GSP Pages 324
23.4 Exercises 328
24 Case Study: A Library Application (Web) 329
24.1 Iteration 1: Web Implementation 329
24.2 Exercise 333
25 Epilogue 335
Appendices
A Software Distribution 337
A.1 The Java Development Kit 337
A.2 The Groovy Development Kit 338
A.3 Ant 338
A.4 The Derby/Cloudscape Database 338
A.5 The Spring Framework 339
A.6 The Tomcat Server 339
A.7 Eclipse IDE 339
A.8 The Textbook Sources 339
B Groovy 341
B.1 Simple and Elegant 341
B.2 Methods 343
B.3 Lists 344
B.4 Classes 344
B.5 Polymorphism 345
B.6 Closures 346
B.7 Exceptions 347
C More on Numbers and Expressions 349
C.1 Classes 349
C.2 Expressions 350
C.3 Operator Associativity 350
Barclay FM.qxd 6/11/06 1:50 PM Page 12
xii Contents
Contents xiii
H More on Closures 393
H.1 Closures and Ambiguity 393
H.2 Closures and Methods 394
H.3 Default Parameters 395
H.4 Closures and Scope 395
H.5 Recursive Closures 396
H.6 Static Typing 397
H.7 Actual Parameter Agreement 398
H.8 Closures, Collections, and Ranges 398
H.9 Return Statement 400
H.10 Testing 401
I More on Classes 404
I.1 Properties and Visibility 404
I.2 Object Navigation 409
I.3 Static Members 413
I.4 Operator Overloading 415
I.5 The invokeMethod 417
I.6 Exercises 419
J Advanced Closures 420
J.1 Simple Closures 421
J.2 Partial Application 423
J.3 Composition 425
J.4 Patterns of Computation 426
J.5 Business Rules 428
J.6 Packaging 432
J.7 List Reduction 439
J.8 Exercises 441
K More on Builders 445
K.1 AntBuilder 445
K.2 Specialized Builders 453
L More on GUI Builders 458
L.1 Menus and Toolbars 458
L.2 Dialogs 465
Bibliography 469
Index 471
Barclay FM.qxd 6/11/06 1:50 PM Page 14
foreword
Scripting languages are not new. Primarily, they are used on Linux and
UNIX machines for things such as shell scripting tasks that automate soft-
ware installations, platform customizations, scientific application prototyp-
ing with Python, and one-shot command-line jobs with bash scripts.
Languages such as PHP have also been widely used for developing high-
volume websites and scripting languages have been found to be suitable for
serious business applications.
Usually, scripting languages are platforms on their own and do not nec-
essarily interact with others. Although bindings may exist for bridging with
other systems, the integration is not always intuitive or natural. Groovy seeks
to fill that gap, bringing a genuine innovative language that can interact
natively with Java by living on the same virtual machine.
Groovy brings a concise and expressive Java-like syntax to ease the learn-
ing curve for Java developers. But beyond the syntax, Groovy also provides
two key aspects to the landscape by providing wrapper APIs around common
JDK Application Programming Interfaces. It simplifies the implementation
of common tasks and integrates meta-programming capabilities to develop
powerful new language constructs or to easily manipulate existing ones.
Groovy can be used in various situations: as a shell scripting language to
do data crunching and file manipulation tasks or to experiment with new
APIs. It can also be adapted for creating full-blown small- to mid-size appli-
cations to leverage the wealth of Java libraries and components. Moreover,
another important use is to marry Java and Groovy by embedding Groovy
inside Java or Java EE applications. This can help write and externalize
often-changing business rules or bring programmatic configuration to an
application infrastructure.
Although the first two uses are quite common, I believe the embedded-
use case is the most appealing and promising. Currently, developers have
been using template engines for customizing and factoring out views, or they
have used business rules engines to externalize some logic. Beyond the
xiv
Barclay FM.qxd 6/11/06 1:50 PM Page 15
Foreword xv
limited functionality set, however, programmers are often given little
support. Fortunately, platform-hosted scripting languages such as Groovy
can help bridge this functionality gap. This is evident with the success of
Groovy and its child—Grails—a versatile model-view-controller (MVC)
Web framework. Sun, too, believes in this alternative way of adding dynam-
icity to applications, by including a new Java Specification Request in Java 6:
the javax.script.* APIs allow seamless embedding of any scripting or
dynamic language into Java applications with a coherent programming API.
Scripting languages have evolved to a point of maturity where they meet
the limitations of the standardized mainstream platforms. When those lan-
guages and platforms come across, that’s when magic happens, and we can
celebrate a marriage made in Heaven.
Ken Barclay and John Savage are respected teachers and are well posi-
tioned to introduce Groovy to both experienced developers and novices.
They demonstrate in a clear manner how Groovy augments the Java plat-
form and how to exploit many of its innovative features. The book is easy to
read and not intimidating for those less experienced with programming. It
is a complete exposition of Groovy that addresses all aspects of the pro-
gramming language.
The structure of the book fulfills this aim by presenting the basics of
Groovy in the early chapters and more advanced concepts in the latter. In
addition, extensive appendices consider more detailed aspects of the lan-
guage.
Deliberately, each chapter is relatively small and easy to absorb, yet they
contain a large number of complete code examples, extensive exercises, and
solutions. To illustrate Groovy in application, the book features a rolling case
study that grows in complexity and sophistication by drawing on the mate-
rials from each preceding chapter. In addition, incremental development
and unit testing are central themes in the text and are necessary to support
Groovy’s dynamic nature. The authors also consider Groovy as a multipara-
digm language.
The authors’ own experience suggests that Groovy has a place in the aca-
demic curriculum as well as the experienced developer’s toolbox.
Have a fun time learning Groovy by reading this great book! You won’t
regret it.
Guillaume Laforge
Groovy Project Manager
JSR-241 Specification Lead
Barclay FM.qxd 6/11/06 1:50 PM Page 16
preface
This book is an introduction to the scripting language Groovy. For Java
developers, Groovy makes writing scripts and applications for the Java plat-
form both fast and easy. It includes many language features found in other
scripting languages such as Python, Ruby, and Smalltalk. As Groovy is based
on Java, applications written in Groovy can make full use of the Java
Application Programming Interfaces (APIs). This means that Groovy inte-
grates seamlessly with frameworks and components written in Java.
Groovy, the scripting language, and Java, the systems programming
language, complement each other. Both contribute to the development of
programming applications. For example, components and frameworks
might be created with Java and “glued” together with Groovy. The ease with
which Groovy can make use of them significantly enhances their usage. The
increasing importance of component architectures, Graphical User
Interfaces (GUIs), database access, and the internet all increase the applica-
bility of scripting in Groovy.
Groovy developers can take advantage of rapid application development
features, such as those found in scripting languages. Groovy is suitable for
many data or file processing tasks, testing applications, or as a replacement
for Java in small- and medium-sized projects.
The syntax of Groovy is similar to the syntax of the Java programming
language. This makes for a relatively short learning curve for Java develop-
ers. Other scripting languages for the Java platform are usually based on ear-
lier predecessors. This is a major problem as they bring extra unwanted
“baggage.” However, as Groovy is Java, it offers a much more natural and
seamless integration into the Java platform.
xvi
Barclay FM.qxd 6/11/06 1:50 PM Page 17
Preface xvii
organiz ation
The text is designed to quickly introduce readers to the principal elements
of the Groovy language. It assumes at least a reading knowledge of Java. For
the later chapters, experience with Swing, Standard Query Language (SQL),
Spring, XML, Ant, and building Web applications would also be useful. The
authors have sought to keep each chapter relatively brief and closely focused.
Some readers may wish to dip into an individual chapter to pick out partic-
ular Groovy features. In any event, the shortness of each chapter should
make its contents relatively easy to absorb.
Many chapters are supported by an appendix to augment the topics cov-
ered. For example, Chapter 7 considers the basics of defining and using
Groovy methods. Appendix G then considers more advanced aspects, such
as overloading and recursion, which are not central to the main text. Again,
this helps to keep chapters short and targeted.
Most chapters also include many small, self-contained examples to illus-
trate language concepts. They are complete, and the reader is encouraged to
execute them as part of the learning process. There are also end-of-chapter
exercises, and the reader is encouraged to attempt them. However, both the
chapter examples and the solutions to the exercises are available on the
book’s website.
A feature of the book is a rolling case study concerned with managing
and maintaining a library’s loan stock. At various points in the text, new
Groovy features are applied to augment the functionality of the case study.
For example, the case study in Chapter 11 exploits methods, closures, and
files introduced in the preceding chapters.
Chapters 1 to 16 cover the basic features of Groovy. For example, there
are discussions of Groovy methods, closures, lists, and maps as well as
support for classes and inheritance.
The important topic of automated unit testing is also addressed.
Groovy’s rapid build-and-run cycle makes it an ideal candidate for develop-
ing unit tests. Groovy exploits the industry standard JUnit framework to
make unit testing both easy and fun. Unit testing used in conjunction with
Groovy combines the flexibility of a dynamically typed language with the
safety offered by statically typed languages. To highlight this point, unit test-
ing is an integral part of most of the case studies.
The second part of the book is presented in Chapters 17 to 24, where
Groovy is used for more advanced applications. For example, persistence is
implemented with the Spring framework in conjunction with the
Cloudscape/Derby relational database management system. Groovy also
supports XML and GUI applications through its novel builder notation. We
finish by considering templates and web applications.
Barclay FM.qxd 6/11/06 1:50 PM Page 18
xviii Preface
conventions
Throughout the book we use an arial typeface to identify Groovy code and
the output from scripts. We also italicize text when introducing a technical
term. The book includes references to websites and to the bibliography.
We do not distinguish between a program and a script. Both terms are
used interchangeably. However, we invariably mean a Groovy script.
acknowledgments
The authors are deeply grateful to those involved in Groovy’s conception,
the committers that maintain its development, and those instrumental in
the Java Specification Request (JSR-241) initiative (http://www.dcs.
napier.ac.uk/~cs05/groovy/groovy.html). This book is our contribution to
publicizing the Groovy language. We are indebted to Guillaume Laforge
(Groovy Project Manager) who keeps Groovy “on-track” and to Andrew
Glover (CTO, Vanward Technologies) for his excellent articles on Groovy on
the IBM Developers website. We are also grateful for the encouragement
and stimulation given by Professor Jon Kerridge (School of Computing,
Napier University, Edinburgh) who sent us Groovy challenges that we might
not otherwise have taken up.
The authors also wish to thank Denise Penrose, Tim Cox, Mary James,
Christine Brandt, and their colleagues at Morgan Kaufmann, Elsevier for
their help in the production of this book. Finally, we are grateful for the many
helpful suggestions from our reviewers Andrew Glover and Sean Burke. Any
outstanding errors in the text are the responsibility of the authors.
Barclay FM.qxd 6/11/06 1:50 PM Page 19
xix
This page intentionally left blank
Barclay chap01.qxd 02/01/1904 9:51 PM Page 1
1
CHAPTER
groovy
1
Barclay chap01.qxd 02/01/1904 9:51 PM Page 2
2 CHAPTER 1 Groovy
A major strength of scripting languages is that the coding effort they require is
relatively small as compared to code written in a systems programming
language. Often, the latter appears to be overly complex and difficult to
understand and maintain. This is because it requires extensive boilerplate or
conversion code.
These systems languages are strongly typed to ensure the safety and robust-
ness of the code. With strong typing, variables must been given a type and they
can only be used in a particular way. Although strong typing makes large pro-
grams more manageable and allows a compiler to (statically) detect certain kinds
of errors, it can be intrusive. For example, strong typing is not helpful when it
is difficult or impossible to decide beforehand which type of a variable it is. This
situation occurs frequently when connecting components together.
To simplify the task of connecting components, scripting languages are
weakly typed. This means that variables can be used in different ways under
different circumstances. However, illegal use of variables is only detected when
the code is actually executing. For example, although Groovy (statically) checks
program syntax at compile time, the (dynamic) check on the correctness
of method calls happens at runtime. As a result, there is the danger that a
Groovy script that compiles cleanly may throw an exception and terminate
prematurely.
Weak typing does not necessarily mean that code is unsafe or that it is not
robust. Advocates have promoted Extreme Programming (Beck, 2004) as a soft-
ware development process. This approach is characterized by an emphasis on
testing. The result is a comprehensive suite of unit tests (Link, 2003) that drive
the development. As a consequence, they help ensure the safety and robustness
of the code by executing it in a wide variety of different scenarios. This is the basis
of the approach we take when developing Groovy scripts. In fact, experience has
shown that the combination of weak typing and unit testing in a scripting lan-
guage is often better than strong type checking in a traditional systems
programming language (see http://www.mindview.net/WebLog/log-0025). We
have both the flexibility of weak typing and the confidence of unit testing.
Barclay chap01.qxd 02/01/1904 9:51 PM Page 3
4 CHAPTER 1 Groovy
Conclusions
The special interest attached to the Winter Solstice altars at Hano is in the fact that they
are made by Tewa priests whose ancestors came to Tusayan about the beginning of the
eighteenth century. The makers claim that their forefathers brought a knowledge of them
from Tcewadi, in the upper valley of the Rio Grande in New Mexico, and that their
relatives in the Tewa pueblos in the east still use like altars in their celebration at the
Tûñtai.
Nothing, so far as known, has yet been published on the Tûñtai altars of the eastern
Tanoan people, but ethnographers may yet find in the kivas of those villages material
which will render the above descriptions of comparative interest. The resemblance of the
Tûñtai altars to that of the Patki and related families in the Walpi Moñkiva at the Winter
Solstice, is a very distant one. Both have snake effigies, but there is practically little else
in common between them, or with the altar erected at the same time by the Pakab
people in the Tcivatokiva. The Tûñtai altars are characteristically Tewan, and, while
homologous with each other, are different from any yet known from the Hopi pueblos.
The purport of the Tûñtai rites at Hano seems to be similar to that of the Hopi Soyaluña,
namely, to draw back the sun in its southern declination, and to fertilize the corn and
other seeds and increase all worldly possessions. As at Walpi, strings with attached
feathers are made and given to men and women with wishes that the gods may bring
them blessings. These strings are also attached to beams of houses, placed in springs of
water, tied to the tails of horses, burros, sheep, dogs, chickens, and indeed every
possession which the Indian has and wishes to increase. The presence of the idol of the
snake means snake worship.
The survival of the Tanoan Tûñtai altars at Hano is typical of the way in which the
Tusayan ritual has grown to its present complicated form. They are instances of an
intrusive element which has not yet been amalgamated, as the knowledge of them is still
limited to unassimilated people and clans.
Similar conditions have existed from time to time during the history of the Hopi, when
new clans were added to those already existing. For many years incoming clans
maintained a strict taboo, and each family held the secrets of its own religion; but as
time went on and assimilation resulted by intermarriage, the religious society arose,
composed of men and women of different clans. The family to which a majority of the
membership belonged continued to hold the chieftaincy, and owned the altar and its
paraphernalia, cherishing the legends of the society. But when men of other clans were
admitted to membership, a mutual reaction of one society on another naturally resulted.
This tended to modifications which have obscured the original character of distinctive
family worship.
The problem of the Hopi ritual, by which is meant the sum of all great ceremonies in the
Hopi calendar, deals largely with a composite system. It implies, as elsewhere pointed
out, an investigation of the characteristic religious observances of several large families
which formerly lived apart in different pueblos. It necessitates a knowledge of the social
composition of Walpi and of the history of the different phratries which make up the
population of the village.
There is a corollary to the above conclusions. No pueblo in the southwest, outside of
Tusayan, has the same ceremonial calendar as Walpi, because the population of none is
made up of the same clans united in the same relative proportions. Hence the old remark
that what is true of one pueblo is true of all, does not apply to their ritual. Some
ceremonies at Jemez, Acoma, Sia, and Zuñi, for instance, are like some ceremonies at
Walpi; but the old ceremonial calendar in any one of these pueblos was different from
that of the other, because the component families were not the same. In the same way
the ceremonies at Hano and Walpi have certain things in common, due no doubt to the
assimilation in the latter of certain Tanoan clans, but their calendars are very different.
The Tûñtai at Hano differs more widely from the Winter Solstice ceremony at Walpi, a
gunshot away, than the Walpi observance differs from that at Oraibi, twenty miles
distant. So we might also predict that if we knew the character of Winter Solstice altars in
the Rio Grande Tewa villages, they would be found to resemble those of Hano more
closely than the altars of Hano resemble those of Walpi.
Transcriber's Note:
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com