SlideShare a Scribd company logo
Ejb 3 Developer Guide A Practical Guide For
Developers And Architects To The Enterprise Java
Beans Standard Michael Sikora Meenakshi Verma
Chris Mawata Lawrence Bean download
https://ebookbell.com/product/ejb-3-developer-guide-a-practical-
guide-for-developers-and-architects-to-the-enterprise-java-beans-
standard-michael-sikora-meenakshi-verma-chris-mawata-lawrence-
bean-4100280
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Ejb 30 Database Persistence With Oracle Fusion Middleware 11g Deepak
Vohra
https://ebookbell.com/product/ejb-30-database-persistence-with-oracle-
fusion-middleware-11g-deepak-vohra-2309890
Ejb 31 Cookbook Richard Reese
https://ebookbell.com/product/ejb-31-cookbook-richard-reese-2428804
Ejb 3 In Action 2nd Edition Debu Panda Reza Rahman Ryan Cuprak
https://ebookbell.com/product/ejb-3-in-action-2nd-edition-debu-panda-
reza-rahman-ryan-cuprak-36083032
Ejb 3 In Action Debu Panda Reza Rahman Derek Lane
https://ebookbell.com/product/ejb-3-in-action-debu-panda-reza-rahman-
derek-lane-4100284
Ejb 30 In Simple Steps Dreamtech Press
https://ebookbell.com/product/ejb-30-in-simple-steps-dreamtech-
press-5411382
Ejb 30 In Simple Steps
https://ebookbell.com/product/ejb-30-in-simple-steps-4090324
Pro Ejb 3 Java Persistence Api Mike Keith Merrick Schincariol
https://ebookbell.com/product/pro-ejb-3-java-persistence-api-mike-
keith-merrick-schincariol-4106144
Beginning Ejb 3 Java Ee 7 Edition 2nd Edition Jonathan Wetherbee
https://ebookbell.com/product/beginning-ejb-3-java-ee-7-edition-2nd-
edition-jonathan-wetherbee-4167430
Beginning Ejb 3 Application Development From Novice To Professional
1st Edition Raghu R Kodali
https://ebookbell.com/product/beginning-ejb-3-application-development-
from-novice-to-professional-1st-edition-raghu-r-kodali-978406
Ejb 3 Developer Guide A Practical Guide For Developers And Architects To The Enterprise Java Beans Standard Michael Sikora Meenakshi Verma Chris Mawata Lawrence Bean
EJB 3 Developer Guide
A Practical Guide for developers and architects to the
Enterprise Java Beans Standard
Michael Sikora
BIRMINGHAM - MUMBAI
EJB 3 Developer Guide
Copyright © 2008 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of
the information presented. However, the information contained in this book is sold
without warranty, either express or implied. Neither the author, Packt Publishing,
nor its dealers or distributors will be held liable for any damages caused or alleged to
be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2008
Production Reference: 1160508
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847195-60-9
www.packtpub.com
Cover Image by Michelle O'Kane (michelle@vodafone.ie)
Table of Contents
Preface 1
Chapter 1: Introduction to the EJB 3 Architecture 7
Introduction to the Java EE Architecture 7
The EJB 3 Architecture 9
EJB Container Services 11
The JPA Persistence Engine 12
EJB 3 Compared with Earlier Versions 13
Getting Started 14
Installing GlassFish 14
Testing the Installation 16
Accessing the Administrator Console 17
Shutting Down GlassFish 19
Downloading Example Source Code 19
Summary 19
Chapter 2: Session Beans 21
Introduction 21
Stateless Session Beans 22
Annotations 23
Creating a Session Bean Client 25
Running the Example 26
The Program Directory Structure 28
The Ant Build Script 29
The Application Client Container 31
Building the Application 32
Stateless Session Bean's LifeCycle 34
Stateful Session Beans 36
Stateful Session Bean's LifeCycle 39
Local Interfaces 41
Summary 44
Table of Contents
[ ii ]
Chapter 3: Entities 45
Introduction 45
EJB 3 Entities 46
Comparison with EJB 2.x Entity Beans 47
Mapping an Entity to a Database Table 48
Introducing the EntityManager 49
Packaging and Deploying Entities 53
The Program Directory Structure 53
Building the Application 54
Field-Based Annotations 56
Generating Primary Keys 57
Table Strategy 57
Sequence Strategy 58
Identity Strategy 59
Auto Strategy 59
Overriding Metadata Defaults 60
Summary 62
Chapter 4: Object/Relational Mapping 63
O/R Mapping Default Behavior 63
A Banking Example Application 64
Customer Entity 65
Account Entity 68
Address Entity 69
Referee Entity 70
Testing the Application 71
O/R Mapping Overriding Defaults 74
Customer Entity 75
Account Entity 79
Address Entity 80
BankServiceBean 82
O/R Mapping Additional Annotations 84
Referee Class 88
BankServiceBean 88
Composite Primary Keys 89
O/R Inheritance Mapping 91
SINGLE_TABLE Strategy 92
JOINED Strategy 94
Table per Concrete Class Strategy 95
Summary 96
Table of Contents
[ iii ]
Chapter 5: The Java Persistence Query Language 97
Introduction 97
Simple Queries 98
Projection 99
Conditional Expressions 99
Aggregate Functions 101
GROUP BY 102
HAVING 102
Queries with Relationships 103
Joins 103
Inner Joins 103
Outer Joins 104
Fetch Joins 104
Collection Comparison Expressions 105
Constructor Expressions 105
SubQueries 106
Functions 107
CONCAT 107
SUBSTRING 107
TRIM 107
LOWER and UPPER 107
LENGTH 108
LOCATE 108
ABS 108
SQRT 108
MOD 108
SIZE 109
Queries with Parameters 109
Positional Parameters 109
Named Parameters 110
Named Queries 110
Handling Date and Time 112
@Temporal annotation 112
Queries with Date Parameters 113
Datetime Functions 113
Bulk Update and Delete 114
Native SQL 114
Summary 118
Table of Contents
[ iv ]
Chapter 6: Entity Manager 119
Application-managed Entity Manager 119
Entity Manager Merge 123
Entity Manager Methods 124
remove() 124
contains() 125
flush() 125
setFlushMode() 125
refresh() 126
clear() 126
Cascade Operations 126
persist 126
remove 127
merge 127
refresh 127
all 128
Extended Persistence Context 128
Entity LifeCycle Callback Methods 130
Entity Listeners 131
Summary 134
Chapter 7: Transactions 135
Introduction 135
Container-Managed Transaction Demarcation 136
SUPPORTS 137
NOT_SUPPORTED 137
REQUIRED 137
REQUIRES_NEW 137
MANDATORY 137
Never 138
Examples of Transaction Attributes 138
REQUIRED Example 138
REQUIRES_NEW Example 140
NOT_SUPPORTED Example 141
SUPPORTS Example 141
MANDATORY Example 143
NEVER Example 144
Controlling Container Managed Transactions 145
SessionSynchronization Interface 146
Doomed Transactions 148
Concurrency and Database Locking 149
Table of Contents
[  ]
Isolation Levels 149
Lost Update Problem 151
Versioning 152
Read and Write Locking 154
UserTransaction Interface 154
Summary 158
Chapter 8: Messaging 159
Introduction 159
Java Message Service (JMS) API 160
Queue Producer and Consumer Examples 161
Synchronous Queue Consumer Example 163
Running the Queue Producer and Synchronous Queue Consumer Examples 165
An Asynchronous Queue Consumer Example 167
Running the Asynchronous Queue Consumer Example 169
Topic Producer and Consumer Examples 169
Synchronous Topic Consumer Example 170
Running the Topic Producer and Synchronous Topic Consumer Examples 171
An Asynchronous Topic Consumer Example 172
Running the Asynchronous Topic Consumer Example 173
Motivation for Message-Driven Beans 174
A Simple Message-Driven Bean Example 174
A Session Bean Queue Producer 174
A Message-Driven Bean Queue Consumer 176
MDB Activation Configuration Properties 177
acknowledgeMode 177
subscriptionDurability 178
messageSelector 179
MessageDrivenContext 179
MDB LifeCycle 180
MDB Example Revisited 181
Sending Message Confirmation to a Client 183
MDBs and Transactions 187
Summary 188
Chapter 9: EJB Timer Service 189
Introduction 189
Timer Service Examples 190
A Single Event Example 190
An Interval Event Example 192
A Timer Interface Example 194
Timers and Transactions 196
Summary 197
Table of Contents
[ vi ]
Chapter 10: Interceptors 199
Interceptor Methods 200
Interceptor Classes 201
Default Interceptors 204
Interceptor Communication 206
Summary 209
Chapter 11: Implementing EJB 3 Web Services 211
Overview of Web Service Concepts 211
The SOAP Protocol 212
The WSDL Standard 213
The UDDI Standard 213
SOA and Web Services 213
Creating a Java Application Web Service 214
Creating an Endpoint Implementation Interface 216
The WSDL Document 217
The portType Element 218
The binding Element 219
The service Element 219
The message and types Elements 220
The GlassFish WSGEN Tool 220
Deploying a Java Application as a Web Service 222
The GlassFish Admin Console Test Harness 223
Creating a Java Web Service Client 224
Overriding JAX-WS Annotation Defaults 226
Deploying an EJB Session Bean as a Web Service 229
Packaging an EJB Web Service 230
Creating an EJB Web Service Client 230
Summary 232
Chapter 12: EJB 3 Security 233
Java EE Container Security 233
Authentication 234
GlassFish Authentication 234
Mapping Roles to Groups 235
Authenticating an EJB Application Client 237
EJB Authorization 239
Declarative Authorization 240
Denying Authorization 241
EJB Security Propagation 242
Programmatic Authorization 243
Java EE Web Container Security 245
Web-Tier Authorization 245
Table of Contents
[ vii ]
Transport Layer Security 246
Web-Tier Authentication 246
Example of Web-Tier Authentication and Authorization 247
Summary 248
Appendix A: Annotations and Their Corresponding Packages 249
Index 251
Preface
Enterprise JavaBeans (EJB) technology is a core part of the Java EE 5 specification.
EJB is a framework for building enterprise-scale object-oriented, distributed,
component-based business applications. EJB business applications are written in
Java, are scalable and can be deployed on any platform that supports the
EJB specification.
EJB applications are deployed to and execute under the control of an EJB
container. The EJB container provides services typically required by enterprise
applications such as security, transaction management, resource pooling, and
systems management.
The EJB 3 specification, released in May 2006, is a radical change from previous
versions of the technology. Developing business applications is considerably easier
with EJB 3. The handling of persistence in particular has radically changed in EJB
3. Persistence is no longer a service provided by an EJB container but rather by a
persistence provider conforming to the Java Persistence API (JPA) specification.
Java applications which need to be persisted but which do not require the services
provided by an EJB container can be persisted outside an EJB container by a JPA
persistence provider. In this book we cover JPA as well as the core EJB 3 services.
This book is a concise, example-driven introduction to EJB 3. The best way to learn a
new software technology is by studying and trying out programming examples. In
this book you will see a lot of code and one example after another. We do not assume
any prior knowledge of EJB. However this book does assume at least a couple of
years’ experience of Java and some knowledge of relational database technology.
The examples in this book have been deployed on the GlassFish application
server. GlassFish was chosen primarily because this is the Java EE 5 reference
implementation.
Preface
[  ]
What This Book Covers
Chapter 1 Introduction to EJB 3—A general overview of the Java EE architecture
including EJB container services, the JPA persistence engine, and initial installation
of the GlassFish application server.
Chapter 2 Session Beans—Creation of a session bean and its client and examples of
running it from the application client container. Exploring the program directory
structure. Packaging and deploying a session bean. A look at the stateless and
stateful session beans lifecycle.
Chapter 3 Entities—Exploring EJB 3 entities. How to package and deploy entities
and map an entity to a database table. Metadata defaults and how to override them.
Generating primary keys.
Chapter 4 Object/Relational Mapping—One-to-one, one-to-many and many-to-many
associations. Default object/relational mapping values and how to override them.
Object/relational inheritance mapping and additional annotations.
Chapter 5 JPQL (Java Persistence Query Language)—Looking at different groups of
queries including aggregate functions, queries with relationships, subqueries, queries
with parameters and named queries. JPQL joins and functions are also explained.
Chapter 6 Entity Manager—Looks in detail at the entity manager. Covers both the EJB
3 container-managed and application-managed entity managers.
Chapter 7 Transactions—ACID properties and isolation levels. Container-managed
transactions. Bean-managed transactions.
Chapter 8 Messaging—Looks at the JMS (Java Messaging Service) API. Examples of
queue producer and queue consumers. Topic producer and consumers. Message
driven beans: their activation configuration properties, lifecycles and transactions.
Chapter 9 EJB Timer Service—Examples of single and interval events. Timer interface
methods. Timers and transactions.
Chapter 10 Interceptors—Covers interceptor methods, classes and interceptor
communication as well as default interceptors.
Chapter 11 Implementing EJB 3 Web Services—An overview of web service concepts
and the web service definition language (WSDL). Creating and deploying a Java
application as a web service. Creating and deploying an EJB session bean as a web
service. Creating a web service client.
Preface
[  ]
Chapter 12 EJB 3 Security—A look at security, GlassFish authentication, declarative
and programmatic EJB authorization and Web Tier authentication and authorization.
The Appendix shows EJB 3 annotations described in this book with their
corresponding packages.
What You Need for This Book
First you must have version 5 or higher of the Java Development Kit (JDK). This can
be downloaded from http://java.sun.com/javase/downloads/index.jsp.
You������������������������
also need a version of Ant equal to or higher than 1.6.5. Ant is a tool for building
Java programs, similar in concept to the Unix Make tool, except that it is platform
independent. Ant is part of Apache’s Jakarta project. If you are unfamiliar with Ant
you should look at the Ant web site (http://ant.apache.org/). If you do not have
Ant there is no need to download it as the GlassFish application server includes a
copy of Ant.
Finally you need a version of GlassFish equal to or higher than V2b41d. This can be
downloaded from https://glassfish.dev.java.net//.
Instructions on setting up environment variables and installing GlassFish are given
in the Getting Started section in Chapter 1.
Who Is This Book For
Previous experience of working with Java is essential and knowledge of relational
databases is desirable.
This book is primarily aimed at professional developers who already have a working
knowledge of Java. Enterprise architects and designers with a background in Java
would also find this book of use.
As this book is an introduction to EJB 3, it is aimed at those who are new to
EJB 3. However, as the new version of EJB is so radically different from the previous
version (EJB 2.x), the book would also be suitable and of interest to those who have
had experience working with EJB 2.x. The text makes it clear where the differences
between the versions of EJB lie, although it is not explored in detail.
Preface
[  ]
Approach of this Book
This book has been written for developers new to EJB 3 who want to use the
technology. Such readers usually want to see examples and program code. In this
book we work through one example after another and we show lots of program
code. If you are new to a technology and have looked at your first HelloWorld
example, the next thing you want to do is to code and run the program yourself.
In the case of EJBs this also means packaging and deploying the EJB to a container.
Although we promise no HelloWorld examples in this book, we look at packaging
and deployment straight after coding our first EJB, rather than ignoring these topics
or leaving them to the end of the book.
All the source code together with packaging and deployment scripts is available
from the book's web site.
This book is not a reference book, so we don't attempt to cover all EJB 3 features.
We've kept this book concise to help you quickly get up and running with EJB 3.
Although an EJB will run in any EJB container, the deployment process is
container-dependent. This means that we need to pick a specific container for our
examples. Sun's open-source, free GlassFish container was chosen primarily because
this was the Java EE reference container implementation and also because GlassFish
has Toplink embedded. Toplink in turn is the reference JPA persistence engine.
We also chose not to use an IDE (Integrated Development Environment) partly
because they are all quite different. A book based on IDE A would be of little use to a
reader using IDE B. As IDEs are screen-based navigational tools, any resulting book
would contain a large number of screenshots and would be at least double in length.
More importantly is the author's view that an IDE is not an ideal learning tool. Apart
from having to learn to navigate through a large number of screens, often an IDE will
hide the underlying EJB technology. Of course once you have learnt EJB an IDE will
make you much more productive in your work.
Instead we use the Ant build tool for compiling, packaging, deploying, and running
our EJBs.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Preface
[  ]
Code words in text are shown as follows: We name our interface TimeService.
java, which contains a single method definition getTime().
A block of code will be set as follows:
@Stateless
public class TimeServiceBean implements TimeService {
public String getTime() {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt.format(%tr, cal);
return fmt.toString();
}
}
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items will be made bold:
@Stateless
public class TimeServiceBean implements TimeService {
private @EJB NiceDayService niceDay;
public String getTime() {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt.format(%tr, cal);
return fmt.toString() +
niceDay.getMessage();
}
}
Any command-line input and output is written as follows:
C:EJB3Chapter02glassfishlab1buildjar –tvf TimeService.jar
New terms and important words are introduced in a bold-type font. Words that
you see on the screen, in menus or dialog boxes for example, appear in our text like
this:  Under the Web Services heading in the Common Tasks pane on the left of the
screen, click on Arithmetic.
Important notes appear in a box like this.
Tips and tricks appear like this.
Preface
[  ]
Reader Feedback
Feedback from our readers is always welcome. Let us know what you think about
this book, what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to feedback@packtpub.com,
making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on www.packtpub.com or email
suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer Support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Downloading the Example Code for the Book
Visit http://www.packtpub.com/files/code/5609_Code.zip to directly
download the example code.
The downloadable files contain instructions on how to use them.
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in text or
code—we would be grateful if you would report this to us. By doing this you can
save other readers from frustration, and help to improve subsequent versions of
this book. If you find any errata, report them by visiting http://www.packtpub.
com/support, selecting your book, clicking on the let us know link, and entering
the details of your errata. Once your errata are verified, your submission will be
accepted and the errata added to the list of existing errata. The existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
some aspect of the book, and we will do our best to address it.
Introduction to the
EJB 3 Architecture
In this chapter we will give an overview of EJB 3 and how it fits into the Java EE
multi-layer framework. We will also look at installing and getting started with the
GlassFish container. The topics covered are:
An overview of Java EE
The EJB 3 Architecture
Getting Started with GlassFish
Introduction to the Java EE Architecture
Modern enterprise applications have their responsibilities divided over a number
of layers. A common architecture is the 3-layer model consisting of presentation,
business, and database layers. The presentation layer is responsible for presenting
a user interface and handling interactions with the end user. The business layer is
responsible for executing business logic. The database layer is responsible for storage
of business data; typically a relational database management system is used for this
layer. Layering is used throughout computer science for managing complexity where
each layer serves a distinct purpose.
•
•
•
Introduction to the EJB 3 Architecture
[  ]
Java Platform Enterprise Edition (Java EE) technology provides services to
enterprise applications using a multi-layer architecture. Java EE applications are
web-enabled and Java–based, which means they may be written once and deployed
on any container supporting the Java EE standard. An application server is the
environment in which the container resides. However, in practice we don't need to
distinguish between an application server and a container, so we will use the terms
interchangeably. The Java EE specification is supported by commercial vendors such
as Sun, IBM, Oracle, BEA Systems as well as open-source ventures such as JBoss.
Java EE presentation layer technologies include servlets, JSP pages, and JSF
components. These are developed for a business application then subsequently
deployed and run in a web container. A client would interact with the web container
either from a browser or an applet. In either case the http or https internet protocol
would be used for communication.
Enterprise JavaBeans version 3 (EJB 3) is the technology Java EE version 5 (Java EE 5)
provides for the business layer. In Java EE 5 we subdivide the business layer into one
layer which is concerned with business processing and a second layer which
deals with persistence. In EJB 3 the business processing artifacts are session and
message-driven beans. These are developed for a business application and deployed
and run in an EJB container. The persistence layer artifact is an entity; this is
persisted to the database layer using a persistence provider or persistence engine.
The persistence engine implements another specification, the Java Persistence
API (JPA). Both EJB 3 and the JPA are specifications for which a number of
organizations provide implementations. Both specifications can be downloaded
from http://www.jcp.org/en/jsr/detail?id=220. The figure below summarizes
Java EE 5 architecture:
Presentation Layer Business Layer Database
Layer
Client Layer Web Layer Business Logic Layer Persistence Layer
Java EE 5 Container
Web Container
Servlet
JSP page
JSF Component
Web Browser
Applet
Java Application
Client
Application
Client Container
Java
Application
Client
JPA Persistence
Engine
Entity
EJB 3 Container
Session Bean
Message Driven
Bean
Relational
Database
Chapter 1
[  ]
Note that our 3-layer model has become 5-layers. The distinction between client/web
and business logic/persistence layers is not always made. Consequently we refer
to Java EE architecture simply as n-layer or multi-layer. A Java EE container offers
many other services such as web services, the Java Messaging Service (JMS), and
resource adapters.
Note from the diagram that we can access an EJB directly from a Java SE application,
such as Swing, without going through a web container. The Java application can be
stand-alone, or can be run from an Application Client Container (ACC). An ACC
enables a client executing in its own Java Virtual Machine (JVM) outside the EJB
container to access a limited number of Java EE services.
The EJB 3 Architecture
The EJB 3 architecture offers a standard for developing distributed, object-oriented,
component-based business applications. The components developed in an EJB
framework are session and message-driven beans. Collectively these are known as
EJBs. These are usually relatively coarse-grained objects encapsulating a business
process. They are components in the sense that EJBs can be combined to create a
business application. Furthermore if the EJBs have been well designed they can be
reused by another application. EJBs are distributed in the sense that they can reside
on different computer servers and can be invoked by a remote client from a different
system on the network.
A session bean must have a business interface, which can be either remote or local.
A remote client invokes the remote interface of a session bean as shown in the
following diagram:
Introduction to the EJB 3 Architecture
[ 10 ]
However a session bean and its client may reside in the same JVM instance. In such
cases the client invokes the local interface of the session bean. The following diagram
shows a web container client invoking the session beans local interface:
Web Container
Servlet
JSP page
JSF Component
EJB 3 Container
Session Bean
JVM
Local Call
Java EE 5 Container
A message-driven bean is an asynchronous recipient of a JMS message. The client,
which can be a Java application or Java EE component such as a session bean, sends
a JMS message to a message queue or topic. The message queue or topic may be
managed by a Java EE container or alternatively by a dedicated JMS sever. The
following diagram shows a client sending a JMS message which is received by a
message-driven bean:
EJBs are deployed and run in a container which is designed to make applications
scalable, multi-user, and thread-safe. An EJB container also provides a number of
services that an enterprise scale business application is likely to need. We will list
these services in the next section.
In contrast to session and message-driven beans, entities are relatively fine-grained
objects which have a relatively long life and need to be persisted. Prior to EJB 3,
entity beans played the role of entities and were defined as remotely accessible
components, like session and message-driven beans. In EJB 3 entities are Java objects
and so can utilize object-oriented features such as inheritance and polymorphism,
which entity beans could not. In EJB 3, entities are persisted by a persistence
provider or persistence engine implementing the JPA specification. This persistence
engine can run within an EJB container or outside a container where a business
application does not require other EJB services.
Chapter 1
[ 11 ]
Strictly speaking EJBs, being remotely accessible components, include only session
and message-driven beans and not entities. However, whenever we refer to EJBs
we will in general include entities, unless the specific context requires us to make a
distinction. When we refer to EJB components, we mean session and message-driven
beans and not entities.
EJBs being Java-based may be written once and deployed on any application server
supporting the EJB standard.
EJB Container Services
An EJB container provides a large number of services and we will list a few of these
here. Much of this book describes some of these services in detail, in particular those
which a business application is likely to invoke.
EJB containers support concurrency and all EJB components are thread-safe. EJB
containers provide pooling for EJB component instances. Pooling, in particular,
contributes to the scalability of the EJB architecture. We will discuss pooling for
session beans in Chapter 2 and for message-driven beans in Chapter 8. Load
balancing and clustering are EJB container services which also contribute to the
scalability of EJB.
EJB containers provide a naming service, the Java Naming and Directory Interface
(JNDI), for accessing EJBs or any other container-managed resource such as JMS
queue connections. In EJB 3 a simpler annotation-based dependency injection facility
is available which in many cases provides an alternative to JNDI. All EJB 3 containers
support Java RMI-IIOP (Remote Method Invocation run over Internet Inter-Orb
Protocol), which enables a session to be remotely accessed by a client. A client does
not need to know whether the invoked EJB is remote or local, residing in the same
JVM. This feature is known as location transparency.
Business systems are often transactional and EJB provides a container-managed
transaction service. This is described in Chapter 7.
EJB supports messaging by providing JMS-based message-driven beans. We will
discuss message-driven beans in Chapter 8.
EJB provides a basic scheduling capability: the Timer service, which is described
in Chapter 9.
A new feature of EJB 3 is the Interceptor service. This allows common, tangential
aspects of EJB components to be separated from any business logic. This concept is
based on AOP (Aspect Oriented Programming) and is described in Chapter 10.
Introduction to the EJB 3 Architecture
[ 12 ]
EJB allows you to convert a stateless session bean into a web service; this is covered
in Chapter 11.
EJB provides standards for both the authentication and authorization aspects
of security. Authentication is concerned with validating the identity of a user.
Authorization is concerned with controlling a user's access to an application, or part
of an application. We have covered security in Chapter 12.
Last, but certainly not the least, most business applications need a service for
persisting entities. In EJB 3 this service is delegated by the container to a Java
Persistence API (JPA) persistence engine.
The JPA Persistence Engine
Many applications do not require the services provided by an EJB container but
still need persistence services. For this reason JPA has been issued as a separate
specification and applications running outside an EJB container can also make use of
JPA services. The main services include:
Entity Manager
Object/Relational Mapping
The Java Persistence Query Language (JPQL)
The Entity Manager provides services for persistence, transaction management,
and managing the lifecycle of entities. Object/Relational metadata annotations
are provided for mapping entities onto relational database tables. JPQL is used
for retrieving persisted entities. We will look at these in more detail in the
forthcoming chapters.
Although the JPA specification is recent, it leverages object/relational mapping
technology associated with products such as Hibernate and Oracle Toplink. These
products have been available for many years; in the case of Toplink for over a
decade. The JPA specification drew heavily on these two products in particular.
Furthermore, Toplink and Hibernate are the actual default persistence engines for a
number of EJB 3 containers. For example, both Sun's GlassFish container and Oracle
Application Server 11g use Toplink as the embedded persistence engine. The JBoss
EJB 3 container uses Hibernate as the embedded persistence engine. These
are pluggable defaults however, so it is possible to use Hibernate with GlassFish
for example.
•
•
•
Chapter 1
[ 13 ]
EJB 3 Compared with Earlier Versions
The main features introduced in EJB 3 can be summarized as:
Simplified Persistence API
Metadata Annotations
Improved Query Language
Use of Defaulting
Dependency Injection
Simplification of Session Beans
The first two features are probably the most important, but we will expand on each
of the above features in this section.
The main difference between EJB 3 and EJB 2.x is the handling of persistence which
we have already outlined. Prior to EJB 3 there was rather limited object/relational
mapping between entity beans and relational tables. Inheritance and polymorphism
were not possible prior to EJB 3. An EJB 3 entity is truly a Java object; this could not
be said of an entity bean.
The other main EJB 3 innovation is the introduction of metadata annotations.
Metadata annotations were first introduced in Java SE 5, so this version of Java or
higher must be used when developing EJB 3 applications. Metadata annotations
can be used as an alternative to XML deployment descriptors both for configuring
EJB components and specifying object/relational mappings with entities. However,
deployment descriptors can be used in both cases. We will look at annotation versus
deployment descriptor aspects in Chapter 2.
The EJB Query language (EJB QL) available in earlier versions was rather
limited in comparison with JPA's JPQL. In particular JPQL provides the
following enhancements:
Projections
GROUP BY and HAVING clauses
Joins
Subqueries
Dynamic Queries
Queries with parameters
Bulk update and delete operations
•
•
•
•
•
•
•
•
•
•
•
•
•
Introduction to the EJB 3 Architecture
[ 14 ]
Extensive use of defaults is made in EJB 3. So, for example, most metadata
annotations do not require elements or parameters to be specified, the default is
usually common, expected behavior. Annotation elements are usually needed only
when we want to configure exceptional behavior.
Dependency injection, first featured in the Spring framework, has been introduced
in EJB 3 as an alternative to JNDI for looking up container-managed resources.
Session beans have been simplified. We no longer need to specify component and
home interfaces. Furthermore the session bean class no longer has to implement a
number of callback interfaces even when these are not required by the application.
In EJB 3 these lifecycle callback methods are implemented by session beans only
when required.
Getting Started
For this book GlassFish was downloaded on Windows XP and all the examples were
run on that platform. The instructions that follow assume a Windows platform is
being used, however the installation instructions for other platforms such as
Linux/Unix are almost the same.
Installing GlassFish
Before installing GlassFish check that version 5 or higher of the Java Development
Kit (JDK) is present on your workstation. This can be downloaded from
http://java.sun.com/javase/downloads/index.jsp
For this book we used JDK 5.0 Update 12.
Set the environment variable JAVA_HOME to point to the directory in which the JDK
is installed. Add %JAVA_HOME%bin, to the PATH environment variable. This
is done by clicking Control Panel from the Start menu. Then double-click the
system icon. Select the Advanced tab on the System Properties box. Finally click
the Environment Variables button.
Next download a version of GlassFish equal to or higher than V2b41d from:
https://glassfish.dev.java.net//
Chapter 1
[ 15 ]
into the directory in which you want to install it. All the code examples in this
book were tested with GlassFish version V2b41d. The actual name of the
downloaded jar file will depend on the version and platform selected. For this
book glassfish-installer-v2-b41d.jar was used. In the same directory as the
downloaded jar file, run the jar file as follows:
java -Xmx256m -jar glassfish-installer-v2-b41d.jar
This will unzip the file and create the glassfish subdirectory.
Set the GLASSFISH_HOME environment variable to the directory where GlassFish was
installed. Add %GLASSFISH_HOME%bin to the PATH environment variable.
Set the environment variable ANT_HOME to the directory in which Ant is installed.
GlassFish comes bundled with the Ant build tool and the installed Ant directory will
be glassfishlibant.
If you already have a version of Ant equal to higher than 1.6.5 then set
ANT_HOME accordingly.
Add %ANT_HOME%bin to the PATH environment variable.
Change the directory to the glassfish directory and complete the installation by
running the Ant setup script:
ant -f setup.xml
The setup process may fail because of port conflicts with existing software you may
have. If so you will need to edit the setup.xml file. Within the file you should see the
following fragment setting up default properties:
.....
property name=domain.name value=domain1/
property name=instance.name value=server/
property name=admin.user value=admin/
property name=admin.password value=adminadmin/
property name=admin.port value=4848/
property name=instance.port value=8080/
property name=orb.port value=3700/
property name=imq.port value=7676/
property name=https.port value=8181/
property name=glassfish.license value=LICENSE.txt/
....
Change the value for the conflicting port, and run setup again.
Introduction to the EJB 3 Architecture
[ 16 ]
Testing the Installation
GlassFish is started with the following command:
asadmin start-domain domain1
You should see the following messages:
In particular this shows the admin console URL and the URL for web applications.
So enter the URL http://localhost:8080 from a browser. If GlassFish has started
up correctly you should get the following page:
Chapter 1
[ 17 ]
Accessing the Administrator Console
Enter the URL http://localhost:4848 from a browser. You should get the
following page:
Introduction to the EJB 3 Architecture
[ 18 ]
The default user name is admin and the default password is adminadmin. After you
have entered these you should get the following page:
The administrator console is used for numerous tasks such as creating and
configuring domains, monitoring performance, and deploying applications.
An alternative for deploying applications is using the asadmin tool from the
command line.
In the remainder of this book we have used the asadmin tool for deployment.
By including it as an Ant target the whole process of compiling, packaging, and
deploying is automated.
Chapter 1
[ 19 ]
Shutting Down GlassFish
To stop GlassFish use the following command:
asadmin stop-domain domain1
Downloading Example Source Code
The source code for the examples can be found as a zip file on the book's
web site. Download the file and unzip it into a drive and directory of your
choice. The examples in the book assume the source code has been downloaded
into the C: directory. Subdirectories correspond to individual chapters:
C:EJB3Chapter02, C:EJB3Chapter03, and so on. You should consult the readme
file before running any scripts.
Summary
We gave an overview of the EJB 3 architecture and its relationship to the
multi-layer Java EE architecture. EJB technology applies to the business processing
and persistence layers of the multi-layer model. There are three main artifacts
a business application using EJB technology will develop: session-beans,
message-driven beans, and entities.
These artifacts are deployed to an EJB container which provides a number of
services. We had a brief look at some of these services. In particular we saw that a
separate service, the Java Persistence API, is provided for persisting entities.
Finally we saw how to get started with Sun's open-source GlassFish EJB 3
container. All the examples which follow in this book have been deployed and
run on GlassFish.
In the following chapter we will look at developing the EJB component which
handles business processing, namely session beans.
Session Beans
Session Beans are an EJB technology for encapsulating business processes or
workflow. In this chapter we will cover the following topics:
Stateless session beans
Stateful session beans
Annotations
Packaging and Deploying a session bean
Running a session bean client from the application client container
Stateless and Stateful session bean lifecycles
Introduction
In object-oriented analysis and design a control class encapsulates business logic for
a use case. Session beans are used to implement such control classes. Check credit
card details, transfer funds, and book reservation are examples of potential session
bean candidates. Session beans are transient and relatively short lived. In particular,
session beans are not persistent; they are not stored in a database or other permanent
file system. Session beans can create and update entities, which are persistent, as we
shall see in the following chapters.
A client interacts with a session bean by invoking one or more methods defined
in the bean. This sequence of method calls we call a session, hence the name
session beans. The client can be a web-tier client such as a servlet or JSP page, or a
standalone Java application program.
Like EJB 2.x, EJB 3 session beans are a component technology. In EJB 3 a session
bean component consists of a bean interface and a bean class. The bean interface
provides all the bean method definitions, the bean class provides the method
implementations. We no longer have to produce a home interface as was required
in EJB 2.x.
•
•
•
•
•
•
Session Beans
[ 22 ]
It is important to stress that the client does not interact directly with a bean. Instead
the client interacts with a proxy generated by the EJB container. This proxy intercepts
method calls and provides the container services such as transaction management
and security.
Session beans come in two flavors: stateless and stateful. We will start with an
example of a stateless session bean.
Stateless Session Beans
A stateless session bean's state spans a single method call. We cannot have method
A updating an instance variable x say, and expect the updated value of x to be
available for any subsequent method invocation. This holds true both for a new
method B which accesses x, or indeed, if method A is invoked a second or subsequent
time. We have no guarantee that the same stateless session bean instance will be
invoked between method calls. For this reason, stateless session beans should not use
instance variables to maintain conversational state.
As a simple example we will develop a stateless session bean which simply returns
the current time to the client. This is almost as minimal as the traditional HelloWorld
example but is more useful. Recall a session bean component consists of a bean
interface and a bean class. We name our interface TimeService.java, which
contains a single method definition getTime():
package ejb30.session;
import javax.ejb.Remote;
@Remote
public interface TimeService {
public String getTime();
}
Note that we have prefixed the interface definition with the @Remote annotation.
This indicates to the EJB container that this bean may be invoked by a remote client.
By remote, we mean a client that does not reside in the same Java Virtual Machine
(JVM) as the container. An interface can also be local as we shall see later in
this chapter.
The @Remote annotation belongs to the javax.ejb package, as we can see from the
import statement. Annotations belong to a number of packages. We list annotations
and their corresponding packages in Appendix A.
Chapter 2
[ 23 ]
Note that we have decided to place our code in the ejb30.session package. The
interface is implemented by the EJB container, and not the application, when the
bean is deployed to the container.
Next we code the bean class itself, TimeServiceBean.java:
package ejb30.session;
import java.util.*;
import javax.ejb.Stateless;
@Stateless
public class TimeServiceBean implements TimeService {
public String getTime() {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt.format(%tr, cal);
return fmt.toString();
}
}
This class contains the implementation of the getTime() business method. This
looks like any Java class, all we have added is the @Stateless annotation. This
indicates to the EJB container that the session bean is stateless.
Annotations
The option of annotations is one of the most important features which distinguishes
EJB 3 from earlier versions. Metadata annotations were introduced in Java SE 5. For
this reason Java SE 5 or higher must be used in conjunction with EJB 3.
In EJB 2.x, instead of annotations we use XML deployment descriptors. As the
name suggests, deployment descriptors are read by the application server when the
EJB is deployed. We will discuss the deployment process later in this chapter. The
deployment descriptor, ejb-jar.xml, for the above session bean is shown below:
?xml version=1.0 encoding=UTF-8?
ejb-jar xmlns=http://java.sun.com/xml/ns/javaee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
metadata-complete=true version=3.0
xsi:schemaLocation=http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/
ejb-jar_3_0.xsd
enterprise-beans
session
display-nameTimeServiceBean/display-name
ejb-nameTimeServiceBean/ejb-name
Session Beans
[ 24 ]
business-remoteejb30.session.TimeService/business-remote
ejb-classejb30.session.TimeServiceBean/ejb-class
session-typeStateless/session-type
transaction-typeContainer/transaction-type
security-identity
use-caller-identity/
/security-identity
/session
/enterprise-beans
/ejb-jar
Note the lines:
business-remoteejb30.session.TimeService/business-remote
and
session-typeStateless/session-type
indicate that we have a remote stateless session bean. All other lines correspond to
default values for an annotated session bean.
Annotations are far simpler to use than deployment descriptors. Deployment
descriptors tend to be verbose, not very readable by humans and error prone when
manually edited. Any non-trivial deployment descriptor file really needs a tool both
for writing and reading. However annotations have been criticized on the grounds
that deployment aspects are tangential to the definition of a bean and should not
intrude in the bean's code. The use of annotations means recompiling a bean when
we only want to change a deployment aspect; modifying a deployment descriptor
does not warrant recompilation. However annotations are optional in EJB 3. We
can still use XML deployment descriptors if we wish. Furthermore we can mix
both annotations and deployment descriptors in EJB 3. In such cases deployment
descriptors always override annotations.
One approach might be to use annotations for those aspects of an EJB which rarely
change between deployments. For example, the relationship of an entity which
we will discuss in Chapter 4, is likely to be invariant. The same can be said for
transaction attributes of a session bean, which we will discuss in Chapter 7. On
the other hand database table names onto which entities are mapped (covered in
Chapter 3) or security aspects (covered in Chapter 12), for example, are more likely
to change between deployments. Consequently deployment descriptors are more
appropriate here.
Chapter 2
[ 25 ]
On large projects the teams or individuals responsible for deployment may not
be the same as those responsible for development. It is unrealistic to expect the
former to add or modify any annotations within code developed by others. In these
circumstances deployment descriptors would be used.
However, because this is an introductory book and we want to keep its length
reasonably short we will only make use of annotations in nearly all our examples.
Creating a Session Bean Client
Next we will create a client which is a standalone Java application. The client simply
references a session bean, invokes the bean's getTime() method, then prints out
the result:
package ejb30.client;
import javax.naming.*;
import ejb30.session.*;
public class Client {
public static void main(String args[]) throws Exception {
InitialContext ctx = new InitialContext();
TimeService timeService =
(TimeService) ctx.lookup(ejb30.session.TimeService);
String time = timeService.getTime();
System.out.println(Time is:  + time);
}
}
Note that because the client is remote we need to use JNDI (Java Naming and
Directory Interface) to lookup the session bean. All EJB containers implement JNDI.
JNDI is a set of interfaces which has many implementations: RMI, LDAP, and
CORBA amongst others. There are two steps for performing a JNDI lookup. The first
step is to create a JNDI connection by creating a javax.naming.InitialContext
object. One way to do this is to create a java.util.Properties object, set JNDI
properties specific to the EJB container, then pass the properties object as an
argument to InitialContext. This will take the form:
Properties env = new Properties();
// Use env.put to set container specific JNDI properties
InitialContext ctx = new InitialContext(env);
An alternative method is to define the properties in a jndi.properties file and use
the no-arg InitialContext constructor:
InitialContext ctx = new InitialContext();
Session Beans
[ 26 ]
The JNDI properties are then accessed at runtime. The GlassFish container provides
a default jndi.properties file which is contained in appserv-rt.jar. This JAR file
must be in the client's classpath, as we shall shortly see when we examine the Ant
build file.
The second step is to use the InitialContext object to lookup the remote EJB. In
our example this is done by the statement:
TimeService timeService =
(TimeService) ctx.lookup(ejb30.session.TimeService);
Note the argument passed is the global JNDI name. This is generated by the
container at deploy time. The form of the global JNDI name is also container-specific.
In the case of GlassFish this is the fully qualified remote session bean interface name.
In our example this is ejb30.session.TimeService. The lookup result is directly
cast to the session bean interface type, namely TimeService.
We can now invoke the session bean business method:
String time = timeService.getTime();
The use of JNDI is one of the more awkward aspects of EJB technology. Fortunately
in EJB 3 the only occasion its use is mandatory is when a client invokes EJB from
outside the container. If we invoke an EJB from within a container, then we can use
dependency injection annotation metadata instead of JNDI lookups. We will return
to this shortly.
Running the Example
First we need to compile the source code. The Ant script is run from the command
line, as follows:
cd C:EJB3Chapter02glassfishlab1
C:EJB3Chapter02glassfishlab1ant compile
This will compile the interface, TimeService.java, the session bean,
TimeServiceBean.java, and the client, Client.java.
The next step is to package the session bean into an EJB module. An EJB module
consists of one or more EJBs contained in a JAR file. In our example we have just one
EJB, TimeService, and we name the JAR file, TimeService.jar:
C:EJB3Chapter02glassfishlab1ant package-ejb
Chapter 2
[ 27 ]
We can use the jar –tvf command to examine the contents of the JAR file:
C:EJB3Chapter02glassfishlab1buildjar –tvf TimeService.jar
...META-INF/
...META-INF/MANIFEST.MF
...ejb30/
...ejb30/session/
...ejb30/session/TimeService.class
.. ejb30/session/TimeServiceBean.class
Note the JAR file contains the standard META-INF directory and the default manifest
file, MANIFEST.MF.
The next step is to deploy the program. We can do this within the GlassFish
administrator console, which has an option for deploying an EJB module.
Alternatively we can use an Ant script as follows:
C:EJB3Chapter02glassfishlab1ant deploy
Deployment is essentially the process by which applications are transferred to the
control of the application server. The developer copies the EJB module to designated
sub-directories within the application server directory structure. However, behind
the scenes a lot more takes place during deployment. Typically some sort of
verification takes places to check that the contents of the EJB module are well formed
and comply with the Java EE specification. If annotations are used, the application
server may generate corresponding XML deployment descriptor files. Additional
vendor-specific XML files and classes and interfaces are typically generated. Entities
will be mapped to a database and optionally corresponding database tables may
be created during deployment. We will discuss entities and databases in Chapter
3. During deployment security roles are mapped to user groups. We will discuss
security in Chapter 12.
Note that some application servers do not have the option of deploying EJB modules.
Such modules need to be placed in an EAR (Enterprise Application Archive) file
before deployment. We shall see an example of an EAR file shortly.
Finally we can run the example with the run-client Ant command:
C:EJB3Chapter02glassfishlab1ant run-client
Buildfile: build.xml
compile:
run-client:
[java] Time is: 03:21:17 PM
BUILD SUCCESSFUL
Session Beans
[ 28 ]
The Program Directory Structure
Before we describe the Ant build scripts in more detail we will look at the directory
structure in which the source code is placed.
lab1: This is the root directory and contains the following files and subdirectories:
build.xml: This is the Ant build script itself. We will describe it in more
detail shortly.
env.properties: This file contains runtime environment property settings
and is read by the Ant build script. Currently the file contains just one value,
glassfish.home, which is the root directory in which GlassFish is installed.
When writing this book GlassFish was installed on Windows in the
C:/glassfish directory, so the contents of env.properties is:
glassfish.home=C:/glassfish
adminpassword: This file contains the GlassFish administrator password
required for the deployment task. This is identified by AS_ADMIN_PASSWORD.
The initial password, which can be reset of course, is adminadmin. So the
contents of adminpassword are:
AS_ADMIN_PASSWORD=adminadmin
src: This subdirectory contains the source code. Recall the client program,
Client.java, is placed in the ejb30.client package. The package name is
reflected in the subdirectory structure. Subdirectories have also been created
to correspond to the ejb30.session package in which TimeService and
TimeServiceBean have been placed.
•
•
•
•
Chapter 2
[ 29 ]
build: This subdirectory contains files created during the build process. For
example, class files created during compilation and JAR files created during
packaging will be placed here.
The Ant Build Script
We use an Ant build file for automating the compilation of client and session bean
source code as well as packaging and deploying the session bean. We also use the
build file for running the client. All these steps are defined as Ant targets. The Ant
build file is listed below:
project name=ejb30notebook basedir=.
property name=build.dir value=${basedir}/build /
property name=src.dir value=${basedir}/src /
property file=env.properties /
path id=j2ee.classpath
pathelement location=${build.dir}/
fileset dir=${glassfish.home}/lib
include name=javaee.jar/
include name=appserv-rt.jar/
/fileset
/path
target name=clean
delete dir=${build.dir}/
mkdir dir=${build.dir} /
mkdir dir=${build.dir}/lib /
/target
target name=all
antcall target=clean/
antcall target=compile/
antcall target=package-ejb/
antcall target=deploy/
antcall target=run-client/
/target
•
Session Beans
[ 30 ]
target name=compile
javac destdir=${build.dir}
srcdir=${src.dir}
classpathref=j2ee.classpath/		
/target
target name=package-ejb depends=compile
jar jarfile=${build.dir}/TimeService.jar
fileset dir=${build.dir}
include name=ejb30/session/** /
/fileset
/jar
/target
target name=deploy
exec executable=${glassfish.home}/bin/asadmin
failonerror=true
vmlauncher=false
arg line=deploy --user admin --passwordfile
adminpassword ${build.dir}/TimeService.jar/
/exec
/target
target name=undeploy
exec executable=${glassfish.home}/bin/asadmin
failonerror=true
vmlauncher=false
arg line=undeploy --user admin --passwordfile
adminpassword TimeService/
/exec
/target
target name=run-client depends=compile
java classname=ejb30.client.Client fork=yes
classpathref=j2ee.classpath/
/target
/project
Within the path tag we have the classpath, identified by j2ee.classpath. This
contains the javaee.jar file (containing libraries such as javax.ejb) required for
compilation and appserv-rt.jar required for runtime execution of a client.
Chapter 2
[ 31 ]
The clean target deletes and recreates the build directory. This is used to ensure
that all generated files such as class and JAR files are recreated from scratch.
The all target performs all the tasks required to deploy and run the example.
The deploy target uses the GlassFish asadmin tool to deploy the TimeService.jar
file. The line:
arg line=deploy --user admin --passwordfile
adminpassword ${build.dir}/TimeService.jar/
specifies that deployment is performed by the admin user. The admin password is
held in a file named adminpassword.
There is also an undeploy target, which removes TimeService.jar from the
application server.
The Application Client Container
Although accessing an EJB from a client using JNDI is simpler than in EJB 2.x, it is
still rather awkward. The good news is that we can dispense with JNDI altogether
if the client runs from within an application client container (ACC). The EJB 3
specification does not mandate that an EJB-compliant application server provides
an ACC but makes its inclusion optional. Consequently not all EJB-compliant
application servers provide an ACC, however GlassFish does.
An ACC enables a client executing in its own JVM outside the EJB container to access a
number of Java EE services such as JMS resources, security, and metadata annotations.
If the previous client example is run from an ACC then we can use dependency
injection annotation metadata instead of JNDI lookups. Here is the new version
of Client:
package ejb30.client;
import javax.naming.*;
import ejb30.session.*;
import javax.ejb.EJB;
public class Client {
@EJB
private static TimeService timeService;
// injected field must be static
public static void main(String args[]) throws Exception {
String time = timeService.getTime();
System.out.println(Time is:  + time);
}
}
Session Beans
[ 32 ]
We use the @EJB annotation to instruct the container to lookup the TimeService
bean and inject a bean reference into the timeService field. This is an example of
field injection. Another kind of dependency injection is setter injection; we shall see
an example of this later in this chapter. We can then invoke any of the TimeService
methods such as timeService.getTime().
Because the Client class runs in a static context, as a main method, the injected field
must also be static.
Building the Application
We need to modify the build process if we are using an ACC. The build steps are
application sever-specific so what follows in this section applies only to GlassFish.
First we create a manifest.mf file with the contents:
Main-Class: ejb30.client.Client
We need to do this because the client will be bundled in a JAR file, as we shall see
shortly, and we need to indicate which class in the JAR file is the application's entry
point. The compilation and EJB packaging tasks require no change. However in
order to use the ACC we must package the client in a JAR file. The following Ant
script creates a Client.jar file.
target name=package-client depends=compile
jar jarfile=${build.dir}/Client.jar
manifest=${config.dir}/manifest.mf
fileset dir=${build.dir}
include name=ejb30/client/Client.class /
/fileset
/jar
/target
Note that we have included the customized manifest file. The next step is to create an
Enterprise Application Archive (EAR) file. An EAR file is a standard JAR file, with an
ear extension, that contains other JAR files embedded within it. The JAR files can be
EJB modules or any Java classes, such as an application client deployed in a JAR file.
An EAR file can also contain a web module, identified by a war extension. We shall
see an example of this later in the book.
In our example the EAR file, which we name TimeService.ear, will contain the EJB
module TimeService.jar and the client JAR file, Client.jar. The Ant script to
create an EAR file is:
target name=package-ear depends=package-ejb
jar destfile=${build.dir}/TimeService.ear
basedir=${build.dir}
includes=TimeService.jar Client.jar/
/target
Chapter 2
[ 33 ]
Again we can use the jar –tvf command to examine the contents of the EAR file:
C:EJB3Chapter02glassfishlab2buildjar –tvf TimeService.ear
...META-INF/
...META-INF/MANIFEST.MF
...Client.jar
.. TimeService.jar
We deploy the EAR file rather than the EJB module. The Ant script shows this:
target name=deploy
exec executable=${glassfish.home}/bin/asadmin
failonerror=true
vmlauncher=false
arg line=deploy --user admin –passwordfile
adminpassword ${build.dir}/TimeService.ear/
/exec
/target
Alternatively we can deploy an EAR file from the GlassFish administrator console.
There is an option for deploying an enterprise application contained in an EAR file.
Finally we need to modify the Ant run-client script:
target name=run-client
exec executable=${glassfish.home}/bin/appclient
failonerror=true
vmlauncher=false
arg line=-client
${glassfish.home}/domains/domain1/generated/xml/
j2ee-apps/TimeService/TimeServiceClient.jar
-mainclass ejb30.client.Client/
Note that we start up the GlassFish ACC by executing the appclient program. At
deployment GlassFish creates a directory under the domains/domain1/generated/
xml/j2ee-apps directory. The name of this generated directory is the same as
the EAR file without the extension, TimeService in our case. In this directory
GlassFish creates a JAR file with the same name as the directory but with Client
appended, TimeServiceClient.jar in our case. The contents of this JAR file are
those of the deployed EAR file together with some GlassFish generated deployment
XML files. When we execute appclient we need to supply the full pathname of
TimeServiceClient.jar as well as the fully qualified main application client class.
From this point on, throughout the book we assume that clients will always run in
an ACC.
Session Beans
[ 34 ]
Stateless Session Bean's LifeCycle
It is import to stress that a session bean's lifecycle is controlled by the container
and not the application. The following state diagram shows the stateless session
bean's lifecycle:
@PreDestroy (if any)
business
method
new instance
dependency injection (if any)
@PostConstruct (if any)
Does Not Exist
Method Ready Pool
The initial state of a stateless session bean is the does-not-exist state. This would be
the case before a container starts up, for example. The next state is the method-ready
pool. When the container starts up, it typically creates a number of stateless session
bean instances in the method-ready pool. However the container can decide at any
time to create such instances. In order to create an instance in the method-ready pool,
the container performs the following steps:
1. The bean is instantiated.
2. The container injects the bean's SessionContext, if applicable. In our
example we have not made use of the SessionContext. The SesionContext
is used by a bean to query the container about the bean's status or context.
3. The container performs any other dependency injection that is specified in
the bean's metadata. Again in our example we have not specified any
such metadata.
4. The container then invokes a PostConstruct callback method if one is
present in the bean. Again we have not invoked such a method in our bean
example. The PostConstruct method would be used for initializing any
resources used by the bean. For example, the session bean may make use of
a JMS queue for sending messages. The connection queue used by JMS could
be initialized in the PostConstruct method. A PostConstruct method is
called only once in the life of an instance, when it has transitioned from the
does-not-exist state to the method-ready pool.
Chapter 2
[ 35 ]
The container then calls a business method on the bean. Each business method call
could originate from a different client. Conversely when a client invokes a business
method on a stateless session bean any instance in the method-ready pool can be
chosen by the container to execute the method.
After a business method has been invoked, the container may decide to destroy the
bean instance (typically if the container decides there are too many instances in the
method-ready pool) or reuse the instance on behalf of any client that invokes its
business methods.
When the container does decide to destroy the instance it first invokes the
PreDestroy callback method if one is present in the bean. In our example we
have not invoked such a method. The PreDestroy method would be used for
tidying up activities, such as closing connections that may have been opened in the
PostConstruct method. A PreDestroy method is called only once in the life of an
instance, when it is about to transition to the does-not-exist state.
These features of instance pooling and instance sharing mean that stateless session
beans scale well to large number of clients.
The listing below shows a modified implementation of TimeServiceBean with a
SessionContext and callback methods added. At this stage the methods merely
print out messages. Later in this book we shall see more meaningful examples.
@Stateless
public class TimeServiceBean implements TimeService {
@Resource private SessionContext ctx;
@PostConstruct
public void init() { System.out.println(
Post Constructor Method init() Invoked); }
public String getTime() {
System.out.println(ctx.getInvokedBusinessInterface());
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt.format(%tr, cal);
return fmt.toString();
}
@PreDestroy
public void tidyUp() {
System.out.println(
Pre Destruction Method tidyUp() Invoked);
}
}
Session Beans
[ 36 ]
Note that there can be at most only one PostConstruct and one PreDestroy
method. The methods can take any name but must be void with no arguments. In
the case of GlassFish, the messages printed out by these methods will appear in the
container's log file, which can be viewed from the GlassFish administrator console.
Note the statement:
@Resource private SessionContext ctx;
This uses the @Resource annotation to inject a reference to the javax.ejb.
SessionContext object into the ctx field. Any kind of dependency injection, apart
from two exceptions, is signaled with the @Resource annotation. The two exceptions
are @EJB, which is used for injecting EJB references and @PersistenceContext,
which is used for injecting EntityManager instances. We will cover the
@PersistenceContext annotation in Chapter 3.
In the getTime() method we have added the statement:
System.out.println(ctx.getInvokedBusinessInterface());
This uses one of SessionContext methods, namely
getInvokedBusinessInterface(). This method returns the session bean
interface through which the current method is invoked. In our example
the result is ejb30.session.TimeService. This is a rather artificial use of
getInvokedBusinessInterface() since our session bean implements just one
interface, namely TimeService. However a session bean could implement two
interfaces: a remote interface and a local interface. We will discuss local interfaces
later in this chapter. One client could invoke TimeServiceBean through the remote
interface and another through the local interface, getInvokedBusinessInterface(),
which would inform us whether the current client is remote or local.
There are a more methods in the SessionContext interface regarding the session
beans current transaction and security contexts. We shall return to this in the
chapters on Transactions and Security.
Stateful Session Beans
In contrast to stateless session beans, stateful session beans maintain state for an
individual client over one or more method requests. A stateful session bean is not
shared among clients, and a client's reference to a bean only ends when the client
ends the session or the session times out. The state is not written to a database but
held in the containers cache and is lost when the container crashes.
Chapter 2
[ 37 ]
The classic example of a stateful session bean is the online shopping cart. The user
adds one or more items to a shopping cart, possibly over a long time period while
the user visits other web sites or is interrupted by a phone call. Finally the user may
decide to purchase the items in the cart, cancel his or her shopping cart session, or
even abandon the session without explicitly terminating it.
The following example illustrates some aspects of a shopping cart. Our shopping cart
will be limited to adding items to a cart and listing the current contents of a cart. First
we define a remote interface as follows:
@Remote
public interface ShoppingCart {
public void initialize();
public void addItem(String item);
public CollectionString getItems();
public void finished();
}
The initialize() method performs initialization; we shall see what this means
shortly. The addItem() method adds an item to the cart. The getItems() method
returns the current contents of the cart. The finished() method is invoked when the
client has finished their session and typically removes the session bean, so allowing
the container to reclaim resources.
Next we look at the bean implementation:
@Stateful
public class ShoppingCartBean implements ShoppingCart {
private ArrayListString items;
@PostConstruct
public void initialize() {
items = new ArrayListString();
}
public void addItem(String item) {
items.add(item);
}
public CollectionString getItems() {
return items;
}
@Remove
public void finished() {
System.out.println(
Remove method finished() Invoked);
}
}
Session Beans
[ 38 ]
First note that we have used the @Stateful annotation to indicate this is a stateful
session bean. We have used a @PostConstruct method, initialize(), to create an
ArrayList named items. Stateful session beans may contain instance variables, such
as items, which are modified by the bean. The reason, of course, is that the state of
such variables is preserved from one method invocation to another. As with stateless
beans we can also have a @PreDestroy method, although we have not created one
in this example. The addItem() and getItems() methods are straightforward and
need no further comment.
We use the @Remove annotation to indicate that after the annotated method has
executed, the client no longer needs the session. The container can then delete
the bean instance. If a @PreDestroy method exists, it will be executed after the
@Remove method. Typically the method would perform tidying up such as closing
connections. In our example the finished() method merely prints a message.
It is not compulsory to have a @Remove annotated method, but it is a good practice.
Without such a method the bean instance will continue to occupy the container's
cache until a timeout period is reached. At this point the bean instance is deleted by
the container. The timeout period is configured by the container's administrator. By
having a @Remove annotated method we are freeing up container resources as soon
as we have made use of them.
The listing below shows a possible client:
public class Client {
@EJB
private static ShoppingCart shoppingCart;
public static void main(String args[]) throws Exception {
shoppingCart.addItem(Bread);
shoppingCart.addItem(Milk);
shoppingCart.addItem(Tea);
System.out.println(Contents of your cart are:);
CollectionString items = shoppingCart.getItems();
for (String item : items) {
System.out.println(item);
}
shoppingCart.finished();
}
}
Chapter 2
[ 39 ]
Stateful Session Bean's LifeCycle
The following state diagram shows the stateful session bean's lifecycle:
timeout
@PostActivate (if any)
@PrePassivate (if any)
@PreDestroy (if any)
business
method
new instance
dependency injection (if any)
@PostConstruct (if any)
Does Not Exist
Passive
Method Ready
@Remove
The lifecycle of a stateful session bean differs from that of a stateless session bean in
a number of respects. There is no pool of identical bean instances, as each instance
serves a single client. A stateful session bean transitions from a does-not-exist to
a method-ready state as soon as a client performs a business interface lookup or a
dependency injection of a bean. So this step is client, and not container initiated.
Once a stateful session bean is in a method-ready state, the container performs the
same steps as with a method-ready stateless session bean:
1. The bean is instantiated.
2. The container injects the bean's SessionContext, if applicable.
3. The container performs any other dependency injection that is specified in
the bean's metadata.
4. The container then invokes a PostConstruct callback method if one is
present in the bean.
The container then calls a business method on the bean.
Recall that a session can involve considerable idle time if a client decides to wait, or
perform other activities, between method calls. The container's cache could become
full of idle stateful session bean instances. To limit such instances, the container
can swap these from the cache out to disk or other storage. This process is called
passivation and involves serialization of the bean instance. When the client decides
to invoke a method on a passivated bean, then the container deserializes the saved
state and invokes the requested method. This process is known as activation. Note
that the method may not be on the original bean instance, but this is safe as at
activation we restore the state which was saved at passivation.
Session Beans
[ 40 ]
The passivation algorithm is container-dependent, and typically is dependent on
factors such as the maximum number of beans which may be held in the containers
cache, the maximum bean idle time, and the victim selection policy of the container.
The GlassFish victim selection policy has the following options: Least Recently Used
(LRU), Not Recently Used (NRU), and First In First Out (FIFO). All of these factors
can be configured by the container administrator.
The bean can provide a @PrePassivate callback method, which is executed
immediately before passivation and a @PostActivate callback method, which is
executed immediately after activation. A session bean's state may contain open
resources such as open sockets, database or JMS connections that cannot be handled
by the container during passivation. In these cases the resource will be closed in the
@PrePassivate method and reopened in the @PostActivate method.
A bean can move from a method-ready state to a does-not-exist state if a @Remove
annotated method is invoked. A bean can also do this if a container configured
timeout period has been reached. In either case a @PreDestroy annotated method is
first invoked.
A passivated bean can also move to a does-not-exist state if a timeout period has
been reached. Note in this case any @PreDestroy annotated method will not
be invoked.
The listing below shows a modified implementation of ShoppingCartBean with the
@PrePassivate and @PostActivate callback methods added. The methods simply
print out corresponding messages.
@Stateful
public class ShoppingCartBean implements ShoppingCart {
private ArrayListString items;
@PostConstruct
public void initialize() {
items = new ArrayListString();
}
public void addItem(String item) {
items.add(item);
}
public CollectionString getItems() {
return items;
}
@PrePassivate
public void logPassivation() {
System.out.println(
PrePassivate method logPassivation() Invoked);
Chapter 2
[ 41 ]
}
@PostActivate
public void logActivation() {
System.out.println(
PostActivate method logActivation() Invoked);
}
@Remove
public void finished() {
System.out.println(
Remove method finished() Invoked);
}
}
Note that there can be at most only one PrePassivate and one PostActivate
method. The methods can take any name but must be void with no arguments.
Note that to simulate bean idle time, and hence conditions for passivation and
activation, we have added a delay of 59 seconds between method calls from
the Client:
public class Client {
public static void main(String args[]) throws Exception {
...
shoppingCart.addItem(Bread);
shoppingCart.addItem(Milk);
Thread.sleep(59000);
shoppingCart.addItem(Tea);
}
}
To test activation and passivation with GlassFish you will also need to log in as a
container administrator and set the Max Cache Size to say 2. The Cache Resize
quantity, which is the number of beans to passivate when the cache is full, is set to
2 and the Cache Idle Timeout to say 15 seconds. Then execute 3 simultaneous
client sessions. This process may be different for other EJB containers.
Local Interfaces
Up to this point all our examples have used the session bean remote interface, as the
clients have run in their own JVM outside the EJB container. Behind the scenes, a
remote interface uses the RMI-IIOP protocol for network operations. This protocol
stipulates that method arguments are passed by value and not by reference. Passing
by value means that an object being passed from the client to the remote bean, or
vice versa, is first serialized then passed over the network then deserialized. This all
Session Beans
[ 42 ]
has an impact in terms of performance. Even if our client is a session bean invoking
another in the same container there is a performance overhead if we use a remote
interface because of the serialization and deserialization taking place. For this
reason EJB technology provides a local interface option for session beans. Method
arguments are passed by reference and not by value so improving performance.
To illustrate all this we shall create a stateless session bean which will be invoked by
and run in the same EJB container, as our original TimeServiceBean. This invoked
bean will just return the string Have a Nice Day. First we define the beans interface,
NiceDayService:
package ejb30.session;
import javax.ejb.Local;
@Local
public interface NiceDayService {
public String getMessage();
}
Note that we have prefixed the interface definition with the @Local annotation. This
indicates to the EJB container that this bean may only be invoked by a local client
running in the same container. The interface consists of just one method definition,
getMessage(). Next we look at the bean implementation, NiceDayServiceBean:
package ejb30.session;
import java.util.*;
import javax.ejb.Stateless;
@Stateless
public class NiceDayServiceBean implements NiceDayService {
public String getMessage() {
return  - Have a Nice Day;
}
}
This is all straightforward. We note that the session bean is stateless and the
getMessage() method returns the string - Have a Nice Day.
Now let's look as to how we might modify the TimeServiceBean to invoke
NiceDayService. The TimeServiceBean will append the NiceDayService message
to the current time. Here is the modified code for TimeServiceBean:
package ejb30.session;
import java.util.*;
import javax.ejb.Stateless;
import javax.ejb.EJB;
@Stateless
Another Random Scribd Document
with Unrelated Content
by General Négrier being wounded. The force then made a
disorderly retreat before imaginary pursuers. In the meantime the
empress-dowager had given positive orders that peace should be
made on any terms. Both parties had thus come round to the status
quo ante bellum—that is to say, they were both equally urgent to
obtain peace, as they had been in May 1884. The agent in bringing
this about was Sir Robert Hart; and it was effected, as great things
usually are, by the adroit use of very simple means. During the
blockade of Formosa a small Chinese lighthouse tender was captured
by the French admiral and detained. As she was essentially non-
combatant, and was serving the interests of humanity in supplying
the numerous lighthouses on the coast of China for the benefit of
the commerce of all nations, Sir Robert Hart instructed his very
capable London agent, Mr Duncan Campbell, to go to Paris and
represent the case to the French Ministers, with a view to obtaining
the release of so useful and harmless a vessel. In this manner the
door was opened to the larger negotiation. Mr Campbell executed
his delicate mission with so much tact, that in the amicable
conversations which ensued between him and certain French officials
the idea of putting an end to a war of which both parties were tired,
and which, moreover, seemed objectless, was ventilated; and in a
few days authority was telegraphed from Peking to Mr Campbell to
sign a protocol.
This was done before the news of the French reverse at Langson
reached Paris. After such a military success M. Jules Ferry could not
imagine that the Chinese Government would adhere to the terms of
the protocol, and therefore he kept the whole negotiation secret
from the Chambers. In the meanwhile the mishap to the French
troops, being greatly exaggerated, excited such intense feeling in
France that M. Ferry, le Tonkinois, was obliged to resign, with the
treaty which might have saved him in his pocket. As for the
empress-dowager, she recked nothing of the success of her brave
troops on the outskirts of the empire, but thought only of the
enormous expense of the war, which had been unpleasantly brought
home to her, and of matters affecting her own convenience. She
therefore had no thought of going back on the treaty, but was even
more urgent than before to have it promptly signed and ratified. The
honours of the peace thus fell in a few days to M. Ferry's successor.
And what was the outcome of a year's fighting which cost China
100,000,000 taels and France some proportionate amount? A simple
reaffirmation of the Li-Fournier convention of May 1884! The
convention itself was short and simple—one clause only exciting
much interest during the negotiations, and that provoked a hot
discussion, not on the substance, but on the verbal form. It was a
stipulation by which the two contracting parties consciously meant
different things, and each fought hard for a phrase sufficiently subtle
to allow each to interpret it in his own way when the time came for
the fulfilment of the treaty provisions. The French were most
desirous of binding the Chinese to employ French industries in all
their new undertakings. China was equally resolute in avoiding any
such obligation. In the end each was satisfied that he could read the
treaty clause in his own favour. But the final victory in the struggle
would go to the side that was most persistent in forcing its meaning
into practice. The French Ministry had announced to the Chambers a
great victory for French manufacturing industries, which were
represented as having by it obtained a monopoly in China. The text
of the treaty, even in the French version, did not, indeed, bear this
out; but the French had the primâ facie argument on their side, that
the introduction of a clause in a treaty referring to the Chinese
patronage of French industries, however worded, must have meant
something more than merely to register the common fact that China
was at liberty to deal with whom she pleased. In the end a
compromise was effected by China's giving to a French syndicate the
contract for excavating the basin and dock at Port Arthur and certain
orders for material, among which was a famous military balloon,
wonderfully symbolic of the whole proceeding.
Ejb 3 Developer Guide A Practical Guide For Developers And Architects To The Enterprise Java Beans Standard Michael Sikora Meenakshi Verma Chris Mawata Lawrence Bean
CHAPTER XXVII.
THE FRENCH PROTECTORATE OF CHRISTIANS.
Alliance with Church the corner-stone of French conquest—Persistence of French
ambitions in the Far East—Protectorate of native Christians—Its abuse by the
propaganda—Forcible erection of cathedrals in Peking—Imperial family
aggrieved thereby—Negotiations for removal of church from palace grounds—Mr
Dunn's mission to Rome—Vatican to send a nuncio—French Government vetos—
French minister vetos transfer of cathedral—Unless transaction placed in his
hands.
The claim of France to protect Christians against the native
authorities in the Far East constitutes the basis and the origin of her
present political position in those countries. The propagation of the
faith was, indeed, a recognised element in the adventures of other
countries besides France; but she has, since the eclipse of Portugal
and Spain, enjoyed the distinction of a working alliance with the
Church in furthering the foreign domination of both. Church and
State, linked in alliance close and potential, played faithfully into
each other's hands, says Parkman ('Jesuits in North America'). In
the reign of Louis XIV. the kingdom of Siam was the object of their
joint attention. A missionary bishop persuaded the most Christian
king that to establish the Church in Siam and convert king and
country to the Catholic faith would open an effectual door for the
extension of French commerce. A century later another bishop
persuaded another Louis to interfere in the affairs of Annam, and
only the events of 1789 cut short an expedition that was being
prepared of politico-ecclesiastical propagandism. Napoleon III. took
up the cause, and actually effected the conquest of Cochin China;
and Gambetta was so enthusiastic on the subject that, while
persecuting the Catholics in France, he was ready to expend the
forces of the Republic in protecting them in distant countries.
There is here, therefore, irrespective of persons or forms of
government, an unbroken tradition, which furnishes a key to the
successive operations of France in the Far East. Thus when she
resolved to join England in hostilities against China in 1857 a pretext
was ready to hand in the murder of a Catholic priest in the interior of
the country, his presence there being a defiance of the laws of the
empire. There has been flux and reflux in French policy, but no
change in its direction; and though prudence has from time to time
set limits to its full expression, the claim to a special representation
of Chinese Christians has been consistently pursued as a cardinal
object of the French military, naval, and diplomatic forces in the Far
East.
The treaties of 1858 for the first time authorised travelling into the
interior, and placed French subjects, whether missionary or not, who
availed themselves of the permission, under the protection of their
own country. But ever since the convention of Peking in 1860 it has
been sought by indirect and unobtrusive means to assume the
protectorate over native Christians as well. The interpolated clause in
the Chinese, which was no part of the authentic French version of
the convention, lent a certain colour to the pretension by seeming to
recognise communities of Chinese Christians as legal units and fit
subjects of international agreement between China and France.
Nevertheless, French interference between the Chinese authorities
and the subjects of the empire of China has never had any treaty
warrant or justification by the law of nations, wrote Sir Rutherford
Alcock in the 'Nineteenth Century,' November 1886; and he added,
China has the remedy in her own hands, to a certain extent, by
refusing to admit the pretension. The Chinese Government had long
been alive to the danger, as its elaborate appeal to the reason of the
Powers in 1871 amply testified, but its eyes were opened still wider
by the lesson of the Tongking war. A disposition was thereafter
evinced to withstand the claim of the French, and the action of
Germany afforded sufficient support to the Chinese position, had the
Government only had the courage and perspicacity to lean upon it.
For in the Catholic propaganda were missionaries of German origin,
who were not permitted to divest themselves of their nationality, but
were made to apply for their passports into the interior not to the
French, but the German, Legation in Peking. Had Italy and Spain
been equally independent, the question of the French, or any other
protectorate, could scarcely have been entertained without
introducing the element of separate foreign nationalism into the
constitution of the Christian communities in China, which would not,
perhaps, have been agreeable to the views of the Catholic
propagandists, for they naturally aspired to maintain their
independence as a compact ecclesiastical organisation.
The dread of the French protectorate was much accentuated by the
enforced restitution of ancient buildings, the most conspicuous
examples of which occurred in the city of Peking itself, and even
within the area of the imperial palace. The sites of three ancient
churches being claimed by the French Minister, the emperor's
Government was compelled to violate its sense of justice by evicting
the existing owners. The original building of one of the three was
found practically intact, though hidden by the houses built round and
against its walls. These of course had to be cleared away, regardless
of the rights of their occupants. The interior fittings and decorations
of the church had disappeared, but, strange to say, much of the
wood carving and other ornaments were gradually recovered from
the old-curiosity shops, where the parts not destroyed had, by the
instinct of the Wardour Street craft, been preserved, begrimed with
the dust of a hundred years and hopelessly unsaleable. By patiently
collecting these disjointed fragments and piecing them together like
a Chinese puzzle, the Fathers were able gradually to restore the
church to something like its original state, so that it became itself an
interesting relic of the golden age of the Jesuits in Peking.
The other two churches had been demolished, and the sites
converted to secular uses, requiring some ingenuity to identify.
When these sites were, under the new dispensation, cleared of
superincumbent buildings, churches were erected as much
exceeding the original as the glory of the Jewish temple, rebuilt after
the Captivity, excelled that of the former house. The restrictions
imposed by the Government on the style of the buildings, the last
vestige of power which they dared assert, bore lightly on the astute
constructors of the new churches. In deference to a common
Chinese objection, perhaps partly superstitious, to lofty structures
overlooking them, a limit was set to the height of the new buildings.
But remonstrances after completion were easily disposed of by the
pious Fathers inviting the objectors to go and measure the towers!
The Chinese seem to have the same constitutional dislike of a
demonstration that they have to a straight line or a right angle, and
a challenge like this never failed to put them to silence. As to their
neglect to exercise their right of supervision during construction, the
shortest way to characterise it is merely to say it was Chinese. The
same kind of negligence also allowed roofs of cathedrals, not in the
capital alone, but in distant provinces, to be covered with yellow
tiles, a colour reserved exclusively for imperial use. It is true the
process was disguised, for the benefit of those who chose to be
blind, by the tiles being whitewashed before being sent aloft, leaving
to the slow action of the weather the gradual revelation of the
imperial colour, which might then, indeed, be represented as the act
of Heaven. Nothing is too transparent to deceive those who are
willing to be deceived.
PEI-T'ANG CATHEDRAL IN PEKING,
PURCHASED BY CHINESE GOVERNMENT.
The cathedral around which the greatest interest centred, however,
was the one which was erected within the palace grounds. The site
had been granted by the great Emperor Kanghsi, the most imperial
of the Manchu line, to the learned fathers who cured his fever by
administering Jesuits' bark, then a new discovery, and whom he
reckoned on attaching to his house by the favours bestowed on
them. The new building was presumably erected on or near the site
of the old, against the most urgent protests of the Court. Every
inducement was offered to the French—larger and better sites,
perhaps other compensations as well—if they would forego their
demand for the resumption of the ground; but the French
Government being set upon marking its ascendancy by a permanent
sign, compelled the erection of the Pei-t'ang Cathedral on the spot
indicated. The Lazarists, who had succeeded to the Jesuits in North
China, had a kindly bishop at their head, who conceded much in the
structure of the new building to soothe the feelings of the imperial
family. Nevertheless, stunted as they were, from the point of view of
architectural symmetry, the double towers of the cathedral were
visible from the palace, and the two belfries commanded a view over
a large part of the precincts. The building was therefore an eyesore
to the inmates for twenty years, on the common ground on which it
would have been offensive even to a provincial population, but still
more as a staring monument of the deepest humiliation the dynasty
had endured.[27] The empress-dowager bore the grievance, but not
with resignation, for soon after the affairs of the empire assumed a
settled aspect she urged her Ministers to find a way to get rid of the
obnoxious building.
Monseigneur Delaplace had, in his former diocese of Chêkiang,
rendered good service to the Government in opposing the rebels, for
which he was granted high Chinese rank. Being dissatisfied with the
action of France after the Tientsin massacre of 1870, he extricated
his mission from the control of the French Legation in Peking, and
from that date till his death in 1882 conducted its affairs in direct
communication with the Tsungli-Yamên. Fully recognising how
hateful his cathedral was to the Chinese, he co-operated with Prince
Kung and Wênsiang in their efforts to remove it, and in 1874 he
actually concluded an agreement with them to that effect. But the
contract was vetoed by the French Government. The sore was thus
reopened and continued to fester until 1881, when there was so
much excitement in the capital that the Church and mission were
thought to be in great danger. During the Tongking troubles the
question of the cathedral was allowed to rest, but no sooner was
peace assured than the Court again became restless, and with
renewed urgency sought a remedy for its grievance.
The negotiations, which proved successful, were entered upon in an
irregular manner, such as has characterised so many of the Chinese
official acts. An Englishman in Peking, who had had business
dealings with the Government, was asked one day by the
confidential factotum of Prince Ch'un whether he could render
assistance in the matter of the Pei-t'ang. The case was explained at
length, and the foreigner, not being then aware of the negotiations
of 1874, suggested, as the most obvious course, trying to make an
arrangement with the Lazarist mission. The Manchu shook his head,
to signify the futility of that proceeding. The enterprise thus seemed
desperate, unless the Imperial Government should exercise its
sovereign right of expropriation,—much too drastic a measure for
any Chinese Government to attempt.
One hope only seemed to remain, a direct appeal to the Vatican.
This led to a long conversation on the Papacy, and the Manchu
official,[28] being a pious and even a learned Buddhist, became
intensely interested in hearing much that was new to him respecting
the position and prerogatives of the European Dalai Lama. Nor did
the great Western Saint, whose vicegerent the Pope claims to be,
fail to evoke the deep reverence of both the Manchu and the
Chinese who were present, so that one might be almost justified in
appropriating words uttered on a different occasion,—they were not
very far from the kingdom ruled by the Western Saint.
But the interesting question was, How was the Vatican to be
approached? By a qualified secret agent intrusted with the full
confidence of the Chinese Court. The mission would be by no means
easy, for should its object become known, it would be thwarted in
advance from mere jealousy, if from no other motive, by Lazarist and
perhaps other Catholic missions, so that access to the Supreme
Pontiff would be blocked at the outset. The mission would also be
certain to arouse the strenuous hostility of the French Government.
After discussing the problem from all sides for three hours, the
Manchu cut it short by the abrupt question, Will you go? No, said
the foreigner; such an undertaking requires quite other qualities
than any I possess. But, he added, after considering the matter, I
think I know the man who might carry it through. Where is he? in
Peking? Bring him here, were rapped out like musketry-fire,
showing how urgent was the subject. The agent recommended to
him was Mr J. G. Dunn, a man of genius and of varied
accomplishments, a Catholic, and having an extensive personal
acquaintance with the propaganda. He was at once invited to
Peking, when another long conference ensued, and Mr Dunn was
requested to draw up a memorandum on the whole scheme for the
information of Prince Ch'un. After waiting some time for a response
Mr Dunn left the capital, decidedly disappointed, for he was eager
for a service so congenial to his character and feelings. Indeed had
the mission been created for the man, or the man for the mission,
the harmony between means and ends could hardly have been
closer.
Several months elapsed before the question emerged again from
official obscurity, and the manner of it is worth relating if only for the
side-light it throws on Chinese methods. Li Hung-chang paid a visit
to the capital in 1885, and soon after his return to Tientsin he
requested his secretaries to find out where Mr Dunn was and to
invite him by telegraph to come to see the viceroy. Not knowing why
he was sent for, any more than Gordon did when summoned from
India five years before, Mr Dunn came, and Li at once entered on
the Pei-t'ang question, showing him his own memorandum on the
subject. The affair having been placed by Prince Ch'un in the hands
of Li Hung-chang to be carried through, Mr Dunn was promptly
commissioned, and in concert with the viceroy's secretary, the very
capable officer who now represents China at Washington, the
emissary's instructions and credentials were drawn up. There were
two separate instructions, and no little confusion was caused
thereby.
On leaving China for Rome, Mr Dunn stipulated that a competent
intermediary should be appointed to interpret his correspondence to
Li Hung-chang, a duty which was intrusted to the commissioner of
customs in Tientsin. The utility of this provision was soon made
manifest, for when telegrams began to arrive from Rome, their
purport was unintelligible, as they seemed irrelevant to the
expropriation of the cathedral, which was Mr Dunn's special mission.
Irritated by this apparent aberration, the viceroy's idea was to recall
the emissary. But when it was suggested that the copies of his
credentials should be first carefully examined the position became
clearer. One part of his instructions was then found to be directed
towards the question of the Christian protectorate, and Mr Dunn
was, in fact, diplomatising with the Pope with a view to his
appointing a nuncio or apostolic delegate to China to represent all
the Catholic missions. The Chinese had not fully mastered this idea,
and even Li Hung-chang, who has a wonderful memory, had
forgotten the existence of the second section of his instructions,
which no doubt Mr Dunn had drawn up himself. The Tsungli-Yamên,
languid and bemused, hesitated to express any opinion, and
assumed their habitual passive attitude. One person alone really
grasped the importance of having the Church in China represented
by the delegate of a Power which has no armies or fleets wherewith
to threaten or attack. The empress-dowager, when the nomination
of Mgr. Agliardi was announced, and his coming depended on formal
imperial invitation, sent the urgent message to the Yamên, Get that
man here; lose no time.
Mr Dunn's negotiations with the Vatican of course soon leaked out;
notices appeared in the press; Mr Punch had his little joke that
though there was evidently a good deal doing, the question was,
Who was Dunn? The French Government took the matter up
energetically through their Minister in Rome, and their diplomatic
efforts having failed, they presented an ultimatum to the Pope which
compelled him to cancel the appointment of his nuncio. France
threatening to terminate the concordat, withdraw the subvention to
the Church in France, and sequestrate its ministers, the Holy Father
had no option but to submit. With tears in his eyes he deplored his
impotence to respond to the invitation of China under such a
truculent menace to his children in France.
While these things were going on in Rome the transference of the
Pei-t'ang Cathedral, which had been settled in principle through Mr
Dunn, was then taken up by the Lazarist Mission, and the popular
Père Favier was deputed by the Bishop of Peking to proceed to
Rome and to Paris to obtain from the Vatican and the General of the
Lazarist Order the specific authority to negotiate the transfer. Having
brought back the necessary powers, a convention was shortly
concluded between Bishop Tagliabue and Li Hung-chang. The
Church made an excellent bargain, as it generally does: a new site
of about thrice the area was granted close to the old on the opposite
side of the broad roadway, and a bountiful compensation in money
was made for the trouble and cost of removal. But after the
agreement was signed the French Government interposed its veto so
far as to insist on being the intermediary through whose hands the
transaction should pass. France also, it was said, had previously
essayed to marchander with China for her consent, but withdrew
when it became clear that further obstruction might entail untoward
consequences. To mark its satisfaction at the final solution of this
question, the Chinese Government eulogised all those who had
helped to bring it about, and bestowed high rank on Bishop
Tagliabue and the Abbé Favier (now bishop).
This transaction supplied a crucial test of French policy and
pretensions in China, the first concrete expression of both that had
been obtained since the forcible restitution of Church property
immediately after the capture of Peking. The coercion, indeed, was
applied on this occasion to the Roman Pontiff and the Catholic
Church rather than to the Chinese Government; but the latter were
not so dull as not to see to what ulterior objects the French scheme
might be extended, given convenient circumstances. They were, in
fact, really alarmed, and the question was discussed with some
warmth in the Chinese as well as in the European press. The end is
not yet, wrote Sir Rutherford Alcock; China may be less open to
intimidation than heretofore, and assert her undoubted right to
refuse the recognition of an assumed protectorate over Roman
missions, irrespective of the nationality of their members. The
French press espoused the cause of the protectorate warmly,
treating it as a most valuable national asset. The Chinese press took
up the question in reply. Their view of the position was
comprehensively summed up in a native newspaper in October 1886
in the following terms:—
It has been said by them of old time that when a man is found acting
injuriously to his own family but benevolently to strangers his
behaviour is unnatural, and there is something hidden under the cloak
of outward kindness.
We have from time to time printed translations from various foreign
newspapers on the subject of the relations between the Chinese
Government and the Pope. Some days ago we reproduced an article
on the same subject from the 'Temps,' a French newspaper of the
highest authority. These articles all indicate that the French
Government is greatly troubled at the prospect of losing what is called
the right to protect Christians in China. This is a question which has
not hitherto been much considered by Chinese statesmen. Those of
them who have been in Europe, or who have studied political affairs
there, know something of the importance of the issues which are
covered up in that apparently harmless word protection; but it is
hardly to be expected that the Ministers and statesmen who have
scarcely travelled beyond the walls of Peking can realise the full
significance of the phrase. Nothing is better calculated to quicken the
apprehension of the Government on this point than the extraordinary
excitement of the French Government, which insists on protecting the
Christians in China whether they desire this protection or not. For now
that the French have so plainly shown their secret designs, it would
be impossible for China to acquiesce, by word or deed, in the
pretensions which France sets up. It is rather suspicious that the
French Government, the greatest enemy of Christianity, which is
constantly oppressing the priests and confiscating their property in
France, should be so intensely desirous of protecting Christians in
China, where this protection is not required. A leading French
statesman, Gambetta, who died a few years ago, left as a legacy to
his followers the doctrine that the Church should be suppressed in
France but supported in all foreign countries. Gambetta was a man
who had no reverence for Heaven, and no religion, and seems to have
regarded Christianity as a disease which he wished his own country to
be rid of, but was not sorry to see it spreading elsewhere. It is
necessary to keep these ideas in mind in order to understand the
action of the French Government to-day.
It would be out of place here to discuss what Christianity is. Like
Buddhism, it had a very pure origin, and the living principles of both
are mercy, benevolence, and peace. But both religions have in course
of ages been overlaid with doctrines and practices which have
obscured the simplicity of their origin, and even changed their
character. But the greatest misfortune to Christianity is that it has
been made use of by princes as a pretext for wars of aggression. In
fact, nearly all the wars of Europe for the last thousand years have
been in some way connected with religion. This is sometimes made a
reproach against Christianity, which professes to be founded on peace
and self-sacrifice, but the reproach is scarcely just. Rather it is the
peaceful character of Christianity which has induced ambitious
statesmen to make use of it to work out their own designs, just as in
private life unscrupulous men are sometimes enabled to carry out
questionable plans by using the names of men of blameless character.
We are only now concerned with the political aspect of Christianity,
not its merits as a religion. The modern history of Turkey affords the
best illustration of the danger of allowing foreign Powers to interfere
in matters of religion. During the last hundred years Russia has
several times made war on Turkey, always on the pretext of protecting
Christians, and it is this which is fast breaking up the Turkish empire.
It is interesting to observe that Russia and France follow the same
policy in this matter. When the French Legation withdrew from Peking
on the 2nd day of the 7th moon of the 10th year of Kwanghsu (22nd
August 1884), the affairs of the Christians were transferred to the
Russian Legation. The Ministers of the Tsungli-Yamên remember very
well how eagerly the Russian Minister assumed the office of protector
of Christians, going to even greater lengths in the way of protection
than the French themselves had done. The reason for this is plain.
Russia, although she has none now, expects to have by-and-by many
Christians in Mongolia and Manchuria who may be extremely useful to
her in her aggressive designs on China. Therefore the Russian
officials, always looking very far ahead, were most anxious to
establish a right of interference for the protection of Christians. And
they could do this without reproach when they were acting not for
themselves but for France during war-time; well knowing that,
whatever position she succeeded in establishing for France, Russia
could claim for herself when the proper time came. But the more
anxious Russia and France are to assert the right of interfering with
Chinese Christians, the more resolute China should be in resisting all
such interference. The only safety for China is to treat Christians,
whether Chinese or foreign, exactly as all other people are treated—to
make no distinctions. Foreign missionaries have the right to travel and
reside in the interior; they can exercise this right without getting
passports from the French Minister. The Catholic missions are
composed of men of all nations, but they all have Ministers in Peking
to whom they can apply for passports. Let the Germans get their
passports from the German Legation, the Spaniards from the Spanish,
Italians, Belgians, and Hollanders from their respective Legations, but
no European State has any right to arrogate to itself the position of
protector of missionaries in general.
It is satisfactory to learn that the head of the Catholic Church is of this
opinion, and although grateful to France for what she has done in the
past, is now desirous of being free from French protection in the
future. To carry out these views, the Pope is about to send to China a
very high official to reside in Peking and perform the functions of a
Minister. As the Pope has no troops and no territory, but is merely a
kind of Dalai Lama, there is no danger to China from opening direct
relations with him. The affairs of the missionaries can then be dealt
with in an open and straightforward manner, as no fear of political
traps will lurk behind. The Christians when they know they are no
longer protected by a military State will understand that their security
will depend on their own wisdom in avoiding offence. And the officials
and people, on the other hand, will gradually learn that the Christians
are only anxious to lead virtuous lives, without any political ambition,
and they will respect them. The Imperial Government will then also be
able to extend its favour to all Christians and missionaries without the
fear of nursing traitors in its bosom. The missionaries have among
them men of great learning and much skill in sciences, which the
Emperor Kanghsi—who must always stand as the model for Chinese
rulers—knew very well how to utilise. The present generation
possesses men no less capable of rendering good services to China,
and there would be no reason for not using them if the suspicion of
their being agents of the French Government were once cleared away.
Notwithstanding so much clear thinking, however, the action of the
Chinese continued, as before, nebulous. They seemed never able to
seize the bull by the horns, but drifted on, allowing themselves
constantly to be put in the wrong, hoping perhaps to accomplish by
illegitimate means what was within their legal competence. Afraid or
unwilling to control the provincial authorities, they allowed outrages
to be perpetrated for which they refused redress until coercion was
applied, thus affording to foreign Powers a not in all cases
unwelcome pretext for extending their protection even to Chinese
Christians. Within a month of the consummation of the transfer of
the Pei-t'ang Cathedral, and after the Marquis Tsêng, fresh from
Europe, had taken his seat at the Board, the Tsungli-Yamên had
fallen into its chronic apathy with regard to Christians. A missionary
named Bodinier arrived in Peking from distant Kweichow for the
purpose of soliciting the intervention or intercession of the French
Legation in favour of the persecuted Christians in that province.
While he was on his journey the Catholics of Chungking in Szechuan
were being similarly maltreated. Certain disturbances in that great
commercial mart culminated in the attack on the house of a wealthy
Christian family, which resisted the assailants, several of whom were
killed in the affray. The magistrates, who had been supine during the
time when the mischief was brewing, thereupon arrested the head
of the Lo family and condemned him to death,—an exercise of
authority which was held to be arbitrary, and invidiously directed
against Christians. Here was an occasion when the Central
Government should have taken prompt action, and so deprived the
French Government of any pretext for interference. It was a moment
when that Government was less apt than usual to put forth its power
in the Christian cause. M. Constans was Minister in China, and he
was personally not at all disposed to assume the protection of
Chinese Christians. Nevertheless, the case being urgent, and the
Tsungli-Yamên either cowardly or indifferent, M. Constans broke
through the rule he had laid down for himself so far as to telegraph
to Paris for instructions. The reply was prompt, doubtless inspired by
the propaganda at home, to the effect that he should take up the
case of Mr Lo. Thus the Chinese threw away a golden opportunity of
showing to the world that the Chinese Christians did not stand in
need of any foreign aid. An impartial investigation might have
shown, indeed, that the Christians were the aggressors, and the
local Chinese officials might have been vindicated from the charges
made against them. But the Government's inaction constantly puts it
in the wrong even when it may be substantially in the right. The
same fatal course has been regularly pursued even to our day, with
results patent to all.
CHAPTER XXVIII.
BRITISH SERVICES: DIPLOMATIC, CONSULAR, AND
JUDICIAL.
Necessity for administrative and judicial control over British subjects—Consular
courts—Supreme court for China and Japan—Personnel of the consular service—
Functions of the diplomatic representatives—Absence of distinction explained by
apathy of Home Government—Need of reform.
The frequent references throughout this work to the part played by
British agents in the development of intercourse with China seem to
call for a short account of the character and status of the official
machinery which served for so many years as the principal working
joint between the two opposed systems of civilisation.
The relations between Great Britain and China were necessarily at
first experimental. The consuls appointed to the five ports were
selected with no special training, and the chief superintendent, to
whom they looked for guidance, was scarcely better furnished than
themselves. Yet, as has been shown, the remoteness of the consuls
from their chief, and of both from the Government they served,
threw them much upon their own resources. How the demand for
independent initiative was responded to by some of the individuals
concerned has been incidentally noticed in previous chapters.
From the time when it assumed direct relations with China, the need
of an effective control over British subjects resorting to that country
weighed heavily on the British Government; for in exempting them
from native jurisdiction the Government took on itself the
responsibility for the good behaviour of its people. The exercise of
this control was necessarily tentative, proceeding step by step as
occasions arose. The unceasing solicitude of the Government for the
orderly conduct of its subjects in China is testified by a long series of
Orders in Council conferring on the consuls and their superintendent
an almost despotic authority over the persons of the British
residents. The operation of this arbitrary system was more
satisfactory than could have been expected, thanks to the high
character of the parties concerned and the common-sense which
governed their mutual relations. In their double capacity, however, of
protectors of Chinese and foreigners against the inroads of British
subjects, and of the latter against the inroads of the Chinese, the
consuls soon discovered that the one part of their duty was easy and
the other difficult; and it is no matter for wonder, therefore, if,
following the line of least resistance, some of them should have
leaned to the side of repression rather than to that of the
encouragement of their countrymen. This was noticeable even in
judicial proceedings, where the consul was supreme over his own
nationals, but had no authority over their opponents. Some check on
the consequences of consular idiosyncrasies and defective legal
knowledge was maintained by a supreme court in Hongkong,
independent alike of the superintendent of trade and of the governor
of the colony, to which court appeals lay from consular decisions.
This prerogative of the colonial court was not unnaturally irksome to
the diplomatic and consular servants of the Foreign Office, and was
doubtless one cause of the coolness, not to say antipathy, with
which the colony has generally been regarded by them.
The treaties of 1858 and 1860 were followed by a great
development in all three services—diplomatic, consular, and judicial.
Some years previously the China consular service began to be
treated as a career for which special preparation was required, the
entry being by competitive examination, through which a certain
number of students were annually sent out to China, there to
complete their education and then take their part in executive work.
When additional ports were opened, therefore, making about twenty
in all, in 1861, there was the full complement of qualified men ready
to occupy the new consular posts, each of them competent to be his
own interpreter. Diplomatic functions were at the same time
withdrawn from Hongkong, where they had been merely nominal for
eighteen years, and became centred in the Chinese capital. A few
years later the judicial authority, so far as it related to the
communities at the Chinese ports, was also withdrawn from
Hongkong, and was conferred upon the Supreme Court for China
and Japan, having its headquarters in Shanghai, established by the
Queen's Order in Council of 1864. The new court was inaugurated
by Sir Edmund Hornby, who brought to the work practical experience
gained in the Levant, the assistant judge being Mr C. W. Goodwin,
Barrister of the Inner Temple. This establishment has furnished a
solvent for many of the difficulties connected with British residence
in the Far East. Adapted with judgment to local circumstances, the
court has proved of immense assistance to the consuls, who,
subordinated judicially to the chief judge, could now obtain from him
proper guidance in their difficulties, a facility of which they availed
themselves freely.
Although a great advance on what preceded it, the Supreme Court
could not of course escape from all the drawbacks which affected
the consular courts. As between British subjects, it enjoyed the full
powers of law courts in the mother country; but as between British
subjects on the one hand, and the natives of the country, or non-
British residents, on the other, the authority of the British court could
only be exercised over the former. This one-sided action has been to
some extent compensated in later times by the judicial qualifications
of consuls representing other Western nationalities, who administer
their own laws with the same impartiality as the British courts do
theirs. But as regards the Chinese no such compensation operates,
for although the treaties make provision for the judicial action of the
Chinese authorities, their conceptions of equity and forms of
procedure being wholly alien to those of the Western nations, their
decisions seldom satisfy the foreign litigant. An attempt to supply a
connecting-link between two radically different juridical ideals was
made in the setting up of mixed courts for the purpose of dealing
with petty cases between natives and foreigners within the
settlements of Shanghai. These courts have been occasionally
presided over by honest and competent judges, assisted by able
foreign assessors; but as the native magistrates, being men of low
rank, could always be overruled by the local executive, they lacked
the power to make their decisions effective.
As it was impossible to set up a separate judicial establishment at
each treaty port where there was but a handful of residents, the
consuls had to continue to perform magisterial duty with all the
inconveniences attending their double function. Efforts were made
by the Home Government to minimise these disadvantages by
infusing a modicum of legal knowledge into the service, for which
purpose they offered inducements to consular officials who should
qualify as barristers. Notwithstanding all this, however, the simple
fact that a consul is bound in his administrative capacity to take a
part in matters which may afterwards come before him as a judge
perpetuates an element of incongruity demanding an uncommon
degree of tact on the part of the official. Some of the worst
consequences to be apprehended from this state of things are
partially obviated by the judge or assistant judge of the Supreme
Court going on circuit, when important cases in the consular districts
require it; but that expedient is only possible at rare intervals.
The wisdom with which the Supreme Court has been directed is
attested by the absence of incident in its history, and by the
universal tacit approval of its proceedings. Its success, indeed, soon
came to be accepted so much as a matter of course that the true
source of it was forgotten. It was, however, recalled vividly to the
public memory by a certain retrograde movement. After a quarter of
a century of satisfactory working her Majesty's Government took a
step which was equivalent to pulling out the corner-stone of the
edifice—the absolute independence of the bench. In order to effect
an economy in salaries, it was ordained that the two incompatible
offices—the judicial and political—should be merged into one,
making the chief judge consul-general, and the assistant judge
consul for Shanghai. By this move the judges became subordinate to
the Legation in Peking, and the Supreme Court itself was subjected
to all the evils of the dual function under which the consuls had been
labouring. Thanks to the exceptional qualities of the holders of the
double office, no glaring scandal arose out of the unnatural
combination; but the protests of the community, and of the
incumbent of the two offices himself, were strong enough to induce
the Foreign Office, after a few years' trial, to retrace their false step
and restore the judge to his independence.
The twenty consular establishments in China on which the Select
Committee of the House of Commons reported in 1872 were
manned by forty effectives on duty, besides a considerable
contingent on furlough. The ten posts subsequently created employ
on an average twenty more. Two complete generations of officials
have passed through the consular mill in fifty years, which may be
moderately reckoned at two hundred men, all of them selected by a
competitive examination only one degree less stringent than that for
the Indian Civil Service, and nearly all of them men of varied
accomplishments. They have been placed in every part of the wide
empire of China, and during their career have been shifted about so
that every one has had chances of interesting himself in localities
strongly contrasted with each other, both as regards official labour
and personal recreation and study. From a body of highly educated
men so situated, it was naturally to be expected that much
enlightenment would be obtained concerning China and its people,
and considerable progress made in the promotion of amiable
intercourse between them and foreigners. These expectations have
not been disappointed. In the period immediately following the
peace of 1860 remarkable activity was shown by British consular
officers. The names of Meadows, Markham, Alabaster, Oxenham,
recall many exploits of exploration in the interior during very
troublous times. Swinhoe, Baber, Hosie, Bourne, Spence, Davenport,
Parker, have continued the work and greatly extended its area.
Others have distinguished themselves in the held of literary
research, and some have found their appropriate reward in
honourable appointments in English universities. On the whole, there
has been lack of neither energy nor capacity in the British consular
service; and yet it is a matter of common remark, even by its
members themselves, that in their primary duty of promoting and
defending the interests of British commerce they have been
unsuccessful. Treaty rights, they admit, have not been safeguarded
at the Chinese ports, and this in spite of every apparent incentive to
exertion in their defence. A distinction, however, must be drawn
between an apparent incentive which is general and remote, such as
the patriotic desire for the advancement of their country's interests,
and those influences which are nearer and more personal. The
attitude of the China consuls can only be fairly estimated in its
relation to that of their chief, and his again in relation to that of the
Home Government. Like master, like man, is an adage which fits
the case, and it is to Peking and to London we must look for the key
to the character of the consular rank and file.
The British Ministers at Peking have been selected without any fixed
rule. The first of the series was taken from the diplomatic circle. The
succeeding three, whose term of office covered a period of twenty
years, were chosen from among the veterans of the consular
service. The next two were taken from the junior ranks of diplomacy,
and the seventh was a military officer from Africa. The appointment
of Sir Robert Hart in 1885, which was cancelled by his wish, afforded
further illustration of the extreme catholicity of the Government's
elective faculty.
The witnesses examined before the Select Committee of the House
of Commons in 1872 were unanimous in insisting on the necessity
for long and special training for the office of consul in China, and this
principle has been strictly followed by the Government. But for the
higher post of superintendent of all the consuls the Government has,
at least since 1885, acted on the theory that no such qualification is
necessary. But the task of a Minister to China is by no means an
easy one. It may be left undone, or it may be done so badly that it
were better not to be done at all, but to discharge the duties of the
office in a creditable manner requires not only high training but large
capacity. The Minister has to conduct his own diplomatic duties in
the capital, in which not the Chinese alone but all or nearly all his
foreign colleagues are openly or secretly thwarting him. He has at
the same time to direct the proceedings of twenty or thirty officers
placed at great distances, whom he has never seen, and every one
of whom is superior to himself in the knowledge of the conditions to
be dealt with. For such a duty it is obvious that an officer sent from
Europe must be incompetent, the circumstances of the service in
China differing essentially from those prevailing elsewhere. The new
incumbent, unless he were a born genius, could never get beyond
the elementary lessons of experience before, overtaken by
promotion, he shakes the Chinese dust off his feet for ever. Much
might of course be learned by personal observation at the consular
ports and conference with local officials and people in the provinces,
but it is somewhat singular that this obvious source of intelligence
has been taken advantage of almost exclusively by those of the
British Ministers who stood the least in need of it. Indeed the only
one of them who made it a rule to visit the treaty ports at intervals
was Sir Rutherford Alcock, whose long experience convinced him of
the necessity of constantly refreshing and extending his knowledge
of local circumstances and people.
A service dispersed over such a large area as the Chinese empire,
carried on by despatches between parties who were strangers to
each other, and one of whom at least had no personal knowledge of
the subjects treated, must have been characterised by an absence of
reality, and must have tended more and more towards a perfunctory
routine. For this, however, the system of appointing Ministers who
were strangers to the country was not wholly responsible. Long
before the Ministers were so selected the secretaries began to be
sent from European schools, and thus the consular service,
disheartened by inadequate pay and a constant menace of further
diminution, saw the few prizes of their profession withdrawn from
their reach. To serve his time quietly, therefore, to earn his pension
and retire without a stain on his character, became more or less the
consular ideal. Ambition was starved among those who had to bear
the burden and heat of a thirty years' residence in China, when they
saw good posts thrown away upon men imported for two or three
years, who were almost useless, and who themselves deplored their
enforced idleness. The disadvantages attending these exotic
importations have been often insisted upon. An old member of the
consul staff comments upon it in the following practical manner:—
In every country administered by the British Crown, or at every Court
at which there is a British representative, the administrator or envoy
has from the moment of his entering on the duties of his office the
assistance of an experienced staff, well versed in the local history and
traditions, or finds himself in the midst of a society the language and
usages of which are familiar to him. In China, where we have been
fighting and negotiating for over fifty years, we are not so fortunate.
A Minister proceeds there, and on his arrival finds himself in a new
and to him unknown country, the staff which he may bring with him
being like himself utterly unacquainted with the East and its peoples.
The Minister is obliged either to grope his way unassisted, or to rely
on the aids and advice of experienced (but not always disinterested)
outsiders. Under these circumstances his only wise course is to put
himself entirely in the hands of the permanent local staff, which, for
this purpose, means the Chinese Secretary. That officer, the real
motive force of the Legation, occupies a position of greater
importance than that of the nominal head of the mission, but, with an
irony which is not uncommon in Government administration, he is the
least appreciated member of the staff. His salary is that of the junior
ranks in the consular service, and yet it is to him that the seniors in
that service look for instructions which he is incompetent to give
them: the result may be imagined. Why should these things be? The
Indian Government has in its service many men of brilliant
attainments, and of knowledge gained in long years of service in the
East, who might be called upon to fill the post of Minister which would
be suitable and congenial to them. And there is an abundance of
choice of junior Legation officers in the well-trained consular service.
Would it not be very advantageous if the working hands in the
Legation were chosen from the most competent Chinese scholars in
the consular service?
Considering their initial qualifications, their social standing, and their
great opportunities, it must be admitted that the men of distinction
who have emerged from the consular service during the last fifty
years seems disproportionately small. It is perhaps invidious to
mention names in this connection, but in response to inquiries
addressed to veterans in the service, four men only are placed in the
first rank as the best representatives of the consular training school.
These are Sir Harry Parkes, Mr T. T. Meadows, Mr H. N. Lay, and Mr
W. F. Mayers. Sir Robert Hart, it should be mentioned, left the
service so early, and Sir Rutherford Alcock joined it so late, in life,
that their distinguished careers can scarcely be claimed as the
product of the consular nursery.
It is impossible to look back over the forty years which have elapsed
since the new relations were established in China without being
struck by a certain change which passed over the character of the
diplomatic and consular services between the first decade of that
period and the second. The anxious years of the rebellion evoked
much active energy on the part of British officials. The serious
opposition to the operation of the treaties was met by very vigorous
action on the part of the consuls at the ports and of the Minister at
the capital. The years 1868 and 1869 may be considered to have
marked the culminating-point of the British official effort to enforce
observance of the treaties in letter and spirit, and to protect all
commercial interests. The change which came over the diplomatic
and consular services at the end of the first decade of diplomatic
relations may be likened to the rising followed by the receding of a
tide. Up till the years we have specified, whatever the difficulties
which beset their office, the consuls showed earnestness in the
defence of the interests confided to them, and acted on the
conviction that their exertions were pleasing to those who were set
in authority over them. Their sense of duty was sustained by the
hope of distinction. After 1869 the discovery was made that the
situation had been undergoing a change of which the service had
been unaware. What was formerly deemed a merit had become a
demerit in consular officers, and on this discovery zeal naturally fell
to a discount. It was but a reflex of the change that had crept over
the spirit of the British Foreign Office, a change which also had
escaped notice until circumstances forced it into publicity. This
seems to have originated with the removal from the scene of Lord
Palmerston, the statesman who for forty years had stood in a
general way for what was manly and straightforward in the British
national character. Though he left a tried and trusted colleague, Lord
Clarendon, in charge of the Foreign Office, and a sturdy permanent
Under-Secretary, perhaps the last custodian of the Palmerstonian
tradition, and who remained at his post for five years longer, yet it
was made evident by results that the spirit which had animated that
great department of State had vanished. The Foreign Office became
nerveless and invertebrate, sentimental and unstable. Those who
had to do with it in the time of Palmerston, Layard, and Hammond
know that since their time the officials bearing the same titles have
been of quite another calibre, have been swayed by different
influences, and above all have exhibited no such knowledge of the
affairs with which they had to deal as their predecessors of the
Palmerstonian era. Many explanations may be given for the new
departure without disparagement of the capacities of the individuals
concerned. Such explanations interest those who may desire to
promote reform in the constitution and the inspiration of the Foreign
Office. It suffices us merely to note the fact by way of accounting for
some of the shortcomings which have been laid to the charge of our
representation in China. We have seen how easily one Foreign
Secretary yielded to the meretricious solicitations of the envoy
Burlingame, and how another allowed himself to be cajoled by the
Marquis Tsêng. After these, and sundry other such, exhibitions it was
impossible for any Minister serving the country in the Far East to
place the old reliance on the support of his Government. With John
Bright, the implacable opponent of Palmerston and his works,
installed at the Board of Trade, whose word was law on such matters
as Chinese commercial treaties, and apparently more anxious to
undo the work of Palmerston than to promote a trade which both he
and his department unaffectedly despised, it was not likely that the
commercial communities trading with China should cherish any hope
of redress of grievances from a Government whose face seemed set
against them. Apathy, therefore, became the principle, to keep the
peace at all sacrifices the avowed policy of British diplomacy in
China. The apparent exception to this rule in the attempted
reclamations in connection with the Margary murder in 1875
afforded in its abortive ending a new corroboration of the rule. The
diplomatic and consular establishments went on grinding out routine
despatches and publishing statistical reports, but with the tacit
understanding that whatsoever is more than these cometh of evil.
Under such conditions it was of little consequence how the Peking
representation might be filled, since it has not for thirty years risen
above the level of comedy, the term applied to it by those who have
grown old in its service.
Such was the situation of affairs when the greatest crisis in the
history of China, or of foreign relations with that country, was sprung
upon the world in 1894. A Legation equal only to clerical routine
suddenly called upon to play a part in a commotion which unhinged
the policy of the world was totally inadequate to the strain, and as a
consequence of the impotence of the Foreign Office and its agent in
China, the interests of Great Britain and, what was only second in
importance, the interests of the Chinese empire were allowed to go
by default. The Chinese were, and perhaps even still remain,
unconscious of the reasons of the collapse of their empire. Perhaps
something of the same kind might be said of the British Foreign
Office in regard to the interests of Great Britain in China. Certainly
there is as yet little sign of a determination to reform the mechanism
of the country's representation, and this, perhaps, because the
preliminary step thereto would be the reform of the Foreign Office
itself. And so the Legation goes on under the nominal headship of a
Minister who must be guided entirely by his Chinese Secretary, an
official of inferior rank and position to the body of consuls whom he
has to control, and for whose authority they can never have genuine
respect.
The recent upheaval has offered many new opportunities of
distinction for the consuls, especially in the interior of China. That
these openings have infused new life into the consular ranks has
been shown in many ways during the last few years; and if natural
selection be allowed to operate freely and the best men be not
discouraged in their efforts for their country's benefit by undue
interferences from Peking, where there is neither knowledge nor
capacity to guide them, it is still possible that the consular service
may play a valuable part in the reconstruction of the foreign
relations of China.
CHAPTER XXIX.
CHINA AND HER RULERS.
Longevity of the State—Government by prestige—Necessity of adaptation to
European ideas—The Empress-dowager—Prince Kung—Wênsiang—Hu Lin-yi—
Tsêng Kwo-fan—Tso Tsung-tang—Chang Chih-tung—Li Hung-chang—His long
and consistent career—Efforts at reorganising national forces.
The long continuance of a State more populous than any other on
record is a phenomenon which to thoughtful minds can hardly fail to
evoke a feeling akin to reverence. De Quincey declared if he met a
Chinaman he would make obeisance to him, saying, There goes a
man 2000 years old. Be the causes of this national longevity what
they may, the fact should make us pause to consider on what
foundation does this great vital national system rest? The most
realistic word-painter of China represents the country as a collection
of villages, each being a unit of self-government,[29] and in
describing village life in minute detail, seems to depict the great
empire, of which each village is a pattern in miniature. Dynasties
may come and dynasties may go, but the Chinese families, their
industries and their customs, go on for ever. It is remarkable with
what ease the people adapt themselves to changes in their ruling
powers, regardless of race or origin; indeed it is a noteworthy fact
that the rulers have for many centuries been more often foreign
than native.[30] Foreign, however, not quite in the sense in which the
word is so easily translated barbarian by the Chinese, and applied
by them to the hated Aryans of the West. The rulers of China have
been of cognate races, more or less imbued with the same generic
ideas as the Chinese themselves, and with tastes akin to theirs. How
this succession of dynasties, each established by violence, has
coexisted with the continuity of the grand national idea of the
emperor being the Son of Heaven can only be explained by the very
practical character of the race, who accept the usurper as divinely
appointed from the moment he has proved himself successful. What
holds, and has held together from ancient times, this great
aggregate of mankind in common usages and ideas is naturally a
mystery to Occidentals, the cohesive principle not being perceptible
to them. China occupies the unique position of a State resting on
moral force,[31] a conception almost as alien to the Western mind as
material progress is to the Eastern, hence the proposition is apt to
be received with amused contempt. Yet a State administered without
police, and ruled without an army, is a something which cannot be
explained away. Government by prestige is, other things being
equal, surely the most economical as well as the most humane of all
species of government; but an obvious consequence is that in
emergencies the Government is beholden to volunteers, and is often
driven to enlist the services of banditti and other forces proscribed
by the law. Imperial prestige, which embraces the relations of the
surrounding tributaries, is but an expansion of the authority of the
head of the family and of the elders of the village, which rests on
moral sanction only. The first collision, however, with the material
forces of Christendom proved that in the system of the modern
world the Chinese principle of government was an anachronism, and
that moral must succumb to physical force. Yet in the midst of the
world's triumph in the pricking of the great Chinese bubble, it had
been well to reflect what the kind of bubble was that was being
pricked. China with her self-contained, self-secreted knowledge,
could not be expected to foresee how the impact of the West was
likely to affect her ancient polity. She had nothing wherewith to
compare herself, and no criterion of good or evil except her own
isolated experience; nor did she know aught of human development
except what was, so to speak, forcibly injected into her, but never
assimilated. What, then, could she do to be saved but to take herself
entirely to pieces like a house that has to be rebuilt on a new plan,
and so fit herself for the companionship and competition of the
worldly Powers, from whose pressure she could by no means
escape? She had to put away the wisdom of ages, the traditions of a
civilisation unbroken for thousands of years, and convert herself into
a mechanical, scientific, and military Power. Something more radical
than reform is involved in such a root-and-branch change: it was not
improvement but transformation that was demanded.
That some such essential changes are necessary to the preservation
of the Chinese empire is probably recognised by all who interest
themselves in the subject—including a large ever-increasing number
of the Chinese themselves; but the gravity of the revolution may well
cause misgivings both as to its possibility and its incalculable effects.
Who among the Chinese rulers is sufficient for such things?
It is not always possible to locate the nervous centre of any
Government in the West, whether its form be autocratic or
representative. With regard to that of China we may safely say it is
never possible—at least for any foreigner. The attempts which have
been from time to time made to assign acts of Government to the
will or influence of certain individuals have in general proved in the
sequel to have been far from hitting the mark. The monarch under
whose authority the whole machine moves is not necessarily the
directing will: indeed he is very often little better than a puppet.
The eunuchs, concubines, and play-actors, who constituted the
Court of the late Emperor Hsien-fêng, the father of the present
young emperor, had more influence probably in bringing on the war
that led the Allies to Peking than any of the high officers or
Ministers, wrote Sir Rutherford Alcock in 1871. Another writer put it
in a more paradoxical form: There is in China something more
powerful than the Emperor, and that is the Viceroy; more powerful
than the Viceroy, and that is the Taotai; more powerful than the
Taotai, and that is the Weiyuen, meaning that the power of
obstruction, extending through every grade of officialdom, is most
widely diffused at the base. Official responsibility and moral
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Ejb Cookbook 1st Edition Ben G Sullins Mark B Whipple
PDF
Ejb notes
PDF
Ejb intro
PPTX
EJB3 Basics
PDF
Enterprise Javabeans 31 Sixth Edition Andrew Lee Rubinger Bill Burke
PDF
Instant Access to Beginning EJB 3 Java EE 7 edition Jonathan Wetherbee ebook ...
PDF
Ejb intro
PPTX
Ejb Cookbook 1st Edition Ben G Sullins Mark B Whipple
Ejb notes
Ejb intro
EJB3 Basics
Enterprise Javabeans 31 Sixth Edition Andrew Lee Rubinger Bill Burke
Instant Access to Beginning EJB 3 Java EE 7 edition Jonathan Wetherbee ebook ...
Ejb intro

Similar to Ejb 3 Developer Guide A Practical Guide For Developers And Architects To The Enterprise Java Beans Standard Michael Sikora Meenakshi Verma Chris Mawata Lawrence Bean (20)

PPT
j2ee Building components
PDF
The J2EE Tutorial 1st edition Edition Stephanie Bodoff
PPTX
The Latest in Enterprise JavaBeans Technology
PDF
The J2EE Tutorial 1st edition Edition Stephanie Bodoff
PDF
EJB 3.0 - Yet Another Introduction
PDF
Mastering Enterprise Javabeans 2nd Ed Ed Roman Scott W Ambler Tyler Jewell
PPTX
Enterprise java beans
PDF
EJB 3.2 - Java EE 7 - Java One Hyderabad 2012
PPT
Ejb (1)
DOC
Java online training from hyderabad
PPT
Ejb course in-mumbai
PPT
Unite5-EJB-2019.ppt
PPT
Aravind vinnakota ejb_architecture
PPT
PPT
ejb.ppt java lecture notes enterprise java
PDF
Ejb 30 Database Persistence With Oracle Fusion Middleware 11g Deepak Vohra
PDF
EJB 3 in Action Second Edition Debu Panda
PPT
PPT
Virtual classroom
PDF
Get Java EE Development with Eclipse - Second Edition Ram Kulkarni free all c...
j2ee Building components
The J2EE Tutorial 1st edition Edition Stephanie Bodoff
The Latest in Enterprise JavaBeans Technology
The J2EE Tutorial 1st edition Edition Stephanie Bodoff
EJB 3.0 - Yet Another Introduction
Mastering Enterprise Javabeans 2nd Ed Ed Roman Scott W Ambler Tyler Jewell
Enterprise java beans
EJB 3.2 - Java EE 7 - Java One Hyderabad 2012
Ejb (1)
Java online training from hyderabad
Ejb course in-mumbai
Unite5-EJB-2019.ppt
Aravind vinnakota ejb_architecture
ejb.ppt java lecture notes enterprise java
Ejb 30 Database Persistence With Oracle Fusion Middleware 11g Deepak Vohra
EJB 3 in Action Second Edition Debu Panda
Virtual classroom
Get Java EE Development with Eclipse - Second Edition Ram Kulkarni free all c...
Ad

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Computing-Curriculum for Schools in Ghana
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
GDM (1) (1).pptx small presentation for students
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Presentation on HIE in infants and its manifestations
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharma ospi slides which help in ospi learning
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Computing-Curriculum for Schools in Ghana
O5-L3 Freight Transport Ops (International) V1.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
RMMM.pdf make it easy to upload and study
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GDM (1) (1).pptx small presentation for students
2.FourierTransform-ShortQuestionswithAnswers.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
VCE English Exam - Section C Student Revision Booklet
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
Anesthesia in Laparoscopic Surgery in India
01-Introduction-to-Information-Management.pdf
Presentation on HIE in infants and its manifestations
Ad

Ejb 3 Developer Guide A Practical Guide For Developers And Architects To The Enterprise Java Beans Standard Michael Sikora Meenakshi Verma Chris Mawata Lawrence Bean

  • 1. Ejb 3 Developer Guide A Practical Guide For Developers And Architects To The Enterprise Java Beans Standard Michael Sikora Meenakshi Verma Chris Mawata Lawrence Bean download https://ebookbell.com/product/ejb-3-developer-guide-a-practical- guide-for-developers-and-architects-to-the-enterprise-java-beans- standard-michael-sikora-meenakshi-verma-chris-mawata-lawrence- bean-4100280 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Ejb 30 Database Persistence With Oracle Fusion Middleware 11g Deepak Vohra https://ebookbell.com/product/ejb-30-database-persistence-with-oracle- fusion-middleware-11g-deepak-vohra-2309890 Ejb 31 Cookbook Richard Reese https://ebookbell.com/product/ejb-31-cookbook-richard-reese-2428804 Ejb 3 In Action 2nd Edition Debu Panda Reza Rahman Ryan Cuprak https://ebookbell.com/product/ejb-3-in-action-2nd-edition-debu-panda- reza-rahman-ryan-cuprak-36083032 Ejb 3 In Action Debu Panda Reza Rahman Derek Lane https://ebookbell.com/product/ejb-3-in-action-debu-panda-reza-rahman- derek-lane-4100284
  • 3. Ejb 30 In Simple Steps Dreamtech Press https://ebookbell.com/product/ejb-30-in-simple-steps-dreamtech- press-5411382 Ejb 30 In Simple Steps https://ebookbell.com/product/ejb-30-in-simple-steps-4090324 Pro Ejb 3 Java Persistence Api Mike Keith Merrick Schincariol https://ebookbell.com/product/pro-ejb-3-java-persistence-api-mike- keith-merrick-schincariol-4106144 Beginning Ejb 3 Java Ee 7 Edition 2nd Edition Jonathan Wetherbee https://ebookbell.com/product/beginning-ejb-3-java-ee-7-edition-2nd- edition-jonathan-wetherbee-4167430 Beginning Ejb 3 Application Development From Novice To Professional 1st Edition Raghu R Kodali https://ebookbell.com/product/beginning-ejb-3-application-development- from-novice-to-professional-1st-edition-raghu-r-kodali-978406
  • 5. EJB 3 Developer Guide A Practical Guide for developers and architects to the Enterprise Java Beans Standard Michael Sikora BIRMINGHAM - MUMBAI
  • 6. EJB 3 Developer Guide Copyright © 2008 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: May 2008 Production Reference: 1160508 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847195-60-9 www.packtpub.com Cover Image by Michelle O'Kane (michelle@vodafone.ie)
  • 7. Table of Contents Preface 1 Chapter 1: Introduction to the EJB 3 Architecture 7 Introduction to the Java EE Architecture 7 The EJB 3 Architecture 9 EJB Container Services 11 The JPA Persistence Engine 12 EJB 3 Compared with Earlier Versions 13 Getting Started 14 Installing GlassFish 14 Testing the Installation 16 Accessing the Administrator Console 17 Shutting Down GlassFish 19 Downloading Example Source Code 19 Summary 19 Chapter 2: Session Beans 21 Introduction 21 Stateless Session Beans 22 Annotations 23 Creating a Session Bean Client 25 Running the Example 26 The Program Directory Structure 28 The Ant Build Script 29 The Application Client Container 31 Building the Application 32 Stateless Session Bean's LifeCycle 34 Stateful Session Beans 36 Stateful Session Bean's LifeCycle 39 Local Interfaces 41 Summary 44
  • 8. Table of Contents [ ii ] Chapter 3: Entities 45 Introduction 45 EJB 3 Entities 46 Comparison with EJB 2.x Entity Beans 47 Mapping an Entity to a Database Table 48 Introducing the EntityManager 49 Packaging and Deploying Entities 53 The Program Directory Structure 53 Building the Application 54 Field-Based Annotations 56 Generating Primary Keys 57 Table Strategy 57 Sequence Strategy 58 Identity Strategy 59 Auto Strategy 59 Overriding Metadata Defaults 60 Summary 62 Chapter 4: Object/Relational Mapping 63 O/R Mapping Default Behavior 63 A Banking Example Application 64 Customer Entity 65 Account Entity 68 Address Entity 69 Referee Entity 70 Testing the Application 71 O/R Mapping Overriding Defaults 74 Customer Entity 75 Account Entity 79 Address Entity 80 BankServiceBean 82 O/R Mapping Additional Annotations 84 Referee Class 88 BankServiceBean 88 Composite Primary Keys 89 O/R Inheritance Mapping 91 SINGLE_TABLE Strategy 92 JOINED Strategy 94 Table per Concrete Class Strategy 95 Summary 96
  • 9. Table of Contents [ iii ] Chapter 5: The Java Persistence Query Language 97 Introduction 97 Simple Queries 98 Projection 99 Conditional Expressions 99 Aggregate Functions 101 GROUP BY 102 HAVING 102 Queries with Relationships 103 Joins 103 Inner Joins 103 Outer Joins 104 Fetch Joins 104 Collection Comparison Expressions 105 Constructor Expressions 105 SubQueries 106 Functions 107 CONCAT 107 SUBSTRING 107 TRIM 107 LOWER and UPPER 107 LENGTH 108 LOCATE 108 ABS 108 SQRT 108 MOD 108 SIZE 109 Queries with Parameters 109 Positional Parameters 109 Named Parameters 110 Named Queries 110 Handling Date and Time 112 @Temporal annotation 112 Queries with Date Parameters 113 Datetime Functions 113 Bulk Update and Delete 114 Native SQL 114 Summary 118
  • 10. Table of Contents [ iv ] Chapter 6: Entity Manager 119 Application-managed Entity Manager 119 Entity Manager Merge 123 Entity Manager Methods 124 remove() 124 contains() 125 flush() 125 setFlushMode() 125 refresh() 126 clear() 126 Cascade Operations 126 persist 126 remove 127 merge 127 refresh 127 all 128 Extended Persistence Context 128 Entity LifeCycle Callback Methods 130 Entity Listeners 131 Summary 134 Chapter 7: Transactions 135 Introduction 135 Container-Managed Transaction Demarcation 136 SUPPORTS 137 NOT_SUPPORTED 137 REQUIRED 137 REQUIRES_NEW 137 MANDATORY 137 Never 138 Examples of Transaction Attributes 138 REQUIRED Example 138 REQUIRES_NEW Example 140 NOT_SUPPORTED Example 141 SUPPORTS Example 141 MANDATORY Example 143 NEVER Example 144 Controlling Container Managed Transactions 145 SessionSynchronization Interface 146 Doomed Transactions 148 Concurrency and Database Locking 149
  • 11. Table of Contents [ ] Isolation Levels 149 Lost Update Problem 151 Versioning 152 Read and Write Locking 154 UserTransaction Interface 154 Summary 158 Chapter 8: Messaging 159 Introduction 159 Java Message Service (JMS) API 160 Queue Producer and Consumer Examples 161 Synchronous Queue Consumer Example 163 Running the Queue Producer and Synchronous Queue Consumer Examples 165 An Asynchronous Queue Consumer Example 167 Running the Asynchronous Queue Consumer Example 169 Topic Producer and Consumer Examples 169 Synchronous Topic Consumer Example 170 Running the Topic Producer and Synchronous Topic Consumer Examples 171 An Asynchronous Topic Consumer Example 172 Running the Asynchronous Topic Consumer Example 173 Motivation for Message-Driven Beans 174 A Simple Message-Driven Bean Example 174 A Session Bean Queue Producer 174 A Message-Driven Bean Queue Consumer 176 MDB Activation Configuration Properties 177 acknowledgeMode 177 subscriptionDurability 178 messageSelector 179 MessageDrivenContext 179 MDB LifeCycle 180 MDB Example Revisited 181 Sending Message Confirmation to a Client 183 MDBs and Transactions 187 Summary 188 Chapter 9: EJB Timer Service 189 Introduction 189 Timer Service Examples 190 A Single Event Example 190 An Interval Event Example 192 A Timer Interface Example 194 Timers and Transactions 196 Summary 197
  • 12. Table of Contents [ vi ] Chapter 10: Interceptors 199 Interceptor Methods 200 Interceptor Classes 201 Default Interceptors 204 Interceptor Communication 206 Summary 209 Chapter 11: Implementing EJB 3 Web Services 211 Overview of Web Service Concepts 211 The SOAP Protocol 212 The WSDL Standard 213 The UDDI Standard 213 SOA and Web Services 213 Creating a Java Application Web Service 214 Creating an Endpoint Implementation Interface 216 The WSDL Document 217 The portType Element 218 The binding Element 219 The service Element 219 The message and types Elements 220 The GlassFish WSGEN Tool 220 Deploying a Java Application as a Web Service 222 The GlassFish Admin Console Test Harness 223 Creating a Java Web Service Client 224 Overriding JAX-WS Annotation Defaults 226 Deploying an EJB Session Bean as a Web Service 229 Packaging an EJB Web Service 230 Creating an EJB Web Service Client 230 Summary 232 Chapter 12: EJB 3 Security 233 Java EE Container Security 233 Authentication 234 GlassFish Authentication 234 Mapping Roles to Groups 235 Authenticating an EJB Application Client 237 EJB Authorization 239 Declarative Authorization 240 Denying Authorization 241 EJB Security Propagation 242 Programmatic Authorization 243 Java EE Web Container Security 245 Web-Tier Authorization 245
  • 13. Table of Contents [ vii ] Transport Layer Security 246 Web-Tier Authentication 246 Example of Web-Tier Authentication and Authorization 247 Summary 248 Appendix A: Annotations and Their Corresponding Packages 249 Index 251
  • 14. Preface Enterprise JavaBeans (EJB) technology is a core part of the Java EE 5 specification. EJB is a framework for building enterprise-scale object-oriented, distributed, component-based business applications. EJB business applications are written in Java, are scalable and can be deployed on any platform that supports the EJB specification. EJB applications are deployed to and execute under the control of an EJB container. The EJB container provides services typically required by enterprise applications such as security, transaction management, resource pooling, and systems management. The EJB 3 specification, released in May 2006, is a radical change from previous versions of the technology. Developing business applications is considerably easier with EJB 3. The handling of persistence in particular has radically changed in EJB 3. Persistence is no longer a service provided by an EJB container but rather by a persistence provider conforming to the Java Persistence API (JPA) specification. Java applications which need to be persisted but which do not require the services provided by an EJB container can be persisted outside an EJB container by a JPA persistence provider. In this book we cover JPA as well as the core EJB 3 services. This book is a concise, example-driven introduction to EJB 3. The best way to learn a new software technology is by studying and trying out programming examples. In this book you will see a lot of code and one example after another. We do not assume any prior knowledge of EJB. However this book does assume at least a couple of years’ experience of Java and some knowledge of relational database technology. The examples in this book have been deployed on the GlassFish application server. GlassFish was chosen primarily because this is the Java EE 5 reference implementation.
  • 15. Preface [ ] What This Book Covers Chapter 1 Introduction to EJB 3—A general overview of the Java EE architecture including EJB container services, the JPA persistence engine, and initial installation of the GlassFish application server. Chapter 2 Session Beans—Creation of a session bean and its client and examples of running it from the application client container. Exploring the program directory structure. Packaging and deploying a session bean. A look at the stateless and stateful session beans lifecycle. Chapter 3 Entities—Exploring EJB 3 entities. How to package and deploy entities and map an entity to a database table. Metadata defaults and how to override them. Generating primary keys. Chapter 4 Object/Relational Mapping—One-to-one, one-to-many and many-to-many associations. Default object/relational mapping values and how to override them. Object/relational inheritance mapping and additional annotations. Chapter 5 JPQL (Java Persistence Query Language)—Looking at different groups of queries including aggregate functions, queries with relationships, subqueries, queries with parameters and named queries. JPQL joins and functions are also explained. Chapter 6 Entity Manager—Looks in detail at the entity manager. Covers both the EJB 3 container-managed and application-managed entity managers. Chapter 7 Transactions—ACID properties and isolation levels. Container-managed transactions. Bean-managed transactions. Chapter 8 Messaging—Looks at the JMS (Java Messaging Service) API. Examples of queue producer and queue consumers. Topic producer and consumers. Message driven beans: their activation configuration properties, lifecycles and transactions. Chapter 9 EJB Timer Service—Examples of single and interval events. Timer interface methods. Timers and transactions. Chapter 10 Interceptors—Covers interceptor methods, classes and interceptor communication as well as default interceptors. Chapter 11 Implementing EJB 3 Web Services—An overview of web service concepts and the web service definition language (WSDL). Creating and deploying a Java application as a web service. Creating and deploying an EJB session bean as a web service. Creating a web service client.
  • 16. Preface [ ] Chapter 12 EJB 3 Security—A look at security, GlassFish authentication, declarative and programmatic EJB authorization and Web Tier authentication and authorization. The Appendix shows EJB 3 annotations described in this book with their corresponding packages. What You Need for This Book First you must have version 5 or higher of the Java Development Kit (JDK). This can be downloaded from http://java.sun.com/javase/downloads/index.jsp. You������������������������ also need a version of Ant equal to or higher than 1.6.5. Ant is a tool for building Java programs, similar in concept to the Unix Make tool, except that it is platform independent. Ant is part of Apache’s Jakarta project. If you are unfamiliar with Ant you should look at the Ant web site (http://ant.apache.org/). If you do not have Ant there is no need to download it as the GlassFish application server includes a copy of Ant. Finally you need a version of GlassFish equal to or higher than V2b41d. This can be downloaded from https://glassfish.dev.java.net//. Instructions on setting up environment variables and installing GlassFish are given in the Getting Started section in Chapter 1. Who Is This Book For Previous experience of working with Java is essential and knowledge of relational databases is desirable. This book is primarily aimed at professional developers who already have a working knowledge of Java. Enterprise architects and designers with a background in Java would also find this book of use. As this book is an introduction to EJB 3, it is aimed at those who are new to EJB 3. However, as the new version of EJB is so radically different from the previous version (EJB 2.x), the book would also be suitable and of interest to those who have had experience working with EJB 2.x. The text makes it clear where the differences between the versions of EJB lie, although it is not explored in detail.
  • 17. Preface [ ] Approach of this Book This book has been written for developers new to EJB 3 who want to use the technology. Such readers usually want to see examples and program code. In this book we work through one example after another and we show lots of program code. If you are new to a technology and have looked at your first HelloWorld example, the next thing you want to do is to code and run the program yourself. In the case of EJBs this also means packaging and deploying the EJB to a container. Although we promise no HelloWorld examples in this book, we look at packaging and deployment straight after coding our first EJB, rather than ignoring these topics or leaving them to the end of the book. All the source code together with packaging and deployment scripts is available from the book's web site. This book is not a reference book, so we don't attempt to cover all EJB 3 features. We've kept this book concise to help you quickly get up and running with EJB 3. Although an EJB will run in any EJB container, the deployment process is container-dependent. This means that we need to pick a specific container for our examples. Sun's open-source, free GlassFish container was chosen primarily because this was the Java EE reference container implementation and also because GlassFish has Toplink embedded. Toplink in turn is the reference JPA persistence engine. We also chose not to use an IDE (Integrated Development Environment) partly because they are all quite different. A book based on IDE A would be of little use to a reader using IDE B. As IDEs are screen-based navigational tools, any resulting book would contain a large number of screenshots and would be at least double in length. More importantly is the author's view that an IDE is not an ideal learning tool. Apart from having to learn to navigate through a large number of screens, often an IDE will hide the underlying EJB technology. Of course once you have learnt EJB an IDE will make you much more productive in your work. Instead we use the Ant build tool for compiling, packaging, deploying, and running our EJBs. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
  • 18. Preface [ ] Code words in text are shown as follows: We name our interface TimeService. java, which contains a single method definition getTime(). A block of code will be set as follows: @Stateless public class TimeServiceBean implements TimeService { public String getTime() { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt.format(%tr, cal); return fmt.toString(); } } When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold: @Stateless public class TimeServiceBean implements TimeService { private @EJB NiceDayService niceDay; public String getTime() { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt.format(%tr, cal); return fmt.toString() + niceDay.getMessage(); } } Any command-line input and output is written as follows: C:EJB3Chapter02glassfishlab1buildjar –tvf TimeService.jar New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: Under the Web Services heading in the Common Tasks pane on the left of the screen, click on Arithmetic. Important notes appear in a box like this. Tips and tricks appear like this.
  • 19. Preface [ ] Reader Feedback Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply drop an email to feedback@packtpub.com, making sure to mention the book title in the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer Support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the Example Code for the Book Visit http://www.packtpub.com/files/code/5609_Code.zip to directly download the example code. The downloadable files contain instructions on how to use them. Errata Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub. com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Questions You can contact us at questions@packtpub.com if you are having a problem with some aspect of the book, and we will do our best to address it.
  • 20. Introduction to the EJB 3 Architecture In this chapter we will give an overview of EJB 3 and how it fits into the Java EE multi-layer framework. We will also look at installing and getting started with the GlassFish container. The topics covered are: An overview of Java EE The EJB 3 Architecture Getting Started with GlassFish Introduction to the Java EE Architecture Modern enterprise applications have their responsibilities divided over a number of layers. A common architecture is the 3-layer model consisting of presentation, business, and database layers. The presentation layer is responsible for presenting a user interface and handling interactions with the end user. The business layer is responsible for executing business logic. The database layer is responsible for storage of business data; typically a relational database management system is used for this layer. Layering is used throughout computer science for managing complexity where each layer serves a distinct purpose. • • •
  • 21. Introduction to the EJB 3 Architecture [ ] Java Platform Enterprise Edition (Java EE) technology provides services to enterprise applications using a multi-layer architecture. Java EE applications are web-enabled and Java–based, which means they may be written once and deployed on any container supporting the Java EE standard. An application server is the environment in which the container resides. However, in practice we don't need to distinguish between an application server and a container, so we will use the terms interchangeably. The Java EE specification is supported by commercial vendors such as Sun, IBM, Oracle, BEA Systems as well as open-source ventures such as JBoss. Java EE presentation layer technologies include servlets, JSP pages, and JSF components. These are developed for a business application then subsequently deployed and run in a web container. A client would interact with the web container either from a browser or an applet. In either case the http or https internet protocol would be used for communication. Enterprise JavaBeans version 3 (EJB 3) is the technology Java EE version 5 (Java EE 5) provides for the business layer. In Java EE 5 we subdivide the business layer into one layer which is concerned with business processing and a second layer which deals with persistence. In EJB 3 the business processing artifacts are session and message-driven beans. These are developed for a business application and deployed and run in an EJB container. The persistence layer artifact is an entity; this is persisted to the database layer using a persistence provider or persistence engine. The persistence engine implements another specification, the Java Persistence API (JPA). Both EJB 3 and the JPA are specifications for which a number of organizations provide implementations. Both specifications can be downloaded from http://www.jcp.org/en/jsr/detail?id=220. The figure below summarizes Java EE 5 architecture: Presentation Layer Business Layer Database Layer Client Layer Web Layer Business Logic Layer Persistence Layer Java EE 5 Container Web Container Servlet JSP page JSF Component Web Browser Applet Java Application Client Application Client Container Java Application Client JPA Persistence Engine Entity EJB 3 Container Session Bean Message Driven Bean Relational Database
  • 22. Chapter 1 [ ] Note that our 3-layer model has become 5-layers. The distinction between client/web and business logic/persistence layers is not always made. Consequently we refer to Java EE architecture simply as n-layer or multi-layer. A Java EE container offers many other services such as web services, the Java Messaging Service (JMS), and resource adapters. Note from the diagram that we can access an EJB directly from a Java SE application, such as Swing, without going through a web container. The Java application can be stand-alone, or can be run from an Application Client Container (ACC). An ACC enables a client executing in its own Java Virtual Machine (JVM) outside the EJB container to access a limited number of Java EE services. The EJB 3 Architecture The EJB 3 architecture offers a standard for developing distributed, object-oriented, component-based business applications. The components developed in an EJB framework are session and message-driven beans. Collectively these are known as EJBs. These are usually relatively coarse-grained objects encapsulating a business process. They are components in the sense that EJBs can be combined to create a business application. Furthermore if the EJBs have been well designed they can be reused by another application. EJBs are distributed in the sense that they can reside on different computer servers and can be invoked by a remote client from a different system on the network. A session bean must have a business interface, which can be either remote or local. A remote client invokes the remote interface of a session bean as shown in the following diagram:
  • 23. Introduction to the EJB 3 Architecture [ 10 ] However a session bean and its client may reside in the same JVM instance. In such cases the client invokes the local interface of the session bean. The following diagram shows a web container client invoking the session beans local interface: Web Container Servlet JSP page JSF Component EJB 3 Container Session Bean JVM Local Call Java EE 5 Container A message-driven bean is an asynchronous recipient of a JMS message. The client, which can be a Java application or Java EE component such as a session bean, sends a JMS message to a message queue or topic. The message queue or topic may be managed by a Java EE container or alternatively by a dedicated JMS sever. The following diagram shows a client sending a JMS message which is received by a message-driven bean: EJBs are deployed and run in a container which is designed to make applications scalable, multi-user, and thread-safe. An EJB container also provides a number of services that an enterprise scale business application is likely to need. We will list these services in the next section. In contrast to session and message-driven beans, entities are relatively fine-grained objects which have a relatively long life and need to be persisted. Prior to EJB 3, entity beans played the role of entities and were defined as remotely accessible components, like session and message-driven beans. In EJB 3 entities are Java objects and so can utilize object-oriented features such as inheritance and polymorphism, which entity beans could not. In EJB 3, entities are persisted by a persistence provider or persistence engine implementing the JPA specification. This persistence engine can run within an EJB container or outside a container where a business application does not require other EJB services.
  • 24. Chapter 1 [ 11 ] Strictly speaking EJBs, being remotely accessible components, include only session and message-driven beans and not entities. However, whenever we refer to EJBs we will in general include entities, unless the specific context requires us to make a distinction. When we refer to EJB components, we mean session and message-driven beans and not entities. EJBs being Java-based may be written once and deployed on any application server supporting the EJB standard. EJB Container Services An EJB container provides a large number of services and we will list a few of these here. Much of this book describes some of these services in detail, in particular those which a business application is likely to invoke. EJB containers support concurrency and all EJB components are thread-safe. EJB containers provide pooling for EJB component instances. Pooling, in particular, contributes to the scalability of the EJB architecture. We will discuss pooling for session beans in Chapter 2 and for message-driven beans in Chapter 8. Load balancing and clustering are EJB container services which also contribute to the scalability of EJB. EJB containers provide a naming service, the Java Naming and Directory Interface (JNDI), for accessing EJBs or any other container-managed resource such as JMS queue connections. In EJB 3 a simpler annotation-based dependency injection facility is available which in many cases provides an alternative to JNDI. All EJB 3 containers support Java RMI-IIOP (Remote Method Invocation run over Internet Inter-Orb Protocol), which enables a session to be remotely accessed by a client. A client does not need to know whether the invoked EJB is remote or local, residing in the same JVM. This feature is known as location transparency. Business systems are often transactional and EJB provides a container-managed transaction service. This is described in Chapter 7. EJB supports messaging by providing JMS-based message-driven beans. We will discuss message-driven beans in Chapter 8. EJB provides a basic scheduling capability: the Timer service, which is described in Chapter 9. A new feature of EJB 3 is the Interceptor service. This allows common, tangential aspects of EJB components to be separated from any business logic. This concept is based on AOP (Aspect Oriented Programming) and is described in Chapter 10.
  • 25. Introduction to the EJB 3 Architecture [ 12 ] EJB allows you to convert a stateless session bean into a web service; this is covered in Chapter 11. EJB provides standards for both the authentication and authorization aspects of security. Authentication is concerned with validating the identity of a user. Authorization is concerned with controlling a user's access to an application, or part of an application. We have covered security in Chapter 12. Last, but certainly not the least, most business applications need a service for persisting entities. In EJB 3 this service is delegated by the container to a Java Persistence API (JPA) persistence engine. The JPA Persistence Engine Many applications do not require the services provided by an EJB container but still need persistence services. For this reason JPA has been issued as a separate specification and applications running outside an EJB container can also make use of JPA services. The main services include: Entity Manager Object/Relational Mapping The Java Persistence Query Language (JPQL) The Entity Manager provides services for persistence, transaction management, and managing the lifecycle of entities. Object/Relational metadata annotations are provided for mapping entities onto relational database tables. JPQL is used for retrieving persisted entities. We will look at these in more detail in the forthcoming chapters. Although the JPA specification is recent, it leverages object/relational mapping technology associated with products such as Hibernate and Oracle Toplink. These products have been available for many years; in the case of Toplink for over a decade. The JPA specification drew heavily on these two products in particular. Furthermore, Toplink and Hibernate are the actual default persistence engines for a number of EJB 3 containers. For example, both Sun's GlassFish container and Oracle Application Server 11g use Toplink as the embedded persistence engine. The JBoss EJB 3 container uses Hibernate as the embedded persistence engine. These are pluggable defaults however, so it is possible to use Hibernate with GlassFish for example. • • •
  • 26. Chapter 1 [ 13 ] EJB 3 Compared with Earlier Versions The main features introduced in EJB 3 can be summarized as: Simplified Persistence API Metadata Annotations Improved Query Language Use of Defaulting Dependency Injection Simplification of Session Beans The first two features are probably the most important, but we will expand on each of the above features in this section. The main difference between EJB 3 and EJB 2.x is the handling of persistence which we have already outlined. Prior to EJB 3 there was rather limited object/relational mapping between entity beans and relational tables. Inheritance and polymorphism were not possible prior to EJB 3. An EJB 3 entity is truly a Java object; this could not be said of an entity bean. The other main EJB 3 innovation is the introduction of metadata annotations. Metadata annotations were first introduced in Java SE 5, so this version of Java or higher must be used when developing EJB 3 applications. Metadata annotations can be used as an alternative to XML deployment descriptors both for configuring EJB components and specifying object/relational mappings with entities. However, deployment descriptors can be used in both cases. We will look at annotation versus deployment descriptor aspects in Chapter 2. The EJB Query language (EJB QL) available in earlier versions was rather limited in comparison with JPA's JPQL. In particular JPQL provides the following enhancements: Projections GROUP BY and HAVING clauses Joins Subqueries Dynamic Queries Queries with parameters Bulk update and delete operations • • • • • • • • • • • • •
  • 27. Introduction to the EJB 3 Architecture [ 14 ] Extensive use of defaults is made in EJB 3. So, for example, most metadata annotations do not require elements or parameters to be specified, the default is usually common, expected behavior. Annotation elements are usually needed only when we want to configure exceptional behavior. Dependency injection, first featured in the Spring framework, has been introduced in EJB 3 as an alternative to JNDI for looking up container-managed resources. Session beans have been simplified. We no longer need to specify component and home interfaces. Furthermore the session bean class no longer has to implement a number of callback interfaces even when these are not required by the application. In EJB 3 these lifecycle callback methods are implemented by session beans only when required. Getting Started For this book GlassFish was downloaded on Windows XP and all the examples were run on that platform. The instructions that follow assume a Windows platform is being used, however the installation instructions for other platforms such as Linux/Unix are almost the same. Installing GlassFish Before installing GlassFish check that version 5 or higher of the Java Development Kit (JDK) is present on your workstation. This can be downloaded from http://java.sun.com/javase/downloads/index.jsp For this book we used JDK 5.0 Update 12. Set the environment variable JAVA_HOME to point to the directory in which the JDK is installed. Add %JAVA_HOME%bin, to the PATH environment variable. This is done by clicking Control Panel from the Start menu. Then double-click the system icon. Select the Advanced tab on the System Properties box. Finally click the Environment Variables button. Next download a version of GlassFish equal to or higher than V2b41d from: https://glassfish.dev.java.net//
  • 28. Chapter 1 [ 15 ] into the directory in which you want to install it. All the code examples in this book were tested with GlassFish version V2b41d. The actual name of the downloaded jar file will depend on the version and platform selected. For this book glassfish-installer-v2-b41d.jar was used. In the same directory as the downloaded jar file, run the jar file as follows: java -Xmx256m -jar glassfish-installer-v2-b41d.jar This will unzip the file and create the glassfish subdirectory. Set the GLASSFISH_HOME environment variable to the directory where GlassFish was installed. Add %GLASSFISH_HOME%bin to the PATH environment variable. Set the environment variable ANT_HOME to the directory in which Ant is installed. GlassFish comes bundled with the Ant build tool and the installed Ant directory will be glassfishlibant. If you already have a version of Ant equal to higher than 1.6.5 then set ANT_HOME accordingly. Add %ANT_HOME%bin to the PATH environment variable. Change the directory to the glassfish directory and complete the installation by running the Ant setup script: ant -f setup.xml The setup process may fail because of port conflicts with existing software you may have. If so you will need to edit the setup.xml file. Within the file you should see the following fragment setting up default properties: ..... property name=domain.name value=domain1/ property name=instance.name value=server/ property name=admin.user value=admin/ property name=admin.password value=adminadmin/ property name=admin.port value=4848/ property name=instance.port value=8080/ property name=orb.port value=3700/ property name=imq.port value=7676/ property name=https.port value=8181/ property name=glassfish.license value=LICENSE.txt/ .... Change the value for the conflicting port, and run setup again.
  • 29. Introduction to the EJB 3 Architecture [ 16 ] Testing the Installation GlassFish is started with the following command: asadmin start-domain domain1 You should see the following messages: In particular this shows the admin console URL and the URL for web applications. So enter the URL http://localhost:8080 from a browser. If GlassFish has started up correctly you should get the following page:
  • 30. Chapter 1 [ 17 ] Accessing the Administrator Console Enter the URL http://localhost:4848 from a browser. You should get the following page:
  • 31. Introduction to the EJB 3 Architecture [ 18 ] The default user name is admin and the default password is adminadmin. After you have entered these you should get the following page: The administrator console is used for numerous tasks such as creating and configuring domains, monitoring performance, and deploying applications. An alternative for deploying applications is using the asadmin tool from the command line. In the remainder of this book we have used the asadmin tool for deployment. By including it as an Ant target the whole process of compiling, packaging, and deploying is automated.
  • 32. Chapter 1 [ 19 ] Shutting Down GlassFish To stop GlassFish use the following command: asadmin stop-domain domain1 Downloading Example Source Code The source code for the examples can be found as a zip file on the book's web site. Download the file and unzip it into a drive and directory of your choice. The examples in the book assume the source code has been downloaded into the C: directory. Subdirectories correspond to individual chapters: C:EJB3Chapter02, C:EJB3Chapter03, and so on. You should consult the readme file before running any scripts. Summary We gave an overview of the EJB 3 architecture and its relationship to the multi-layer Java EE architecture. EJB technology applies to the business processing and persistence layers of the multi-layer model. There are three main artifacts a business application using EJB technology will develop: session-beans, message-driven beans, and entities. These artifacts are deployed to an EJB container which provides a number of services. We had a brief look at some of these services. In particular we saw that a separate service, the Java Persistence API, is provided for persisting entities. Finally we saw how to get started with Sun's open-source GlassFish EJB 3 container. All the examples which follow in this book have been deployed and run on GlassFish. In the following chapter we will look at developing the EJB component which handles business processing, namely session beans.
  • 33. Session Beans Session Beans are an EJB technology for encapsulating business processes or workflow. In this chapter we will cover the following topics: Stateless session beans Stateful session beans Annotations Packaging and Deploying a session bean Running a session bean client from the application client container Stateless and Stateful session bean lifecycles Introduction In object-oriented analysis and design a control class encapsulates business logic for a use case. Session beans are used to implement such control classes. Check credit card details, transfer funds, and book reservation are examples of potential session bean candidates. Session beans are transient and relatively short lived. In particular, session beans are not persistent; they are not stored in a database or other permanent file system. Session beans can create and update entities, which are persistent, as we shall see in the following chapters. A client interacts with a session bean by invoking one or more methods defined in the bean. This sequence of method calls we call a session, hence the name session beans. The client can be a web-tier client such as a servlet or JSP page, or a standalone Java application program. Like EJB 2.x, EJB 3 session beans are a component technology. In EJB 3 a session bean component consists of a bean interface and a bean class. The bean interface provides all the bean method definitions, the bean class provides the method implementations. We no longer have to produce a home interface as was required in EJB 2.x. • • • • • •
  • 34. Session Beans [ 22 ] It is important to stress that the client does not interact directly with a bean. Instead the client interacts with a proxy generated by the EJB container. This proxy intercepts method calls and provides the container services such as transaction management and security. Session beans come in two flavors: stateless and stateful. We will start with an example of a stateless session bean. Stateless Session Beans A stateless session bean's state spans a single method call. We cannot have method A updating an instance variable x say, and expect the updated value of x to be available for any subsequent method invocation. This holds true both for a new method B which accesses x, or indeed, if method A is invoked a second or subsequent time. We have no guarantee that the same stateless session bean instance will be invoked between method calls. For this reason, stateless session beans should not use instance variables to maintain conversational state. As a simple example we will develop a stateless session bean which simply returns the current time to the client. This is almost as minimal as the traditional HelloWorld example but is more useful. Recall a session bean component consists of a bean interface and a bean class. We name our interface TimeService.java, which contains a single method definition getTime(): package ejb30.session; import javax.ejb.Remote; @Remote public interface TimeService { public String getTime(); } Note that we have prefixed the interface definition with the @Remote annotation. This indicates to the EJB container that this bean may be invoked by a remote client. By remote, we mean a client that does not reside in the same Java Virtual Machine (JVM) as the container. An interface can also be local as we shall see later in this chapter. The @Remote annotation belongs to the javax.ejb package, as we can see from the import statement. Annotations belong to a number of packages. We list annotations and their corresponding packages in Appendix A.
  • 35. Chapter 2 [ 23 ] Note that we have decided to place our code in the ejb30.session package. The interface is implemented by the EJB container, and not the application, when the bean is deployed to the container. Next we code the bean class itself, TimeServiceBean.java: package ejb30.session; import java.util.*; import javax.ejb.Stateless; @Stateless public class TimeServiceBean implements TimeService { public String getTime() { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt.format(%tr, cal); return fmt.toString(); } } This class contains the implementation of the getTime() business method. This looks like any Java class, all we have added is the @Stateless annotation. This indicates to the EJB container that the session bean is stateless. Annotations The option of annotations is one of the most important features which distinguishes EJB 3 from earlier versions. Metadata annotations were introduced in Java SE 5. For this reason Java SE 5 or higher must be used in conjunction with EJB 3. In EJB 2.x, instead of annotations we use XML deployment descriptors. As the name suggests, deployment descriptors are read by the application server when the EJB is deployed. We will discuss the deployment process later in this chapter. The deployment descriptor, ejb-jar.xml, for the above session bean is shown below: ?xml version=1.0 encoding=UTF-8? ejb-jar xmlns=http://java.sun.com/xml/ns/javaee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance metadata-complete=true version=3.0 xsi:schemaLocation=http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ ejb-jar_3_0.xsd enterprise-beans session display-nameTimeServiceBean/display-name ejb-nameTimeServiceBean/ejb-name
  • 36. Session Beans [ 24 ] business-remoteejb30.session.TimeService/business-remote ejb-classejb30.session.TimeServiceBean/ejb-class session-typeStateless/session-type transaction-typeContainer/transaction-type security-identity use-caller-identity/ /security-identity /session /enterprise-beans /ejb-jar Note the lines: business-remoteejb30.session.TimeService/business-remote and session-typeStateless/session-type indicate that we have a remote stateless session bean. All other lines correspond to default values for an annotated session bean. Annotations are far simpler to use than deployment descriptors. Deployment descriptors tend to be verbose, not very readable by humans and error prone when manually edited. Any non-trivial deployment descriptor file really needs a tool both for writing and reading. However annotations have been criticized on the grounds that deployment aspects are tangential to the definition of a bean and should not intrude in the bean's code. The use of annotations means recompiling a bean when we only want to change a deployment aspect; modifying a deployment descriptor does not warrant recompilation. However annotations are optional in EJB 3. We can still use XML deployment descriptors if we wish. Furthermore we can mix both annotations and deployment descriptors in EJB 3. In such cases deployment descriptors always override annotations. One approach might be to use annotations for those aspects of an EJB which rarely change between deployments. For example, the relationship of an entity which we will discuss in Chapter 4, is likely to be invariant. The same can be said for transaction attributes of a session bean, which we will discuss in Chapter 7. On the other hand database table names onto which entities are mapped (covered in Chapter 3) or security aspects (covered in Chapter 12), for example, are more likely to change between deployments. Consequently deployment descriptors are more appropriate here.
  • 37. Chapter 2 [ 25 ] On large projects the teams or individuals responsible for deployment may not be the same as those responsible for development. It is unrealistic to expect the former to add or modify any annotations within code developed by others. In these circumstances deployment descriptors would be used. However, because this is an introductory book and we want to keep its length reasonably short we will only make use of annotations in nearly all our examples. Creating a Session Bean Client Next we will create a client which is a standalone Java application. The client simply references a session bean, invokes the bean's getTime() method, then prints out the result: package ejb30.client; import javax.naming.*; import ejb30.session.*; public class Client { public static void main(String args[]) throws Exception { InitialContext ctx = new InitialContext(); TimeService timeService = (TimeService) ctx.lookup(ejb30.session.TimeService); String time = timeService.getTime(); System.out.println(Time is: + time); } } Note that because the client is remote we need to use JNDI (Java Naming and Directory Interface) to lookup the session bean. All EJB containers implement JNDI. JNDI is a set of interfaces which has many implementations: RMI, LDAP, and CORBA amongst others. There are two steps for performing a JNDI lookup. The first step is to create a JNDI connection by creating a javax.naming.InitialContext object. One way to do this is to create a java.util.Properties object, set JNDI properties specific to the EJB container, then pass the properties object as an argument to InitialContext. This will take the form: Properties env = new Properties(); // Use env.put to set container specific JNDI properties InitialContext ctx = new InitialContext(env); An alternative method is to define the properties in a jndi.properties file and use the no-arg InitialContext constructor: InitialContext ctx = new InitialContext();
  • 38. Session Beans [ 26 ] The JNDI properties are then accessed at runtime. The GlassFish container provides a default jndi.properties file which is contained in appserv-rt.jar. This JAR file must be in the client's classpath, as we shall shortly see when we examine the Ant build file. The second step is to use the InitialContext object to lookup the remote EJB. In our example this is done by the statement: TimeService timeService = (TimeService) ctx.lookup(ejb30.session.TimeService); Note the argument passed is the global JNDI name. This is generated by the container at deploy time. The form of the global JNDI name is also container-specific. In the case of GlassFish this is the fully qualified remote session bean interface name. In our example this is ejb30.session.TimeService. The lookup result is directly cast to the session bean interface type, namely TimeService. We can now invoke the session bean business method: String time = timeService.getTime(); The use of JNDI is one of the more awkward aspects of EJB technology. Fortunately in EJB 3 the only occasion its use is mandatory is when a client invokes EJB from outside the container. If we invoke an EJB from within a container, then we can use dependency injection annotation metadata instead of JNDI lookups. We will return to this shortly. Running the Example First we need to compile the source code. The Ant script is run from the command line, as follows: cd C:EJB3Chapter02glassfishlab1 C:EJB3Chapter02glassfishlab1ant compile This will compile the interface, TimeService.java, the session bean, TimeServiceBean.java, and the client, Client.java. The next step is to package the session bean into an EJB module. An EJB module consists of one or more EJBs contained in a JAR file. In our example we have just one EJB, TimeService, and we name the JAR file, TimeService.jar: C:EJB3Chapter02glassfishlab1ant package-ejb
  • 39. Chapter 2 [ 27 ] We can use the jar –tvf command to examine the contents of the JAR file: C:EJB3Chapter02glassfishlab1buildjar –tvf TimeService.jar ...META-INF/ ...META-INF/MANIFEST.MF ...ejb30/ ...ejb30/session/ ...ejb30/session/TimeService.class .. ejb30/session/TimeServiceBean.class Note the JAR file contains the standard META-INF directory and the default manifest file, MANIFEST.MF. The next step is to deploy the program. We can do this within the GlassFish administrator console, which has an option for deploying an EJB module. Alternatively we can use an Ant script as follows: C:EJB3Chapter02glassfishlab1ant deploy Deployment is essentially the process by which applications are transferred to the control of the application server. The developer copies the EJB module to designated sub-directories within the application server directory structure. However, behind the scenes a lot more takes place during deployment. Typically some sort of verification takes places to check that the contents of the EJB module are well formed and comply with the Java EE specification. If annotations are used, the application server may generate corresponding XML deployment descriptor files. Additional vendor-specific XML files and classes and interfaces are typically generated. Entities will be mapped to a database and optionally corresponding database tables may be created during deployment. We will discuss entities and databases in Chapter 3. During deployment security roles are mapped to user groups. We will discuss security in Chapter 12. Note that some application servers do not have the option of deploying EJB modules. Such modules need to be placed in an EAR (Enterprise Application Archive) file before deployment. We shall see an example of an EAR file shortly. Finally we can run the example with the run-client Ant command: C:EJB3Chapter02glassfishlab1ant run-client Buildfile: build.xml compile: run-client: [java] Time is: 03:21:17 PM BUILD SUCCESSFUL
  • 40. Session Beans [ 28 ] The Program Directory Structure Before we describe the Ant build scripts in more detail we will look at the directory structure in which the source code is placed. lab1: This is the root directory and contains the following files and subdirectories: build.xml: This is the Ant build script itself. We will describe it in more detail shortly. env.properties: This file contains runtime environment property settings and is read by the Ant build script. Currently the file contains just one value, glassfish.home, which is the root directory in which GlassFish is installed. When writing this book GlassFish was installed on Windows in the C:/glassfish directory, so the contents of env.properties is: glassfish.home=C:/glassfish adminpassword: This file contains the GlassFish administrator password required for the deployment task. This is identified by AS_ADMIN_PASSWORD. The initial password, which can be reset of course, is adminadmin. So the contents of adminpassword are: AS_ADMIN_PASSWORD=adminadmin src: This subdirectory contains the source code. Recall the client program, Client.java, is placed in the ejb30.client package. The package name is reflected in the subdirectory structure. Subdirectories have also been created to correspond to the ejb30.session package in which TimeService and TimeServiceBean have been placed. • • • •
  • 41. Chapter 2 [ 29 ] build: This subdirectory contains files created during the build process. For example, class files created during compilation and JAR files created during packaging will be placed here. The Ant Build Script We use an Ant build file for automating the compilation of client and session bean source code as well as packaging and deploying the session bean. We also use the build file for running the client. All these steps are defined as Ant targets. The Ant build file is listed below: project name=ejb30notebook basedir=. property name=build.dir value=${basedir}/build / property name=src.dir value=${basedir}/src / property file=env.properties / path id=j2ee.classpath pathelement location=${build.dir}/ fileset dir=${glassfish.home}/lib include name=javaee.jar/ include name=appserv-rt.jar/ /fileset /path target name=clean delete dir=${build.dir}/ mkdir dir=${build.dir} / mkdir dir=${build.dir}/lib / /target target name=all antcall target=clean/ antcall target=compile/ antcall target=package-ejb/ antcall target=deploy/ antcall target=run-client/ /target •
  • 42. Session Beans [ 30 ] target name=compile javac destdir=${build.dir} srcdir=${src.dir} classpathref=j2ee.classpath/ /target target name=package-ejb depends=compile jar jarfile=${build.dir}/TimeService.jar fileset dir=${build.dir} include name=ejb30/session/** / /fileset /jar /target target name=deploy exec executable=${glassfish.home}/bin/asadmin failonerror=true vmlauncher=false arg line=deploy --user admin --passwordfile adminpassword ${build.dir}/TimeService.jar/ /exec /target target name=undeploy exec executable=${glassfish.home}/bin/asadmin failonerror=true vmlauncher=false arg line=undeploy --user admin --passwordfile adminpassword TimeService/ /exec /target target name=run-client depends=compile java classname=ejb30.client.Client fork=yes classpathref=j2ee.classpath/ /target /project Within the path tag we have the classpath, identified by j2ee.classpath. This contains the javaee.jar file (containing libraries such as javax.ejb) required for compilation and appserv-rt.jar required for runtime execution of a client.
  • 43. Chapter 2 [ 31 ] The clean target deletes and recreates the build directory. This is used to ensure that all generated files such as class and JAR files are recreated from scratch. The all target performs all the tasks required to deploy and run the example. The deploy target uses the GlassFish asadmin tool to deploy the TimeService.jar file. The line: arg line=deploy --user admin --passwordfile adminpassword ${build.dir}/TimeService.jar/ specifies that deployment is performed by the admin user. The admin password is held in a file named adminpassword. There is also an undeploy target, which removes TimeService.jar from the application server. The Application Client Container Although accessing an EJB from a client using JNDI is simpler than in EJB 2.x, it is still rather awkward. The good news is that we can dispense with JNDI altogether if the client runs from within an application client container (ACC). The EJB 3 specification does not mandate that an EJB-compliant application server provides an ACC but makes its inclusion optional. Consequently not all EJB-compliant application servers provide an ACC, however GlassFish does. An ACC enables a client executing in its own JVM outside the EJB container to access a number of Java EE services such as JMS resources, security, and metadata annotations. If the previous client example is run from an ACC then we can use dependency injection annotation metadata instead of JNDI lookups. Here is the new version of Client: package ejb30.client; import javax.naming.*; import ejb30.session.*; import javax.ejb.EJB; public class Client { @EJB private static TimeService timeService; // injected field must be static public static void main(String args[]) throws Exception { String time = timeService.getTime(); System.out.println(Time is: + time); } }
  • 44. Session Beans [ 32 ] We use the @EJB annotation to instruct the container to lookup the TimeService bean and inject a bean reference into the timeService field. This is an example of field injection. Another kind of dependency injection is setter injection; we shall see an example of this later in this chapter. We can then invoke any of the TimeService methods such as timeService.getTime(). Because the Client class runs in a static context, as a main method, the injected field must also be static. Building the Application We need to modify the build process if we are using an ACC. The build steps are application sever-specific so what follows in this section applies only to GlassFish. First we create a manifest.mf file with the contents: Main-Class: ejb30.client.Client We need to do this because the client will be bundled in a JAR file, as we shall see shortly, and we need to indicate which class in the JAR file is the application's entry point. The compilation and EJB packaging tasks require no change. However in order to use the ACC we must package the client in a JAR file. The following Ant script creates a Client.jar file. target name=package-client depends=compile jar jarfile=${build.dir}/Client.jar manifest=${config.dir}/manifest.mf fileset dir=${build.dir} include name=ejb30/client/Client.class / /fileset /jar /target Note that we have included the customized manifest file. The next step is to create an Enterprise Application Archive (EAR) file. An EAR file is a standard JAR file, with an ear extension, that contains other JAR files embedded within it. The JAR files can be EJB modules or any Java classes, such as an application client deployed in a JAR file. An EAR file can also contain a web module, identified by a war extension. We shall see an example of this later in the book. In our example the EAR file, which we name TimeService.ear, will contain the EJB module TimeService.jar and the client JAR file, Client.jar. The Ant script to create an EAR file is: target name=package-ear depends=package-ejb jar destfile=${build.dir}/TimeService.ear basedir=${build.dir} includes=TimeService.jar Client.jar/ /target
  • 45. Chapter 2 [ 33 ] Again we can use the jar –tvf command to examine the contents of the EAR file: C:EJB3Chapter02glassfishlab2buildjar –tvf TimeService.ear ...META-INF/ ...META-INF/MANIFEST.MF ...Client.jar .. TimeService.jar We deploy the EAR file rather than the EJB module. The Ant script shows this: target name=deploy exec executable=${glassfish.home}/bin/asadmin failonerror=true vmlauncher=false arg line=deploy --user admin –passwordfile adminpassword ${build.dir}/TimeService.ear/ /exec /target Alternatively we can deploy an EAR file from the GlassFish administrator console. There is an option for deploying an enterprise application contained in an EAR file. Finally we need to modify the Ant run-client script: target name=run-client exec executable=${glassfish.home}/bin/appclient failonerror=true vmlauncher=false arg line=-client ${glassfish.home}/domains/domain1/generated/xml/ j2ee-apps/TimeService/TimeServiceClient.jar -mainclass ejb30.client.Client/ Note that we start up the GlassFish ACC by executing the appclient program. At deployment GlassFish creates a directory under the domains/domain1/generated/ xml/j2ee-apps directory. The name of this generated directory is the same as the EAR file without the extension, TimeService in our case. In this directory GlassFish creates a JAR file with the same name as the directory but with Client appended, TimeServiceClient.jar in our case. The contents of this JAR file are those of the deployed EAR file together with some GlassFish generated deployment XML files. When we execute appclient we need to supply the full pathname of TimeServiceClient.jar as well as the fully qualified main application client class. From this point on, throughout the book we assume that clients will always run in an ACC.
  • 46. Session Beans [ 34 ] Stateless Session Bean's LifeCycle It is import to stress that a session bean's lifecycle is controlled by the container and not the application. The following state diagram shows the stateless session bean's lifecycle: @PreDestroy (if any) business method new instance dependency injection (if any) @PostConstruct (if any) Does Not Exist Method Ready Pool The initial state of a stateless session bean is the does-not-exist state. This would be the case before a container starts up, for example. The next state is the method-ready pool. When the container starts up, it typically creates a number of stateless session bean instances in the method-ready pool. However the container can decide at any time to create such instances. In order to create an instance in the method-ready pool, the container performs the following steps: 1. The bean is instantiated. 2. The container injects the bean's SessionContext, if applicable. In our example we have not made use of the SessionContext. The SesionContext is used by a bean to query the container about the bean's status or context. 3. The container performs any other dependency injection that is specified in the bean's metadata. Again in our example we have not specified any such metadata. 4. The container then invokes a PostConstruct callback method if one is present in the bean. Again we have not invoked such a method in our bean example. The PostConstruct method would be used for initializing any resources used by the bean. For example, the session bean may make use of a JMS queue for sending messages. The connection queue used by JMS could be initialized in the PostConstruct method. A PostConstruct method is called only once in the life of an instance, when it has transitioned from the does-not-exist state to the method-ready pool.
  • 47. Chapter 2 [ 35 ] The container then calls a business method on the bean. Each business method call could originate from a different client. Conversely when a client invokes a business method on a stateless session bean any instance in the method-ready pool can be chosen by the container to execute the method. After a business method has been invoked, the container may decide to destroy the bean instance (typically if the container decides there are too many instances in the method-ready pool) or reuse the instance on behalf of any client that invokes its business methods. When the container does decide to destroy the instance it first invokes the PreDestroy callback method if one is present in the bean. In our example we have not invoked such a method. The PreDestroy method would be used for tidying up activities, such as closing connections that may have been opened in the PostConstruct method. A PreDestroy method is called only once in the life of an instance, when it is about to transition to the does-not-exist state. These features of instance pooling and instance sharing mean that stateless session beans scale well to large number of clients. The listing below shows a modified implementation of TimeServiceBean with a SessionContext and callback methods added. At this stage the methods merely print out messages. Later in this book we shall see more meaningful examples. @Stateless public class TimeServiceBean implements TimeService { @Resource private SessionContext ctx; @PostConstruct public void init() { System.out.println( Post Constructor Method init() Invoked); } public String getTime() { System.out.println(ctx.getInvokedBusinessInterface()); Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt.format(%tr, cal); return fmt.toString(); } @PreDestroy public void tidyUp() { System.out.println( Pre Destruction Method tidyUp() Invoked); } }
  • 48. Session Beans [ 36 ] Note that there can be at most only one PostConstruct and one PreDestroy method. The methods can take any name but must be void with no arguments. In the case of GlassFish, the messages printed out by these methods will appear in the container's log file, which can be viewed from the GlassFish administrator console. Note the statement: @Resource private SessionContext ctx; This uses the @Resource annotation to inject a reference to the javax.ejb. SessionContext object into the ctx field. Any kind of dependency injection, apart from two exceptions, is signaled with the @Resource annotation. The two exceptions are @EJB, which is used for injecting EJB references and @PersistenceContext, which is used for injecting EntityManager instances. We will cover the @PersistenceContext annotation in Chapter 3. In the getTime() method we have added the statement: System.out.println(ctx.getInvokedBusinessInterface()); This uses one of SessionContext methods, namely getInvokedBusinessInterface(). This method returns the session bean interface through which the current method is invoked. In our example the result is ejb30.session.TimeService. This is a rather artificial use of getInvokedBusinessInterface() since our session bean implements just one interface, namely TimeService. However a session bean could implement two interfaces: a remote interface and a local interface. We will discuss local interfaces later in this chapter. One client could invoke TimeServiceBean through the remote interface and another through the local interface, getInvokedBusinessInterface(), which would inform us whether the current client is remote or local. There are a more methods in the SessionContext interface regarding the session beans current transaction and security contexts. We shall return to this in the chapters on Transactions and Security. Stateful Session Beans In contrast to stateless session beans, stateful session beans maintain state for an individual client over one or more method requests. A stateful session bean is not shared among clients, and a client's reference to a bean only ends when the client ends the session or the session times out. The state is not written to a database but held in the containers cache and is lost when the container crashes.
  • 49. Chapter 2 [ 37 ] The classic example of a stateful session bean is the online shopping cart. The user adds one or more items to a shopping cart, possibly over a long time period while the user visits other web sites or is interrupted by a phone call. Finally the user may decide to purchase the items in the cart, cancel his or her shopping cart session, or even abandon the session without explicitly terminating it. The following example illustrates some aspects of a shopping cart. Our shopping cart will be limited to adding items to a cart and listing the current contents of a cart. First we define a remote interface as follows: @Remote public interface ShoppingCart { public void initialize(); public void addItem(String item); public CollectionString getItems(); public void finished(); } The initialize() method performs initialization; we shall see what this means shortly. The addItem() method adds an item to the cart. The getItems() method returns the current contents of the cart. The finished() method is invoked when the client has finished their session and typically removes the session bean, so allowing the container to reclaim resources. Next we look at the bean implementation: @Stateful public class ShoppingCartBean implements ShoppingCart { private ArrayListString items; @PostConstruct public void initialize() { items = new ArrayListString(); } public void addItem(String item) { items.add(item); } public CollectionString getItems() { return items; } @Remove public void finished() { System.out.println( Remove method finished() Invoked); } }
  • 50. Session Beans [ 38 ] First note that we have used the @Stateful annotation to indicate this is a stateful session bean. We have used a @PostConstruct method, initialize(), to create an ArrayList named items. Stateful session beans may contain instance variables, such as items, which are modified by the bean. The reason, of course, is that the state of such variables is preserved from one method invocation to another. As with stateless beans we can also have a @PreDestroy method, although we have not created one in this example. The addItem() and getItems() methods are straightforward and need no further comment. We use the @Remove annotation to indicate that after the annotated method has executed, the client no longer needs the session. The container can then delete the bean instance. If a @PreDestroy method exists, it will be executed after the @Remove method. Typically the method would perform tidying up such as closing connections. In our example the finished() method merely prints a message. It is not compulsory to have a @Remove annotated method, but it is a good practice. Without such a method the bean instance will continue to occupy the container's cache until a timeout period is reached. At this point the bean instance is deleted by the container. The timeout period is configured by the container's administrator. By having a @Remove annotated method we are freeing up container resources as soon as we have made use of them. The listing below shows a possible client: public class Client { @EJB private static ShoppingCart shoppingCart; public static void main(String args[]) throws Exception { shoppingCart.addItem(Bread); shoppingCart.addItem(Milk); shoppingCart.addItem(Tea); System.out.println(Contents of your cart are:); CollectionString items = shoppingCart.getItems(); for (String item : items) { System.out.println(item); } shoppingCart.finished(); } }
  • 51. Chapter 2 [ 39 ] Stateful Session Bean's LifeCycle The following state diagram shows the stateful session bean's lifecycle: timeout @PostActivate (if any) @PrePassivate (if any) @PreDestroy (if any) business method new instance dependency injection (if any) @PostConstruct (if any) Does Not Exist Passive Method Ready @Remove The lifecycle of a stateful session bean differs from that of a stateless session bean in a number of respects. There is no pool of identical bean instances, as each instance serves a single client. A stateful session bean transitions from a does-not-exist to a method-ready state as soon as a client performs a business interface lookup or a dependency injection of a bean. So this step is client, and not container initiated. Once a stateful session bean is in a method-ready state, the container performs the same steps as with a method-ready stateless session bean: 1. The bean is instantiated. 2. The container injects the bean's SessionContext, if applicable. 3. The container performs any other dependency injection that is specified in the bean's metadata. 4. The container then invokes a PostConstruct callback method if one is present in the bean. The container then calls a business method on the bean. Recall that a session can involve considerable idle time if a client decides to wait, or perform other activities, between method calls. The container's cache could become full of idle stateful session bean instances. To limit such instances, the container can swap these from the cache out to disk or other storage. This process is called passivation and involves serialization of the bean instance. When the client decides to invoke a method on a passivated bean, then the container deserializes the saved state and invokes the requested method. This process is known as activation. Note that the method may not be on the original bean instance, but this is safe as at activation we restore the state which was saved at passivation.
  • 52. Session Beans [ 40 ] The passivation algorithm is container-dependent, and typically is dependent on factors such as the maximum number of beans which may be held in the containers cache, the maximum bean idle time, and the victim selection policy of the container. The GlassFish victim selection policy has the following options: Least Recently Used (LRU), Not Recently Used (NRU), and First In First Out (FIFO). All of these factors can be configured by the container administrator. The bean can provide a @PrePassivate callback method, which is executed immediately before passivation and a @PostActivate callback method, which is executed immediately after activation. A session bean's state may contain open resources such as open sockets, database or JMS connections that cannot be handled by the container during passivation. In these cases the resource will be closed in the @PrePassivate method and reopened in the @PostActivate method. A bean can move from a method-ready state to a does-not-exist state if a @Remove annotated method is invoked. A bean can also do this if a container configured timeout period has been reached. In either case a @PreDestroy annotated method is first invoked. A passivated bean can also move to a does-not-exist state if a timeout period has been reached. Note in this case any @PreDestroy annotated method will not be invoked. The listing below shows a modified implementation of ShoppingCartBean with the @PrePassivate and @PostActivate callback methods added. The methods simply print out corresponding messages. @Stateful public class ShoppingCartBean implements ShoppingCart { private ArrayListString items; @PostConstruct public void initialize() { items = new ArrayListString(); } public void addItem(String item) { items.add(item); } public CollectionString getItems() { return items; } @PrePassivate public void logPassivation() { System.out.println( PrePassivate method logPassivation() Invoked);
  • 53. Chapter 2 [ 41 ] } @PostActivate public void logActivation() { System.out.println( PostActivate method logActivation() Invoked); } @Remove public void finished() { System.out.println( Remove method finished() Invoked); } } Note that there can be at most only one PrePassivate and one PostActivate method. The methods can take any name but must be void with no arguments. Note that to simulate bean idle time, and hence conditions for passivation and activation, we have added a delay of 59 seconds between method calls from the Client: public class Client { public static void main(String args[]) throws Exception { ... shoppingCart.addItem(Bread); shoppingCart.addItem(Milk); Thread.sleep(59000); shoppingCart.addItem(Tea); } } To test activation and passivation with GlassFish you will also need to log in as a container administrator and set the Max Cache Size to say 2. The Cache Resize quantity, which is the number of beans to passivate when the cache is full, is set to 2 and the Cache Idle Timeout to say 15 seconds. Then execute 3 simultaneous client sessions. This process may be different for other EJB containers. Local Interfaces Up to this point all our examples have used the session bean remote interface, as the clients have run in their own JVM outside the EJB container. Behind the scenes, a remote interface uses the RMI-IIOP protocol for network operations. This protocol stipulates that method arguments are passed by value and not by reference. Passing by value means that an object being passed from the client to the remote bean, or vice versa, is first serialized then passed over the network then deserialized. This all
  • 54. Session Beans [ 42 ] has an impact in terms of performance. Even if our client is a session bean invoking another in the same container there is a performance overhead if we use a remote interface because of the serialization and deserialization taking place. For this reason EJB technology provides a local interface option for session beans. Method arguments are passed by reference and not by value so improving performance. To illustrate all this we shall create a stateless session bean which will be invoked by and run in the same EJB container, as our original TimeServiceBean. This invoked bean will just return the string Have a Nice Day. First we define the beans interface, NiceDayService: package ejb30.session; import javax.ejb.Local; @Local public interface NiceDayService { public String getMessage(); } Note that we have prefixed the interface definition with the @Local annotation. This indicates to the EJB container that this bean may only be invoked by a local client running in the same container. The interface consists of just one method definition, getMessage(). Next we look at the bean implementation, NiceDayServiceBean: package ejb30.session; import java.util.*; import javax.ejb.Stateless; @Stateless public class NiceDayServiceBean implements NiceDayService { public String getMessage() { return - Have a Nice Day; } } This is all straightforward. We note that the session bean is stateless and the getMessage() method returns the string - Have a Nice Day. Now let's look as to how we might modify the TimeServiceBean to invoke NiceDayService. The TimeServiceBean will append the NiceDayService message to the current time. Here is the modified code for TimeServiceBean: package ejb30.session; import java.util.*; import javax.ejb.Stateless; import javax.ejb.EJB; @Stateless
  • 55. Another Random Scribd Document with Unrelated Content
  • 56. by General Négrier being wounded. The force then made a disorderly retreat before imaginary pursuers. In the meantime the empress-dowager had given positive orders that peace should be made on any terms. Both parties had thus come round to the status quo ante bellum—that is to say, they were both equally urgent to obtain peace, as they had been in May 1884. The agent in bringing this about was Sir Robert Hart; and it was effected, as great things usually are, by the adroit use of very simple means. During the blockade of Formosa a small Chinese lighthouse tender was captured by the French admiral and detained. As she was essentially non- combatant, and was serving the interests of humanity in supplying the numerous lighthouses on the coast of China for the benefit of the commerce of all nations, Sir Robert Hart instructed his very capable London agent, Mr Duncan Campbell, to go to Paris and represent the case to the French Ministers, with a view to obtaining the release of so useful and harmless a vessel. In this manner the door was opened to the larger negotiation. Mr Campbell executed his delicate mission with so much tact, that in the amicable conversations which ensued between him and certain French officials the idea of putting an end to a war of which both parties were tired, and which, moreover, seemed objectless, was ventilated; and in a few days authority was telegraphed from Peking to Mr Campbell to sign a protocol. This was done before the news of the French reverse at Langson reached Paris. After such a military success M. Jules Ferry could not imagine that the Chinese Government would adhere to the terms of the protocol, and therefore he kept the whole negotiation secret from the Chambers. In the meanwhile the mishap to the French troops, being greatly exaggerated, excited such intense feeling in France that M. Ferry, le Tonkinois, was obliged to resign, with the treaty which might have saved him in his pocket. As for the empress-dowager, she recked nothing of the success of her brave troops on the outskirts of the empire, but thought only of the enormous expense of the war, which had been unpleasantly brought home to her, and of matters affecting her own convenience. She
  • 57. therefore had no thought of going back on the treaty, but was even more urgent than before to have it promptly signed and ratified. The honours of the peace thus fell in a few days to M. Ferry's successor. And what was the outcome of a year's fighting which cost China 100,000,000 taels and France some proportionate amount? A simple reaffirmation of the Li-Fournier convention of May 1884! The convention itself was short and simple—one clause only exciting much interest during the negotiations, and that provoked a hot discussion, not on the substance, but on the verbal form. It was a stipulation by which the two contracting parties consciously meant different things, and each fought hard for a phrase sufficiently subtle to allow each to interpret it in his own way when the time came for the fulfilment of the treaty provisions. The French were most desirous of binding the Chinese to employ French industries in all their new undertakings. China was equally resolute in avoiding any such obligation. In the end each was satisfied that he could read the treaty clause in his own favour. But the final victory in the struggle would go to the side that was most persistent in forcing its meaning into practice. The French Ministry had announced to the Chambers a great victory for French manufacturing industries, which were represented as having by it obtained a monopoly in China. The text of the treaty, even in the French version, did not, indeed, bear this out; but the French had the primâ facie argument on their side, that the introduction of a clause in a treaty referring to the Chinese patronage of French industries, however worded, must have meant something more than merely to register the common fact that China was at liberty to deal with whom she pleased. In the end a compromise was effected by China's giving to a French syndicate the contract for excavating the basin and dock at Port Arthur and certain orders for material, among which was a famous military balloon, wonderfully symbolic of the whole proceeding.
  • 59. CHAPTER XXVII. THE FRENCH PROTECTORATE OF CHRISTIANS. Alliance with Church the corner-stone of French conquest—Persistence of French ambitions in the Far East—Protectorate of native Christians—Its abuse by the propaganda—Forcible erection of cathedrals in Peking—Imperial family aggrieved thereby—Negotiations for removal of church from palace grounds—Mr Dunn's mission to Rome—Vatican to send a nuncio—French Government vetos— French minister vetos transfer of cathedral—Unless transaction placed in his hands. The claim of France to protect Christians against the native authorities in the Far East constitutes the basis and the origin of her present political position in those countries. The propagation of the faith was, indeed, a recognised element in the adventures of other countries besides France; but she has, since the eclipse of Portugal and Spain, enjoyed the distinction of a working alliance with the Church in furthering the foreign domination of both. Church and State, linked in alliance close and potential, played faithfully into each other's hands, says Parkman ('Jesuits in North America'). In the reign of Louis XIV. the kingdom of Siam was the object of their joint attention. A missionary bishop persuaded the most Christian king that to establish the Church in Siam and convert king and country to the Catholic faith would open an effectual door for the extension of French commerce. A century later another bishop persuaded another Louis to interfere in the affairs of Annam, and only the events of 1789 cut short an expedition that was being prepared of politico-ecclesiastical propagandism. Napoleon III. took up the cause, and actually effected the conquest of Cochin China;
  • 60. and Gambetta was so enthusiastic on the subject that, while persecuting the Catholics in France, he was ready to expend the forces of the Republic in protecting them in distant countries. There is here, therefore, irrespective of persons or forms of government, an unbroken tradition, which furnishes a key to the successive operations of France in the Far East. Thus when she resolved to join England in hostilities against China in 1857 a pretext was ready to hand in the murder of a Catholic priest in the interior of the country, his presence there being a defiance of the laws of the empire. There has been flux and reflux in French policy, but no change in its direction; and though prudence has from time to time set limits to its full expression, the claim to a special representation of Chinese Christians has been consistently pursued as a cardinal object of the French military, naval, and diplomatic forces in the Far East. The treaties of 1858 for the first time authorised travelling into the interior, and placed French subjects, whether missionary or not, who availed themselves of the permission, under the protection of their own country. But ever since the convention of Peking in 1860 it has been sought by indirect and unobtrusive means to assume the protectorate over native Christians as well. The interpolated clause in the Chinese, which was no part of the authentic French version of the convention, lent a certain colour to the pretension by seeming to recognise communities of Chinese Christians as legal units and fit subjects of international agreement between China and France. Nevertheless, French interference between the Chinese authorities and the subjects of the empire of China has never had any treaty warrant or justification by the law of nations, wrote Sir Rutherford Alcock in the 'Nineteenth Century,' November 1886; and he added, China has the remedy in her own hands, to a certain extent, by refusing to admit the pretension. The Chinese Government had long been alive to the danger, as its elaborate appeal to the reason of the Powers in 1871 amply testified, but its eyes were opened still wider by the lesson of the Tongking war. A disposition was thereafter
  • 61. evinced to withstand the claim of the French, and the action of Germany afforded sufficient support to the Chinese position, had the Government only had the courage and perspicacity to lean upon it. For in the Catholic propaganda were missionaries of German origin, who were not permitted to divest themselves of their nationality, but were made to apply for their passports into the interior not to the French, but the German, Legation in Peking. Had Italy and Spain been equally independent, the question of the French, or any other protectorate, could scarcely have been entertained without introducing the element of separate foreign nationalism into the constitution of the Christian communities in China, which would not, perhaps, have been agreeable to the views of the Catholic propagandists, for they naturally aspired to maintain their independence as a compact ecclesiastical organisation. The dread of the French protectorate was much accentuated by the enforced restitution of ancient buildings, the most conspicuous examples of which occurred in the city of Peking itself, and even within the area of the imperial palace. The sites of three ancient churches being claimed by the French Minister, the emperor's Government was compelled to violate its sense of justice by evicting the existing owners. The original building of one of the three was found practically intact, though hidden by the houses built round and against its walls. These of course had to be cleared away, regardless of the rights of their occupants. The interior fittings and decorations of the church had disappeared, but, strange to say, much of the wood carving and other ornaments were gradually recovered from the old-curiosity shops, where the parts not destroyed had, by the instinct of the Wardour Street craft, been preserved, begrimed with the dust of a hundred years and hopelessly unsaleable. By patiently collecting these disjointed fragments and piecing them together like a Chinese puzzle, the Fathers were able gradually to restore the church to something like its original state, so that it became itself an interesting relic of the golden age of the Jesuits in Peking.
  • 62. The other two churches had been demolished, and the sites converted to secular uses, requiring some ingenuity to identify. When these sites were, under the new dispensation, cleared of superincumbent buildings, churches were erected as much exceeding the original as the glory of the Jewish temple, rebuilt after the Captivity, excelled that of the former house. The restrictions imposed by the Government on the style of the buildings, the last vestige of power which they dared assert, bore lightly on the astute constructors of the new churches. In deference to a common Chinese objection, perhaps partly superstitious, to lofty structures overlooking them, a limit was set to the height of the new buildings. But remonstrances after completion were easily disposed of by the pious Fathers inviting the objectors to go and measure the towers! The Chinese seem to have the same constitutional dislike of a demonstration that they have to a straight line or a right angle, and a challenge like this never failed to put them to silence. As to their neglect to exercise their right of supervision during construction, the shortest way to characterise it is merely to say it was Chinese. The same kind of negligence also allowed roofs of cathedrals, not in the capital alone, but in distant provinces, to be covered with yellow tiles, a colour reserved exclusively for imperial use. It is true the process was disguised, for the benefit of those who chose to be blind, by the tiles being whitewashed before being sent aloft, leaving to the slow action of the weather the gradual revelation of the imperial colour, which might then, indeed, be represented as the act of Heaven. Nothing is too transparent to deceive those who are willing to be deceived.
  • 63. PEI-T'ANG CATHEDRAL IN PEKING, PURCHASED BY CHINESE GOVERNMENT. The cathedral around which the greatest interest centred, however, was the one which was erected within the palace grounds. The site had been granted by the great Emperor Kanghsi, the most imperial of the Manchu line, to the learned fathers who cured his fever by administering Jesuits' bark, then a new discovery, and whom he reckoned on attaching to his house by the favours bestowed on them. The new building was presumably erected on or near the site of the old, against the most urgent protests of the Court. Every inducement was offered to the French—larger and better sites, perhaps other compensations as well—if they would forego their demand for the resumption of the ground; but the French Government being set upon marking its ascendancy by a permanent sign, compelled the erection of the Pei-t'ang Cathedral on the spot indicated. The Lazarists, who had succeeded to the Jesuits in North
  • 64. China, had a kindly bishop at their head, who conceded much in the structure of the new building to soothe the feelings of the imperial family. Nevertheless, stunted as they were, from the point of view of architectural symmetry, the double towers of the cathedral were visible from the palace, and the two belfries commanded a view over a large part of the precincts. The building was therefore an eyesore to the inmates for twenty years, on the common ground on which it would have been offensive even to a provincial population, but still more as a staring monument of the deepest humiliation the dynasty had endured.[27] The empress-dowager bore the grievance, but not with resignation, for soon after the affairs of the empire assumed a settled aspect she urged her Ministers to find a way to get rid of the obnoxious building. Monseigneur Delaplace had, in his former diocese of Chêkiang, rendered good service to the Government in opposing the rebels, for which he was granted high Chinese rank. Being dissatisfied with the action of France after the Tientsin massacre of 1870, he extricated his mission from the control of the French Legation in Peking, and from that date till his death in 1882 conducted its affairs in direct communication with the Tsungli-Yamên. Fully recognising how hateful his cathedral was to the Chinese, he co-operated with Prince Kung and Wênsiang in their efforts to remove it, and in 1874 he actually concluded an agreement with them to that effect. But the contract was vetoed by the French Government. The sore was thus reopened and continued to fester until 1881, when there was so much excitement in the capital that the Church and mission were thought to be in great danger. During the Tongking troubles the question of the cathedral was allowed to rest, but no sooner was peace assured than the Court again became restless, and with renewed urgency sought a remedy for its grievance. The negotiations, which proved successful, were entered upon in an irregular manner, such as has characterised so many of the Chinese official acts. An Englishman in Peking, who had had business dealings with the Government, was asked one day by the
  • 65. confidential factotum of Prince Ch'un whether he could render assistance in the matter of the Pei-t'ang. The case was explained at length, and the foreigner, not being then aware of the negotiations of 1874, suggested, as the most obvious course, trying to make an arrangement with the Lazarist mission. The Manchu shook his head, to signify the futility of that proceeding. The enterprise thus seemed desperate, unless the Imperial Government should exercise its sovereign right of expropriation,—much too drastic a measure for any Chinese Government to attempt. One hope only seemed to remain, a direct appeal to the Vatican. This led to a long conversation on the Papacy, and the Manchu official,[28] being a pious and even a learned Buddhist, became intensely interested in hearing much that was new to him respecting the position and prerogatives of the European Dalai Lama. Nor did the great Western Saint, whose vicegerent the Pope claims to be, fail to evoke the deep reverence of both the Manchu and the Chinese who were present, so that one might be almost justified in appropriating words uttered on a different occasion,—they were not very far from the kingdom ruled by the Western Saint. But the interesting question was, How was the Vatican to be approached? By a qualified secret agent intrusted with the full confidence of the Chinese Court. The mission would be by no means easy, for should its object become known, it would be thwarted in advance from mere jealousy, if from no other motive, by Lazarist and perhaps other Catholic missions, so that access to the Supreme Pontiff would be blocked at the outset. The mission would also be certain to arouse the strenuous hostility of the French Government. After discussing the problem from all sides for three hours, the Manchu cut it short by the abrupt question, Will you go? No, said the foreigner; such an undertaking requires quite other qualities than any I possess. But, he added, after considering the matter, I think I know the man who might carry it through. Where is he? in Peking? Bring him here, were rapped out like musketry-fire, showing how urgent was the subject. The agent recommended to
  • 66. him was Mr J. G. Dunn, a man of genius and of varied accomplishments, a Catholic, and having an extensive personal acquaintance with the propaganda. He was at once invited to Peking, when another long conference ensued, and Mr Dunn was requested to draw up a memorandum on the whole scheme for the information of Prince Ch'un. After waiting some time for a response Mr Dunn left the capital, decidedly disappointed, for he was eager for a service so congenial to his character and feelings. Indeed had the mission been created for the man, or the man for the mission, the harmony between means and ends could hardly have been closer. Several months elapsed before the question emerged again from official obscurity, and the manner of it is worth relating if only for the side-light it throws on Chinese methods. Li Hung-chang paid a visit to the capital in 1885, and soon after his return to Tientsin he requested his secretaries to find out where Mr Dunn was and to invite him by telegraph to come to see the viceroy. Not knowing why he was sent for, any more than Gordon did when summoned from India five years before, Mr Dunn came, and Li at once entered on the Pei-t'ang question, showing him his own memorandum on the subject. The affair having been placed by Prince Ch'un in the hands of Li Hung-chang to be carried through, Mr Dunn was promptly commissioned, and in concert with the viceroy's secretary, the very capable officer who now represents China at Washington, the emissary's instructions and credentials were drawn up. There were two separate instructions, and no little confusion was caused thereby. On leaving China for Rome, Mr Dunn stipulated that a competent intermediary should be appointed to interpret his correspondence to Li Hung-chang, a duty which was intrusted to the commissioner of customs in Tientsin. The utility of this provision was soon made manifest, for when telegrams began to arrive from Rome, their purport was unintelligible, as they seemed irrelevant to the expropriation of the cathedral, which was Mr Dunn's special mission.
  • 67. Irritated by this apparent aberration, the viceroy's idea was to recall the emissary. But when it was suggested that the copies of his credentials should be first carefully examined the position became clearer. One part of his instructions was then found to be directed towards the question of the Christian protectorate, and Mr Dunn was, in fact, diplomatising with the Pope with a view to his appointing a nuncio or apostolic delegate to China to represent all the Catholic missions. The Chinese had not fully mastered this idea, and even Li Hung-chang, who has a wonderful memory, had forgotten the existence of the second section of his instructions, which no doubt Mr Dunn had drawn up himself. The Tsungli-Yamên, languid and bemused, hesitated to express any opinion, and assumed their habitual passive attitude. One person alone really grasped the importance of having the Church in China represented by the delegate of a Power which has no armies or fleets wherewith to threaten or attack. The empress-dowager, when the nomination of Mgr. Agliardi was announced, and his coming depended on formal imperial invitation, sent the urgent message to the Yamên, Get that man here; lose no time. Mr Dunn's negotiations with the Vatican of course soon leaked out; notices appeared in the press; Mr Punch had his little joke that though there was evidently a good deal doing, the question was, Who was Dunn? The French Government took the matter up energetically through their Minister in Rome, and their diplomatic efforts having failed, they presented an ultimatum to the Pope which compelled him to cancel the appointment of his nuncio. France threatening to terminate the concordat, withdraw the subvention to the Church in France, and sequestrate its ministers, the Holy Father had no option but to submit. With tears in his eyes he deplored his impotence to respond to the invitation of China under such a truculent menace to his children in France. While these things were going on in Rome the transference of the Pei-t'ang Cathedral, which had been settled in principle through Mr Dunn, was then taken up by the Lazarist Mission, and the popular
  • 68. Père Favier was deputed by the Bishop of Peking to proceed to Rome and to Paris to obtain from the Vatican and the General of the Lazarist Order the specific authority to negotiate the transfer. Having brought back the necessary powers, a convention was shortly concluded between Bishop Tagliabue and Li Hung-chang. The Church made an excellent bargain, as it generally does: a new site of about thrice the area was granted close to the old on the opposite side of the broad roadway, and a bountiful compensation in money was made for the trouble and cost of removal. But after the agreement was signed the French Government interposed its veto so far as to insist on being the intermediary through whose hands the transaction should pass. France also, it was said, had previously essayed to marchander with China for her consent, but withdrew when it became clear that further obstruction might entail untoward consequences. To mark its satisfaction at the final solution of this question, the Chinese Government eulogised all those who had helped to bring it about, and bestowed high rank on Bishop Tagliabue and the Abbé Favier (now bishop). This transaction supplied a crucial test of French policy and pretensions in China, the first concrete expression of both that had been obtained since the forcible restitution of Church property immediately after the capture of Peking. The coercion, indeed, was applied on this occasion to the Roman Pontiff and the Catholic Church rather than to the Chinese Government; but the latter were not so dull as not to see to what ulterior objects the French scheme might be extended, given convenient circumstances. They were, in fact, really alarmed, and the question was discussed with some warmth in the Chinese as well as in the European press. The end is not yet, wrote Sir Rutherford Alcock; China may be less open to intimidation than heretofore, and assert her undoubted right to refuse the recognition of an assumed protectorate over Roman missions, irrespective of the nationality of their members. The French press espoused the cause of the protectorate warmly, treating it as a most valuable national asset. The Chinese press took up the question in reply. Their view of the position was
  • 69. comprehensively summed up in a native newspaper in October 1886 in the following terms:— It has been said by them of old time that when a man is found acting injuriously to his own family but benevolently to strangers his behaviour is unnatural, and there is something hidden under the cloak of outward kindness. We have from time to time printed translations from various foreign newspapers on the subject of the relations between the Chinese Government and the Pope. Some days ago we reproduced an article on the same subject from the 'Temps,' a French newspaper of the highest authority. These articles all indicate that the French Government is greatly troubled at the prospect of losing what is called the right to protect Christians in China. This is a question which has not hitherto been much considered by Chinese statesmen. Those of them who have been in Europe, or who have studied political affairs there, know something of the importance of the issues which are covered up in that apparently harmless word protection; but it is hardly to be expected that the Ministers and statesmen who have scarcely travelled beyond the walls of Peking can realise the full significance of the phrase. Nothing is better calculated to quicken the apprehension of the Government on this point than the extraordinary excitement of the French Government, which insists on protecting the Christians in China whether they desire this protection or not. For now that the French have so plainly shown their secret designs, it would be impossible for China to acquiesce, by word or deed, in the pretensions which France sets up. It is rather suspicious that the French Government, the greatest enemy of Christianity, which is constantly oppressing the priests and confiscating their property in France, should be so intensely desirous of protecting Christians in China, where this protection is not required. A leading French statesman, Gambetta, who died a few years ago, left as a legacy to his followers the doctrine that the Church should be suppressed in France but supported in all foreign countries. Gambetta was a man who had no reverence for Heaven, and no religion, and seems to have regarded Christianity as a disease which he wished his own country to be rid of, but was not sorry to see it spreading elsewhere. It is necessary to keep these ideas in mind in order to understand the action of the French Government to-day. It would be out of place here to discuss what Christianity is. Like Buddhism, it had a very pure origin, and the living principles of both
  • 70. are mercy, benevolence, and peace. But both religions have in course of ages been overlaid with doctrines and practices which have obscured the simplicity of their origin, and even changed their character. But the greatest misfortune to Christianity is that it has been made use of by princes as a pretext for wars of aggression. In fact, nearly all the wars of Europe for the last thousand years have been in some way connected with religion. This is sometimes made a reproach against Christianity, which professes to be founded on peace and self-sacrifice, but the reproach is scarcely just. Rather it is the peaceful character of Christianity which has induced ambitious statesmen to make use of it to work out their own designs, just as in private life unscrupulous men are sometimes enabled to carry out questionable plans by using the names of men of blameless character. We are only now concerned with the political aspect of Christianity, not its merits as a religion. The modern history of Turkey affords the best illustration of the danger of allowing foreign Powers to interfere in matters of religion. During the last hundred years Russia has several times made war on Turkey, always on the pretext of protecting Christians, and it is this which is fast breaking up the Turkish empire. It is interesting to observe that Russia and France follow the same policy in this matter. When the French Legation withdrew from Peking on the 2nd day of the 7th moon of the 10th year of Kwanghsu (22nd August 1884), the affairs of the Christians were transferred to the Russian Legation. The Ministers of the Tsungli-Yamên remember very well how eagerly the Russian Minister assumed the office of protector of Christians, going to even greater lengths in the way of protection than the French themselves had done. The reason for this is plain. Russia, although she has none now, expects to have by-and-by many Christians in Mongolia and Manchuria who may be extremely useful to her in her aggressive designs on China. Therefore the Russian officials, always looking very far ahead, were most anxious to establish a right of interference for the protection of Christians. And they could do this without reproach when they were acting not for themselves but for France during war-time; well knowing that, whatever position she succeeded in establishing for France, Russia could claim for herself when the proper time came. But the more anxious Russia and France are to assert the right of interfering with Chinese Christians, the more resolute China should be in resisting all such interference. The only safety for China is to treat Christians, whether Chinese or foreign, exactly as all other people are treated—to make no distinctions. Foreign missionaries have the right to travel and reside in the interior; they can exercise this right without getting passports from the French Minister. The Catholic missions are
  • 71. composed of men of all nations, but they all have Ministers in Peking to whom they can apply for passports. Let the Germans get their passports from the German Legation, the Spaniards from the Spanish, Italians, Belgians, and Hollanders from their respective Legations, but no European State has any right to arrogate to itself the position of protector of missionaries in general. It is satisfactory to learn that the head of the Catholic Church is of this opinion, and although grateful to France for what she has done in the past, is now desirous of being free from French protection in the future. To carry out these views, the Pope is about to send to China a very high official to reside in Peking and perform the functions of a Minister. As the Pope has no troops and no territory, but is merely a kind of Dalai Lama, there is no danger to China from opening direct relations with him. The affairs of the missionaries can then be dealt with in an open and straightforward manner, as no fear of political traps will lurk behind. The Christians when they know they are no longer protected by a military State will understand that their security will depend on their own wisdom in avoiding offence. And the officials and people, on the other hand, will gradually learn that the Christians are only anxious to lead virtuous lives, without any political ambition, and they will respect them. The Imperial Government will then also be able to extend its favour to all Christians and missionaries without the fear of nursing traitors in its bosom. The missionaries have among them men of great learning and much skill in sciences, which the Emperor Kanghsi—who must always stand as the model for Chinese rulers—knew very well how to utilise. The present generation possesses men no less capable of rendering good services to China, and there would be no reason for not using them if the suspicion of their being agents of the French Government were once cleared away. Notwithstanding so much clear thinking, however, the action of the Chinese continued, as before, nebulous. They seemed never able to seize the bull by the horns, but drifted on, allowing themselves constantly to be put in the wrong, hoping perhaps to accomplish by illegitimate means what was within their legal competence. Afraid or unwilling to control the provincial authorities, they allowed outrages to be perpetrated for which they refused redress until coercion was applied, thus affording to foreign Powers a not in all cases unwelcome pretext for extending their protection even to Chinese Christians. Within a month of the consummation of the transfer of
  • 72. the Pei-t'ang Cathedral, and after the Marquis Tsêng, fresh from Europe, had taken his seat at the Board, the Tsungli-Yamên had fallen into its chronic apathy with regard to Christians. A missionary named Bodinier arrived in Peking from distant Kweichow for the purpose of soliciting the intervention or intercession of the French Legation in favour of the persecuted Christians in that province. While he was on his journey the Catholics of Chungking in Szechuan were being similarly maltreated. Certain disturbances in that great commercial mart culminated in the attack on the house of a wealthy Christian family, which resisted the assailants, several of whom were killed in the affray. The magistrates, who had been supine during the time when the mischief was brewing, thereupon arrested the head of the Lo family and condemned him to death,—an exercise of authority which was held to be arbitrary, and invidiously directed against Christians. Here was an occasion when the Central Government should have taken prompt action, and so deprived the French Government of any pretext for interference. It was a moment when that Government was less apt than usual to put forth its power in the Christian cause. M. Constans was Minister in China, and he was personally not at all disposed to assume the protection of Chinese Christians. Nevertheless, the case being urgent, and the Tsungli-Yamên either cowardly or indifferent, M. Constans broke through the rule he had laid down for himself so far as to telegraph to Paris for instructions. The reply was prompt, doubtless inspired by the propaganda at home, to the effect that he should take up the case of Mr Lo. Thus the Chinese threw away a golden opportunity of showing to the world that the Chinese Christians did not stand in need of any foreign aid. An impartial investigation might have shown, indeed, that the Christians were the aggressors, and the local Chinese officials might have been vindicated from the charges made against them. But the Government's inaction constantly puts it in the wrong even when it may be substantially in the right. The same fatal course has been regularly pursued even to our day, with results patent to all.
  • 73. CHAPTER XXVIII. BRITISH SERVICES: DIPLOMATIC, CONSULAR, AND JUDICIAL. Necessity for administrative and judicial control over British subjects—Consular courts—Supreme court for China and Japan—Personnel of the consular service— Functions of the diplomatic representatives—Absence of distinction explained by apathy of Home Government—Need of reform. The frequent references throughout this work to the part played by British agents in the development of intercourse with China seem to call for a short account of the character and status of the official machinery which served for so many years as the principal working joint between the two opposed systems of civilisation. The relations between Great Britain and China were necessarily at first experimental. The consuls appointed to the five ports were selected with no special training, and the chief superintendent, to whom they looked for guidance, was scarcely better furnished than themselves. Yet, as has been shown, the remoteness of the consuls from their chief, and of both from the Government they served, threw them much upon their own resources. How the demand for independent initiative was responded to by some of the individuals concerned has been incidentally noticed in previous chapters. From the time when it assumed direct relations with China, the need of an effective control over British subjects resorting to that country weighed heavily on the British Government; for in exempting them from native jurisdiction the Government took on itself the
  • 74. responsibility for the good behaviour of its people. The exercise of this control was necessarily tentative, proceeding step by step as occasions arose. The unceasing solicitude of the Government for the orderly conduct of its subjects in China is testified by a long series of Orders in Council conferring on the consuls and their superintendent an almost despotic authority over the persons of the British residents. The operation of this arbitrary system was more satisfactory than could have been expected, thanks to the high character of the parties concerned and the common-sense which governed their mutual relations. In their double capacity, however, of protectors of Chinese and foreigners against the inroads of British subjects, and of the latter against the inroads of the Chinese, the consuls soon discovered that the one part of their duty was easy and the other difficult; and it is no matter for wonder, therefore, if, following the line of least resistance, some of them should have leaned to the side of repression rather than to that of the encouragement of their countrymen. This was noticeable even in judicial proceedings, where the consul was supreme over his own nationals, but had no authority over their opponents. Some check on the consequences of consular idiosyncrasies and defective legal knowledge was maintained by a supreme court in Hongkong, independent alike of the superintendent of trade and of the governor of the colony, to which court appeals lay from consular decisions. This prerogative of the colonial court was not unnaturally irksome to the diplomatic and consular servants of the Foreign Office, and was doubtless one cause of the coolness, not to say antipathy, with which the colony has generally been regarded by them. The treaties of 1858 and 1860 were followed by a great development in all three services—diplomatic, consular, and judicial. Some years previously the China consular service began to be treated as a career for which special preparation was required, the entry being by competitive examination, through which a certain number of students were annually sent out to China, there to complete their education and then take their part in executive work. When additional ports were opened, therefore, making about twenty
  • 75. in all, in 1861, there was the full complement of qualified men ready to occupy the new consular posts, each of them competent to be his own interpreter. Diplomatic functions were at the same time withdrawn from Hongkong, where they had been merely nominal for eighteen years, and became centred in the Chinese capital. A few years later the judicial authority, so far as it related to the communities at the Chinese ports, was also withdrawn from Hongkong, and was conferred upon the Supreme Court for China and Japan, having its headquarters in Shanghai, established by the Queen's Order in Council of 1864. The new court was inaugurated by Sir Edmund Hornby, who brought to the work practical experience gained in the Levant, the assistant judge being Mr C. W. Goodwin, Barrister of the Inner Temple. This establishment has furnished a solvent for many of the difficulties connected with British residence in the Far East. Adapted with judgment to local circumstances, the court has proved of immense assistance to the consuls, who, subordinated judicially to the chief judge, could now obtain from him proper guidance in their difficulties, a facility of which they availed themselves freely. Although a great advance on what preceded it, the Supreme Court could not of course escape from all the drawbacks which affected the consular courts. As between British subjects, it enjoyed the full powers of law courts in the mother country; but as between British subjects on the one hand, and the natives of the country, or non- British residents, on the other, the authority of the British court could only be exercised over the former. This one-sided action has been to some extent compensated in later times by the judicial qualifications of consuls representing other Western nationalities, who administer their own laws with the same impartiality as the British courts do theirs. But as regards the Chinese no such compensation operates, for although the treaties make provision for the judicial action of the Chinese authorities, their conceptions of equity and forms of procedure being wholly alien to those of the Western nations, their decisions seldom satisfy the foreign litigant. An attempt to supply a connecting-link between two radically different juridical ideals was
  • 76. made in the setting up of mixed courts for the purpose of dealing with petty cases between natives and foreigners within the settlements of Shanghai. These courts have been occasionally presided over by honest and competent judges, assisted by able foreign assessors; but as the native magistrates, being men of low rank, could always be overruled by the local executive, they lacked the power to make their decisions effective. As it was impossible to set up a separate judicial establishment at each treaty port where there was but a handful of residents, the consuls had to continue to perform magisterial duty with all the inconveniences attending their double function. Efforts were made by the Home Government to minimise these disadvantages by infusing a modicum of legal knowledge into the service, for which purpose they offered inducements to consular officials who should qualify as barristers. Notwithstanding all this, however, the simple fact that a consul is bound in his administrative capacity to take a part in matters which may afterwards come before him as a judge perpetuates an element of incongruity demanding an uncommon degree of tact on the part of the official. Some of the worst consequences to be apprehended from this state of things are partially obviated by the judge or assistant judge of the Supreme Court going on circuit, when important cases in the consular districts require it; but that expedient is only possible at rare intervals. The wisdom with which the Supreme Court has been directed is attested by the absence of incident in its history, and by the universal tacit approval of its proceedings. Its success, indeed, soon came to be accepted so much as a matter of course that the true source of it was forgotten. It was, however, recalled vividly to the public memory by a certain retrograde movement. After a quarter of a century of satisfactory working her Majesty's Government took a step which was equivalent to pulling out the corner-stone of the edifice—the absolute independence of the bench. In order to effect an economy in salaries, it was ordained that the two incompatible offices—the judicial and political—should be merged into one,
  • 77. making the chief judge consul-general, and the assistant judge consul for Shanghai. By this move the judges became subordinate to the Legation in Peking, and the Supreme Court itself was subjected to all the evils of the dual function under which the consuls had been labouring. Thanks to the exceptional qualities of the holders of the double office, no glaring scandal arose out of the unnatural combination; but the protests of the community, and of the incumbent of the two offices himself, were strong enough to induce the Foreign Office, after a few years' trial, to retrace their false step and restore the judge to his independence. The twenty consular establishments in China on which the Select Committee of the House of Commons reported in 1872 were manned by forty effectives on duty, besides a considerable contingent on furlough. The ten posts subsequently created employ on an average twenty more. Two complete generations of officials have passed through the consular mill in fifty years, which may be moderately reckoned at two hundred men, all of them selected by a competitive examination only one degree less stringent than that for the Indian Civil Service, and nearly all of them men of varied accomplishments. They have been placed in every part of the wide empire of China, and during their career have been shifted about so that every one has had chances of interesting himself in localities strongly contrasted with each other, both as regards official labour and personal recreation and study. From a body of highly educated men so situated, it was naturally to be expected that much enlightenment would be obtained concerning China and its people, and considerable progress made in the promotion of amiable intercourse between them and foreigners. These expectations have not been disappointed. In the period immediately following the peace of 1860 remarkable activity was shown by British consular officers. The names of Meadows, Markham, Alabaster, Oxenham, recall many exploits of exploration in the interior during very troublous times. Swinhoe, Baber, Hosie, Bourne, Spence, Davenport, Parker, have continued the work and greatly extended its area.
  • 78. Others have distinguished themselves in the held of literary research, and some have found their appropriate reward in honourable appointments in English universities. On the whole, there has been lack of neither energy nor capacity in the British consular service; and yet it is a matter of common remark, even by its members themselves, that in their primary duty of promoting and defending the interests of British commerce they have been unsuccessful. Treaty rights, they admit, have not been safeguarded at the Chinese ports, and this in spite of every apparent incentive to exertion in their defence. A distinction, however, must be drawn between an apparent incentive which is general and remote, such as the patriotic desire for the advancement of their country's interests, and those influences which are nearer and more personal. The attitude of the China consuls can only be fairly estimated in its relation to that of their chief, and his again in relation to that of the Home Government. Like master, like man, is an adage which fits the case, and it is to Peking and to London we must look for the key to the character of the consular rank and file. The British Ministers at Peking have been selected without any fixed rule. The first of the series was taken from the diplomatic circle. The succeeding three, whose term of office covered a period of twenty years, were chosen from among the veterans of the consular service. The next two were taken from the junior ranks of diplomacy, and the seventh was a military officer from Africa. The appointment of Sir Robert Hart in 1885, which was cancelled by his wish, afforded further illustration of the extreme catholicity of the Government's elective faculty. The witnesses examined before the Select Committee of the House of Commons in 1872 were unanimous in insisting on the necessity for long and special training for the office of consul in China, and this principle has been strictly followed by the Government. But for the higher post of superintendent of all the consuls the Government has, at least since 1885, acted on the theory that no such qualification is
  • 79. necessary. But the task of a Minister to China is by no means an easy one. It may be left undone, or it may be done so badly that it were better not to be done at all, but to discharge the duties of the office in a creditable manner requires not only high training but large capacity. The Minister has to conduct his own diplomatic duties in the capital, in which not the Chinese alone but all or nearly all his foreign colleagues are openly or secretly thwarting him. He has at the same time to direct the proceedings of twenty or thirty officers placed at great distances, whom he has never seen, and every one of whom is superior to himself in the knowledge of the conditions to be dealt with. For such a duty it is obvious that an officer sent from Europe must be incompetent, the circumstances of the service in China differing essentially from those prevailing elsewhere. The new incumbent, unless he were a born genius, could never get beyond the elementary lessons of experience before, overtaken by promotion, he shakes the Chinese dust off his feet for ever. Much might of course be learned by personal observation at the consular ports and conference with local officials and people in the provinces, but it is somewhat singular that this obvious source of intelligence has been taken advantage of almost exclusively by those of the British Ministers who stood the least in need of it. Indeed the only one of them who made it a rule to visit the treaty ports at intervals was Sir Rutherford Alcock, whose long experience convinced him of the necessity of constantly refreshing and extending his knowledge of local circumstances and people. A service dispersed over such a large area as the Chinese empire, carried on by despatches between parties who were strangers to each other, and one of whom at least had no personal knowledge of the subjects treated, must have been characterised by an absence of reality, and must have tended more and more towards a perfunctory routine. For this, however, the system of appointing Ministers who were strangers to the country was not wholly responsible. Long before the Ministers were so selected the secretaries began to be sent from European schools, and thus the consular service, disheartened by inadequate pay and a constant menace of further
  • 80. diminution, saw the few prizes of their profession withdrawn from their reach. To serve his time quietly, therefore, to earn his pension and retire without a stain on his character, became more or less the consular ideal. Ambition was starved among those who had to bear the burden and heat of a thirty years' residence in China, when they saw good posts thrown away upon men imported for two or three years, who were almost useless, and who themselves deplored their enforced idleness. The disadvantages attending these exotic importations have been often insisted upon. An old member of the consul staff comments upon it in the following practical manner:— In every country administered by the British Crown, or at every Court at which there is a British representative, the administrator or envoy has from the moment of his entering on the duties of his office the assistance of an experienced staff, well versed in the local history and traditions, or finds himself in the midst of a society the language and usages of which are familiar to him. In China, where we have been fighting and negotiating for over fifty years, we are not so fortunate. A Minister proceeds there, and on his arrival finds himself in a new and to him unknown country, the staff which he may bring with him being like himself utterly unacquainted with the East and its peoples. The Minister is obliged either to grope his way unassisted, or to rely on the aids and advice of experienced (but not always disinterested) outsiders. Under these circumstances his only wise course is to put himself entirely in the hands of the permanent local staff, which, for this purpose, means the Chinese Secretary. That officer, the real motive force of the Legation, occupies a position of greater importance than that of the nominal head of the mission, but, with an irony which is not uncommon in Government administration, he is the least appreciated member of the staff. His salary is that of the junior ranks in the consular service, and yet it is to him that the seniors in that service look for instructions which he is incompetent to give them: the result may be imagined. Why should these things be? The Indian Government has in its service many men of brilliant attainments, and of knowledge gained in long years of service in the East, who might be called upon to fill the post of Minister which would be suitable and congenial to them. And there is an abundance of choice of junior Legation officers in the well-trained consular service. Would it not be very advantageous if the working hands in the Legation were chosen from the most competent Chinese scholars in the consular service?
  • 81. Considering their initial qualifications, their social standing, and their great opportunities, it must be admitted that the men of distinction who have emerged from the consular service during the last fifty years seems disproportionately small. It is perhaps invidious to mention names in this connection, but in response to inquiries addressed to veterans in the service, four men only are placed in the first rank as the best representatives of the consular training school. These are Sir Harry Parkes, Mr T. T. Meadows, Mr H. N. Lay, and Mr W. F. Mayers. Sir Robert Hart, it should be mentioned, left the service so early, and Sir Rutherford Alcock joined it so late, in life, that their distinguished careers can scarcely be claimed as the product of the consular nursery. It is impossible to look back over the forty years which have elapsed since the new relations were established in China without being struck by a certain change which passed over the character of the diplomatic and consular services between the first decade of that period and the second. The anxious years of the rebellion evoked much active energy on the part of British officials. The serious opposition to the operation of the treaties was met by very vigorous action on the part of the consuls at the ports and of the Minister at the capital. The years 1868 and 1869 may be considered to have marked the culminating-point of the British official effort to enforce observance of the treaties in letter and spirit, and to protect all commercial interests. The change which came over the diplomatic and consular services at the end of the first decade of diplomatic relations may be likened to the rising followed by the receding of a tide. Up till the years we have specified, whatever the difficulties which beset their office, the consuls showed earnestness in the defence of the interests confided to them, and acted on the conviction that their exertions were pleasing to those who were set in authority over them. Their sense of duty was sustained by the hope of distinction. After 1869 the discovery was made that the situation had been undergoing a change of which the service had been unaware. What was formerly deemed a merit had become a
  • 82. demerit in consular officers, and on this discovery zeal naturally fell to a discount. It was but a reflex of the change that had crept over the spirit of the British Foreign Office, a change which also had escaped notice until circumstances forced it into publicity. This seems to have originated with the removal from the scene of Lord Palmerston, the statesman who for forty years had stood in a general way for what was manly and straightforward in the British national character. Though he left a tried and trusted colleague, Lord Clarendon, in charge of the Foreign Office, and a sturdy permanent Under-Secretary, perhaps the last custodian of the Palmerstonian tradition, and who remained at his post for five years longer, yet it was made evident by results that the spirit which had animated that great department of State had vanished. The Foreign Office became nerveless and invertebrate, sentimental and unstable. Those who had to do with it in the time of Palmerston, Layard, and Hammond know that since their time the officials bearing the same titles have been of quite another calibre, have been swayed by different influences, and above all have exhibited no such knowledge of the affairs with which they had to deal as their predecessors of the Palmerstonian era. Many explanations may be given for the new departure without disparagement of the capacities of the individuals concerned. Such explanations interest those who may desire to promote reform in the constitution and the inspiration of the Foreign Office. It suffices us merely to note the fact by way of accounting for some of the shortcomings which have been laid to the charge of our representation in China. We have seen how easily one Foreign Secretary yielded to the meretricious solicitations of the envoy Burlingame, and how another allowed himself to be cajoled by the Marquis Tsêng. After these, and sundry other such, exhibitions it was impossible for any Minister serving the country in the Far East to place the old reliance on the support of his Government. With John Bright, the implacable opponent of Palmerston and his works, installed at the Board of Trade, whose word was law on such matters as Chinese commercial treaties, and apparently more anxious to undo the work of Palmerston than to promote a trade which both he and his department unaffectedly despised, it was not likely that the
  • 83. commercial communities trading with China should cherish any hope of redress of grievances from a Government whose face seemed set against them. Apathy, therefore, became the principle, to keep the peace at all sacrifices the avowed policy of British diplomacy in China. The apparent exception to this rule in the attempted reclamations in connection with the Margary murder in 1875 afforded in its abortive ending a new corroboration of the rule. The diplomatic and consular establishments went on grinding out routine despatches and publishing statistical reports, but with the tacit understanding that whatsoever is more than these cometh of evil. Under such conditions it was of little consequence how the Peking representation might be filled, since it has not for thirty years risen above the level of comedy, the term applied to it by those who have grown old in its service. Such was the situation of affairs when the greatest crisis in the history of China, or of foreign relations with that country, was sprung upon the world in 1894. A Legation equal only to clerical routine suddenly called upon to play a part in a commotion which unhinged the policy of the world was totally inadequate to the strain, and as a consequence of the impotence of the Foreign Office and its agent in China, the interests of Great Britain and, what was only second in importance, the interests of the Chinese empire were allowed to go by default. The Chinese were, and perhaps even still remain, unconscious of the reasons of the collapse of their empire. Perhaps something of the same kind might be said of the British Foreign Office in regard to the interests of Great Britain in China. Certainly there is as yet little sign of a determination to reform the mechanism of the country's representation, and this, perhaps, because the preliminary step thereto would be the reform of the Foreign Office itself. And so the Legation goes on under the nominal headship of a Minister who must be guided entirely by his Chinese Secretary, an official of inferior rank and position to the body of consuls whom he has to control, and for whose authority they can never have genuine respect.
  • 84. The recent upheaval has offered many new opportunities of distinction for the consuls, especially in the interior of China. That these openings have infused new life into the consular ranks has been shown in many ways during the last few years; and if natural selection be allowed to operate freely and the best men be not discouraged in their efforts for their country's benefit by undue interferences from Peking, where there is neither knowledge nor capacity to guide them, it is still possible that the consular service may play a valuable part in the reconstruction of the foreign relations of China.
  • 85. CHAPTER XXIX. CHINA AND HER RULERS. Longevity of the State—Government by prestige—Necessity of adaptation to European ideas—The Empress-dowager—Prince Kung—Wênsiang—Hu Lin-yi— Tsêng Kwo-fan—Tso Tsung-tang—Chang Chih-tung—Li Hung-chang—His long and consistent career—Efforts at reorganising national forces. The long continuance of a State more populous than any other on record is a phenomenon which to thoughtful minds can hardly fail to evoke a feeling akin to reverence. De Quincey declared if he met a Chinaman he would make obeisance to him, saying, There goes a man 2000 years old. Be the causes of this national longevity what they may, the fact should make us pause to consider on what foundation does this great vital national system rest? The most realistic word-painter of China represents the country as a collection of villages, each being a unit of self-government,[29] and in describing village life in minute detail, seems to depict the great empire, of which each village is a pattern in miniature. Dynasties may come and dynasties may go, but the Chinese families, their industries and their customs, go on for ever. It is remarkable with what ease the people adapt themselves to changes in their ruling powers, regardless of race or origin; indeed it is a noteworthy fact that the rulers have for many centuries been more often foreign than native.[30] Foreign, however, not quite in the sense in which the word is so easily translated barbarian by the Chinese, and applied by them to the hated Aryans of the West. The rulers of China have been of cognate races, more or less imbued with the same generic
  • 86. ideas as the Chinese themselves, and with tastes akin to theirs. How this succession of dynasties, each established by violence, has coexisted with the continuity of the grand national idea of the emperor being the Son of Heaven can only be explained by the very practical character of the race, who accept the usurper as divinely appointed from the moment he has proved himself successful. What holds, and has held together from ancient times, this great aggregate of mankind in common usages and ideas is naturally a mystery to Occidentals, the cohesive principle not being perceptible to them. China occupies the unique position of a State resting on moral force,[31] a conception almost as alien to the Western mind as material progress is to the Eastern, hence the proposition is apt to be received with amused contempt. Yet a State administered without police, and ruled without an army, is a something which cannot be explained away. Government by prestige is, other things being equal, surely the most economical as well as the most humane of all species of government; but an obvious consequence is that in emergencies the Government is beholden to volunteers, and is often driven to enlist the services of banditti and other forces proscribed by the law. Imperial prestige, which embraces the relations of the surrounding tributaries, is but an expansion of the authority of the head of the family and of the elders of the village, which rests on moral sanction only. The first collision, however, with the material forces of Christendom proved that in the system of the modern world the Chinese principle of government was an anachronism, and that moral must succumb to physical force. Yet in the midst of the world's triumph in the pricking of the great Chinese bubble, it had been well to reflect what the kind of bubble was that was being pricked. China with her self-contained, self-secreted knowledge, could not be expected to foresee how the impact of the West was likely to affect her ancient polity. She had nothing wherewith to compare herself, and no criterion of good or evil except her own isolated experience; nor did she know aught of human development except what was, so to speak, forcibly injected into her, but never assimilated. What, then, could she do to be saved but to take herself
  • 87. entirely to pieces like a house that has to be rebuilt on a new plan, and so fit herself for the companionship and competition of the worldly Powers, from whose pressure she could by no means escape? She had to put away the wisdom of ages, the traditions of a civilisation unbroken for thousands of years, and convert herself into a mechanical, scientific, and military Power. Something more radical than reform is involved in such a root-and-branch change: it was not improvement but transformation that was demanded. That some such essential changes are necessary to the preservation of the Chinese empire is probably recognised by all who interest themselves in the subject—including a large ever-increasing number of the Chinese themselves; but the gravity of the revolution may well cause misgivings both as to its possibility and its incalculable effects. Who among the Chinese rulers is sufficient for such things? It is not always possible to locate the nervous centre of any Government in the West, whether its form be autocratic or representative. With regard to that of China we may safely say it is never possible—at least for any foreigner. The attempts which have been from time to time made to assign acts of Government to the will or influence of certain individuals have in general proved in the sequel to have been far from hitting the mark. The monarch under whose authority the whole machine moves is not necessarily the directing will: indeed he is very often little better than a puppet. The eunuchs, concubines, and play-actors, who constituted the Court of the late Emperor Hsien-fêng, the father of the present young emperor, had more influence probably in bringing on the war that led the Allies to Peking than any of the high officers or Ministers, wrote Sir Rutherford Alcock in 1871. Another writer put it in a more paradoxical form: There is in China something more powerful than the Emperor, and that is the Viceroy; more powerful than the Viceroy, and that is the Taotai; more powerful than the Taotai, and that is the Weiyuen, meaning that the power of obstruction, extending through every grade of officialdom, is most widely diffused at the base. Official responsibility and moral
  • 88. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com