100% found this document useful (9 votes)
66 views52 pages

Instant Ebooks Textbook Client Server Web Apps With JavaScript and Java Rich Scalable and RESTful 1st Edition Saternos Casimir Download All Chapters

Client

Uploaded by

maatygeiber
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 (9 votes)
66 views52 pages

Instant Ebooks Textbook Client Server Web Apps With JavaScript and Java Rich Scalable and RESTful 1st Edition Saternos Casimir Download All Chapters

Client

Uploaded by

maatygeiber
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/ 52

Download the full version of the textbook now at textbookfull.

com

Client Server Web Apps with JavaScript and


Java Rich Scalable and RESTful 1st Edition
Saternos Casimir

https://textbookfull.com/product/client-server-
web-apps-with-javascript-and-java-rich-scalable-
and-restful-1st-edition-saternos-casimir/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Building RESTful Web Services with Java EE 8 Create modern


RESTful web services with the Java EE 8 API Mario-Leander
Reimer
https://textbookfull.com/product/building-restful-web-services-with-
java-ee-8-create-modern-restful-web-services-with-the-java-ee-8-api-
mario-leander-reimer/
textbookfull.com

Building web and mobile ArcGIS Server applications with


JavaScript Lewin

https://textbookfull.com/product/building-web-and-mobile-arcgis-
server-applications-with-javascript-lewin/

textbookfull.com

RESTful Java Web Services A pragmatic guide to designing


and building RESTful APIs using Java 3rd Edition
Balachandar
https://textbookfull.com/product/restful-java-web-services-a-
pragmatic-guide-to-designing-and-building-restful-apis-using-java-3rd-
edition-balachandar/
textbookfull.com

97 Things Every Java Programmer Should Know Collective


wisdom from the experts 1st Edition Trisha Gee

https://textbookfull.com/product/97-things-every-java-programmer-
should-know-collective-wisdom-from-the-experts-1st-edition-trisha-gee/

textbookfull.com
Finite Element Computations in Mechanics with R: A
Problem-Centered Programming Approach 1st Edition Khameel
Bayo Mustapha
https://textbookfull.com/product/finite-element-computations-in-
mechanics-with-r-a-problem-centered-programming-approach-1st-edition-
khameel-bayo-mustapha/
textbookfull.com

SAP Gateway and OData Third Edition SAP PRESS Carsten


Bönnen

https://textbookfull.com/product/sap-gateway-and-odata-third-edition-
sap-press-carsten-bonnen/

textbookfull.com

Jumpstarting the Raspberry Pi Zero W control the world


around you with a 10 computer First Edition Peck

https://textbookfull.com/product/jumpstarting-the-raspberry-pi-zero-w-
control-the-world-around-you-with-a-10-computer-first-edition-peck/

textbookfull.com

Internet Addiction in Adolescents The PROTECT Program for


Evidence Based Prevention and Treatment Katajun Lindenberg

https://textbookfull.com/product/internet-addiction-in-adolescents-
the-protect-program-for-evidence-based-prevention-and-treatment-
katajun-lindenberg/
textbookfull.com

New Directions in Third Wave Human Computer Interaction


Volume 2 Methodologies Michael Filimowicz

https://textbookfull.com/product/new-directions-in-third-wave-human-
computer-interaction-volume-2-methodologies-michael-filimowicz/

textbookfull.com
Business of IT, Law and Business 1st Edition Frank Hatstat

https://textbookfull.com/product/business-of-it-law-and-business-1st-
edition-frank-hatstat/

textbookfull.com
Client-Server Web Apps with JavaScript and Java
by Casimir Saternos
Copyright © 2014 EzGraphs, LLC. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].
Editors: Simon St. Laurent and Allyson MacDonald Indexer: Judith McConville
Production Editor: Kristen Brown Cover Designer: Karen Montgomery
Copyeditor: Gillian McGarvey Interior Designer: David Futato
Proofreader: Amanda Kersey Illustrator: Rebecca Demarest

April 2014: First Edition

Revision History for the First Edition:


2014-03-27: First release

See http://oreilly.com/catalog/errata.csp?isbn=9781449369330 for release details.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Client-Server Web Apps with JavaScript and Java, the image of a large Indian civet, and related
trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.

ISBN: 978-1-449-36933-0
[LSI]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

1. Change Begets Change. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


Web Users 2
Technology 3
Software Development 4
What Has Not Changed 5
The Nature of the Web 6
Server-Driven Web Development Considered Harmful 7
Why Client-Server Web Applications? 8
Code Organization/Software Architecture 8
Flexibility of Design/Use of Open Source APIs 8
Prototyping 9
Developer Productivity 9
Application Performance 9
Conclusion 11

2. JavaScript and JavaScript Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13


Learning JavaScript 14
JavaScript History 15
A Functional Language 16
Scope 17
First-Class Functions 18
Function Declarations and Expressions 20
Function Invocations 22
Function Arguments 22
Objects 23
JavaScript for Java Developers 23
HelloWorld.java 23

iii
HelloWorld.java (with Variables) 27
Development Best Practices 29
Coding Style and Conventions 29
Browsers for Development 29
Integrated Development Environments 30
Unit Testing 31
Documentation 31
Project 31

3. REST and JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37


What Is REST? 38
Resources 38
Verbs (HTTP Request Methods) 38
Uniform Resource Identifiers 39
REST Constraints 40
Client–Server 41
Stateless 41
Cacheable 42
Uniform Interface 42
Layered 42
Code on Demand 43
HTTP Response Codes 43
What Is Success? 43
JSON (JavaScript Object Notation) 44
HATEOAS 46
REST and JSON 47
API Measures and Classification 48
Functional Programming and REST 49
Project 50
Other Web API Tools 54
Constraints Redux 54

4. Java Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Java Language 58
Java Virtual Machine (JVM) 58
Java Tools 60
Build Tools 61
Benefits of Maven 63
Functionality of Maven 64
Version Control 65
Unit Testing 65
JSON Java Libraries 66

iv | Table of Contents
Projects 66
Java with JSON 66
JVM Scripting Languages with JSON 69
Conclusion 72

5. Client-Side Frameworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Overview 75
Starting Point One: Responsive Web Design 77
HTML5 Boilerplate 78
Bootstrap 79
Starting Point Two: JavaScript Libraries and Frameworks 79
Browser Compatibility 79
Frameworks 80
Functionality 80
Popularity 81
Obtaining Starter Projects 82
Download Directly from Repositories 82
Download from Starter Sites 82
IDE-Generated Starter Projects 83
The Rise of the Front-End Engineer 83
Client-Side Templating 84
Asset Pipelines 84
Development Workflow 85
Project 85
Conclusion 88

6. Java Web API Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89


Simpler Server-Side Solutions 90
Java-Based Servers 91
Java HTTP Server 92
Embedded Jetty Server 93
Restlet 95
Roo 96
Embedded Netty Server 100
Play Server 102
Other Lightweight Server Solutions 105
JVM-Based Servers 105
Jython 106
Web Application Servers 107
Development Usage 107

Table of Contents | v
Conclusion 107

7. Rapid Development Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109


Developer Productivity 109
Optimizing Developer and Team Workflow 112
Example: Web Application Fix 114
Example: Testing Integration 115
Example: Greenfield Development 116
Productivity and the Software Development Life Cycle 117
Management and Culture 117
Technical Architecture 118
Software Tools 119
Performance 120
Testing 120
Underlying Platform(s) 122
Conclusion 122

8. API Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123


A Decision to Design 124
Practical Web APIs Versus RESTful APIs 125
Guidelines 127
Nouns as Resources; Verbs as HTTP Actions 127
Query Parameters as Modifiers 128
Web API Versions 129
HTTP Headers 130
Linking 130
Responses 130
Documentation 130
Formatting Conventions 131
Security 131
Project 131
Running the Project 132
Server Code 132
Curl and jQuery 134
Theory in Practice 135

9. jQuery and Jython. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137


Server Side: Jython 138
Python Web Server 138
Jython Web Server 138
Mock APIs 139
Client Side: jQuery 140

vi | Table of Contents
DOM Traversal and Manipulation 141
Utility Functions 142
Effects 142
Event Handling 143
Ajax 143
jQuery and Higher-Level Abstractions 143
Project 144
Basic HTML 145
JavaScript and jQuery 145
Conclusion 147

10. JRuby and Angular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149


Server Side: JRuby and Sinatra 150
Workflow 150
Interactive Ruby Shell 151
Ruby Version Manager (RVM) 151
Packages 152
Sinatra 153
JSON Processing 154
Client Side: AngularJS 155
Model 155
Views 156
Controllers 156
Services 156
Comparing jQuery and Angular 156
DOM Versus Model Manipulation 157
Unobtrusiveness of Angular 157
Project 158
Conclusion 165

11. Packaging and Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


Java and JEE Packaging 167
JEE Deployment 169
GUI Administration 171
Command-Line Administration 173
Non-JEE Deployment 174
Server Outside 175
Server Alongside 176
Server Inside 177
Implications of Deployment Choice 178
Load Balancing 178
Automating Application Deployment 180

Table of Contents | vii


Project 181
Client 181
Server 182
Conclusion 182

12. Virtualization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183


Full Virtualization 183
Virtual Machine Implementations 185
VMWare 185
VirtualBox 185
Amazon EC2 186
Management of Virtual Machines 186
Vagrant 186
Packer 186
DevOps Configuration Management 187
Containers 188
LXC 188
Docker 189
Project 190
Docker Help 191
Image and Container Maintenance 191
Java on Docker 192
Docker and Vagrant Networking 194
Conclusion 195

13. Testing and Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197


Types of Testing 198
Formal Versus Informal 198
Extent of Testing 198
Who Tests What for Whom? 199
Testing as an Indicator of Organizational Maturity 199
CMM to Assess Process Uniformity 200
Maven to Promote Uniform Processes 200
BDD to Promote Uniform Processes 202
Testing Frameworks 203
JUnit 204
Jasmine 205
Cucumber 205
Project 206
JUnit 207
Jasmine 207
Cucumber 209

viii | Table of Contents


Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Maven Site Reports 209
Conclusion 210

14. Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211


Community 211
History 212
Coda 212

A. JRuby IRB and Java API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

B. RESTful Web API Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

C. References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

Table of Contents | ix
Preface

There are only two hard things in Computer


Science: cache invalidation and naming things.
—Phil Karlton
While cache invalidation is not a difficulty encountered when writing a book, choosing
a suitable title is. The title of this book is intended to represent a broad area of changes
in web development that have resulted in a new approach to designing web applications.
Of course, many aspects of web development can be considered new. Developers scram‐
ble to keep up with enhancements to desktop browsers, new mobile device clients,
evolving programming languages, the availability of faster processors, and an increas‐
ingly discerning audience of users with growing expectations about usability and in‐
teractivity. These changes require developers to continually innovate when coming up
with solutions for their specific projects. But many of these solutions have broader
implications and are not isolated to any particular project.
Therefore, I chose “client-server” as the term which in many ways captures the changes
to web development that have occurred in response to these innovations. Other de‐
scriptions of modern development practices currently in vogue don’t adequately rep‐
resent the problem domain. Web application development is associated with desktop
browsers, but excludes the increasingly relevant area of mobile applications.
The terms Single Page Application and Single Page Interface have been used to distin‐
guish modern web applications from earlier static websites. These terms correctly iden‐
tify modern sites as far more dynamic and interactive than their predecessors.
However, many modern dynamic applications are made up of multiple pages rather
than a single page. The focus in these terms is on the page, the client portion of an
application. They make no specific statement about corresponding server-side devel‐
opment. There are JavaScript frameworks that are also associated with highly dynamic
pages (such as Angular, Ember, and Backbone), but these are also concerned with the

xi
client tier. I wanted the title of this book to encompass more than front-end innovations
and to recognize the corresponding server-side design and web service messaging.
The method of communication captured by the popular acronym REST (Representa‐
tional State Transfer) does suggest the web service messaging style. But the definition
of REST as specified by its author Roy Fielding is very limiting. On his blog, Fielding
lists specific restrictions to REST that are commonly violated in so-called RESTful APIs.
And some even question whether a JSON API can be truly RESTful due to the fact that
it does not satisfy all of the constraints associated with the style of architecture. There
is a continuum by which REST services can be described; so that an API can be described
as RESTful only to the degree that it adheres to the constraints. REST does include client-
server as one of its constraints, and the verb and URL naming conventions are certainly
applicable.
So a JavaScript client consuming messages from a pragmatic “RESTful” API is a signif‐
icant part of the method of development. What about the server component?
Java Enterprise Edition (JEE) includes the JAX-RS API, which uses Java’s flavor of REST
(which is not inherently strict) and is demonstrable using the Jersey reference imple‐
mentation. But limiting to JAX-RS web application development ignores frameworks
and alternate JVM language solutions that are available and particularly appealing for
quick prototypes.
And so crystallizing the intentions of a book in a simple, catchy title is not an easy task.
Fortunately, James Ward did a presentation at OSCON 2012 in which he described the
development of “Client-Server Web Applications with HTML5 and Java.” He listed the
benefits of a method of web application development that is increasingly popular, a
method that I have been involved with in recent years on various projects. And the
phrase “client-server” is the key to understanding what this method is. It captures the
fundamental architectural changes that include aspects of the terms listed above, but
represents the distinct partitioning between the client and server and considers each of
the roles significant.
A client-server architecture of web applications requires a shift (in some cases seismic)
in the way programmers work. This book was written to enable developers to deal with
this revolution. Specifically, it is intended to provide a proper perspective in building
the latest incarnation of modern web applications.

Who Is This Book For?


This book is written for web application developers who are are familiar with the Java
programming language, as well as HTML, JavaScript, and CSS. It is geared toward those
who “learn by doing” and prefer to see and create specific examples of new technologies
and techniques integrated with standard tools. If you want a better understanding of

xii | Preface
recent developments in JavaScript and how the language and its development process
compare with those of Java, this book is for you.
A bit of a balancing act is evident as you read this book. On the one hand, the most
important thing you can take away is a sense of the “big picture”—the influences and
trends causing a shift in the technologies in use. On the other hand, technologies are
often best understood by seeing specific examples. If you are interested in an overview
of how these technologies actually fit together, you will benefit from this book.
My goal in writing this is to help you to make informed decisions. Good decisions result
in the right technologies being used on new projects. They allow you to avoid pitfalls
caused by mixing incompatible technologies or having the wrong expectations about
the implications of a given decision. They help you to step into projects in process and
better support existing code. In short, informed decisions will make you a more pro‐
ductive programmer. They help you make effective use of your time in researching areas
of specific interest in your work now and in the future.

How This Book Is Organized


Chapter 1 provides a general overview of the client-server web application architecture.
It discusses the history of web development and provides a justification for the paradigm
shift in development. This leads into the next three chapters that will describe the tools
used in the development process.
Chapter 2 describes JavaScript and the tools used in JavaScript development.
Chapter 3 introduces web API design, REST, and the tools used when developing
RESTful applications over HTTP.
Chapter 4 pertains to Java and other software that’s used in the remainder of this book.
The next section of the book discusses higher-level constructs (such as client libraries
and application servers) and how these provide separation and allow for rapid devel‐
opment.
Chapter 5 describes major client-side JavaScript frameworks.
Chapter 6 addresses Java API servers and services.
Chapter 7 discusses rapid development practices.
Chapter 8 delves into API design in greater depth.
With an understanding of libraries and a process for speedy development of prototypes,
the next several chapters apply these to specific projects using various JVM languages
and frameworks. The next two chapters use lightweight web servers and microframe‐
works instead of traditional Java web application packaging and servers.
Chapter 9 provides an overview of a project using jQuery and Jython.

Preface | xiii
Chapter 10 documents the development of a project using JRuby and Angular.
The final chapters detail projects using traditional Java web application servers and
libraries.
Chapter 11 looks at the range of packaging and deployment options available in the Java
ecosystem.
Chapter 12 explores virtualization and innovations emerging from the management of
large server environments.
Chapter 13 draws attention to testing and documentation.
Chapter 14 wraps up with some final thoughts on responding to the tumultuous changes
to Internet-related technologies and software development.
Appendix A describes how to explore and manipulate Java classes interactively.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to variables, method
names, and other code elements, as well as the contents of files.
Constant width bold
Highlights new code in an example.
Constant width italic
Shows text that should be replaced with user-supplied values.

This element signifies a tip, suggestion, or general note.

This element indicates a warning or caution.

xiv | Preface
Code Examples
Projects and code examples in this book are hosted on https://github.com/java-
javascript/client-server-web-apps. You can view them online or download a .zip file for
local use. The assets are organized by chapter.
The code examples provided in this book are geared toward illustrating specific func‐
tionality rather than addressing all concerns of a fully functional application. Differ‐
ences include:

• Production systems include greater refinement of selected data types, validation


rules, exception handing routines, and logging mechanisms.
• Most production systems will include one or more backend datastores. To limit the
scope of discussion, databases are not accessed in most of the examples.
• The modern web application includes a large amount of infrastructure geared to‐
ward mobile device access and browser compatibility. Again, unless these are the
specific topic of discussion, responsive design is eschewed for a more minimal
design.
• The practice of some degree of unobtrusive JavaScript to separate CSS and Java‐
Script from HTML is a generally accepted best practice. In the examples in this
book, they are frequently commingled because all aspects of a given application can
be immediately apprised by viewing a single file.
• Unit tests and testing examples are only included when they are directly related to
the topic under discussion. Production systems would include far greater test cov‐
erage and extensive testing in general.

That said, this book is intended to help you get your job done. In general, you may use
the code in this book in your programs and documentation. You do not need to contact
us for permission unless you are reproducing a significant portion of the code. For
example, writing a program that uses several sections of code from this book does not
require permission. Selling or distributing a CD-ROM of examples from O’Reilly books
does require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Client-Server Web Apps with JavaScript
and Java” by Casimir Saternos (O’Reilly). Copyright 2014 EzGraphs, LLC.,
978-1-449-36933-0.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at [email protected].

Preface | xv
Long Command Formats
Code displayed inline will be adjusted to be readable in this context. One convention
used is that of backslashes to allow newlines in operating system commands. So for
instance, the following commands are equivalent and would execute the same way in a
bash session. (Bash is a standard operating system shell that you see when accessing a
Linux server or Mac OS X at the command line.)
ls -l *someVeryLongName*
...
ls -l \
*someVeryLongName*
The same convention also appears in other settings where OS commands are used, such
as Dockerfiles.
Similarly, JSON strings, being valid JavaScript, can be broken up to fit on multiple lines:
o={"name": "really long string here and includes many words"}

// The following, as expected, evaluates to true.


JSON.stringify(o)=='{"name":"really long string here and includes many words"}'

// The same string broken into multiple lines is equivalent.


// So the following statement also evaluates to true.
JSON.stringify(o)=='{"name":' +
'"some really long ' +
'JSON string is here' +
' and includes many, many words"}'

Safari® Books Online


Safari Books Online is an on-demand digital library that
delivers expert content in both book and video form from
the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.

xvi | Preface
How to Contact Us
Every example in this book has been tested, but occasionally you may encounter prob‐
lems. Mistakes and oversights can occur and we will gratefully receive details of any that
you find, as well as any suggestions you would like to make for future editions. Please
address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/client-server-web-apps-js.
To comment or ask technical questions about this book, send email to bookques
[email protected].
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments
Thank you to the following people:

• Meg, Ally, Simon, and the gang at O’Reilly for the opportunity to write this book.
• My brother Neal Saternos and Dr. James Femister for the early suggestions from
days gone by that I might be able to do the “programming thing.”
• Michael Bellomo, Don Deasey, and Scott Miller for their time and expertise as
technical reviewers.
• Charles Leo Saternos for taking a break from Lua game development to do some
fine image and design work.
• Caleb Lewis Saternos for inspiration in perserverence (early morning run anyone?)
and editorial work.
• David Amidon for the first opportunity to work as a software developer and Doug
Pelletier for first the opportunity to develop Java web apps.

Preface | xvii
• All the folks that headed up the projects that inspired this book, including managers
Wayne Hefner, Tony Powell, Dave Berry, Jay Colson, and Pat Doran, and chief
software architects Eric Fedok and Michael Bellomo.
• Geoffrey Grosenbach from PluralSight, Nat Dunn from Webucator, Caroline Kvit‐
ka (and others from Oracle and Java Magazine) for technical writing opportunities
over the past several years that led to the current one.
• My parents Leo and Clara Saternos for bringing me up in a loving household that
included a Radio Shack Color Computer when having a PC at home was still a
novelty and my sister Lori for reminders of important things that have nothing to
do with programming.

My love and thanks to my wonderful wife Christina and children Clara Jean, Charles
Leo, Caleb Lewis, and Charlotte Olivia for the consistent love, support, patience, and
inspiration while this project was underway.
Finally, J.S. Bach serves as a creative inspiration on many levels. Not the least of which
is the dedication that would appear at the beginning of his works—and so I say with
him, Soli Deo Gloria.

xviii | Preface
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
CHAPTER 1
Change Begets Change

The entrepreneur always searches for a change,


responds to it, and exploits it as an opportunity.
—Peter Drucker
What kinds of changes encourage developers to adopt a client-server approach? Shifts
in user behavior, technology, and software development process are the significant
forces that have driven developers to change their patterns of design. Each of these
factors, in a unique and significant way, makes established patterns obsolete. Together
they have encouraged related innovations and a convergence in practice despite the
absence of enforcement or mandated standardization.
Web users have changed. In the early days of the Web, users were satisfied with static
pages and primitive user interfaces. The modern web user has come to expect a high-
performance, interactive, well-designed, dynamic experience. These higher expecta‐
tions were met with an explosion in new technologies and expansion of web browser
capabilities. Today’s web developer needs to use tools and a development approach that
are aligned with the modern web scene.
Technology has changed. Browsers and JavaScript engines are faster. Workstations and
laptops are far more powerful, to say nothing of the plethora of mobile devices now
being used to surf the Web. Web service APIs are the expectation for a modern web
application rather than a rare additional feature. Cloud computing is revolutionizing
the deployment and operation of web applications.

1
Software development has changed. The now popular “Agile Manifesto” values:

• Individuals and interactions over processes and tools


• Working software over comprehensive documentation
• Customer collaboration over contract negotiation
• Responding to change over following a plan

It is now possible to quickly spin up web applications that prove—at least on a small
scale—the viability of a given technology. There is tremendous value to prototyping. As
Fred Brooks, author of The Mythical Man Month (Addison-Wesley Professional), fa‐
mously stated: “Plan to throw one away; you will, anyhow.” A prototype can allow for
early customer or end user interaction that helps solidify requirements early in the
process. It is no longer an insurmountable task to write a functional web application in
a matter of minutes.

Web Users
Modern web application users have well-defined expectations about how they will be
able to interact with a web application:

• Web applications will be available across multiple platforms.


• They will provide a consistent experience across devices.
• They will respond with little or no latency.

The Gartner group claims that in 2014, the personal cloud will replace the PC at the
center of users’ digital lives. There are many implications for web app development.
Users are more technologically savvy and have high expectations for site responsiveness.
They are less passive than in previous years and instead are interactive and engaged.
Websites need to be designed in a way that suggests no limitations in the ability of a
browser to mimic native application experience.
Users expect an application to be exposed in various ways and available in different
situations. Responsive design and support for multiple browsers, platforms, and devices
are the new norm. The use of JavaScript libraries and frameworks is essential to support
the wide variety of target clients.
The New York Times recently reported on the impatience of web users. Among its
findings: a company’s website will be visited less often than that of a close competitor if
it is slower by more than 250 milliseconds. Performance needs to be a key consideration
in web application development.

2 | Chapter 1: Change Begets Change


Technology
Java web application developers are typically familiar with server-side dynamic content.
J2EE and JSP have been refined into JEE and JSF. Projects such as Spring provide ad‐
ditional capabilities geared toward server-side development. This mode of development
made a great deal of sense in the early days of the Web, when web pages were relatively
static, servers were relatively fast, JavaScript engines were slow, and there were few
libraries and techniques to address browser incompatibilities.
By way of contrast, a modern client-server approach involves a server largely responsible
for providing access to resources (typically communicated as messages in XML or
JSON) in response to client requests. In the old server-driven approach, the browser
requested an entire page and it was generated (along with relevant data) for rendering
in the browser. In the client-server approach, the server initially serves pages with little
data. The pages make asynchronous requests to the server as the user interacts with it
and the server simply responds to these events with messages that cause the current
page to be updated.
Initial web development efforts consisted of the creation of static HTML sites. Later,
these sites were augmented with dynamic content using server-side processing (CGI,
Java Servlets). Subsequently, more structured language integration emerged using
server-side templating (ASP, PHP, JSP) and MVC frameworks. More recent technologies
continue in the same tradition and provide additional abstractions of one sort or
another.
Based upon a desire to shield developers from design concerns and the underlying
architecture of the Web, component-based frameworks have emerged. Tag libraries were
an early innovation, and now a component-based approach has been widely adopted
in several popular frameworks:

• Java Server Faces (JSF), an XML-based templating system and component frame‐
work with centralized configurable navigation.
• The Google Web Toolkit is another component framework that leverages the abil‐
ities of Java programmers by letting them focus on Java coding with little need to
directly modify HTML, CSS, or JavaScript.

Each of these frameworks has its place and has been used successfully in production
systems. But like many solutions that try to hide underlying complexities, their usage
is problematic in situations where you need greater control (such as the ability to inte‐
grate large amounts of JavaScript) or you do not conform to the framework assumptions
(for instance, availability of server sessions). This is because these solutions attempt to
hide the fundamental architecture of the Web, which uses an HTTP request-response
protocol following the client-server computing model.

Technology | 3
Browser innovations also led to a shift of responsibility from the server to the client. In
the late 1990s, Microsoft developed the underlying technologies that led to Ajax (a term
coined on February 18, 2005 by Jesse James Garrett). Ajax is an acronym for “asyn‐
chronous JavaScript and XML,” but is more generally applied to various technologies
used to communicate with the server within the context of a given web page. This
allowed small messages to be sent, which made better use of bandwidth when designing
JavaScript-based web applications. Browser performance has increased significantly due
to processor improvements and optimizations to JavaScript engines, so it has made
sense to offload more work from the server to the browser. User interface responsiveness
has evolved to a new level of sophistication.
Mobile device browsers have also provided an additional incentive to further isolate
client-side code from the server. In some cases, a well-designed application leveraging
responsive design principles can be created. If this is not an option, a single consistent
API available for all device clients is very appealing.
Roy Fielding’s doctoral dissertation in 2000 led Java EE 6 to new APIs that deviated from
the previous component-based trajectory. JAX-RS (Java API for RESTful Web Services)
and Jersey (a “production quality reference implementation”) are designed to create
applications reflecting a client-server architecture with RESTful communications.

Software Development
In the past, setting up a new Java project was a rather monumental task. A vast array of
configuration options made it tedious and error-prone. Very little was automated, as
the assumption was that each project would have unique characteristics that developers
would want to account for to meet their specific requirements.
Later influences led to innovations that made setting up a project much simpler. “Con‐
vention over configuration” was an influential mantra of the Ruby on Rails community.
Maven and other Java projects also chose sensible defaults and target easy setup for a
subset of popular use cases.
The availability of scripting languages on the JVM makes it possible to speed develop‐
ment by bypassing the somewhat rigorous type checking of Java. Languages like Groovy,
Python (Jython), and Ruby are loosely typed and constructed in a manner that requires
less code to accomplish equivalent functionality. So-called microframeworks like Sina‐
tra or Play provide minimal Domain Specific Languages (DSLs) to quickly write web
applications and services. And so today, it is a trivial task to set up a minimal set of web
services in a development environment.
The failure of enough large-scale waterfall-style software projects has also made it clear
that there are many advantages to producing a small-scale version of the final product.
A prototype (or prototypes) of the final product can serve many purposes:

4 | Chapter 1: Change Begets Change


• Verify technical foundation of the project
• Create constructs that bridge disparate technologies to be used together
• Allow end user interaction to clarify intended usage and user interface design
• Allow system designers to clarify the interfaces and data structures to be passed
between systems
• Allow programmers to work on different parts of the application in parallel

Prototypes have numerous benefits:

• They are a specific, tangible asset representing the final system to be designed. As
such, they incorporate information that is otherwise stored in design documents,
diagrams, and other artifacts (and frequently in more informal locations like email
and people’s memories of water-cooler conversations).
• Prototypes are concrete implementations. As such, they present the requirements
in a much more tangible form. This can lead to a better understanding of the extent
and quality of the requirements gathered, and can suggest areas where there is need
of clarification.
• Prototypes can immediately expose potential points of failure that are not apparent
before attempting a specific implementation.
• The preceding benefits can lead to better estimates and scheduling due to a more
comprehensive understanding of what is intended.

Prototyping can be leveraged extensively in client-server web application development


because of the clear and unambiguous separation between the client and server. Pro‐
totypes of the server can be provided to the client developers (and vice versa) while
development proceeds in parallel. Or if development is not proceeding in parallel,
server-side calls can be quickly stubbed out so that client-side code can be developed.

What Has Not Changed


The fundamental nature of the Web (a client-server architecture transmitted over
HTTP) has not changed.
New technology does not change everything. High-level programming languages have
not removed the need to understand operating system specifics. Object-relational map‐
ping frameworks have not removed the need to understand relational databases and
SQL. In like manner, there have been consistent attempts to ignore the underlying ar‐
chitecture of the Web in an effort to emulate the experience of desktop applications.

What Has Not Changed | 5


Random documents with unrelated
content Scribd suggests to you:
of September 1893—Rabbi-al-awal 1311 H., sent a Mission
consisting of a few officers under the leadership of Sir
Mortimer Durand to Kabul. And by the Mercy of God Almighty
the two Governments in a friendly manner concluded an
agreement, on November 12, 1893—2 Jamadi-al-awal 1311
H., regarding the limits of the country of H.H. the Amir
towards India, for hundreds of (krohs) miles from Wakhan on
the north to Persia on the south.
(2) In this agreement it was decided between the two
Governments, already bound by agreements and
engagements, that the Indian Government will never interfere
at any time in the countries lying on that side of the line in the
direction of Afghanistan, and that his Highness also will cause
no interference at any time in the countries that may be lying
outside the boundary line in the direction of India.
(3) With the object of demarcating this long boundary with
facility and celerity, it was agreed upon by the two kingdoms,
already bound by treaties and engagements, to divide this
boundary line into certain parts, and each part of this line
should be marked where it is found necessary by the British
and Afghan Commissioners.
(4) Therefore I send this proclamation to you, that I have
been appointed Commissioner by the Government of India to
demarcate that portion of the boundary which pertains to the
tribes noted at the beginning of this proclamation. In this
condition of affairs I shall probably start shortly towards
Afghan limits for Asmar, and being joined at this place by a
Commissioner appointed by H.H. the Amir, demarcate the
boundaries of Afghanistan from Chanak towards the Kabul
river. I shall then, I hope, be able to point out the boundary on
the spot. Until this is done it is not an easy matter for me to
explain the exact features of the boundary. But at present a
brief sketch of the boundary will be understood by you from
the following details:
(5) Whereas the kingdom of Great Britain has agreed that
H.H. the Amir should retain in his possession the country of
Asmar on the north to Chanak situated on the Kunar river, or
the river of Kashkar, the boundary demarcation will
commence from Chanak in a south-westerly direction up to
Kunar, and at a distance of a few English miles from the bank
of the Kunar river towards Bajaur. From Kunar the boundary
line goes southwards, and, taking a bend, ascends the hills
close to Satala Sar, which hills divide the watershed between
the Kunar and Panj-kora rivers. From Satala Sar the
boundary line passes over the crest of the hill, on one side of
which the waters flowing from the Dag Hills fall into the Panj-
kora river, whilst the waters on the other side passing through
the Satala valley, fall into the Kabul river. And in the centre of
this hill lies the Kotal of Satala. The extreme end of the
boundary touches the Kabul river in the vicinity of Polosi.
(6) From a review of the above details you will understand
that in addition to the countries watered by the Kunar river
which lie towards the limits of the Indian dominions, H.H. the
Amir has agreed not to interfere in all that country the eastern
waters of which fall into the Panj-kora river; nor to interfere or
stretch his hand in that quarter of the Mohmand country the
waters of which fall into the Kabul river below Polosi.
(7) On this account your future concerns and relationship
will lie solely with the British Government and no one else,
and I have a hope that by degrees there will be the same
bonds of friendship between you on the one part, and myself
and the frontier officers of the British Government on the other
part, which has existed between the said officers and other
tribes who reside outside the limits of the boundaries of the
Peshawar District.
(8) The last request is that you should firmly believe, and
on this point I will give you every assurance and satisfaction,
that the Government of India has no intention of going beyond
these limits, which form the present boundaries of the Indian
Empire, and that it has no desire to mix itself in any way with
the affairs of your country. Written on the 7th of Zu’l-hijjah
1311 H.—a.d. June 12, 1894.

the road to lundi khana, khyber pass

Since nothing whatever had been decided about the Mohmand


line, the publication of such a rescript was a most improper and
provocative proceeding. The Amir was offended, while the Sipah
Salar retaliated by destroying all copies of the proclamation that
found their way across the border. No doubt, too, it was a sense of
lingering irritation which a little later caused Abdur Rahman to
repudiate the Durand Agreement, where it concerned the Mohmand-
Bajaur region. Ghulam Haidar made the views of the Amir quite clear
at a meeting with Mr. R. Udny and Surgeon-Captain McNabb on
August 12, in Jelalabad. The Sipah Salar there rejected entirely the
proposed division of the Mohmands, claiming, in place of the Panj-
kora-Kunar line, to exercise jurisdiction over them down to the
Peshawar valley. Similarly, the Afghan Commander-in-Chief refused
to secede an inch of Kafiristan. Troubles also followed in the wake of
the Bruce mission. Breaking camp on October 1, and marching viâ
the Gomul valley into Southern Waziristan, the laager at Wano was
attacked by the Waziris on November 3, with such success that an
expedition under Sir William Lockhart was immediately sent against
them. In the end the boundary, from the Gomul in the south to the
Tochi and the Kurram in the north, was settled, the solution of the
Mohmand impasse on April 9, 1895, being due solely to the fact that
detailed for duty on the Mohmand-Bajaur section was the most
distinguished survey officer of his day—Colonel (now Sir Thomas)
Holdich. In no wise rebuffed by the remarkable deficiencies of the
Durand Agreement nor the discrepancies of the Udny manifesto, this
officer contrived through clever adaptation of available geographical
data to evolve something of a border line, although no part of the
boundary defined south of the Hindu Kush bore any relation to the
frontier laid down by Durand or Udny.
Events in the Mohmand country were not confined to the
excitement emanating from the proposed delimitation of the
hinterland. During the last five years an Afghan freebooter from
Jandol, Umra Khan, had made bold bids for supremacy alternately
against the Khan of Jandol and the Mir of Dir, uniting with the one
against the other as his interests dictated and opportunity served.
Success attended him when, in an attempt to occupy part of the
Kunar valley, upon which Abdur Rahman had already cast eyes, he
was badly defeated by Ghulam Haidar. In due course he recovered
and re-establishing his rule over Dir and Nawagai, he contracted an
alliance with Shir Afzal, lately Mehtar of Chitral. At the moment this
man was a fugitive; and, as such, a cat’s-paw of the Amir of
Afghanistan from whose custody he had been permitted to escape,
since Abdur Rahman was proposing to step into his shoes if any
conspicuous result attended Umra Khan’s operations in Chitral.
Moreover, Ghulam Haidar and Umra Khan had come to terms upon
a basis which furnished the Afghan king-maker with supplies,
volunteers and ammunition. If the nature of the agreement between
Abdur Rahman and Shir Afzal were never entirely disclosed, the
character of the understanding between the Sipah Salar of the Amir
of Afghanistan and the progressive ruffian from Jandol was soon
confirmed. As Ghulam Haidar watched over the welfare of the Udny
party in the Lower Kunar valley, the situation shifted early in the New
Year of 1895 from the Mohmand country to Chitral. Here the sudden
appearance of Umra Khan at the head of a motley force on behalf of
Shir Afzal had precipitated a dynastic war. While Umra Khan seized
Kala Drosh in Lower Chitral proclaiming Shir Afzal, the British agent
in Gilgit, Dr. (now Sir George) Robertson, advancing from that station
threw himself into Chitral and set up a cadet of the reigning family as
the rightful ruler. Umra Khan, supported by large numbers of well-
armed Afghan infantry from the Sipah Salar’s camp at Asmar and
plentifully supplied with Kabul breechloaders and ammunition,
advanced against Dr. Robertson, inflicting upon him a crushing
defeat. The effect of this disaster on British prestige was in a
measure effaced by the pluck and determination of the Chitral
garrison, before whom, on March 3, 1895, Umra Khan settled
himself for a siege. His triumph was short lived, since on April 18, the
investment was rudely disturbed by the arrival of Colonel Kelly with
650 men from Gilgit. By then, too, a larger force had taken the field,
for General Sir Robert Low, at the head of 15,000 soldiers with
30,000 transport animals and 10,000 followers, had embarked upon
a campaign in the Swat-Bajaur-Chitral country.
Through the accidence of these events matters had come to an
absolute dead-lock in the Mohmand-Bajaur-Asmar region. The Udny
commission had been withdrawn with only a part of its work
accomplished, the chief receiving the honour of knighthood for his
services. Elsewhere, too, the situation was unsatisfactory. The
border tribes, alarmed at the prospect of enforced demarcation, their
fears accentuated by the establishment of military posts at Wano, in
the Tochi and Kurram valleys, on the Malakand—the key to Swat—at
Chakdara where the Panj-kora had been bridged, and on the
Samana ridge, trembled for their independence. Moreover the
presence of these survey parties was constantly used for the
purpose of exploiting tribal sentiment by Ghulam Haidar, who would
not have acted as he did without very definite instructions and very
acute knowledge of the Amir’s sympathies. Abdur Rahman was thus
engaging in a double game. Exercising a potent inimical authority
over events in the Chitral crisis, as that affair waned he was at pains
to show his amiability towards Great Britain. In April 1895, almost
simultaneously with the raising of the Chitral siege, Nasr Ullah left
Kabul on his visit to England. He arrived in London in May, leaving
for Kabul in the following August, the recipient of a G.C.M.G. and the
bearer of a similar honour to his brother Habib Ullah. The real
purport of the Mission, to secure authority to open direct relations
between Kabul and the India Office as well as with the Viceroy and
to establish official representation in London, failed. The Amir of
Afghanistan professed to find a slight in the curt refusal of the
Imperial Government to accede to his requests, and was in high
dudgeon. Nevertheless, there was nothing remarkable in this
rejection of the Amir’s petition. Sir Henry Fowler, however, committed
a blunder in sanctioning an invitation which led merely to the
ventilation of grievances and paved the way for those preposterous
claims to independent sovereignty which distinguished the later
years of Abdur Rahman’s rule, and, since his demise, have ranked
among the many pretensions of Habib Ullah.
By the autumn of 1895 the Chitral imbroglio had been
straightened, and the remaining months of the year were occupied
with the proceedings of the Pamir Boundary Commission and the
doings of the Afghan army in Kafiristan. Here Abdur Rahman had
embarked upon a brief campaign, which, after forty days of actual
warfare, terminated in the spring of 1896. Aside from these
operations, interest in the frontier situation was riveted upon the
curious theological studies which Abdur Rahman had been pursuing
in Kabul. Expectations were also raised by communications evidently
passing between Ghulam Haidar and the principal border fanatics
Said Akbar of the Aka Khels, the Sarlor Fakir—the Mad Mullah of the
Swat—and the Hadda Mullah. After much labour and while the
letters were in exchange, Abdur Rahman had composed a treatise,
the Twakim-ud-din, expounding the merits of the jehad or holy war,
and the virtues of the ghazi. Satisfied with this work, at the close of
1895, he convened for the Nauroz festival, March 21, 1896, a great
convocation of mullahs drawn from all parts of his dominions and the
Indo-Afghan borderland as well, at which he dilated upon the
essential principles of that doctrine which specially enjoins the
extinction of the infidel. It was a dangerous way to secure his
recognition as one of the supreme heads of Islam, and obviously
antagonistic to the preservation of harmonious relations between the
tribesmen and the Government of India. After much earnest
exhortation the holy men were dismissed, comforted by many gifts
and gracious words. Concerned at the action of the Amir and
compelled to notice the conduct of Ghulam Haidar, the Viceroy of
India (Earl of Elgin) on May 2, 1896, addressed to Abdur Rahman a
remonstrance upon the unfriendly attitude of his frontier officials. The
reply from Kabul is best illustrated by the action of some mullahs
who had been summoned to the Nauroz festival. At the Id of
Pilgrimage, May 25, the title Zia-ul-Millat wa ud-Din, the Light of the
Nation and Religion, was offered to Abdur Rahman. When
confirmation of this tribute had been received from the whole of
Afghanistan the Amir adopted it at a special Durbar on August 24, at
the same time appropriating to himself the further dignity of King of
Islam.
Save for these occurrences in Kabul, a few riots in the Tochi
valley in February, and the conclusion of the work of the Pamir
Boundary Commission the year 1896 was undisturbed. Intrigues
were afoot, however, and emissaries of the Mahommedan religion, in
the shape of bigoted travelling fakirs, were “out” as the perfervid
exponents of a Moslem crusade. Early in May 1897, Abdur Rahman
received at Kabul with great state a Turkish visitor from
Constantinople. A few hours later on the same day the Amir
summoned all the mullahs of the city to a private audience.
Meanwhile correspondence passed between the leading lights of the
Moslem world on both sides of the frontier, and evidences of unrest
and disaffection were increasing. With suspicions lulled by eighteen
months’ comparative calm, or set at rest by the fact that the Chitral
reliefs had been unmolested, the frontier political officers in the Tochi
explored routes, made surveys and constructed roads in
continuation of the protective works which were begun in the Tochi
valley so soon as that area was occupied. The Tochi lies only a little
north of Waziristan and so close to Wano that the Waziris were
readily roused to avenge themselves by the mullahs when
opportunity offered. It came—with the visit of Mr. Gee, the political
officer in Tochi, to Maizar, June 10, 1897, when a treacherous attack
was made upon the party and 72 casualties inflicted. In spite of the
extreme heat of this month retaliatory measures were at once put
into execution, General Corrie Bird taking the field with 7000
soldiers, 10,000 transport animals and 3000 followers.
The mullahs were now actively extolling the cause of the jehad to
their disciples when the persistent efforts of the Hadda Mullah to
excite Mahommedan fanaticism in Swat, Bajaur and Dir were
unexpectedly furthered by the appearance in Swat of the Mad
Mullah. The companion of the Hadda Mullah in his recent stay in
Kabul, he had come direct from the Afghan capital, declaring
everywhere that a holy war had been proclaimed. Under the
enthusiasm inspired by the eloquence of this restless spirit, the Mad
Fakir’s progress through Swat was in the nature of a triumph. Thana
had declared itself for him, when on July 26, the fury of the storm
broke over Malakand and Chakdara. By August 1, a field force of two
brigades under Major-General Sir Bindon Blood arrived at Malakand,
where the opposing tribesmen numbered 20,000 men. Meanwhile,
the apostles of the movement looked to Kabul for their orders.
Letters and proclamations, purporting to describe the Amir’s interest
in it, were issued; and, as the tribes rallied to his call, Hadda Mullah,
relying upon the kindly offices of Ghulam Haidar and emulating the
example of the Mad Fakir, led on August 7, an attack against the
British frontier post at Shabkaddar. Unfortunately for Indo-Afghan
relations the muster for this affair contained, besides several
thousand Mohmands, a large proportion of Afghans from the Kunar
valley, the Khugiani country, the Laughman and Jelalabad districts,
the Basawal and Hazarnao villages, and soldiers in plain clothes
from the Kabul garrison. It was no longer possible for the
Government of India to ignore the complicity of the Afghan frontier
officials. So pronounced was their sympathy with the rising that
Abdur Rahman addressed a firman to the Sipah Salar, containing an
expression of his grave displeasure at their misconduct.
Matters had gone too far to be adjusted by such means, and on
August 13, 1897, Sir Richard Udny, instrumental with Brigadier-
General (now Major-General Sir Edmond) Elles, who was
commanding at Peshawar, in abandoning the Khyber Pass to the
unsupported custody of Afridi militia, directed an emphatic
remonstrance to the Amir of Afghanistan. His Highness was informed
of the nature of the reports which had reached the Government of
India, and was required to take immediate steps to recall his subjects
and to prevent the repetition of so exceedingly grave an offence.
After reminding the Amir that the Viceroy, in May 1896, had called
his Highness’s attention to the unfriendly conduct of the Sipah Salar,
the letter concluded as follows:
It is impossible that Afghan sepoys can have joined in this
attack without the knowledge of the Sipah Salar, and the
Viceroy is constrained to warn your Highness that, if you do
not control the Sipah Salar, or withdraw him from his
command on the frontier, your Highness must be held
responsible for his actions.
Abdur Rahman replied at once to the charges of the Government
of India, returning a denial and reading the correspondence at a
Kabul Durbar held on August 18, in commemoration of his
assumption of the title Zia-ul-Millat wa ud-Din. Facts were a little too
strong for much importance to be attached to this refutation; but the
rebuke, which had now been administered, warned him, doubtless,
that the limits of Government patience in his direction had been
reached. Correspondence on the question became protracted, and
the initial response from Kabul had barely been received when a
further fillip was given to the fighting on the frontier. For several days,
as early as August 16, warnings had been received that the Afridis
were preparing to descend upon the Khyber. It was further stated
that this area of operations would be increased by a simultaneous
attack from the Orakzais against the Samana ridge in support of the
Afridi movement. To its subsequent confusion the Indian
Government at the time was relying upon reports from Sir Richard
Udny, Commissioner of Peshawar, and Brigadier-General Elles,
whose conception of the seriousness of the situation did not prompt
him to employ in support of the posts in the Khyber any portion of the
10,000 men lying idle under his command. Equally with those of Sir
Richard Udny, the exertions of General Elles upon this occasion
were very disappointing.
On August 17, when no less a frontier personage than Malik Amin
Khan reported that an Afridi lasakar of 10,000 men accompanied by
1500 mullahs was preparing to descend upon the Khyber, Sir
Richard Udny telegraphed to Simla:
I am watching events in Orakzai and Afridi country very
carefully from this side, and all my reports from reliable
sources say that up to date there is no serious or general
movement, either among Orakzais or Afridis....
Two days later, August 19, Brigadier-General Elles, telegraphing
to Simla, stated that Sir Richard Udny had informed him that Malik
Amin Khan’s information was much exaggerated, adding that
Captain Barton, Commandant of the Khyber rifles, had reported the
Afridi gathering to be smaller than originally imagined. On the next
day, August 20, alarmed at the gravity of his position and advised by
the officer commanding the Peshawar forces, Sir Richard Udny
withdrew Captain Barton from his post at Lundi Kotal. After
consultation with Colonel Aslam Khan and Brigadier-General Elles,
on the same day in a telegram to the Punjab Government, he
advocated, in spite of the objections of Colonel Aslam Khan to such
a policy, the leaving of the defence of the Khyber positions to the
unsupported activities of the native levies, in accordance with the
terms of the Khyber Agreement of 1881 by which the Afridis were
made responsible for the safety of the pass. In this singular point of
view Brigadier-General Elles concurred, contenting himself, in spite
of the condition of affairs with a faint-hearted and useless
promenade in the direction of Jamrud. Meanwhile, with assistance
withheld, disaster was deliberately invited. So it happened that, on
August 23, when Sir Richard Udny, in a telegram to the Government
of India, was again referring to the terms of the Khyber Agreement,
the advancing wave of the Afridi tide actually broke against Ali
Masjid. From early morning of this day Afridi met Afridi in a brief,
bloody struggle round British supremacy in this border stronghold.
True to their salt, the men who had been in charge of our posts held
out against their own tribesmen until unsupported resistance was no
longer possible. Fort Maude and Ali Masjid fell that same night,
Lundi Kotal resisted valiantly until August 25, capitulating almost at
the moment when the Orakzais were advancing to the attack against
the Samana ridge. There the position was cleared by General
Yeatman Biggs who, having reinforced the garrisons, dissipated his
victory in an ignominious withdrawal harried by his enemy. Tactical
blundering thus accomplished at this point what political irresolution
had effected in respect of the Khyber.

ali masjid fort

In whatever degree the Amir of Afghanistan by his letter of August


18, may have exculpated himself from events preliminary to the Tirah
campaign, the exodus of armed bands from Afghan territory
continued to meet with only passive resistance from the frontier
officials. Under pressure of accumulating evidence, forwarded direct
from Kabul by the British agent, the Viceroy of India on August 30,
1897, addressed a further communication to Abdur Rahman, in the
course of which he wrote:
... It is right that I should tell your Highness that the
information which I have received indicates that tribesmen
from your Highness’s territories have joined the Mullah of
Hadda, and have in other respects committed aggression
against the British Government. Bodies of men from
Jelalabad district crossed the Kabul river openly with flags
flying and drums beating. After the fight at Shabkaddar they
returned in the same manner, carrying their dead and helping
their wounded. On the side of Khost numbers of camels
stolen from my troops in Dawar have been taken across the
border, and it is even reported that these camels have been
ordered to be collected by Sirdar Sherindil Khan. Your
Highness will no doubt recognise the propriety of directing the
restoration of camels belonging to the Government of India,
which have been stolen and carried into Afghan territory.
Your Highness has said that “tribesmen can never join
such a movement openly for fear of me. If any one has come
he must have gone secretly.” What I now ask your Highness,
in accordance with those assurances of friendship which you
have so readily made, is that you will publicly announce to the
tribesmen through your local officers that, if they cross the
border and join in disturbances against the British
Government, they will incur your displeasure. The belief is
entertained by many misguided persons that they will not
incur your Highness’s displeasure by acting in a hostile
manner against the British Government, and this belief can be
dispelled if your Highness’s local officers will keep watch
along the Kabul river and at other places in order to prevent
your Highness’s subjects from crossing the frontier with
hostile intentions, whether secretly or openly. I ask your
Highness, therefore, to issue orders to this effect....
Before the Amir could reply to the letter of August 30 from the
Viceroy, a deputation of Afridi elders, whose intentions certainly lent
colour to the Viceroy’s plaint, arrived at Jelalabad en route to Kabul
for the purpose of presenting a petition to Abdur Rahman. This
document, dated September 5, 1897, was as follows:
The British Government has been from olden times
gradually encroaching upon our country, and even upon
Afghan territory, and has erected forts at various points within
our borders. We have complained of this to the Afghan
Government on many occasions, but your Highness has paid
no attention to our complaints. Therefore, being helpless and
having regard to Islam and our constancy in religion, we have
now, under the guidance of God, opened the door of jehad in
the face of the said Government, and we have severed our
connection with them in every way. We have plundered and
destroyed five forts on the Samana above Hangu, one fort at
Shinauri, at the foot of the Samana, in British territory, one fort
at the Ublan Pass, near Kohat, etc., etc. There are, however,
three big forts on the top of the said mountain (the Samana)
which have not been taken yet. By the grace of God we will
destroy and burn these also. All the people of Tirah have
taken up their position on the top of the mountain (Samana);
and at its base, from Kohat to the Rud-i-Kurman in the district
of Kurram the frontier of the Orakzai runs, and the tribesmen
have been making jehad from time to time within their
respective limits. We will never consent to tender our
allegiance to the British Government and become their
subjects. We will never give up the reins of authority of our
country to the hands of the Government. On the contrary we
are willing to tender our allegiance to the King of Islam. It is
incumbent on the Government of Islam not only to look after
our interests, and consider our position, but that of the whole
of Afghanistan. We therefore send these eighteen persons
from among our Maliks, Mullahs, and Elders, with our
petitions to your Highness’s presence. We are at present
engaged in a jehad on the Samana range, and we request
that your Highness will be pleased to do what is for our good
and benefit; and, by the grace of God, we will act up to your
Highness’s instructions, because we leave the conduct and
management of our affairs in the hands of your Highness in
every respect. We have used our endeavours with our
tribesmen to do service to your Highness. This is the time to
gain the object of your Highness. All the Moslems are now at
the disposal of your Highness in the shape of regular troops,
artillery and money. If the British prove victorious, they will
ruin the Moslems. The services to be done on this side may
be left to us by your Highness. We hope that after the perusal
of our petition your Highness will favour us with a reply. Dated
7 Rabi-us-Sani, 1315 (September 7, 1897).
This prayer of the Afridis had not reached Kabul, when a further
letter, September 6, was sent to the Amir from the Government of
India, anticipating Afghan assistance in catching the Hadda Mullah
should he escape into the Kunar valley. Meanwhile, the aspect of the
precise relations existing between Kabul and the revolting tribesmen,
and disclosed by this deputation from the Afridi jirga was not very
much improved when, on September 10, Abdur Rahman, in
acknowledging the letter of August 30, wrote:
... I have ordered the local officers to keep watch on
Afghan subjects to the best of their ability, and prevent them
from joining Mullah Hadda.... No tribesmen from my territories
can do such an act in an open manner. Some of them,
however, have great faith in Mullah Hadda, and it is possible
that they may have joined him during the night, travelling like
thieves by unfrequented roads. How is it possible to keep
watch on thieves during nights along such an extensive
frontier?... My kind friend, such an arrangement could only be
possible by posting about 10,000 soldiers on all the mountain
tops and at all the fords in that district. Then they will be able
to execute properly such an arrangement, otherwise how
would it be possible to stop the people who are familiar with
the country? If the well-known roads be guarded against
them, they can owing to their knowledge of the country find
paths over mountains and through desert tracts to cross the
frontier. As far as possible, however, the local officials have
been watching and will watch any open movements of the
tribesmen.
As regards the dead and the wounded whom your
Excellency writes that the tribesmen carried away with them
after the fight at Shabkaddar, I beg to state that, if they have
brought back their dead secretly, they have already, according
to their custom, buried them, and now no trace can be
obtained of them. As to the wounded, if questions be asked
they explain that they are always engaged in tribal feuds, with
one another, and they often kill and wound one another, and
that the wounded men have received their wounds in such
tribal feuds; and, as the witnesses belong to the people
concerned, it is difficult to prove anything contrary to what
they allege....
As regards the camels which the Waziri thieves stole from
the troops in Dawar, and brought to Khost where they sold
them to the inhabitants, I have to state that Sirdar Sherindil
Khan has ordered the owners of the camels to keep them
safe. If your Excellency considers it necessary that the
camels should be taken back from them, then, as the
inhabitants of Khost have bought the camels from the Waziri
thieves, the price current in the country should be given to
them and the camels taken back, so that the people of Khost
may not suffer loss...!
The air of truculent triumph which pervaded this communication
elicited no rebuke. Naturally enough a government, which made no
effective preparation to protect the native guards of British posts in
their hour of need, would hesitate to take exception at the twist of a
Persian phrase. Two days later, September 12, the same strain of
insolence, coupled with many amiable sentiments, could be detected
in the reply to the Viceroy’s letter of September 6. With remarkable
effrontery Abdur Rahman expressed the fear that collisions might
occur in the Kunar valley between the Afghan and British forces, if
the pursuit of Hadda Mullah were pushed too far in that direction.
Events, culminating with the fall of Saraghari fort on September
12, were making it incumbent to administer sharp punishment to the
Afridis; and the Tirah field force, 60,000 strong, was concentrated at
Kohat under Lieutenant-General Sir William Lockhart for this
purpose. Concerned at the dislocation of border affairs, at the loss of
revenue attendant upon the closing of the Khyber, and deriving an
inspiration from the magnitude of the force which was collecting for
service with General Lockhart, the Amir himself from this time
became less obstructive, withdrawing his own troops from outlying
posts, refusing to harbour armed fugitives and turning a very cold
shoulder to those who invoked his aid. In consequence of this
change of front he refused to permit the Afridi elders to come to
Kabul, detaining them in Jelalabad while he posted in public in the
capital on September 23, the following reply:
I have perused your petitions, all of which were with one
object. I now write to you in reply that it is eighteen years
since I came to Kabul, and you know yourselves that I went to
Rawal Pindi (in April 1885) by the Khyber route. In
consideration of my friendship with the British Government I
had gone to their country as their guest, and on my way I
found many of your tribesmen on both sides of the pass, who
made salaams to me. If what you state now is true, why did
you not tell me at that time about the matter, so that I might
have conferred with H.E. the Viceroy about it? Some years
after this when the boundary was being laid down, Sir
Mortimer Durand passed through the Khyber and came to
Kabul. All the frontier tribesmen knew of this, and saw the
Mission with their own eyes. Why did not then your Mullahs,
and Maliks, and Elders come to me when Sir Mortimer
Durand came with authority to settle the boundary, so that I
could have discussed the matter with him? At that time you all
remained silent, and silence indicates consent. I do not know
on what account now a breach has taken place between you
and the English. But after you have fought with them, and
displeased them, you inform me.
I have entered into an alliance with the British Government
in regard to matters of State, and up to the present time no
breach of the agreement has occurred from the side of the
British, notwithstanding that they are Christians. We are
Moslems and followers of the religion of the Prophet, and also
of the four Kalifs of the Prophet. How can we then commit a
breach of an agreement? What do you say about the verse in
the Koran—Fulfil your promise; to fulfil your promise is the
first duty of a Moslem. God, on the day when the first promise
was taken, asked all the creatures whether he was their God
or not. They said, “Yes, you are our God and our Creator.”
Therefore, on the day of the resurrection the first question will
be about the observance of agreements. Infidels and
Moslems will thus be distinguished by this test. You will thus
see that the matter of the agreement is of great importance. I
will never, without cause or occasion, swerve from an
agreement, because the English, up to the present time, have
in no way departed from the line of boundary laid down in the
map they have agreed upon with me. Then why should I do
so? To do so will be far from justice. I cannot, at the instance
of a few interested people, bring ignominy on myself and my
people.
What you have done with your own hands you must now
carry on your own backs. I have nothing to do with you. You
are the best judge of your affairs. Now that you have got into
trouble (literally, spoiled the matter) you want me to help you.
You have allowed the time when matters might have been
ameliorated to slip by. Now I cannot say or do anything. I
have sent back from Jelalabad the Maliks you had deputed to
me. I gave them each a lungi and ten rupees for their road
expenses, and I did not trouble them to come to Kabul.
In spite of the Amir’s attitude towards the Afridi deputation on
September 23, and his emphatic denial of the complicity of Ghulam
Haidar in his letter to the Viceroy on August 18, evidence of Afghan
participation was again unpleasantly prominent, negotiations for
peace with certain of the tribal factions being complicated by the acts
of the Afghan commander-in-chief. On one occasion, September 1,
when the Hadda Mullah had been compelled to disperse an Afghan
lashkar by specific orders from the Amir, Ghulam Haidar had sent
the fakir encouraging messages, a present of five British rifles,
cartridges and a horse. Five weeks later Major Deane, political agent
in the Dir-Swat-Chitral country, complained on October 8 that two
mule-loads of ammunition sent by Umra Khan from Kabul had
passed through Ghulam Haidar’s camp at Asmar; while a few days
previously Sir Bindon Blood had reported from Panj-kora, September
28:
The jirga told the native political assistant that the Sipah
Salar had encouraged them to attack the troops, promising
ammunition as well as compensation in kind for any loss of
grain....
Again, when the Mahmunds finally submitted, dreading Kabul
reprisals for their surrender they begged to be protected from Abdur
Rahman and Ghulam Haidar. Although these were merely the under-
currents of the situation as it appeared at the outset of the Tirah
campaign in 1897, by the close of those operations in 1898
tribesmen of all denominations of fanatical obstinacy were alluding to
the encouragement which they had received from the Sipah Salar
and Abdur Rahman. Over the singular propensity for blundering
which distinguished the elect in these two years and the protracted
misfortunes attending Anglo-Indian arms during the long series of
minor wars which concluded with the Tirah, it is permissible at length
to draw the veil. In any case, the Tirah, no less a stage in the course
of Anglo-Afghan history than were the earlier occurrences, is of
fading interest in this little survey; the trend of affairs passes, almost
with relief, to consideration of the happier prospect which the advent
of a new Viceroy, Lord Curzon of Kedleston, January 1899,
inaugurated for India itself and of the more encouraging note
introduced into Imperial relations with the spheres beyond its
borders.
jamrud fort
CHAPTER XVII

ANGLO-AFGHAN RELATIONS—continued
Upon the conclusion of the Tirah campaign the forward policy
ceased to be measured by the virulence of Anglo-Afghan amenities.
Relations between Kabul and Calcutta were dominated by the
pleasant impressions of his guest which Abdur Rahman had
gathered when, as the Honourable George Nathaniel Curzon, M.P.,
the incoming Viceroy had visited Kabul in 1894. With much care this
distinguished student had made an elaborate examination of border
politics, presenting the results of his diligence in a series of scholarly
and exhaustive studies of Russia in Central Asia, Persia and the
Persian Question, The Pamirs and the Source of the Oxus, and A
Recent Journey in Afghanistan. By reason of these journeys across
Asiatic Russia, the Pamirs, Afghanistan and Persia, and through his
remarkable opportunities for observation, unrivalled powers of
assimilation, grasp of subject, luminosity of judgment and lucidity of
expression, Mr. George Curzon was without a peer as an authority
on frontier problems. When this brilliant and indefatigable mind was
called to India as Lord Curzon of Kedleston, the methods by which
the forward policy had been regulated in the closing decade of the
nineteenth century had broken down, the labour of reconstruction
reverting to a man who at least was the foremost expert of his time.
Modifications were now essential; and Lord Curzon at once put into
execution a number of important reforms in the economic and
military control of the north-west frontier. The regular garrison in
Chitral was lessened by one third. The soldiers in Lower Swat and
the Malakand were reduced from 3550 men to one battalion and a
half of native infantry and a small detachment of cavalry, while
regular troops were withdrawn from the Gilgit Agency. Similarly,
communication with Malakand was strengthened by constructing a

You might also like