100% found this document useful (1 vote)
27 views

Instant Access to Groovy Programming An Introduction for Java Developers 1st Edition Kenneth Barclay ebook Full Chapters

Kenneth

Uploaded by

razeeqfasya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
27 views

Instant Access to Groovy Programming An Introduction for Java Developers 1st Edition Kenneth Barclay ebook Full Chapters

Kenneth

Uploaded by

razeeqfasya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Download Full ebookname - Read Now at ebookname.

com

Groovy Programming An Introduction for Java


Developers 1st Edition Kenneth Barclay

https://ebookname.com/product/groovy-programming-an-
introduction-for-java-developers-1st-edition-kenneth-
barclay/

OR CLICK BUTTON

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming Groovy Dynamic Productivity for the Java


Developer 1st Edition Venkat Subramaniam

https://ebookname.com/product/programming-groovy-dynamic-productivity-
for-the-java-developer-1st-edition-venkat-subramaniam/

ebookname.com

Programming Groovy 2 Dynamic Productivity for the Java


Developer 2nd Edition Venkat Subramaniam

https://ebookname.com/product/programming-groovy-2-dynamic-
productivity-for-the-java-developer-2nd-edition-venkat-subramaniam/

ebookname.com

Java An Introduction to Problem Solving and Programming


6th Edition Walter Savitch

https://ebookname.com/product/java-an-introduction-to-problem-solving-
and-programming-6th-edition-walter-savitch/

ebookname.com

The Globalization of Chinese Companies Strategies for


Conquering International Markets 1st Edition Arthur Yeung

https://ebookname.com/product/the-globalization-of-chinese-companies-
strategies-for-conquering-international-markets-1st-edition-arthur-
yeung/
ebookname.com
Portugal DK Eyewitness Travel Guide Dk Travel.

https://ebookname.com/product/portugal-dk-eyewitness-travel-guide-dk-
travel/

ebookname.com

Robust Ethics The Metaphysics and Epistemology of Godless


Normative Realism 1st Edition Erik J. Wielenberg

https://ebookname.com/product/robust-ethics-the-metaphysics-and-
epistemology-of-godless-normative-realism-1st-edition-erik-j-
wielenberg/
ebookname.com

A Case Based Approach to Pacemakers ICDs and Cardiac


Resynchronization 1st Edition Paul A. Friedman

https://ebookname.com/product/a-case-based-approach-to-pacemakers-
icds-and-cardiac-resynchronization-1st-edition-paul-a-friedman/

ebookname.com

Cephalopod Cognition 1st Edition Anne-Sophie Darmaillacq

https://ebookname.com/product/cephalopod-cognition-1st-edition-anne-
sophie-darmaillacq/

ebookname.com

Midway 1942 Turning point in the Pacific 2nd Edition Mark


Stille

https://ebookname.com/product/midway-1942-turning-point-in-the-
pacific-2nd-edition-mark-stille/

ebookname.com
jQuery Cookbook Solutions Examples for jQuery Developers
Animal Guide 1st Edition Cody Lindley

https://ebookname.com/product/jquery-cookbook-solutions-examples-for-
jquery-developers-animal-guide-1st-edition-cody-lindley/

ebookname.com
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

AMSTERDAM • BOSTON • HEIDELBERG • LONDON


NEW YORK • OXFORD • PARIS • SAN DIEGO
SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO
Morgan Kaufmann Publishers is an imprint of Elsevier
Barclay FM.qxd 6/11/06 1:50 PM Page 4

Publisher Denise E. M. Penrose


Publishing Services Manager George Morrison
Senior Editor Tim Cox
Assistant Editor Mary E. James
Project Manager Marilyn E. Rash
Cover Design Chen Design
Composition and Illustrations SPi
Production Services SPi
Interior printer Maple-Vail Book Manufacturing Group
Cover printer Phoenix Color Corp.
Morgan Kaufmann Publishers is an imprint of Elsevier.
500 Sansome Street, Suite 400, San Francisco, CA 94111
This book is printed on acid-free paper.
© 2007 by Elsevier Inc. All rights reserved.
Designations used by companies to distinguish their products are often claimed as trademarks or registered trade-
marks. In all instances in which Morgan Kaufmann Publishers is aware of a claim, the product names appear in
initial capital or all capital letters. Readers, however, should contact the appropriate companies for more complete
information regarding trademarks and registration.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any
means—electronic, mechanical, photocopying, scanning, or otherwise—without prior written permission of the
publisher.
Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK:
phone: (+44) 1865 843830, fax: (+44) 1865 853333, E-mail: [email protected]. You may also complete
your request online via the Elsevier homepage (http://elsevier.com), by selecting “Support & Contact” then
“Copyright and Permission” and then “Obtaining Permissions.”
Library of Congress Cataloging-in-Publication Data
Barclay, Kenneth A., 1947-
Groovy programming : an introduction for Java developers /
Kenneth Barclay, John Savage.
p. cm.
Includes bibliographical references and index.
ISBN-13: 978-0-12-372507-3 (alk. paper)
ISBN-10: 0-12-372507-0 (alk. paper)
1. Java (Computer program language) I. Savage, W. J. (W. John) II. Title.
QA76.73.J38B358 2006
005. 13'3–dc22 2006036352
For information on all Morgan Kaufmann publications,
visit our Web site at www.mkp.com or www.books.elsevier.com
Printed in the United States of America
07 08 09 10 5 4 3 2 1
Barclay FM.qxd 6/11/06 1:50 PM Page 5

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

4 Lists, Maps, and Ranges 27


4.1 Lists 27
4.2 List Methods 29
4.3 Maps 31
4.4 Map Methods 33
4.5 Ranges 34
4.6 Exercises 35
5 Simple Input and Output 39
5.1 Simple Output 39
5.2 Formatted Output 41
5.3 Simple Input 42
5.4 Exercises 45
6 Case Study: A Library Application (Modeling) 47
6.1 Iteration 1: Specification and List Implementation 47
6.2 Iteration 2: Map Implementation 50
6.3 Exercises 52
7 Methods 53
7.1 Methods 53
7.2 Method Parameters 56
7.3 Default Parameters 56
7.4 Method Return Values 57
7.5 Parameter Passing 59
7.6 Scope 61
7.7 Collections as Method Parameters and Return Values 62
7.8 Exercises 63
8 Flow of Control 67
8.1 While Statement 67
8.2 For Statement 69
8.3 If Statement 71
8.4 Switch Statement 74
8.5 Break Statement 78
8.6 Continue Statement 79
8.7 Exercises 80
9 Closures 85
9.1 Closures 85
9.2 Closures, Collections, and Strings 90
9.3 Other Closure Features 96
9.4 Exercises 100
Barclay FM.qxd 6/11/06 1:50 PM Page 9

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

16 Case Study: A Library Application


(Inheritance) 195
16.1 Specification 195
16.2 Iteration 1: Confirm the Polymorphic Effect 196
16.3 Iteration 2: Demonstrate the Required Functionality 199
16.4 Iteration 3: Provide User Feedback 204
16.5 Iteration 4: Enforce Constraints 212
16.6 Exercises 217
17 Persistence 219
17.1 Simple Queries 219
17.2 Relations 221
17.3 Database Updates 224
17.4 Objects from Tables 228
17.5 Inheritance 230
17.6 The Spring Framework 232
17.7 Exercises 237
18 Case Study: A Library Application
(Persistence) 239
18.1 Iteration 1: Persist the Domain Model 239
18.2 Iteration 2: The Impact of Persistence 251
18.3 Exercises 258
19 XML Builders and Parsers 259
19.1 Groovy Markup 259
19.2 MarkupBuilder 261
19.3 XML Parsing 264
19.4 Exercises 276
20 GUI Builders 277
20.1 SwingBuilder 277
20.2 Lists and Tables 286
20.3 Box and BoxLayout Classes 292
20.4 Exercises 294
21 Template Engines 297
21.1 Strings 297
21.2 Templates 298
21.3 Exercises 302
Barclay FM.qxd 6/11/06 1:50 PM Page 11

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

C.4 Variable Definitions 351


C.5 Compound Assignment Operators 353
C.6 Logical Operators 353
C.7 Conditional Operator 354
C.8 Qualified Numerical Literals 355
C.9 Conversions 355
C.10 Static Typing 358
C.11 Testing 358
D More on Strings and Regular Expressions 361
D.1 Regular Expressions 361
D.2 Single Character Match 362
D.3 Match at the Beginning 363
D.4 Match at the End 363
D.5 Match Zero or More 363
D.6 Match One or More 364
D.7 Match None or One 364
D.8 Match Number 364
D.9 Character Classes 365
D.10 Alternation 366
D.11 Miscellaneous Notations 366
D.12 Grouping 367
E More on Lists, Maps, and Ranges 369
E.1 Classes 370
E.2 Lists 371
E.3 Ranges 372
E.4 The Spread Operator 372
E.5 Testing 373
F More on Simple Input and Output 376
F.1 Formatted Output 376
F.2 Console Class 379
G More on Methods 382
G.1 Recursive Methods 382
G.2 Static Typing 384
G.3 Actual Parameter Agreement 386
G.4 Method Overloading 387
G.5 Default Parameter Ambiguity 387
G.6 Collections as Method Parameters and Return Values 389
Barclay FM.qxd 6/11/06 1:50 PM Page 13

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.

soft ware distribution


The authors have prepared a supporting website—http://www.dcs.
napier.ac.uk/~kab/groovy/groovy.html—that contains the working scripts
for all of the examples and case studies presented in the book. Answers to
the end-of-chapter exercises are also included.
Groovy is under constant review and is subject to revision. It is the aim
of the authors to use this website to keep the reader informed of significant
changes. Therefore, the reader is advised to consult it for up-to-date infor-
mation.

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

about the authors


Ken Barclay and John Savage are lecturers in computer science at Napier
University in Edinburgh, Scotland. They both have more than 25 years of
experience teaching software development to students and professionals in
commerce and industry. They have been actively involved with the evolution
and development of object-oriented practices in C++, Java, Ada, and the
Unified Modeling Language (UML).
Since their first involvement with object orientation, they have led the
development of the ROME project—an object modeling tool—that is dis-
tributed with their books on object orientation and the UML. They are the
authors of several publications about software development, including
Object-Oriented Design with UML and Java (Butterworth-Heinemann/
Elsevier, 2003).

xix
This page intentionally left blank
Barclay chap01.qxd 02/01/1904 9:51 PM Page 1

1
CHAPTER

groovy

This first chapter introduces Groovy as a unique scripting language designed to


augment the Java platform. It offers Javalike syntax, native support for Maps and
Lists, methods, classes, closures, and builders. With its dynamic weak typing
and seamless access to the Java Applications Programming Interface (API), it is
well suited to the development of many small- to medium-sized applications.

1.1 why scripting?


Generally, scripting languages such as Groovy are more expressive and operate at
higher levels of abstraction than systems programming languages such as Java. This
often results in more rapid application development and higher programmer
productivity. However, scripting languages serve a different purpose than their sys-
tems language counterparts. They are designed for “gluing” applications together
rather than implementing complex data structures and algorithms. Therefore, to be
useful, a scripting language must have access to a wide range of components.
In general, scripting languages do not replace systems programming
languages. They complement them (Ousterhout, 1998). Typically, systems
programming languages should be used in applications that

● require the development of complex algorithms or data structures


● are computationally intensive
● manipulate large datasets
● implement well-defined, slowly changing requirements
● are part of a large project.

1
Barclay chap01.qxd 02/01/1904 9:51 PM Page 2

2 CHAPTER 1 Groovy

However, scripting languages should be used for applications that

● connect preexisting components


● manipulate a variety of different entities that change rapidly
● have a graphical user interface
● have rapidly evolving functionality
● are part of a small- to medium-sized project.

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

1.2 why groovy? 3

1.2 why groovy?


The Java compiler produces bytecodes that execute on the Java Virtual Machine
(JVM). Groovy classes are binary compatible with Java. This means that the
bytecodes produced by the Groovy compiler are the same as those produced by
the Java compiler. Hence, Groovy is Java as far as the JVM is concerned. This
means that Groovy is able to immediately exploit the various Java APIs such as
JDBC for database development (Fisher et al., 2003) and Swing for developing
GUI applications (Topley, 1998).
Groovy aims to shift much of the “heavy lifting” from the developer to the
language itself. For example, when adding a button to a GUI, we simply specify
the code to execute when the button is pressed. There is no need to add an event
handler to the button as an instance of a class implementing a particular
interface. Groovy does this for us.
Groovy is an object-oriented scripting language in which everything is an
object. Unlike Java, there are no exceptions to this rule. This brings an important
element of uniformity to the language. Groovy is also dynamically typed so that
the notion of a type lies within the object, not the variable that references it. An
immediate consequence is that Groovy does not require the declaration of the
type of a variable, method parameter, or method return value. This gives it the
beneficial effects of significantly shrinking the code size and giving the program-
mer the freedom to defer type decisions to runtime.
Groovy also seeks to unify instance fields and methods declared in classes
by supporting the concept of a property. A property removes the distinction
between an instance field (attribute) and a method. In effect, a client considers
a property as the combination of the instance field and its getter/setter methods.
Important data structures, Lists and Maps, are native to the Groovy language.
A List object or a Map object can be directly expressed in a Groovy script. For
novice developers and professionals alike, the immediacy of Lists and Maps can
make their programming tasks that much simpler. Complementing Lists and
Maps are iterator methods, such as each, that simplify how the elements in these
collections are to be processed. The processing itself is described by a closure—an
object that represents a code block. This immensely useful construct can be
referenced by variables, parameterized to generalize its applicability, passed as a
parameter to methods and other closures, and can be an instance field of classes.
It has a huge effect on programming in Groovy.
Hierarchical data structures like XML can also be directly represented in a
Groovy script with Groovy builders. Using notations found in XPath (see
http://www.w3.org/TR/xpath20/), Groovy readily expresses the traversal of these
structures and how to reference their parts. Once again, an iterator and a clo-
sure provide the mechanism to process them.
Barclay chap01.qxd 02/01/1904 9:51 PM Page 4

4 CHAPTER 1 Groovy

Groovy builders are generally applicable to any nested tree-structure. For


example, they can be used to describe a graphical application that is assembled
from various component widgets. Here, too, closures play a part, this time
operating as event handlers for components such as menu items and buttons.
Standard Query Language (SQL) processing also has the same uniform
approach. Again, an iterator method such as eachRow combines with a closure
to express how to process the rows of a database table.
Discovering Diverse Content Through
Random Scribd Documents
back its flank en potence, and tried to hold on, it was completely
turned, and would have been cut off, but for a fierce charge by the
34th, who came up from the reserve and held the enemy in check
long enough for the rest to retire—with the loss of only 36 prisoners
(two of them officers). The retreat of the left wing compelled the
Portuguese in the centre to give back also—they had to make their
way across a valley and stream closely pursued, but behaved most
steadily, and lost less than might have been expected—though some
130 were cut off and captured. The right wing pivoted, in its
withdrawal, on an isolated hill held by Da Costa’s 2nd Line, which
was gallantly maintained to the end of the day. The centre and left
lost more than a mile of ground, but were in good enough order to
take up a new position, selected by Hill on a height in front of the
village of Yguaras, where they repulsed with loss a final attack made
by one of Darmagnac’s regiments which pursued too fiercely[992].
D’Erlon was re-forming his troops, much scattered in the woods,
when at 4 p.m. there arrived from Marcalain the head of Campbell’s
Portuguese brigade, followed by Morillo’s and O’Donnell’s
Spaniards. Their approach was observed, and no further attacks
were made by the French. D’Erlon winds up his account of the day
by observing, quite correctly, that he had driven Hill out of his
position, inflicted much loss on him, and got possession of the road
to Yrurzun. So he had—the Allies had lost 156 British and about 900
Portuguese, of whom 170 were prisoners. The French casualties
must have been about 800 in all, if we may make a rough calculation
from the fact that they lost 39 officers—10 in Abbé’s division, 29 in
Darmagnac’s[993].
But it is not to win results such as these that 18,000 men attack
8,000, and fight them for seven hours[994]. And what was the use of
such a tactical success, when meanwhile Soult’s main body had
been beaten and scattered to the winds, so that Reille and Clausel
were bringing up 14,000 demoralized soldiers, instead of 30,000
confident ones, to join the victorious D’Erlon?
This unpleasant fact stared Soult in the face, when he rode back
to Olague to receive the reports of his two lieutenants. It was useless
to think of further attempts on the Tolosa road, or molestation of
Graham. D’Erlon’s three divisions were now his only intact force,
capable of engaging in an action with confidence: the rest were not
only reduced to a wreck in number, but were ‘spent troops’ from the
point of view of morale. The only thing to be done was to retreat as
fast as possible, using the one solid body of combatants to cover the
retreat of the rest. All that Soult afterwards wrote to Paris about his
movements of July 31 being the logical continuation of his design of
July 30—‘de me rapprocher de la frontière pour y prendre des
subsistances, avec l’espoir de joindre la réserve du Général
Villatte[995],’ was of course mere insincerity. He changed his whole
plan, and fled in haste, merely because he was forced to do so.
One strange resolve, however, he made on the evening of July
30. The safest and shortest way home was by the Puerto de Velate,
Elizondo, and Maya; and Clausel’s and Reille’s troops at Olague and
Lanz were well placed for taking this route. This was not the case
with D’Erlon’s men at Lizaso and the newly won villages in front of it.
Instead of bidding the routed corps hurry straight on, and bringing
D’Erlon down to cover them, the Marshal directed Reille and Clausel
to leave the great road, to cut across by Olague to Lizaso, and to get
behind D’Erlon, who would hold on till they were past his rear. All
would then take the route of the Puerto de Arraiz and go by
Santesteban. This was a much more dangerous line of retreat; so
much so that the choice excites surprise. Soult told Clarke that his
reason for taking the risk was that D’Erlon had got so far west that
there was no time to move him back to the Velate road—which
seems an unconvincing argument. For Clausel and Reille had to
transfer themselves to the Puerto de Arraiz road, which would take
just as much time; and D’Erlon could not retreat till they had cleared
his rear. The real explanation would seem to be that Soult thought
that the British column on the Velate road, being victorious, would
start sooner and pursue more vigorously than Hill’s troops, who had
just been defeated. If Reille and Clausel were pressed without delay,
their divisions would go to pieces: D’Erlon, on the other hand, could
be relied upon to stand his ground as long as was needful. If this
was Soult’s idea, his prescience was justified.
SECTION XXXVIII: CHAPTER VI
SOULT’S RETREAT, JULY 31-AUG. 3

When Soult’s orders of the evening of July 29th had been issued,
there was no longer any pretence kept up that the Army was
executing a voluntary strategical movement, planmässig as the
German of 1918 would have expressed the idea, and not
absconding under pressure of the enemy.
At 1 o’clock midnight Clausel’s and Reille’s harassed troops at
Olague and Lanz went off as fast as their tired legs would carry
them, and leaving countless stragglers behind. D’Erlon could not
retire till the morning, when he sent off Darmagnac and Maransin to
follow the rest of the army, retaining Abbé’s division as his rearguard,
which held the heights north of Lizaso for some time after their
comrades had gone.
Wellington’s orders issued at nightfall[996] were such as suited
Soult fairly well, for the British general had not foreseen that which
was unlikely, and he had been deceived to some extent by the
reports which had come in. The deductions which he drew from what
he had ascertained were that a large body of the enemy had
retreated eastward, and would fall into the Roncesvalles road, but
that the main force would follow the Velate-Elizondo chaussée. That
Soult would lead all that survived to him of his army over the Puerto
de Arraiz passes, to Santesteban, had not struck him as a likely
contingency. Hence his detailed orders overnight were inappropriate
to the facts which appeared next morning. He directed Picton to
pursue whatever was before him on the Roncesvalles road—thinking
that Foy and Lamartinière would escape in that direction; but lest
they should have gone off by Eugui and the Col de Urtiaga he
directed Pakenham to take the 6th Division from Olague, when it
should have reached that place, across the hills to Eugui, from
whence he could join Picton if necessary. Campbell’s Portuguese
were to turn off in the same direction and make for Eugui and the
Alduides. Unfortunately, Picton was thus set to pursue nothing, while
Pakenham was twelve hours behind Foy, and never likely to catch
him.
The main pursuit was to be urged on the chaussée leading by
Olague and Lanz to Elizondo, whither it was supposed that Soult
would have taken the bulk of his army. From Ostiz and the
neighbourhood Byng and Cole were to march in this direction,
conducted by Wellington himself, while from the other side Hill was
to lead thither his own four brigades, and the Spanish reinforcements
which had reached him at the end of the combat of Beunza.
Only Dalhousie and the 7th Division were directed to take the
route of the Puerto de Arraiz, and this not with the object of pursuing
the main French army, but rather as a flanking movement to favour
the operation allotted to Hill. And Dalhousie, unfortunately, was not
well placed for the march allotted to him, since he was near Ostiz,
and had to get to his destination by a cross march via Lizaso.
A separate note for Charles Alten, written at the same time as the
rest of the orders, but not sent out till the following morning, directed
the Light Division to march back to Zubieta where it would be able to
communicate with the column that went by the Puerto de Arraiz, i.e.
that of Dalhousie[997], and be well placed for flank operations against
the retreating enemy.
The net result of all this was to send over half the available troops
—Picton, Pakenham, Campbell, Byng, and Cole—on roads where
no enemy would be found. And Hill’s force would have suffered the
same fate, if it had not been in such close touch with D’Erlon that it
could not help following, when it enemy’s route became evident.
Unfortunately—as Soult had perhaps calculated—Hill had troops
whose ranks had been terrible thinned, and who were tired out by an
unsuccessful action fought on the preceding afternoon.
The day’s work was unsatisfactory. Picton, of course, found out at
Zubiri that everything that had been on the Roncesvalles road—the
small detachment already spoken of[998], and a mass of stragglers—
had turned up toward Eugui and the Alduides on the preceding night.
And Cole discovered that Foy had passed the Puerto de Urtiaga a
whole march ahead of him. Wellington, with the column on the great
chaussée, pressed rapidly across the Velate and reached Irurita,
with the exasperating result that he discovered that only 500 to 2,000
French had passed that way[999]. On the other hand, he had news
from the west that an immense mass of the enemy had gone by the
Puerto de Arraiz, with Hill and Dalhousie after them. There were
doubts whether the pursuing force was not dangerously small—at
any rate, it would have to be cautious. And it was tiresome that the
position of the Light Division was still unknown—it might (or might
not) have a chance of falling on the flank of Soult’s long column,
either at Santesteban or at Sumbilla. Wellington’s own troops had
marched far and fast from Ostiz to Irurita, but there was in the
evening enough energy left in Byng’s brigade for a short push
farther. News came in that a great convoy of food from St. Jean de
Luz had just reached Elizondo, where it had halted under the
protection of the regiment which D’Erlon had left there on the 27th.
By a forced march in the evening Byng’s flank companies surprised
and captured the whole—a good supply of bread, biscuit, and brandy
—the escort making off without resistance. The brigadier had the
heads of the brandy casks stove in, before the weary troops could
get at them, ‘it was a sight to see the disappointed soldiers lying
down on their faces and lapping up the liquor with their hands[1000].’
All this, of course, was unimportant. The real interest of the
doings of July 31st lay on the road from Lizaso to the Puerto de
Arraiz. Hill, as was natural, was late in discovering that the whole of
the French army had passed across his front, since Abbé’s division
still lay at eight in the morning in battle-order blocking his way. But
having got the news of the decisive success won by his chief on the
preceding day, Hill had to attack the hitherto victorious enemy in
front of him, knowing that the general situation was such that they
could not possibly stand. His advance was not made till 10 a.m.—a
sufficient proof of the difficulty of resuming the offensive with tired
and beaten troops. When once, however, it began, the 2nd Division
showed that if its numbers were wasted, its fighting power was still
strong. And the delay in its attack allowed of the arrival of the 7th
Division, who were able to co-operate in a way that would have been
impossible if the fighting had started at daybreak.
On the other hand, the hours between dawn and 10 a.m., during
which his retreat was unmolested, were invaluable to Soult, whose
army was jammed in the passes in a most dangerous fashion. He
had taken the lead himself, with the two cavalry divisions and the
baggage, ordering Reille, whose troops were the most demoralized
of all, to follow, with Clausel in his rear—D’Erlon stopping behind as
rearguard to hold back the enemy. Now cavalry moves slowly in an
uphill climb on a narrow road; while worn-out mules and pack-horses
go much slower still, and are always breaking down and obstructing
the route. The result was a complete block in the defiles: when Reille
heard firing commencing in the rear, he grew so anxious that he
ordered his infantry to push on anyhow, and thrust their way through
the baggage by force[1001]. This naturally made matters still worse.
Clausel found a better plan: the Puerto de Arraiz gives its name to
what is really not a single path, but three parallel ones of various
merit, all crossing the same dip in the main crest of the Pyrenees
within a short distance of each other. They come together again on
the north side of the watershed near the village of Donna Maria,
whence some writers call the whole group ‘the Donna Maria passes.’
Clausel, leaving the best and most obvious track to the others,
crossed by the most eastern of the three, the Puerto de Arraiz
proper, while the cavalry, Reille, and D’Erlon took the western route
which is locally known as the Puerto de Eradi, and comes down
more directly on to Santesteban.
When Hill’s attack began to develop from Lizaso, D’Erlon ordered
Abbé’s division to give ground, before it was too closely pressed, but
halted it for a stand again, on heights by the Venta de Urroz, six
miles farther north, at the foot of the passes. Darmagnac and
Maransin were visible higher up the crest, where they were waiting
till the road should be clear in front of them. It was now nearly two
o’clock, and Dalhousie’s division was nearing the front, and was
visible closing towards Hill’s right. Undoubtedly the proper game was
to await its arrival, and use it to turn Abbé’s flank. But Hill directed
his leading troops to prevent the enemy from withdrawing, and the
vanguard was this day in charge of the reckless William Stewart,
who despite his Maya wound had come back to his troops, and
appeared with his damaged leg strapped to his saddle in a roll of
cushions. He ordered Fitzgerald’s brigade to attack at once frontally:
this was really wicked; the three battalions had lost nearly half their
numbers at Maya, and 150 men more at Beunza on the preceding
afternoon. They were a mere wreck—under 1,000 bayonets: the
position opposite them was a steep wooded hill, held by the most
intact division of the whole French army, over 7,000 strong. The
attack was delivered with great courage, but was hopeless from the
first, and repelled with loss[1002]. Stewart then repeated it, throwing in
Pringle’s brigade as it came up from the rear, to support Fitzgerald’s,
and turning on two guns, which had been brought up with much
difficulty, to shell the woods beside the road. A second attack was
thus delivered with equal want of success. But Dalhousie’s troops
having now come up on the right[1003], a third push was successful,
and Abbé went back, and retired behind Darmagnac, who now took
over the rearguard. The hours gained in this combat had sufficed to
clear the road, and on the further advance of the British, D’Erlon’s
corps gave back rapidly but in good order, and was in full retreat
down the northern watershed when a dense fog came on, and
caused Hill to halt his troops. Stewart’s first wholly unnecessary
frontal attack had resulted in the loss of the acting-brigadier,
Fitzgerald, wounded and a prisoner[1004], and of nearly 200 casualties
among his three weak battalions—91 in the 92nd Highlanders alone,
who having put 750 men in line at Maya on the 25th came out of
action on the 31st with only 250 surviving. The 7th Division had 117
casualties distributed between six English and Portuguese units—
and the total loss in the combat was 387, including a score of
prisoners. That Stewart himself was again wounded and sent to the
rear, after only twelve hours at the front, was a testimonial to his
courage, but a very fortunate event for the 2nd Division. The French
cannot have lost much over 200 men[1005].
Having thus cleared the passes, Hill thought it was his duty to
carry out Wellington’s original orders of the preceding night[1006], by
closing in towards the main body on the Maya chaussée; he did so
by taking a hill track called the Puerto de Sangre, which runs from
Arraiz to Almandoz. Of course this was a grave mistake, as troops
were wanted rather on the Santesteban than on the Elizondo road.
Hill must not be too much blamed, as Wellington might have sent
him new orders to keep to the direction of the enemy’s retreat, and
did not. The danger involved in this move was that only the 7th
Division was left to pursue Soult’s main body, and the force in the
upper Bastan was unnecessarily increased. The responsibility rests
with Wellington, who, even after reaching Irurita in the afternoon and
finding practically no traces of enemy in the Bastan, could not
believe that the French had gone off en masse by the passes to
Santesteban. He would make no sweeping changes in his plan till he
got full information. ‘I shall make the troops dine, and see what is to
be done in the evening’ was his message to Murray[1007]. The
evening brought Hill’s news, and by dawn Wellington was much
more clear about the situation—‘as far as I can judge the enemy
have six divisions between Doña Maria and St. Estevan. There are
three divisions certainly about Eugui and Roncesvalles[1008].’ The
distribution of the French was even still misjudged—there were
troops representing eight divisions, not six, in the Central Bastan
valley. And only one division, Foy’s, had passed eastward; though so
many lost detachments and bands of stragglers had followed it, that
an impression of much larger numbers had been produced.
Despite of Wellington’s misconceptions, Soult’s position at
Santesteban that evening was most uncomfortable. His cavalry
scouts had brought him news that there was a heavy British column
on his right flank, at Elizondo in the Upper Bastan (Cole and Byng).
His rearguard had been fiercely attacked by another column
(Dalhousie and Hill). There were large possibilities of the arrival of
other foes from the north and west, if Graham had not been kept
employed by Villatte. And it was growing most obvious that the story
which D’Erlon had reported, to the effect that the Reserve Division
had crossed the Bidassoa, and was advancing, could not be true.
For cavalry patrols pushing down the river towards Vera could not
find any signs of friendly troops, and had been fired on by Spanish
outposts—Longa’s men. When Soult next wrote to Paris he spoke
out with much bitterness on the criminal torpidity of Villatte, who
might at least, without risking anything, have occupied Vera and the
gorge of the Bidassoa, and have tried to get into touch with the army
in the field. It must be remembered that down to the 30th all Soult’s
communications with his bases at Bayonne and St. Jean-Pied-du-
Port had been either by Maya or by Roncesvalles. He had thrown up
the latter line when he marched north; the former was now closed to
him by the reported arrival of a large hostile force at Elizondo. The
only way home was by the road down the Bidassoa by Sumbilla to
Echalar; and now it turned out that there was no certainty that this
road might not have been blocked by detachments from Graham’s
army. The situation was anything but hopeful, and a complete
disaster was by no means outside the bounds of possibility. One
thing was certain—the army must get out of the Santesteban cul-de-
sac as soon as possible, and by the only road that was not known to
be intercepted. But prompt flight was rendered difficult by the
presence at head-quarters of two divisions of quite useless cavalry, a
convoy of many thousands of wounded, and the baggage of eight
divisions.
At evening on the 31st the Marshal had been so much disturbed
by the news of the presence of the British at Elizondo, from whence
they could descend on Santesteban by following the road along the
Bidassoa, that he had thrown out the whole of Reille’s surviving
infantry (perhaps 6,000 men) to cover the road by the river against
any attack. But the enemy did not move that night—Wellington was
resting his men and waiting for news. Dalhousie had halted on the
heights by the Puerto de Arraiz when the fog came down at 5 p.m.,
and did not follow D’Erlon down to the valley.
Hence Soult had the power to arrange for a flitting before dawn,
on the only possible route—a gorge twelve miles long where the
road follows the rocky bed of the Bidassoa in all its curves, with the
water on its left and steep wooded hills on its right. The line of march
was headed by one infantry battalion of Reille’s corps to clear the
way[1009], then came Treillard’s dragoons[1010], six regiments, taking
up an intolerable length of road, then the remains of Lamartinière’s
division[1011], then the wounded followed by the baggage train, then
the handful of men that represented the wrecked division of
Maucune, then (apparently) Pierre Soult’s cavalry[1012]. D’Erlon’s
corps was to follow—in the order Abbé, Maransin, Darmagnac,
followed by another mass of baggage. Clausel’s wing was directed
to bring up the rear, with the task of holding back any pursuit either
from the direction of Elizondo or that of the Donna Maria passes. It
was certain that there was danger from both sides—so the start was
made early—at 2.30, long ere dawn. Reille was directed to lead the
column along the river as far as the bifurcation of the routes to Vera
and to Echalar, where he was to take the latter, and turn off from the
Bidassoa: for the last stage into France was to be made over the
Puerto de Echalar and not over the more westerly Puerto de Vera.
Apparently D’Erlon was ordered to branch off at Sumbilla with his
infantry alone, and to take a separate mountain-track to Echalar,
which few maps mark. This is, at any rate, Soult’s statement; but as
D’Erlon makes no mention of such directions, and did not actually go
that way (though Clausel did), the order matters little to the historian.
The unpleasant possibilities of the situation of the French on the
night of July 31st-August 1st seem to have been more clearly
discerned by Soult than by Wellington—as was natural, since the
Marshal knew much better the exact state of his own army. There
was a positive danger that it might be enveloped from all sides on
the following day. But Wellington does not seem to have
contemplated so great an operation, though he had a clear notion
that the enemy might be much incommoded and harassed if all went
well. He had hopes that something might be done by means of the
Light Division—whose position was still, most unluckily, a matter of
doubt. He had written on the preceding afternoon to Charles Alten to
say that if he had got back to Zubieta, he ought to be told that a large
body of the enemy was marching by the Donna Maria passes: ‘it is
very desirable that you should endeavour to head them at St.
Estevan. If you should find that you cannot head them there, you
might at Sumbilla, or you might cut in upon their column of march:
they are in the greatest disorder. The head of our troops is here at
Irurita, and others are following the enemy by Doña Maria.
Communicate this to Sir Thomas Graham, via Goizueta[1013].’ It is
quite clear that there is no idea of encirclement in this order, but only
one of molestation. And it is equally obvious that Wellington had no
idea of using any of Graham’s forces to block the gorge of the
Bidassoa. His message to that general on the 31st is, ‘we are going
to act immediately against a column which is retiring by the Doña
Maria road. We have plenty of troops in the proper direction, and if
we can overtake the column, I hope its rear will suffer
considerably[1014].’ Graham is asked for no help; and, what is more
curious, Wellington in his last preceding letter had told him that he
attached no importance to keeping possession of Vera, at the actual
gorge of the Bidassoa. ‘I have a letter from General Giron,
expressing apprehensions of the consequences to his position of
losing Vera. The fact is, that Vera is no object to anybody. The
heights are important for the communication with Lesaca by the
valley of the Bidassoa, and the heights on the other side open the
débouché into France. But the loss of both would not affect the
position of Irun, if the passages through the rocky heights on the
right of Irun are well guarded, for which Longa is allotted: and that is
what it is most important to take care of.’[1015] This, it is true, was
written on the 30th, before Wellington had ascertained that any
French force was to retire by Santesteban. But it coincides
completely with Graham’s contemporary letter to his commander,
expressing exactly the same opinion. ‘General Giron seems anxious,
on hearing of Soult’s being repulsed, to undertake an offensive
operation against the Puerto de Vera, which I could not encourage,
being persuaded that his troops would not succeed, against so
strong a post, and that his failure would be very prejudicial.’
In fact it is clear that Graham and Wellington both discouraged
the idea of sending a considerable force to the gorge of the
Bidassoa, which a day later would have proved of incalculable
importance. A single division placed on the cross-roads to Vera and
Echalar by the bridge of Yanzi would have cut Soult’s only line of
retreat. His infantry, no doubt, or great part of it, could have escaped
over the mountains, but the whole of his cavalry and train, and no
doubt many infantry also, must have been captured. To make
matters easy for the enemy, Soult had placed at the head of his
interminable column useless dragoons, and the smallest and most
demoralized of his corps of infantry. Neither Reille’s wasted divisions
nor Treillard’s cavalry could have cut their way through 5,000 steady
troops at the mouth of the defile. And D’Erlon could not have got up
—the road in front of him for miles being blocked with baggage and
helpless horsemen, and his rear harassed by vigorous pursuit.
Unfortunately, however, when Longa complained that he was too
weak on the heights opposite Vera, and reported that the French
were turning back, and that his post at the bridge of Yanzi would be
attacked, no more was done to strengthen him than the moving of
one brigade of Barcena’s division to the heights by Lesaca, from
which a single battalion was sent down to the Yanzi position. Yet this
solitary unit had no small effect on the events of August 1, caused a
panic among the enemy, and delayed Soult’s march for hours. What
would have happened if Graham and Giron had sent down a solid
force (e.g. one British and one or two Spanish brigades) it is
impossible to say with accuracy, but the results must have been
tremendous.
There can be no doubt that the legend according to which
Wellington schemed for the complete encirclement of Soult’s army
on the 1st of August, though early and well supported, is inaccurate.
The form which it takes in Napier[1016], Larpent, and Stanhope’s
Conversations with the Duke of Wellington, is that on the evening of
the 31st arrangements were being made for a concentric attack on
Soult, but that they were foiled, under Wellington’s own eyes, by a
party of marauding British soldiers, who strayed near the French
camp, and were taken prisoners. Their appearance from the
Elizondo side betrayed, it is alleged, to Soult that he was outflanked,
and caused him to march in the night instead of at dawn—by which
time he would have been surrounded. Unfortunately for the legend,
we have Soult’s own contemporary dispatch of August 2 to prove
that the news of the presence of the British at Elizondo was brought
him by a cavalry patrol, which reached the village just as it and the
convoy in it were captured by Byng’s brigade. They got away, but
could not tell him whether the convoy-escort had, or had not,
escaped. Moreover, much earlier in the day, Reille had warned the
Marshal that the British were coming up in force on the Velate-
Elizondo road—so the whole story falls through.
Wellington’s limited ambitions of August 1 are made clear by his
dispatch written at 6 in the morning, which says that he is sending
the 4th Division on to Santesteban ‘with the intention of aiding
Dalhousie’s advance, and to endeavour to cut some of them off.’ It is
true that he adds, ‘I sent in triplicate to the Light Division at Zubieta
yesterday, to desire that General Alten should move toward St.
Estevan, and at all events get hold of Sumbilla if he could. But I have
heard nothing of him[1017].’ He was therefore not relying on certain
help from the Light Division, or from Graham or from Longa, though
advices of the situation were sent to all three. Of the troops under his
own hand he only sent the 4th Division to join the hunt. Cole was
directed to push the French on the north bank of the Bidassoa, while
Dalhousie was pressing them on the south bank. Byng was told to
remain stationary, till Hill’s column should come up from Almandoz,
‘when I shall know better how things are situated on all sides, and
how far Sir Rowland has advanced.’
The 4th Division, starting early despite of its long march on the
preceding day, was attacking the French rear by seven o’clock in the
morning—7th Division diaries would seem to show that Dalhousie
was much later in closing. We have, oddly enough, no good account
of the fight that ensued from any British source[1018]; but Clausel’s
narrative enables us to understand pretty well what happened. At
dawn Vandermaesen’s division had been left as rearguard on the hill
facing Santesteban on the north side of the Bidassoa, with Taupin’s
in support, while Conroux’s was trying to make its way towards
Sumbilla, but found the path blocked by D’Erlon’s baggage in front.
Wherefore Clausel directed his brigadiers to give up any idea of
keeping to the road, and to march along the slopes above it, so long
as was possible. When the British appeared, they attacked with long
lines of skirmishers, keeping to the hillside and attempting to turn
Vandermaesen’s flank on the high ground. The French, therefore,
also extended themselves uphill, but reached the crest only after the
enemy had just crowned it. ‘On this ground, where no regular
deployment could take place, the side which had got to the top first
had every advantage.’ Vandermaesen’s battalions evidently broke
up, as we are told that they got into trouble, ‘continuing a retrograde
movement high up the mountain among horrid precipices,’ and were
only rallied on two of Taupin’s regiments above the gorge of the
defile between Santesteban and Sumbilla, where Clausel had to halt
perforce, because there was a complete block in front of him—
Darmagnac’s division of D’Erlon’s corps was halted there from
absolute inability to proceed, owing to trouble in front. The French
narrative then describes an hour of incoherent fighting on the slopes
above Sumbilla, in which Darmagnac’s troops on the road below
were also engaged. It ended with the retreat of all Clausel’s three
divisions across the hills, each taking its own way by foot-tracks up a
different spur of the Atchiola range, and arriving in succession in the
upland valley of Echalar by separate routes. The British did not
follow, but stuck to Darmagnac and the baggage-train down in the
road, whom they continued to press and persecute. All this reads like
a serious fight and a deliberate retreat—but the critical historian must
remark that to all appearances Clausel is glozing over a complete
débandade and a disorderly flight across the mountains—for that
there was no real resistance is shown by the casualty list of the
pursuing British. The 4th Division brigades, English and Portuguese,
lost that day precisely three men killed and three officers and 42 men
wounded among their twelve battalions—i. e. there can have been
no attempt at a stand at any time in the morning—and from the first
moment, when Vandermaesen’s flank was turned, the enemy must
have continued to make off over inaccessible ground as hard as he
could go. If he had tried to hold the pursuers back, the 4th Division
would have shown more than 48 killed and wounded. The 7th
Division had no casualties at all, so evidently did not get to the front
in time to do more than pick up stragglers and baggage. The same
impression of mere flight is produced by the French lists of officers
killed and hurt—six in Vandermaesen’s division, one in Conroux’s,
none in Taupin’s—this should, on the usual proportion between the
ranks, represent perhaps 150 or 160 as the total loss of Clausel’s
corps[1019]. Obviously then, we are facing the record of a flight not of
a fight; and the conduct of these same divisions on the following
morning, when attacked by Barnes’s brigade—of which, more in its
proper place—sufficiently explains the happenings of August 1st.
So much for the chronicle of the rearguard. That of the vanguard
is much more interesting. Reille, as has been before mentioned, was
in charge of the advance, which consisted of one battalion of the
120th Regiment, followed by Treillard’s dragoon division, the
baggage of the corps, and the main convoy of wounded; the rest of
the infantry was separated by a couple of miles of impedimenta from
the leading battalion. There was no trouble, though progress was
very slow, until, late in the morning, the head of the column arrived
near the bridge of Yanzi, where a by-path, leading down from that
village and from Lesaca, crosses the Bidassoa. The bridge of Yanzi
was, as has been mentioned above—the extreme right point of the
long observation line which Longa’s Spaniards had been holding
since July 25th. The village above it, on the west bank, a mile uphill,
was occupied by a battalion of Barcena’s division of the Galician
Army, lent to Longa on the preceding day—the 2nd Regiment of
Asturias[1020]. But there were two companies of Longa’s own on
outlying picket at the bridge, which had been barricaded but not
broken. The road from Santesteban bifurcates a short distance up-
stream from the bridge, the left-hand branch following the bank of
the Bidassoa to Vera, the right-hand one diverging inland and uphill
to Echalar. The route of the French was not across the bridge, since
they were not going to Lesaca or Yanzi, nor past it, since they were
not going to Vera; they had to turn off eastward at the cross-roads,
almost opposite the bridge but a little south of it, and to follow the
minor road which leads up to Echalar along the south bank of the
Sari stream, on which that village stands. When Reille’s battalion at
the head of the marching column came to the cross roads, it was
fired upon by the Spanish post at the bridge. This created some
confusion: the critic can only ask with wonder why Reille, who had
six cavalry regiments under his orders, had not sent out vedettes
along the roads far ahead, and become aware long before of the
obstruction in his front: evidently, however, he had not. After the first
shots were fired, there was a general stoppage all down the column.
The battalion at its head could see that the Spaniards were very few,
and prepared to dislodge them. Meanwhile the dragoons had halted
and many of them, at places where the river was level with the road,
walked their horses into the stream, to let them drink. Suddenly there
came a violent explosion of musketry from the front—the bridge was
being attacked and forced. But to those far down the road, who could
not see the bridge, it sounded as if the enemy was assailing and
driving in the solitary battalion on which the safety of the whole army
depended for the moment. A great part of the dragoons shouted
‘right about turn,’ and galloped backward up the pass without having
received any order[1021], till they plunged into General Reille and his
staff, moving at the head of Lamartinière’s division, and nearly rode
them down. The column of infantry blocking the road stopped the
further progress of the foremost fugitives, who got jammed in a mass
by the impetus of squadrons pressing behind them. Reille could not
make out the cause of the panic, but filed the 2nd Léger out of the
road and sent them past the dragoons by a footpath on the slope, by
which they got to the bridge. It was found that the Spaniards had
been driven from it, and forced to retire up the west bank of the river,
the way to Echalar being clear. Thereupon the battalion of the 120th,
followed by the 2nd Léger, turned up the road, and after them the
leading regiments of dragoons. The officers in charge at the front
forgot that their enemies might return, and left no one to guard the
bridge. Hence, when Reille came up in person a little later, he was
vexed to find that the Spaniards had reappeared on the rocky farther
bank of the river half a mile above the bridge, and were firing across
the ravine at the passing cavalry, causing much confusion and some
loss. Unable to cross the river, which had precipitous banks at this
point, he ordered that the next infantry which arrived—the 2nd
battalion of the 120th—should deploy on the slopes above the road,
and keep down the enemy’s fire by continuous volleys. He also
directed another battalion to cross the bridge, and work up-stream till
they should come on the flank of the Spaniards, and then to drive
them away. This was done, and the rest of the dragoons,
Lamartinière’s infantry, and the head of the column of baggage filed
past the cross-roads and went on towards Echalar—with Reille
himself in their company. He had left a battalion at the Yanzi bridge,
with orders to hold the pass, but had little expectation of seeing it
molested again, taking the enemy for a mere party of guerrilleros.
But worse was now to come. The Spanish companies which had
been driven off were now reinforced by the main body of the
regiment of Asturias, which, coming down from Yanzi village, made a
vigorous attack on the bridge, swept back the French battalion which
was holding it[1022], and began firing into the baggage train which was
passing the cross roads at that moment. The bulk of it turned back in
confusion, and rushed up the defile, soon causing a complete block
among the convoy of wounded and the division of Maucune, which
was the next combatant unit in the line of march. The Spaniards held
the bridge for more than two hours, during which complete anarchy
prevailed on the road as far as Sumbilla, where D’Erlon’s rearguard,
the division of Darmagnac, was now engaged in skirmishing with the
British 4th Division. The real difficulty was that owing to the bad
arrangement of the order of march, it took an inordinate time to bring
fresh troops from the rear up to the head of the column; while Reille,
now safely arrived at Echalar and busy in arranging his troops in
position there, does not seem to have thought for a moment of what
might be going on behind him[1023]. Maucune’s division (a mere
wreck) came up at last, thrusting the baggage and wounded aside:
its general confesses that ‘it fought feebly with the Spaniards at the
bridge—its loss was not more than 30 men. The division was so
weak, its men so short of cartridges, that it was necessary to wait for
one of Count D’Erlon’s divisions to come up, before the road could
be cleared[1024].’ He does not add—but his corps-commander[1025]
gives us the fact—that ‘the 7th Division ended by quitting the road
and throwing itself into the mountains in order to avoid the enemy’s
fire,’ i. e. it went over the hills in disorder, and arrived at Echalar as a
mob rather than a formed body. Abbé’s troops, at the head of
D’Erlon’s column, at last got up, after a desperate scramble through
the mass of baggage, wounded, and (apparently) cavalry also, for
some of Pierre Soult’s regiments seem to have been marching after
Maucune. ‘Jammed between the river, whose right bank is very
steep, and the mountain, whose slopes are wooded and
impracticable, the soldiers shoved the train aside, upsetting much
into the river, and turning the disorder of the movement to profit by
pillaging all that they could lay their hands upon[1026].’ At last Abbé
got four or five battalions disentangled[1027] and formed them to attack
the bridge, which was carried by the 64th Regiment after a struggle
which did the Asturians much credit—the French units engaged
showed a loss of 9 officers, probably therefore of some 200 men[1028].
Leaving a couple of battalions to guard the bridge and the knoll
beyond it, Abbé hurried the rest of his division towards Echalar, the
baggage following as it could, mixed with the troops that were
coming up from the rear. Thus the greater part of D’Erlon’s corps got
through; but there was still one more episode to come in this day of
alarms and excursions. Darmagnac’s division, at the rear of all, had
reached the cross-roads, and had relieved Abbé’s battalions at the
bridge by a covering force of its own, when a new and furious fire of
musketry suddenly broke out from the slopes above, and a swarm of
green-coated skirmishers rushed down the heights, carried the knoll
and the bridge below it, and opened fire on the passing troops—
Darmagnac’s rear brigade—and the mass of baggage which was
mixed with it. This marked the arrival—when it was too late—of the
much tried British Light Division, whose unfortunate adventures of
the last three days it is necessary to explain.
It will be remembered that Wellington had sent orders to Charles
Alten, on the 29th July, that he should move from Zubieta to such a
point on the Tolosa-Yrurzun road as might seem best—possibly
Lecumberri. This dispatch travelled fast, and Alten marched that
same night to Saldias—a short stage but fatiguing, as marches in the
dark are prone to be. Next day—the 30th—the Light Division made
an extremely long and exhausting march by vile mountain roads to
Lecumberri, hearing all day incessant cannonading and musketry fire
to their left—this was the noise of the second battle of Sorauren and
the combat of Beunza. Unfortunately Alten was in touch neither with
Hill nor with Head-Quarters, and though he reached Lecumberri at
dark on the 30th, got no news of what had happened till late on the
afternoon of the 31st, when one of Wellington’s aides-de-camp rode
in, ‘more dead than alive from excessive fatigue[1029],’ bearing the
order issued late on the 30th for the return of the division to Zubieta.
He brought the news of Soult’s defeat—but Wellington and every
one else had supposed that the French would go back by the Puerto
de Velate, and Alten’s orders were merely to get into communication
with the 7th Division, sent on the side-operation by the Puerto de
Arraiz, which was at the time of the issue of the order thought
comparatively subsidiary[1030]. The Light Division marched that
evening to Leyza—eight or nine miles on a mountain road—not a
bad achievement for the dark hours, but critics (wise after the event)
whispered that Alten might have got to Saldias, eight miles farther, if
he had chosen to push the men. It, at any rate, made a mighty
difference to the fate of the campaign that Wellington’s next orders,
those issued from Almandoz at noon on the 31st, found the Light
Division not near Zubieta but at Leyza, when they were handed in
during the small hours before dawn on the 1st.
This dispatch, as will be remembered, told Alten that Soult had
retired by the Puerto de Arraiz and Santesteban, and was obviously
going home through the gorge of the Bidassoa, by Vera and Echalar.
He was directed to ‘head off’ the enemy at Santesteban, if that were
possible, if not at Sumbilla seven miles farther north—or at least to
‘cut in upon their column of march’ somewhere[1031]. All this would
have been quite possible, if Wellington had not on the 29th sent the
Light Division on the unlucky southward march from Zubieta to
Lecumberri. This misdirection was at the root of all subsequent
misadventure. We may add that it would still have been possible, if
the dispatch sent off in the early morning of the 31st to bid the
division come back to Zubieta, had contained any indication that the
enemy was retiring by Santesteban, or that haste was necessary.
But it had only directed Alten to ‘put his division in movement for
Zubieta,’ but to keep up his touch with Lecumberri, and told him that
Dalhousie would be marching by the passes of Donna Maria[1032].
The Almandoz note, which contained the really important general
information and detailed orders, wandered about for many hours in
the sabretache of an aide-de-camp who could not know where Alten
was, and found him after many hours of groping in the night at
Leyza, and not at Zubieta. From the latter place, only six miles from
Santesteban, the operation directed by Wellington would have been
possible to execute in good time—from Leyza (on the other side of a
difficult pass, and many miles farther away) it was not. This simple
fact settled the fate of the Light Division on August 1.
Alten put his men under arms at dawn on that morning, and
marched, as ordered, for Santesteban via Zubieta; having passed
the latter place and got to Elgorriaga, four miles farther on, he
received the news that the enemy had left Santesteban early, and
could not be headed off there. Wellington’s alternative scheme
dictated an attempt to break into Soult’s line of march at Sumbilla, so
the Light Division was put in motion by the very bad country road
over the mountain of Santa Cruz from Elgorriaga to Aranaz and
Yanzi. The men had already gone a full day’s journey, and were
much fatigued. They had (it will be remembered) executed a night
march from Lecumberri to Leyza only twelve hours back. The Santa
Cruz path was heart-breaking—officers had to dismount and walk up
to spare their horses: the men went bent double under their
knapsacks: the day was one of blazing August sunshine: the track
was over big stones embedded in deep shale—one sufferer
compared his progress to striding from one stepping-stone to
another[1033].
On reaching the crest of the Santa Cruz mountain, opposite
Sumbilla, at four in the afternoon, the Light Division at last came in
sight of the enemy—a dense and disorderly column hurrying along
the road from Sumbilla northward, pressed by the 4th Division, the
bickering fire of whose skirmishers could be seen round the tail of
the rearguard. They were separated from the observer’s point of
view by the canon of the Bidassoa, here very deep and precipitous—
the Santa Cruz mountain is over 3,000 feet high. It would have taken
much time to scramble down the steep path to Sumbilla, and the
enemy was already past that village. Alten, therefore, resolved to
push for the bridge of Yanzi, seven miles farther on, with the hope of
cutting off at least the rearguard of the French.
But this seven miles was too much for men already in the last
stages of fatigue from over-marching and want of food. ‘When the
cry was set up “the enemy,” the worn soldiers raised their bent heads
covered with dust and sweat: we had nearly reached the summit of
the tremendous mountain, but nature was quite exhausted. Many
men had lagged behind, having accomplished thirty miles over rocky
roads interspersed with loose stones. Many fell heavily on the naked
rock, frothing at the mouth, black in the face, and struggling in their
last agonies. Others, unable to drag one leg after the other, leaned
on the muzzles of their firelocks, muttering in disconsolate accents
that “they had never fallen out before”[1034].’
This was a heart-breaking sight for the divisional commander,
who could see both the opportunity still offered him, and the
impossibility of taking full advantage of it. After a short halt the
troops, or such of them as could still keep up, were started off again
to shuffle down the shaly track on the north side of the mountain. At
the foot of it, by a brook near the village of Aranaz, the 2nd Brigade
was told to halt and fall out—it was a trifle more exhausted than the
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like