An Introduction to EJB
In the late 1990s, as Java was bolstered by the emergence of separate technologies (such as RMI, JTA, and CORBA) that addressed the enterprise needs of large-scale applications, a need arose for a business component framework that could unify these technologies and incorporate them under a standard component development model. EJB was born to fill this need. Over the ensuing years, EJB has evolved to encompass numerous features (while judiciously rejecting others), and it has matured into a robust and standard framework for deploying and executing business components in a distributed, multiuser environment.
What Is EJB?
Each release of EJB is managed through the Java Community Process (JCP) as a Java Specification Request (JSR). The latest release, which is covered in this book, is defined by JSR 345: Enterprise JavaBeansTM 3.2. EJB JSRs prior to EJB 3.0 covered Persistent components, but since the introduction of JPA, persistence is now managed through its own JSRs. Nonetheless, the two areas complement each other well, and we have included several chapters in this book dedicated largely to JPA.
The EJB 3.2 spec, entitled JSR 345: Enterprise JavaBeansTM, Version 3.2 EJB Core Contracts and Requirements, together with the class library defined in the EJB 3.2 API, define both a component model and a container framework.
The EJB Component Model
As a component model, EJB defines three object types that developers may build and customize as follows:
• Session beans can be stateless, stateful, or singleton, and they perform business service operations. These services may be declaratively configured to operate in distributed, transactional, and access-controlled contexts.
• Message-driven beans (MDBs) are invoked asynchronously in response to external events through association with a messaging queue or topic.
Complementing this, the Java Persistence API (JPA) principally defines the following persistent object type:
• Entities are objects that have unique identities and represent persistent business data.
Session and message-driven beans are EJBs, and they are often referred to collectively as enterprise beans. In earlier versions of EJB, entities were referred to as entity beans, and they also fell into this category. In EJB 3, however, entities are now managed by a persistence provider and not the EJB container, and they are no longer considered enterprise beans.
The EJB Container
The EJB container provides the supporting environment in which EJB components operate. This environment offers transaction and security services, pooling and caching of resources, component life-cycle services, concurrency support, and more—all of which we will explore throughout this book. EJB components specify the details of how they wish to interact with their supporting container using EJB-specific metadata that is either captured by the container and applied to the EJB’s behavior at run time, or interpreted at the time an EJB component is deployed to an EJB container and used to construct wrapping.
Core Features of the EJB Development Model
Throughout its life, EJB has maintained its focus on delivering components imbued with a handful of core features.
Declarative Metadata
One of the hallmarks of the EJB component model is the ability for developers to specify the behavior of both enterprise beans and entities declaratively (as opposed to programmatically) using their choice of Java annotations and/or XML descriptors. This greatly simplifies the development process, since much customization can be added to a bean without having to encumber the Java source with service implementation code. To accommodate developer preference and application flexibility, EJB offers developers their choice of both annotations and XML, with the ability to use both
methods simultaneously within the same EJB or entity, for specifying behavior in metadata. In cases where the same piece of metadata is defined both in an annotation and in XML, the XML declaration takes precedence in resolving the conflict. Additional benefits of this approach are explored later, in the “EJB 3 Simplified Development Model” section of this chapter.
Configuration by Exception
Coupled with the ability to specify behavior declaratively is the strong use of intelligent defaults in EJB. Much behavior is attached automatically to an EJB or an entity without it being declared explicitly, such as the transactional behavior of session bean methods and the names of the table and columns that map to an entity’s persistent data properties. An annotation, or its counterpart in XML, needs to be specified explicitly only when non-default behavior is desired. In the most common cases, where the default behavior is leveraged, this approach leads to very sparse, clean code. This development model is known as configuration by exception, because only in exceptional (non-default) cases is it necessary to configure the behavior of the component explicitly.
Scalability
Large-scale applications demand the ability to scale well as the client load increases. The EJB server employs resource pooling to maximize object reuse, utilizes a persistence cache to avoid repeatedly querying or creating the same objects, and implements an optimistic locking strategy in the middle tier to reduce load on the relational database management system (RDBMS) and to avoid concurrency locking issues. The EJB container also manages an EJB’s life cycle, allowing dependent resources to be freed up and reused to optimize performance.
Location Transparency
EJBs may be configured for remote access, allowing them to be accessed across a network connection. A client, which may be another EJB, simply requests an instance of a remote EJB, and the local and remote EJB containers transparently manage the communication details.
Transactionality
The Java Transaction API (JTA) defines a standard API for distributed transactions, and the EJB container acts as a JTA transaction manager to EJBs. Since its inception, the EJB spec has defined a standard model for declaratively specifying container-managed transactional behavior on enterprise beans.
Multiuser Security
Method-level access control may be specified declaratively on EJBs, enforcing user- and role-level privileges defined by application server administrators.
Portability
Spec-compliant enterprise beans are deployable to any application server that implements EJB, at least in theory. In practice (and this was particularly true of releases prior to EJB 3), vendors provided their own metadata definitions that enterprise bean developers grew to rely upon, locking them into a particular vendor’s implementation. As EJB has matured, it has grown to incorporate many of these formerly platform-specific features, so that EJBs implemented today are far more portable than in the past.
Reusability
EJBs are loosely coupled components. An EJB may be reused and packaged into multiple applications, though it must be bundled with, or have access to, the business interfaces of dependent EJBs.
Persistence
Although no longer covered in the EJB spec, JPA entities are an essential complement to EJB. Entities are persistent domain objects with unique identities. An entity class maps to a database table, and each entity instance is represented by a single row in that table.
Progression of the EJB Spec
Each time a new version of the EJB spec is introduced, it includes new, significant features to address popular demand and adopt emerging technologies. Here is a brief summary of how the EJB spec has progressed since its birth in 1996, or more importantly, since its first commercial implementations in 1998.
EJB 1.0
The initial release, 1.0, began with support for stateful and stateless service objects, called session beans; and optional support for persistent domain objects, called entity beans. For portability, EJBs were made accessible through a special remote interface that offered portability and remotability, but incurred the overhead of a remoting infrastructure and pass-by-value semantics.
EJB 1.1
The follow-up release, 1.1, mandated support among vendors for entity beans, and introduced the XML deployment descriptor to replace storing metadata in a special serialized class file.
EJB 2.0
EJB 2.0 addressed the overhead and pass-by-value shortcomings of remote interfaces by introducing the local interface. Only clients running inside the J2EE container could access an EJB through its local interface, but pass-by-reference method calls allowed for more efficient interchanges between components. A new type of EJB was also introduced—the message-driven bean (MDB), which could participate in asynchronous messaging systems. Entity beans gained support for container-managed relationships (CMRs), allowing bean developers to declaratively specify persistent relationships between entity beans that were managed by the EJB container. Also, Enterprise JavaBeans Query Language (EJB QL) was introduced, which gave developers the ability to query entity bean instances using a language that resembled SQL.
EJB 2.1
EJB 2.1 added support for Web Services, allowing a session bean to expose an endpoint interface, and a timer service that allowed EJBs to be invoked at designated times or intervals. EJB 2.1 also provided expanded EJB QL functions, and an XML schema was introduced as a replacement for the DTD that defined the ejb-jar.xml deployment descriptor.
EJB 3.0
EJB 3.0 was a major milestone in the evolution of the standard. Introducing a new, simplified development model (see below), EJB components became POJOs (plain old Java objects); an EJB’s bean class was no longer required to implement EJB-specific interfaces, and the properties that made a Java class an EJB were factored out into Java annotations or captured externally in the ejb-jar.xml deployment descriptor file. With a few basic conditions, any class could become an EJB and leverage the enterprise services offered by an EJB container.
Also new in EJB 3.0, the Entity Beans portion of the spec was replaced by the new JPA spec and, consistent with the new simplified development model, JPA entities were POJOs as well. JPA entities were also decoupled from the EJB container and could be used independently of EJB, including in a pure Java SE environment.
EJB 3.1
EJB 3.1 further improved upon the simplified development model introduced in EJB 3.0. The no-interface option was now supported for Local EJBs. The Singleton pattern was offered for Session beans along with Asynchronous and enhanced Timer support. EJB Lite—an embeddable subset of the EJB Container’s functionality—allowed EJB components to be executed in the same VM as an EJB client.
EJB 3.2
In EJB 3.2, the Asynchronous and enhanced Timer features are added to the EJB Lite subset. Along with other improvements, the bean developer is offered more control over the transactionality of life-cycle interceptor methods, and the rules governing declaration of Local and Remote behavior have been simplified.
EJB 3 Simplified Development Model
EJB 3.0 was a significant departure from earlier releases. The architects of EJB 3 set out to redesign the development experience; to introduce a greatly simplified development model that would reduce the complexity of the enterprise beans themselves; and, at the same time, incorporate many of the ideas found in peer technologies. The consensus is in: the spec has been widely hailed as having achieved these goals, and in so doing has overcome many of the problems that prevented earlier versions of EJB from becoming widely adopted.
XML and Annotations
If you are familiar with earlier versions of EJB, one of the first things you will notice in EJB 3 is that it is no longer necessary to capture EJB metadata in a deployment descriptor. EJB now lets you store your EJB metadata inside your bean source using Java annotations. This isn’t to say that XML deployment descriptors have gone away; they are still alive and well, and many developers prefer them to annotations. Using XML decouples the Java source from the EJB metadata, allowing the same entity or enterprise bean classes to be used in different contexts, where the context-specific information is captured in the XML and doesn’t “pollute” the bean class.
Many users, however, will prefer to view their EJB metadata directly in the context of their POJO classes and use annotations. To avoid wading into a religious war (vocal proponents on both sides abound), we suggest that you choose for yourself. A simple rule we follow is this: if we need to decouple our entity and bean classes from their EJB metadata, as when we want to use the same entity classes with two different entity inheritance strategies, we put our metadata in XML. Otherwise, we stick with annotations. Don’t forget—you can always mix and match, relying on the firm policy that whenever metadata is specified for an element using both XML and annotations, the XML always wins. This allows any role (see the “EJB Roles” section later in the chapter) downstream of the bean developer to override metadata settings without having to update the Java source, since overrides can be applied exclusively to the XML descriptors.
Note ■ a more advanced strategy, which we also recommend, is to use annotations only when defining behavior on an enterprise bean or an entity that is truly integral to its definition, such as the relationship type of an entity relationship field, or the transactional requirements of a method on a session bean. anything that could reasonably be overridden, such as the name of the table to which an entity maps, or the details of a value generator used for populating the primary key on an entity, would go in the XML descriptor, where it can be specified at deploy time by an application assembler, perhaps in consultation with a database administrator. While there is no harm in specifying default values using annotations in the Java source file, this approach recognizes the difference between firm metadata, which ought not to be modified, and loose metadata that may be freely modified without changing the behavior of the enterprise bean or entity.
Dependency Injection
After an EJB is instantiated inside the Java EE container, but before it is handed out to a client, the container may initialize property data on the instance according to rules defined for that enterprise bean. This feature is called dependency injection, and it is an example of inversion of control pattern, whereby an external provider initializes the properties of an object instance instead of by the class itself. EJB 3 introduced the use of dependency injection in Java EE and, largely because it caught on so well, this feature has now been given its own spec. The current dependency injection API is managed through JSR-330: Dependency Injection for JavaTM, and the functionality is further extended through JSR 346: Contexts and Dependency Injection for JavaTM EE 1.1, which we cover in Chapter 10, “Contexts and Dependency Injection.”
Note ■ Injection uses a “push” model to push data out to the bean, and it occurs regardless of whether the bean actually uses the data. If there is a chance that the data will not be used, the bean may elect to avoid incurring the cost of the resource derivation by performing a Java naming and directory Interface (JndI) lookup in Java code to “pull” the data, only if it is actually (or likely to be) used.
Common examples of dependency injection use in EJB are as follows:
Injecting an • EntityManager into a session bean for interacting with entities in a persistence unit
Injecting a • UserTransaction into a session bean that manages its transaction demarcation
Interceptors: Callback Methods
Both enterprise beans and entities may designate some of their methods, or methods on separate classes, to be called when certain life-cycle events occur. For instance, a session bean may indicate that a certain method should be called after the bean has been instantiated, but before it has been handed off to a client. This method may initialize state information on the bean, or look up resources using JNDI, or any other action it wishes, provided that it does not require a transactional context. Such callback methods are called interceptors, and they allow bean developers to participate programmatically in the interaction between an enterprise bean, or an entity, and its container. An important advantage of this pattern (also known as cross-cutting) is that a single interceptor may defined once and then applied to multiple methods, or even multiple EJBs.
POJO Implementation
EJB 3 took great strides to eliminate the trappings that beset enterprise bean classes and their required interfaces in earlier EJB releases. Similar to complaints over having to define XML metadata to specify even the most basic bean behavior, developers found it burdensome to have to write custom interfaces to handle an enterprise bean’s factory support, and inconvenient to require a session bean’s interfaces to extend EJB-specific interfaces. All of these limitations were addressed in EJB 3.
Home methods are no longer mandated, although they’re still supported. For session beans and MDBs, a default constructor replaces the no-argument ejbCreate() method required by earlier EJB specs.
For entities, the Home interface is replaced by an EntityManagerFactory instance that produces EntityManager instances for a JPA persistence unit to manage entity life-cycle operations, including query execution.
Intelligent Use of Defaults
An excellent example of how EJB 3 simplifies the development process is its leveraging of default behavior to provide rich functionality with no coding or declarative metadata required. For instance, by simply marking a POJO with the @Entity annotation, all of its public properties automatically become persistent fields, and the table and column names take on derived values that match the entity and field names. Additional annotations or XML elements are only required when overriding the default behavior of a particular area. Only when the table name does not match the entity name is the @Table annotation required. Great care has been taken to ensure that the default values match the most common usages so that, in the majority of use cases, explicit metadata is not required, leading to leaner, more clutter-free code.
Note ■ one consequence of relying on default behavior is that the class does not describe its full behavior anywhere, so you need to have a good understanding of the default behavior that is being applied. Ides can be useful in deriving and displaying the enterprise bean or entity with its fully defaulted values explicitly shown.
Distributed Computing Model
Essential to any enterprise application is the ability to execute tasks and run components in separate Java threads or processes. Through the RMI-based remoting services, clients in an application client tier may access EJBs running in an application server anywhere on the network. The pass-by-value behavior of remote interface methods provides a coarse-grained model designed to reduce network traffic between clients and servers that are loosely connected to each other. Many applications that use EJB do not require remote access, however, and elect to configure their EJBs for local use. This eliminates the overhead of remote access support while continuing to offer the remaining enterprise services.
EJB Roles
The EJB spec defines seven roles for individuals involved in the different stages of defining an enterprise bean or entity, or in providing services and API implementation to enterprise beans. This book is targeted at the three roles involved in defining enterprise beans and their associated metadata. In practice, one or more of these roles may be performed by the same individual, and certain tasks may be performed by one role and overridden by another; but it is useful to understand the logical partitioning of tasks in the EJB development process. We will refer to these roles in various sections throughout the book.
The Enterprise Bean Provider
The Enterprise Bean Provider, also known as the Bean Provider, has the responsibility of defining and implementing the business logic and structure of an enterprise bean. This includes defining the Java class, implementing service methods, specifying transactional and security information declaratively on the bean and its methods, injection or lookup of required resources, and anything else that can be applied to the enterprise bean class.
Applied to JPA entities, the Bean Provider defines the persistent structure of the entity and its relationships with other entities. The provider may define mapping and primary key–generation behavior, but this role is generally limited to defining the logical dependencies and structure of the entity.
The Application Assembler
The Application Assembler combines EJBs into EJB modules and entities into persistence archives, and then it combines these modules together with other Java EE modules to produce an application. This task requires resolving references to logical server resources including references between EJBs. The Application Assembler must work with the interfaces and metadata defined for the EJB and entity components but need not be familiar with the implementation details.
The Deployer
The Deployer takes an application that has been assembled by the Application Assembler and deploys it to a particular application server instance or cluster. The Deployer must resolve all of the external dependencies defined by the EJB component, mapping them to concrete resources installed in the application server environment. In the case of entities, the Deployer may provide or override the details of the live database objects to which the entities will map.
How This Book Is Organized
To orient you to the structure of the remainder of this book, here is a brief summary of each chapter. There is no requirement that you read these chapters in order. Sample programs accompany each chapter, and they may be run independently of one another. Topics are introduced progressively, though, and thus if you find a reference in one chapter to a term or concept that is not defined in that chapter, chances are that it was defined in an earlier chapter of the book.
Chapter 1: Introduction to the EJB 3 Architecture
This chapter opens by introducing the book and offering an orientation to EJB. This orientation covers the EJB development framework and component model, the core features of EJB, the history of EJB, the EJB 3 simplified development model, and the EJB distributed computing model. The chapter concludes with a “Getting Started” section to help you install the NetBeans IDE and GlassFish Java EE reference implementation server required to run the many sample applications provided with this book.
Chapter 2: EJB Session Beans
Chapter 2 explores EJB’s primary service object: the session bean. Session beans are examined in their many roles: as entity facades, as service components—both with and without state, as singleton or timer-driven objects, and as the primary orchestrators of transaction and security services.
Chapter 3: Entities and the Java Persistence API
The Java Persistence API (JPA) is introduced, along with the various persistence services that are available to support entities both within a Java EE container and outside of one. This chapter covers basic O/R mappings, and it introduces the Java Persistence Query Language, or JPQL.
Chapter 4: Advanced Persistence Features
Delving into more advanced persistence concepts, this chapter describes the support offered in JPA for mapping entity inheritance hierarchies. Examples of the three supported inheritance mapping strategies identify the strengths and weaknesses of each approach in order to help you decide which one best suits the particular needs of your application. Among other topics, this chapter also covers complex primary key (PK) mappings, ID generators for autopopulating primary key values using a database sequence or table, locking strategies and cache management.
Chapter 5: EJB Message-Driven Beans
This chapter describes how you can use MDBs to add asynchronous, event-driven behavior to your application. JMS, Java’s messaging API, is explained and demonstrated in this chapter’s code examples.
Chapter 6: EJB and Web Services
Session beans provide an excellent implementation for Web Services, and this chapter explores EJB’s support for this fine marriage of technologies.
Chapter 7: Integrating Session Beans, Entities, Message-Driven Beans, and Web Services
After covering all of the different component model types individually, Chapter 7 brings them all together in an integrated Java EE application. We think you will find it particularly useful to see how everything fits together to produce a running application.
Chapter 8: Transaction Support in EJB
EJB offers rich transaction service support, and it makes it easy for Bean Providers to declaratively specify custom container-provided transactional behavior on an enterprise bean. EJB also allows enterprise beans to opt out of this model, and control their own transaction demarcation behavior. This chapter applies two alternative transactional models to a single logical scenario for weighing the benefits of each approach.
Chapter 9: EJB Performance and Testing
This chapter provides an invaluable look at how to gauge the performance of your EJB components in order to help you decide which of the many options EJB offers is right for your application. In addition to explaining how to set up performance tests, we present some performance test cases that we have run, complete with our assessments of the results.
Chapter 10: Contexts and Dependency Injection
Introduced in Java EE 6, Contexts and Dependency Injection (CDI) services augment the component model defined in EJB with a powerful means of injecting resources into your application whose life cycles are contextual and conveniently managed by the server. This chapter introduces CDI and explains how EJB developers can leverage this support to enrich an application’s behavior.
Chapter 11: EJB Packaging and Deployment
Assembly and deployment are rolled into this chapter, as we cover the tasks required of the Application Assembler and Deployer roles. This chapter discusses packaging EJB and persistence modules, assembling modules in different ways into an enterprise archive (EAR) file, resolving references between modules and between EJBs packaged into different modules, and binding resource requirements to concrete resources installed in the target application server environment.
Chapter 12: EJB Client Applications
In this chapter, we walk you through application architectures and different programming models that you can use to build applications, including the pros and cons of each approach. Once we have done that, we settle on one application architecture—developing Web applications using JavaServer Faces (JSF) technology. We then drill down into the JSF architecture and concepts, and focus on integrating JSF user interface components and the JSF navigation model with the EJB/WebService/JPA back-end application that we developed in Chapter 7.
Finally, we also explain how to use a lightweight application client container to execute your session beans in a pure Java SE environment. This lightweight container provides EJBs that execute in its environment with some of the services (such as container injection) that are offered by a true EJB container.
Chapter 13: Testing in an Embeddable EJB Container
In a production deployment EJB components run in a Java EE environment, inside an application server. For testing purposes, EJB allows you to test your EJB components within a lightweight subset of the EJB Container, known as EJB Lite and implemented as an Embeddable EJB Container, that can run in a pure Java SE environment. This chapter covers a variety of EJB testing scenarios and guides you in using JUnit to test EJB components (and JPA entities) in GlassFish’s Embeddable EJB Container.
Getting Started
This section of the chapter will get you ready with the software installation and configuration required to work with the samples in the rest of the book. At the time of this writing, the EJB 3.2 specification was on its way to being finalized. The GlassFish application server had implemented the specification that allowed the developer community to get hands-on experience with the new specification.
GlassFish is an open source application server that implements the newest features of the Java EE platform. In fact, GlassFish is the reference implementation for all of the specifications of the Java EE platform, including the EJB 3.2 specification. Glassfish releases are tracked closely by the NetBeans IDE, ensuring that NetBeans supports the very latest state of the Java EE specifications and making NetBeans the ideal platform for deploying and running the examples in this book. You will find that each successive chapter is accompanied by a NetBeans application project comprised of one or more additional projects representing the EJB, Web, or other modules that demonstrate the features covered in that chapter. Although these sample applications are all configured to run in the GlassFish server, they are portable (by virtue of following the Java EE standards) and may be deployed to the Java EE 7 server of your choice.
Although we built and tested the examples in this book using NetBeans in a Windows 7 environment, the code samples are not operating system specific, and they can be executed on any system that can run NetBeans and its integrated GlassFish server. Nevertheless, you might have to tweak the environment settings to install and execute NetBeans and its integrated GlassFish server on other operating systems.
Note ■ You can find more details on the netBeans Ide and its integrated GlassFish application server at the following website: http://netbeans.org/features/index.html.
The remaining sections of this chapter will cover the following:
Downloading the NetBeans IDE •
Installing NetBeans and its integrated GlassFish server •
Testing NetBeans and GlassFish installation •
Administrating the GlassFish application server •
Even if you are familiar with NetBeans and GlassFish, we recommend that you read through the following sections, as running the sample code in the rest of the chapters depends on this setup being done correctly.
Downloading the NetBeans IDE
You can download the latest NetBeans installer from the following location: http://netbeans.org/downloads/
Make sure that you download the installer with “Java EE” technology, as shown in Figure 1-1. This installer will also contain the required Java SE and GlassFish packages. Ant is included with GlassFish; you can either use it or configure the environment properties to use another installation. The GlassFish project recommends that you use Ant, which is bundled with its install.
Figure 1-1. Downloading the NetBeans IDE
Note ■ When we started writing this book, the latest netBeans version was 7.2. during the process of writing it, version 7.3 was released. We have tested the setup and the sample code using the netBeans 7.3 version.
Once the download is complete, you are set to start the installation of NetBeans along with its integrated GlassFish server.
Installing NetBeans IDE and Its Integrated GlassFish Server
Navigate to the directory where the NetBeans IDE installer has been downloaded, and run the installer. The first page of the installer wizard lists the packages that will be installed. If you see the “No compatible JDK was found” warning message, as shown in Figure 1-2, then you will have to exit the wizard and first download and install Java Platform (JDK) 7 from the following location.
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Figure 1-2. Installing NetBeans. “No compatible JDK was found” warning
Note ■ even if you don’t see the "No compatible JDK was found" warning, verify that you have Java platform (JdK) 7 installed. If you don’t have the Java platform (JdK) 7 installed, then you might get a "javac: invalid target release: 1.7" error while executing the samples in this book.
Rerun the NetBeans installer after a compatible JDK version is installed. Verify that the “No compatible JDK found” warning does not reoccur, and traverse the wizard, keeping all of the default values selected. The “Summary” page will list the folders where the NetBeans IDE and the GlassFish application server will be installed. Finish the wizard by pressing the Install button, as shown in Figure 1-3
Figure 1-3. Installing the NetBeans IDE and GlassFish application server
After a successful installation, your NetBeans IDE and GlassFish application server will be ready for use. In the upcoming sections, we will show you how to create a simple NetBeans project and verify that the installed GlassFish server is functioning properly.
Testing the NetBeans IDE and GlassFish Installation
Assuming that all of the preceding steps have been executed successfully, you are ready to start the NetBeans IDE and the integrated GlassFish application server. We will also demonstrate a few simple tests to ensure that you are set to run the samples in this book.
Starting NetBeans IDE
The NetBeans IDE provides a graphical environment for creating, deploying, and executing Java EE applications. Administrative tasks like starting and shutting down the GlassFish server domains can also be performed using NetBeans.
Invoke NetBeans, either by selecting “NetBeans” in the Start Menu of your Windows 7 machine or running C:\Program Files\NetBeans 7.3\bin\netbeans64.exe from the command prompt. Note that the exact path will depend on the installation location that is mentioned in Figure 1-3, and for 32-bit systems the executable will be named netbeans.exe. If you are running Windows 8, then you need to press the “Windows” key and start typing “NetBeans.” The Apps Search tool will search for the NetBeans executable that you can select to launch the NetBeans IDE.
Testing Using Sample Project
Once the NetBeans IDE has opened, we will create a sample project to test the compilation, deployment, and execution aspects of the IDE as well as the application server.
To create a new project, open the New Project wizard by pressing Ctrl-Shift-N. Select the Java Web category and the Web Application project, as shown in Figure 1-4. Traverse the wizard, keeping all of the default values selected, and Finish the wizard.
Figure 1-4. Creating a sample test project
NetBeans will create a project named WebApplication1. Next we will create a servlet under the project WebApplication1. To create a servlet, invoke the context menu by right clicking on the project name in the project navigator. Select the Servlet ... menu that is available under New, as shown in Figure 1-5.
1-5. Creating a test servlet
In the New Servlet wizard, enter a package name and Finish the wizard keeping the other default values, as shown in Figure 1-6. We have used setup as the package name.
Figure
Figure 1-6. Traversing the New Servlet wizard
After the NewServlet class is created, we can instantly run it by invoking the context menu on the servlet file and selecting the Run File menu option, as shown in Figure 1-7.
Figure 1-7. Running the servlet
When we run the servlet, NetBeans will automatically start the integrated GlassFish server. You might have to provide necessary permissions to the Java EE and application server-related functionality if the Window firewall shows one or more Windows Security Alert dialogs, as shown in Figure 1-8.
Figure 1-8. Allowing access if Windows Firewall shows an alert
As part of running the servlet, NetBeans will compile, package, and deploy it to the integrated GlassFish server. After the deployment, NetBeans will automatically open the servlet URL in the default browser, as shown in Figure 1-9.
1-9.
Successful execution of the servlet class means that the installation of NetBeans and the integrated GlassFish server has gone through successfully, and the setup to run the examples presented in this book is ready.
Note ■ By no means is this section of the chapter a user guide for the GlassFish application server. For more information on GlassFish, see http://glassfish.java.net/downloads/quickstart/index.html.
Figure
Running the servlet class
Administrating the GlassFish Application Server
NetBeans provides us with a graphical interface to perform various GlassFish server-related administrative tasks. You can restart, start, and stop the GlassFish server from the Services tab, as shown in Figure 1-10.
Once GlassFish has successfully started, you can test whether the server is able to accept the basic HTTP requests. To do so, open a browser, type in the URL http://localhost:8080/ and, if the server is up and running, you will be able to see the page shown in Figure 1-11.
Figure 1-10. Administrating the Glassfish application server
Figure 1-11. Testing GlassFish server
Note ■ Substitute localhost with the machine name or Ip address if you are trying to access it from a machine other than the one on which GlassFish is installed. If you changed the port number during installation, use that port instead of 8080.
The next step is to test the access to the administration console of the GlassFish server. Make sure that the GlassFish server is up and running, and then select the View Domain Admin Console menu option from the context menu, as shown in Figure 1-10. NetBeans will launch the default browser and open the administrator console. Alternatively, you can type in the URL http://localhost:4848/, and you will be able to see the administration console page, as shown in Figure 1-12.
Note ■ Substitute localhost with the machine name or Ip address if you are trying to gain access from a machine other than the one on which GlassFish is installed. You will have to enter the username and password on the administration console login page. If you changed the port number during installation, use that port instead of 4848.
Troubleshooting
Even after precisely following the steps mentioned in this chapter and taking the utmost care while installing and configuring the NetBeans IDE along with its integrated GlassFish application server, you may face problems while running the sample code that accompanies this book. This section will try to highlight issues that you may come across and provides information on how to mitigate them.
Figure 1-12. The GlassFish administration console
“No Compatible JDK was found” warning during installation
You get a No compatible JDK was found warning message on the first page of the NetBeans installer wizard.
Diagnosis
Samples in this book require NetBeans version 7.3 or later. NetBeans 7.3 in turn requires Java Platform (JDK) 7. You will get a No compatible JDK was found warning message if Java Platform (JDK) 7 is not installed on your machine.
Solution
You will have to exit the wizard and install Java Platform (JDK) 7 after downloading it from the following location. http://www.oracle.com/technetwork/java/javase/downloads/index.html
Unable to see GlassFish server’s test page
You are unable to see the GlassFish server’s test page as shown in Figure 1-11, after installing the NetBeans IDE and its integrated GlassFish application server.
Diagnosis
You may not able to see the test page because of the following reasons: GlassFish server is not running.
Browser is unable to resolve the server’s hostname. •
Incorrect port number is mentioned in the URL.
Solution
Start/restart the GlassFish server using the context menu as shown in Figure
1-10
Verify that the machine name or the IP address that is used in the URL is correct. You can find
your machine’s IP address by executing the ipconfig command on your Windows machine’s command prompt. If you are using localhost then verify that the browser is able to resolve it by looping it back to your machine’s IP address.
Verify that the port number used in the URL is correct. This solution is explained in a section
that follows.
Unable to resolve “localhost” hostname
Your browser or the NetBeans IDE’s tester is able to run the GlassFish server’s test page using the machine name or the IP address but is unable to resolve the localhost hostname.
Diagnosis
The NetBeans IDE’s tester or the browser is unable to loopback to your machine using localhost.
Solution
Update the C:\Windows\System32\drivers\etc\hosts file of your Windows machine to add an entry that maps the IP address of your machine to localhost.
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
<IP address of your machine> localhost
Browser is unable to connect to “8080” port
The host name part of your URL is correct, but your browser is unable to connect to the GlassFish application server at port 8080.
Diagnosis
Your browser will be unable to use the 8080 port number for the GlassFish application server if it is used by another application. During installation the configuration tool will first try to assign the 8080 port to the GlassFish application server, but if it detects that the 8080 port number is unavailable then it will assign a different port number to it.
Solution
You can find the port at which GlassFish application server is running with the following steps:
Navigate to the
• Services tab of the NetBeans IDE and invoke the context menu on the GlassFish server node as shown in Figure 1-10.
Select the • Properties menu option to open the Servers dialog.
Select the GlassFish server instance in the left panel. •
The
• Location text field, under the Common tab, will show the port number at which the GlassFish application server is running.
Errors while compiling or executing sample application projects
You get compilation errors after opening the sample application project, or the sample application project does not execute as expected.
Diagnosis
The samples provided as part of this book are tested with NetBeans version 7.3 and Java Platform (JDK) 7.
You might get the “javac: invalid target release: 1.7” error while compiling the sample application projects provided with this book if the NetBeans IDE is not configured to use Java Platform (JDK) 7.
The sample application code contains hard-coded port numbers corresponding to the NetBeans installation on which they were created. The sample will not execute as expected if the port number hard-coded in the sample code is different from your NetBeans installation.
Solution
To resolve the “javac: invalid target release: 1.7” error, you have to verify that NetBeans is using Java Platform (JDK) 7. You may have to install it from the URL mentioned in the earlier sections.
If the sample application is not working as expected, then verify that the port numbers used by the sample code are same as that of your NetBeans installation.
You can consult the Readme.txt file provided with each sample application for additional information.
Unable to send or receive the “wine order” mail
You are unable to send or receive the “wine order” mail while executing the sample application project.
Diagnosis
Few sample projects send out a mail as part of their execution. You may have trouble sending the mail and may not receive it because of the following reasons:
You have not updated the • from and to e-mail addresses in the sample code.
You are running the sample on a machine that is behind a firewall. •
• JMS Resource configuration is incorrect.
• JavaMail Session configuration is incorrect.
Solution
Before you execute the sample application project that sends out a mail, verify that:
You have created and configured the
• JMS Resource as shown in Chapter 5.
You have created and configured the • JavaMail Session as shown in Chapter 5.
• from and to e-mail addresses in the sample’s source code.
•
You have updated the
You are not behind a firewall.
You can consult the Readme.txt file provided with the sample application of Chapter 5 for information on how to configure JavaMail Session properties for popular mail services.
Even after verifying these details, if you are facing problems in sending or receiving the mail, then check the GlassFish server log for any more details on the issue.
Conclusion
This chapter opened with an introduction to this book and EJB. This orientation covered essential information about the core features of EJB, the EJB framework, and the component model. It included a brief overview of the history of EJB, the EJB 3 simplified development model, and the EJB distributed computing model.
In the “How This Book Is Organized” section, we provided a summary of each chapter to illustrate the general flow of the book, and to help you decide which areas to focus on first, should you wish to read the chapters out of sequence.
The chapter concluded with a “Getting Started” section to help you install and configure the NetBeans IDE and its integrated GlassFish application server, which has the reference implementation of the latest Java EE specifications, and to verify that the installation was successful. Having completed this task, you now have the required software infrastructure to run the code samples in this book and to examine the many features of EJB throughout the subsequent chapters.
When Do You Use Session Beans?
Session beans are used to write business logic, maintain a conversation state for the client, and model back-end processes or user tasks that perform one or more business operations. Typical examples include the following:
A session bean in a human resources application that creates a new employee and assigns the
employee to a particular department
A session bean in an expense reporting application that creates a new expense report
A session bean in an order entry application that creates a new order for a particular customer
A session bean that manages the contents of a shopping cart in an e-commerce application
A session bean that leverages transaction services in an EJB container (removing the need for
an application developer to write the transaction support)
A session bean used to address deployment requirements when the client applications are not
collocated on the same server
A session bean that leverages the security support provided by the container on the
component or method level
A session bean that implements logging functionality and is shared between different
components of an application
Session beans can be used in traditional 2-tier or 3-tier architectures with professional/rich client applications, or in 3-tier web-based applications. These applications can be deployed in different logical and physical tier combinations. In the next section, we will investigate some of the possible combinations.
3-Tier Architecture with Rich Client
Figure 2-1 shows a typical architecture for a session bean in 3 tiers with a rich client front-end application that has some data entry screens used by end users, such as customer service representatives, bank tellers, and so on. These client applications can be developed using Java Swing technology with the Java Platform, Standard Edition (Java SE), or they can be plain old Java objects (POJOs), which are run from the command line. Generally, the end user launches the client application from his or her desktop, enters some data, and triggers an event by pressing some user interface component, such as a Submit button. The general workflow may look something like this:
1. User action establishes a connection to the session bean running in the EJB container using remote method invocation (RMI).
2. The client application invokes one or more business methods in the session bean.
3. The session bean processes the request and validates data by interacting with databases, enterprise applications, legacy systems, and so on to perform a certain business operation or task.
4. Finally, the session bean sends a response back to the client application, either through data collections or simple objects that contain acknowledgment messages.
3-Tier Architecture for a Web Application
This architecture, as shown in Figure 2-2, is typically front-ended by a web application running in the browser of a desktop or laptop computer. These days, other types of client devices, such as smart phones, tablets, cell phones, and telnet devices, are also being used to run these applications. The web application running in a browser or mobile device renders the user interface (data entry screens, submit buttons, and so on) using web technologies such as JavaServer Pages (JSP), JavaServer Faces (JSF), or Java Servlets. Typical user actions, such as entering search criteria or adding certain items to the web application shopping cart, will invoke/call session beans running in an EJB container via one of the aforementioned web technologies. Once the session bean gets invoked, it processes the request and sends a response back to the web application, which formats the response as required and then sends the response on to the requesting client device (browser, smart phone, telnet, and so forth).

In the 3-tier architecture just discussed, the client application (which is the web application) and the session beans can be run within the same instance of an application server (collocated) or from different instances running on the same machine. They can also be run on physically-separate machines that have an instance of an application server.
Figure 2-1. Session beans in a 3-tier architecture with a Rich Client
Figure 2-2. Session beans in a 3-tier architecture with a web application
Another random document with no related content on Scribd:
remember her very well, she was German. Else Weining, her name was—before the war she would come with a girl she’d picked up here in Paris, just a common whore, a most curious business. They were deeply in love. They would sit at a table in the corner—I can show you their actual table. They never talked much and they drank very little; as far as the drink went those two were bad clients, but so interesting that I did not much mind—I grew almost attached to Else Weining. Sometimes she would come all alone, come early. “Pu,” she would say in her hideous French; “Pu, she must never go back to that hell.” Hell! Sacrénom—she to call it hell! Amazing they are, I tell you, these people. Well, the girl went back, naturally she went back, and Else drowned herself in the Seine. Amazing they are—ces invertis, I tell you!’
But not all the histories were so tragic as this one; Monsieur Pujol found some of them quite amusing. Quarrels galore he was able to relate, and light infidelities by the dozen. He would mimic a manner of speech, a gesture, a walk—he was really quite a good mimic—and when he did this his friends were not bored; they would sit there and split their sides with amusement.
And now Monsieur Pujol was laughing himself, cracking jokes as he covertly watched his clients. From where she and Mary sat near the door, Stephen could hear his loud, jovial laughter
‘Lord,’ sighed Pat, unenlivened as yet by the beer; ‘some people do seem to feel real good this evening.’
Wanda, who disliked the ingratiating Pujol, and whose nerves were on edge, had begun to grow angry. She had caught a particularly gross blasphemy, gross even for this age of stupid blaspheming. ‘Le salaud!’ she shouted, then, inflamed by drink, an epithet even less complimentary.
‘Hush up, do!’ exclaimed the scandalized Pat, hastily gripping Wanda’s shoulder.
But Wanda was out to defend her faith, and she did it in somewhat peculiar language.
People had begun to turn round and stare; Wanda was causing quite a diversion. Dickie grinned and skilfully egged her on, not
perceiving the tragedy that was Wanda. For in spite of her tender and generous heart, Dickie was still but a crude young creature, one who had not yet learnt how to shiver and shake, and had thus remained but a crude young creature. Stephen glanced anxiously at Mary, half deciding to break up this turbulent party; but Mary was sitting with her chin on her hand, quite unruffled, it seemed, by Wanda’s outburst. When her eyes met Stephen’s she actually smiled, then took the cigarette that Jeanne Maurel was offering; and something in this placid, self-assured indifference went so ill with her youth that it startled Stephen. She in her turn must quickly light a cigarette, while Pat still endeavoured to silence Wanda.
Valérie said with her enigmatic smile: ‘Shall we now go on to our next entertainment?’
They paid the bill and persuaded Wanda to postpone her abuse of the ingratiating Pujol. Stephen took one arm, Dickie West the other, and between them they coaxed her into the motor; after which they all managed to squeeze themselves in—that is, all except Dickie, who sat by the driver in order to guide the innocent Burton.
3
A L N they surprised what at first appeared to be the most prosaic of family parties. It was late, yet the mean room was empty of clients, for Le Narcisse seldom opened its eyes until midnight had chimed from the church clocks of Paris. Seated at a table with a red and white cloth were the Patron and a lady with a courtesy title. ‘Madame,’ she was called. And with them was a girl, and a handsome young man with severely plucked eyebrows. Their relationship to each other was . . . well . . . all the same, they suggested a family party. As Stephen pushed open the shabby swing door, they were placidly engaged upon playing belotte.
The walls of the room were hung with mirrors thickly painted with cupids, thickly sullied by flies. A faint blend of odours was wafted from the kitchen which stood in proximity to the toilet. The host rose at once and shook hands with his guests. Every bar had its social customs, it
seemed. At the Ideal one must share Monsieur Pujol’s lewd jokes; at Le Narcisse one must gravely shake hands with the Patron.
The Patron was tall and exceedingly thin—a clean-shaven man with the mouth of an ascetic. His cheeks were delicately tinted with rouge, his eyelids delicately shaded with kohl; but the eyes themselves were an infantile blue, reproachful and rather surprised in expression.
For the good of the house, Dickie ordered champagne; it was warm and sweet and unpleasantly heady. Only Jeanne and Mary and Dickie herself had the courage to sample this curious beverage. Wanda stuck to her brandy and Pat to her beer, while Stephen drank coffee; but Valérie Seymour caused some confusion by gently insisting on a lemon squash—to be made with fresh lemons. Presently the guests began to arrive in couples. Having seated themselves at the tables, they quickly became oblivious to the world, what with the sickly champagne and each other. From a hidden recess there emerged a woman with a basket full of protesting roses. The stout vendeuse wore a wide wedding ring—for was she not a most virtuous person? But her glance was both calculating and shrewd as she pounced upon the more obvious couples; and Stephen watching her progress through the room, felt suddenly ashamed on behalf of the roses. And now at a nod from the host there was music; and now at a bray from the band there was dancing. Dickie and Wanda opened the ball—Dickie stodgy and firm, Wanda rather unsteady. Others followed. Then Mary leant over the table and whispered:
‘Won’t you dance with me, Stephen?’
Stephen hesitated, but only for a moment. Then she got up abruptly and danced with Mary.
The handsome young man with the tortured eyebrows was bowing politely before Valérie Seymour. Refused by her, he passed on to Pat, and to Jeanne’s great amusement was promptly accepted.
Brockett arrived and sat down at the table. He was in his most prying and cynical humour. He watched Stephen with coldly observant eyes, watched Dickie guiding the swaying Wanda, watched Pat in the arms of the handsome young man, watched the whole bumping, jostling crowd of dancers.
The blended odours were becoming more active. Brockett lit a cigarette. ‘Well, Valérie darling? You look like an outraged Elgin marble. Be kind, dear, be kind; you must live and let live, this is life. . . .’ And he waved his soft, white hands. ‘Observe it—it’s very wonderful, darling. This is life, love, defiance, emancipation!’
Said Valérie with her calm little smile: ‘I think I preferred it when we were all martyrs!’
The dancers drifted back to their seats and Brockett manœuvred to sit beside Stephen. ‘You and Mary dance well together,’ he murmured. ‘Are you happy? Are you enjoying yourselves?’
Stephen, who hated this inquisitive mood, this mood that would feed upon her emotions, turned away as she answered him, rather coldly: ‘Yes, thanks—we’re not having at all a bad evening.’
And now the Patron was standing by their table; bowing slightly to Brockett he started singing. His voice was a high and sweet baritone; his song was of love that must end too soon, of life that in death is redeemed by ending. An extraordinary song to hear in such a place— melancholy and very sentimental. Some of the couples had tears in their eyes—tears that had probably sprung from champagne quite as much as from that melancholy singing. Brockett ordered a fresh bottle to console the Patron. Then he waved him away with a gesture of impatience.
There ensued more dancing, more ordering of drinks, more dalliance by the amorous couples. The Patron’s mood changed, and now he must sing a song of the lowest boites in Paris. As he sang he skipped like a performing dog, grimacing, beating time with his hands, conducting the chorus that rose from the tables.
Brockett sighed as he shrugged his shoulders in disgust, and once again Stephen glanced at Mary; but Mary, she saw, had not understood that song with its inexcusable meaning. Valérie was talking to Jeanne Maurel, talking about her villa at St. Tropez; talking of the garden, the sea, the sky, the design she had drawn for a green marble fountain. Stephen could hear her charming voice, so cultured, so cool —itself cool as a fountain; and she marvelled at this woman’s perfect poise, the genius she possessed for complete detachment; Valérie had
closed her ears to that song, and not only her ears but her mind and spirit.
The place was becoming intolerably hot, the room too overcrowded for dancing. Lids drooped, mouths sagged, heads lay upon shoulders—there was kissing, much kissing at a table in the corner. The air was fœtid with drink and all the rest; unbreathable it appeared to Stephen. Dickie yawned an enormous, uncovered yawn; she was still young enough to feel rather sleepy. But Wanda was being seduced by her eyes, the lust of the eye was heavy upon her, so that Pat must shake a lugubrious head and begin to murmur anent General Custer.
Brockett got up and paid the bill; he was sulky, it seemed, because Stephen had snubbed him. He had not spoken for quite half an hour, and refused point-blank to accompany them further. ‘I’m going home to my bed, thanks—good morning,’ he said crossly, as they crowded into the motor.
They drove to a couple more bars, but at these they remained for only a very few minutes. Dickie said they were dull and Jeanne Maurel agreed—she suggested that they should go on to Alec’s.
Valérie lifted an eyebrow and groaned. She was terribly bored, she was terribly hungry. ‘I do wish I could get some cold chicken,’ she murmured.
A as she lived Stephen never forgot her first impressions of the bar known as Alec’s—that meeting-place of the most miserable of all those who comprised the miserable army. That merciless, drugdealing, death-dealing haunt to which flocked the battered remnants of men whom their fellow men had at last stamped under; who, despised of the world, must despise themselves beyond all hope, it seemed, of salvation. There they sat, closely herded together at the tables, creatures shabby yet tawdry, timid yet defiant—and their eyes, Stephen never forgot their eyes, those haunted, tormented eyes of the invert.
Of all ages, all degrees of despondency, all grades of mental and physical ill-being, they must yet laugh shrilly from time to time, must yet tap their feet to the rhythm of music, must yet dance together in response to the band—and that dance seemed the Dance of Death to Stephen. On more than one hand was a large, ornate ring, on more than one wrist a conspicuous bracelet; they wore jewelry that might only be worn by these men when they were thus gathered together At Alec’s they could dare to give way to such tastes—what was left of themselves they became at Alec’s.
Bereft of all social dignity, of all social charts contrived for man’s guidance, of the fellowship that by right divine should belong to each breathing, living creature; abhorred, spat upon, from their earliest days the prey to a ceaseless persecution, they were now even lower than their enemies knew, and more hopeless than the veriest dregs of creation. For since all that to many of them had seemed fine, a fine, selfless and at times even noble emotion, had been covered with shame, called unholy and vile, so gradually they themselves had sunk down to the level upon which the world placed their emotions. And looking with abhorrence upon these men, drink-sodden, doped as were only too many, Stephen yet felt that some terrifying thing stalked abroad in that unhappy room at Alec’s; terrifying because if there were a God His anger must rise at such vast injustice. More pitiful even than her lot was theirs, and because of them mighty should be the world’s reckoning.
Alec the tempter, the vendor of dreams, the dispenser of illusions whiter than snow; Alec, who sold little packets of cocaine for large bundles of notes, was now opening wine, with a smile and a flourish, at the next-door table.
He set down the bottle: ‘Et voilà, mes filles!’
Stephen looked at the men; they seemed quite complacent.
Against the wall sat a bald, flabby man whose fingers crept over an amber chaplet. His lips moved; God alone knew to whom he prayed, and God alone knew what prayers he was praying—horrible he was, sitting there all alone with that infamous chaplet between his fingers.
The band struck up a onestep. Dickie still danced, but with Pat, for Wanda was now beyond dancing. But Stephen would not dance, not among these men, and she laid a restraining hand upon Mary. Despite her sense of their terrible affliction, she could not dance in this place with Mary.
A youth passed with a friend and the couple were blocked by the press of dancers in front of her table. He bent forward, this youth, until his face was almost on a level with Stephen’s—a grey, drug-marred face with a mouth that trembled incessantly.
‘Ma sœur,’ he whispered.
For a moment she wanted to strike that face with her naked fist, to obliterate it. Then all of a sudden she perceived the eyes, and the memory came of a hapless creature, distracted, bleeding from bursting lungs, hopelessly pursued, glancing this way, then that, as though looking for something, some refuge, some hope—and the thought: ‘It’s looking for God who made it.’
Stephen shivered and stared at her tightly clenched hands; the nails whitened her flesh. ‘Mon frère,’ she muttered.
And now some one was making his way through the crowd, a quiet, tawny man with the eyes of the Hebrew; Adolphe Blanc, the gentle and learned Jew, sat down in Dickie’s seat beside Stephen. And he patted her knee as though she were young, very young and in great need of consolation.
‘I have seen you for quite a long time, Miss Gordon. I’ve been sitting just over there by the window.’ Then he greeted the others, but the greeting over he appeared to forget their very existence; he had come, it seemed, only to talk to Stephen.
He said: ‘This place—these poor men, they have shocked you. I’ve been watching you in between the dances. They are terrible, Miss Gordon, because they are those who have fallen but have not risen again—there is surely no sin so great for them, so unpardonable as the sin of despair; yet as surely you and I can forgive. . . .’
She was silent, not knowing what she should answer
But he went on, in no way deterred by her silence. He spoke softly, as though for her ears alone, and yet as a man might speak when consumed by the flame of some urgent and desperate mission. ‘I am glad that you have come to this place, because those who have courage have also a duty.’
She nodded without comprehending his meaning.
‘Yes, I am glad that you have come here,’ he repeated. ‘In this little room, to-night, every night, there is so much misery, so much despair, that the walls seem almost too narrow to contain it—many have grown callous, many have grown vile, but these things in themselves are despair, Miss Gordon. Yet outside there are happy people who sleep the sleep of the so-called just and righteous. When they wake it will be to persecute those who, through no known fault of their own, have been set apart from the day of their birth, deprived of all sympathy, all understanding. They are thoughtless, these happy people who sleep— and who is there to make them think, Miss Gordon?’
‘They can read,’ she stammered, ‘there are many books. . . .’
But he shook his head. ‘Do you think they are students? Ah, but no, they will not read medical books; what do such people care for the doctors? And what doctor can know the entire truth? Many times they meet only the neurasthenics, those of us for whom life has proved too bitter. They are good, these doctors—some of them very good; they work hard trying to solve our problem, but half the time they must work in the dark—the whole truth is known only to the normal invert. The doctors cannot make the ignorant think, cannot hope to bring home the sufferings of millions; only one of ourselves can some day do that. . . . It will need great courage but it will be done, because all things must work toward ultimate good; there is no real wastage and no destruction.’ He lit a cigarette and stared thoughtfully at her for a moment or two. Then he touched her hand. ‘Do you comprehend? There is no destruction.’
She said: ‘When one comes to a place like this, one feels horribly sad and humiliated. One feels that the odds are too heavily against any real success, any real achievement. Where so many have failed who can hope to succeed? Perhaps this is the end.’
Adolphe Blanc met her eyes. ‘You are wrong, very wrong—this is only the beginning. Many die, many kill their bodies and souls, but they cannot kill the justice of God, even they cannot kill the eternal spirit. From their very degradation that spirit will rise up to demand of the world compassion and justice.’
Strange—this man was actually speaking her thoughts, yet again she fell silent, unable to answer.
Dickie and Pat came back to the table, and Adolphe Blanc slipped quietly away; when Stephen glanced round his place was empty, nor could she perceive him crossing the room through the press and maze of those terrible dancers.
5
D went sound asleep in the car with her head against Pat’s inhospitable shoulder. When they got to her hotel she wriggled and stretched. ‘Is it . . . is it time to get up?’ she murmured.
Next came Valérie Seymour and Jeanne Maurel to be dropped at the flat on the Quai Voltaire; then Pat who lived a few streets away, and last but not least the drunken Wanda. Stephen had to lift her out of the car and then get her upstairs as best she could, assisted by Burton and followed by Mary. It took quite a long time, and arrived at the door, Stephen must hunt for a missing latchkey.
When they finally got home, Stephen sank into a chair. ‘Good Lord, what a night—it was pretty awful.’ She was filled with the deep depression and disgust that are apt to result from such excursions.
But Mary pretended to a callousness that in truth she was very far from feeling, for life had not yet dulled her finer instincts; so far it had only aroused her anger. She yawned. ‘Well, at least we could dance together without being thought freaks; there was something in that. Beggars can’t be choosers in this world, Stephen!’
CHAPTER
49
O fine June day Adèle married her Jean in the church of NotreDame-des-Victoires—the shrine of innumerable candles and prayers, of the bountiful Virgin who bestows many graces. From early dawn the quiet old house in the Rue Jacob had been in a flutter— Pauline preparing the déjeuner de noces, Pierre garnishing and sweeping their sitting-room, and both of them pausing from time to time to embrace the flushed cheeks of their happy daughter.
Stephen had given the wedding dress, the wedding breakfast and a sum of money; Mary had given the bride her lace veil, her white satin shoes and her white silk stockings; David had given a large gilt clock, purchased for him in the Palais Royal; while Burton’s part was to drive the bride to the church, and the married pair to the station.
By nine o’clock the whole street was agog, for Pauline and Pierre were liked by their neighbours; and besides, as the baker remarked to his wife, from so grand a house it would be a fine business.
‘They are after all generous, these English,’ said he; ‘and if Mademoiselle Gordon is strange in appearance, one should not forget that she served la France and must now wear a scar as well as ribbon.’ Then remembering his four sons slain in the war, he sighed— sons are sons to a king or a baker.
David, growing excited, rushed up and down stairs with offers to help which nobody wanted, least of all the flustered and anxious bride at the moment of putting on tight satin slippers.
‘Va donc! Tu ne peux pas m’aider, mon chou, veux tu te taire, alors!’ implored Adèle.
In the end Mary had had to find collar and lead and tie David up to the desk in the study, where he brooded and sucked his white satin bow, deciding that only the four-legged were grateful. But at long last Adèle was arrayed to be wed, and must show herself shyly to Mary and Stephen. She looked very appealing with her good, honest face; with her round, bright eyes like those of a blackbird. Stephen wished her well from the bottom of her heart, this girl who had waited so long for her mate—had so patiently and so faithfully waited.
I church were a number of friends and relations; together with those who will journey for miles in order to attend a funeral or wedding. Poor Jean looked his worst in a cheap dress suit, and Stephen could smell the pomade on his hair; very greasy and warm it smelt, although scented. But his hand was unsteady as he groped for the ring, because he was feeling both proud and humble; because, loving much, he must love even more and conceive of himself as entirely unworthy And something in that fumbling, unsteady hand, in that sleekly greased hair and those ill-fitting garments, touched Stephen, so that she longed to reassure, to tell him how great was the gift he offered—security, peace, and love with honour.
The young priest gravely repeated the prayers—ancient, primitive prayers, yet softened through custom. In her mauve silk dress Pauline wept as she knelt; but Pierre’s handkerchief was spread out on the stool to preserve the knees of his new grey trousers. Next to Stephen were sitting Pauline’s two brothers, one in uniform, the other retired and in mufti, but both wearing medals upon their breasts and thus worthily representing the army. The baker was there with his wife and three daughters, and since the latter were still unmarried, their eyes were more often fixed upon Jean in his shoddy dress suit than upon their Missals. The greengrocer accompanied the lady whose chickens it was Pauline’s habit to prod on their breastbones; while the cobbler who mended Pierre’s boots and shoes, sat ogling the buxom and comely young laundress.
The Mass drew to its close. The priest asked that a blessing might be accomplished upon the couple; asked that these two might live to behold, not only their own but their children’s children, even unto the third and fourth generation. Then he spoke of their duty to God and to each other, and finally moistened their bowed young heads with a generous sprinkling of holy water And so in the church of NotreDame-des-Victoires—that bountiful Virgin who bestows many graces —Jean and his Adèle were made one flesh in the eyes of their church, in the eyes of their God, and as one might confront the world without flinching.
Arm in arm they passed out through the heavy swing doors and into Stephen’s waiting motor. Burton smiled above the white favour in his coat; the crowd, craning their necks, were also smiling. Arrived back at the house, Stephen, Mary, and Burton must drink the health of the bride and bridegroom. Then Pierre thanked his employer for all she had done in giving his daughter so splendid a wedding. But when that employer was no longer present, when Mary had followed her into the study, the baker’s wife lifted quizzical eyebrows.
‘Quel type! On dirait plutôt un homme; ce n’est pas celle-là qui trouvera un mari!’
The guests laughed. ‘Mais oui, elle est joliment bizarre’; and they started to make little jokes about Stephen.
Pierre flushed as he leaped to Stephen’s defence. ‘She is good, she is kind, and I greatly respect her and so does my wife—while as for our daughter, Adèle here has very much cause to be grateful. Moreover she gained the Croix de Guerre through serving our wounded men in the trenches.’
The baker nodded. ‘You are quite right, my friend—precisely what I myself said this morning.’
But Stephen’s appearance was quickly forgotten in the jollification of so much fine feasting—a feasting for which her money had paid, for which her thoughtfulness had provided. Jokes there were, but no longer directed at her—they were harmless, well meant if slightly broad jokes made at the expense of the bashful bridegroom. Then before even Pauline had realized the time, there was Burton strolling into the kitchen, and Adèle must rush off to change her dress, while Jean must change also, but in the pantry.
Burton glanced at the clock. ‘Faut dépêcher vous, ’urry, if you’re going to catch that chemin de fer,’ he announced as one having authority. ‘It’s a goodish way to the Guard de Lions.’ 3
T evening the old house seemed curiously thoughtful and curiously sad after all the merry-making. David’s second white bow had come
untied and was hanging in two limp ends from his collar. Pauline had gone to church to light candles; Pierre, together with Pauline’s niece who would take Adèle’s place, was preparing dinner. And the sadness of the house flowed out like a stream to mingle itself with the sadness in Stephen. Adèle and Jean, the simplicity of it . . . they loved, they married, and after a while they would care for each other all over again, renewing their youth and their love in their children. So orderly, placid and safe it seemed, this social scheme evolved from creation; this guarding of two young and ardent lives for the sake of the lives that might follow after. A fruitful and peaceful road it must be. The same road had been taken by those founders of Morton who had raised up children from father to son, from father to son until the advent of Stephen; and their blood was her blood—what they had found good in their day, seemed equally good to their descendant. Surely never was outlaw more law-abiding at heart, than this, the last of the Gordons.
So now a great sadness took hold upon her, because she perceived both dignity and beauty in the coming together of Adèle and Jean, very simply and in accordance with custom. And this sadness mingling with that of the house, widened into a flood that compassed Mary and through her David, and they both went and sat very close to Stephen on the study divan. As the twilight gradually merged into dusk, these three must huddle even closer together—David with his head upon Mary’s lap, Mary with her head against Stephen’s shoulder.
CHAPTER 50 1
S ought to have gone to England that summer; at Morton there had been a change of agent, and once again certain questions had arisen which required her careful personal attention. But time had not softened Anna’s attitude to Mary, and time had not lessened Stephen’s exasperation—the more so as Mary no longer hid the bitterness that she felt at this treatment. So Stephen tackled the business by writing a number of long and wearisome letters, unwilling
to set foot again in the house where Mary Llewellyn would not be welcome. But as always the thought of England wounded, bringing with it the old familiar longing—homesick she would feel as she sat at her desk writing those wearisome business letters. For even as Jamie must crave for the grey, wind-swept street and the wind-swept uplands of Beedles, so Stephen must crave for the curving hills, for the long green hedges and pastures of Morton. Jamie openly wept when such moods were upon her, but the easement of tears was denied to Stephen.
In August Jamie and Barbara joined them in a villa that Stephen had taken at Houlgate. Mary hoped that the bathing would do Barbara good; she was not at all well. Jamie worried about her. And indeed the girl had grown very frail, so frail that the housework now tried her sorely; when alone she must sit down and hold her side for the pain that was never mentioned to Jamie. Then too, all was not well between them these days; poverty, even hunger at times, the sense of being unwanted outcasts, the knowledge that the people to whom they belonged—good and honest people—both abhorred and despised them, such things as these had proved very bad housemates for sensitive souls like Barbara and Jamie.
Large, helpless, untidy and intensely forlorn, Jamie would struggle to finish her opera; but quite often these days she would tear up her work, knowing that what she had written was unworthy. When this happened she would sigh and peer round the studio, vaguely conscious that something was not as it had been, vaguely distressed by the dirt of the place to which she herself had helped to contribute— Jamie, who had never before noticed dirt, would feel aggrieved by its noxious presence. Getting up she would wipe the keys of the piano with Barbara’s one clean towel dipped in water
‘Can’t play,’ she would grumble, ‘these keys are all sticky.’
‘Oh, Jamie—my towel—go and fetch the duster!’
The quarrel that ensued would start Barbara’s cough, which in turn would start Jamie’s nerves vibrating. Then compassion, together with unreasoning anger and a sudden uprush of sex-frustration, would make her feel well-nigh beside herself—since owing to Barbara’s failing health, these two could be lovers now in name only. And this
forced abstinence told on Jamie’s work as well as her nerves, destroying her music, for those who maintain that the North is cold, might just as well tell us that hell is freezing. Yet she did her best, the poor uncouth creature, to subjugate the love of the flesh to the pure and more selfless love of the spirit—the flesh did not have it all its own way with Jamie.
That summer she made a great effort to talk, to unburden herself when alone with Stephen; and Stephen tried hard to console and advise, while knowing that she could help very little. All her offers of money to ease the strain were refused point-blank, sometimes almost with rudeness—she felt very anxious indeed about Jamie.
Mary in her turn was deeply concerned; her affection for Barbara had never wavered, and she sat for long hours in the garden with the girl who seemed too weak to bathe, and whom walking exhausted.
‘Let us help,’ she pleaded, stroking Barbara’s thin hand, ‘after all, we’re much better off than you are. Aren’t you two like ourselves? Then why mayn’t we help?’
Barbara slowly shook her head: ‘I’m all right—please don’t talk about money to Jamie.’
But Mary could see that she was far from all right; the warm weather was proving of little avail, even care and good food and sunshine and rest seemed unable to ease that incessant coughing.
‘You ought to see a specialist at once,’ she told Barbara rather sharply one morning.
But Barbara shook her head yet again: ‘Don’t, Mary—don’t, please . . . you’ll be frightening Jamie.’
A their return to Paris in the autumn, Jamie sometimes joined the nocturnal parties; going rather grimly from bar to bar, and drinking too much of the crème-de-menthe that reminded her of the bull’s eyes at Beedles. She had never cared for these parties before, but now she was clumsily trying to escape, for a few hours at least, from the pain of
existence. Barbara usually stayed at home or spent the evening with Stephen and Mary. But Stephen and Mary would not always be there, for now they also went out fairly often; and where was there to go to except the bars? Nowhere else could two women dance together without causing comment and ridicule, without being looked upon as freaks, argued Mary. So rather than let the girl go without her, Stephen would lay aside her work—she had recently started to write her fourth novel.
Sometimes, it is true, their friends came to them, a less sordid and far less exhausting business; but even at their own house the drink was too free: ‘We can’t be the only couple to refuse to give people a brandy and soda,’ said Mary, ‘Valérie’s parties are awfully dull; that’s because she’s allowed herself to grow cranky!’
And thus, very gradually just at first, Mary’s finer perceptions began to coarsen.
T passed, and now more than a year had slipped by, yet Stephen’s novel remained unfinished; for Mary’s face stood between her and her work—surely the mouth and the eyes had hardened?
Still unwilling to let Mary go without her, she dragged wearily round to the bars and cafés, observing with growing anxiety that Mary now drank as did all the others—not too much perhaps, but quite enough to give her a cheerful outlook on existence.
The next morning she was often deeply depressed, in the grip of a rather tearful reaction: ‘It’s too beastly—why do we do it?’ she would ask.
And Stephen would answer: ‘God knows I don’t want to, but I won’t let you go to such places without me. Can’t we give it all up? It’s appallingly sordid!’
Then Mary would flare out with sudden anger, her mood changing as she felt a slight tug on the bridle. Were they to have no friends? she would ask. Were they to sit still and let the world crush them? If they were reduced to the bars of Paris, whose fault was that? Not hers and
not Stephen’s. Oh, no, it was the fault of the Lady Annas and the Lady Masseys who had closed their doors, so afraid were they of contamination!
Stephen would sit with her head on her hand, searching her sorely troubled mind for some ray of light, some adequate answer.
4
T winter Barbara fell very ill. Jamie rushed round to the house one morning, hatless, and with deeply tormented eyes: ‘Mary, please come —Barbara can’t get up, it’s a pain in her side. Oh, my God—we quarrelled . . .’ Her voice was shrill and she spoke very fast: ‘Listen— last night—there was snow on the ground, it was cold—I was angry . . . I can’t remember . . . but I know I was angry—I get like that. She went out—she stayed out for quite two hours, and when she came back she was shivering so. Oh, my God, but why did we quarrel, whatever? She can’t move; it’s an awful pain in her side . . .’
Stephen said quietly: ‘We’ll come almost at once, but first I’m going to ring up my own doctor.’
5
B was lying in the tiny room with the eye-shaped window that would not open. The stove had gone out in the studio, and the air was heavy with cold and dampness. On the piano lay some remnants of manuscript music torn up on the previous evening by Jamie.
Barbara opened her eyes: ‘Is that you, my bairn?’
They had never heard Barbara call her that before—the great, lumbering, big-boned, long-legged Jamie.
‘Yes, it’s me.’
‘Come here close . . .’ The voice drifted away.
‘I’m here—oh, I’m here! I’ve got hold of your hand. Look at me, open your eyes again—Barbara, listen, I’m here—don’t you feel me?’
Stephen tried to restrain the shrill, agonized voice: ‘Don’t speak so loud, Jamie, perhaps she’s sleeping;’ but she knew very well that this was not so; the girl was not sleeping now, but unconscious.
Mary found some fuel and lighted the stove, then she started to tidy the disordered studio. Flakes of flue lay here and there on the floor; thick dust was filming the top of the piano. Barbara had been waging a losing fight—strange that so mean a thing as this dust should, in the end, have been able to conquer. Food there was none, and putting on her coat Mary finally went forth in quest of milk and other things likely to come in useful. At the foot of the stairs she was met by the concierge; the woman looked glum, as though deeply aggrieved by this sudden and very unreasonable illness. Mary thrust some money into her hand, then hurried away intent on her shopping.
When she returned the doctor was there; he was talking very gravely to Stephen: ‘It’s double pneumonia, a pretty bad case—the girl’s heart’s so weak. I’ll send in a nurse. What about the friend, will she be any good?’
‘I’ll help with the nursing if she isn’t,’ said Mary.
Stephen said: ‘You do understand about the bills—the nurse and all that?’
The doctor nodded.
They forced Jamie to eat: ‘For Barbara’s sake . . Jamie, we’re with you, you’re not alone, Jamie.’
She peered with her red-rimmed, short-sighted eyes, only half understanding, but she did as they told her. Then she got up without so much as a word, and went back to the room with the eye-shaped window. Still in silence she squatted on the floor by the bed, like a dumb, faithful dog who endured without speaking. And they let her alone, let her have her poor way, for this was not their Calvary but Jamie’s.
The nurse arrived, a calm, practical woman: ‘You’d better lie down for a bit,’ she told Jamie, and in silence Jamie lay down on the floor.
‘No, my dear—please go and lie down in the studio.’
She got up slowly to obey this new voice, lying down, with her face to the wall, on the divan.
The nurse turned to Stephen: ‘Is she a relation?’
Stephen hesitated, then she shook her head.
‘That’s a pity, in a serious case like this I’d like to be in touch with some relation, some one who has a right to decide things. You know what I mean—it’s double pneumonia.’
Stephen said dully: ‘No—she’s not a relation.’
‘Just a friend?’ the nurse queried.
‘Just a friend,’ muttered Stephen.
6
T went back that evening and stayed the night. Mary helped with the nursing; Stephen looked after Jamie.
‘Is she a little—I mean the friend—is she mental at all, do you know?’ The nurse whispered, ‘I can’t get her to speak—she’s anxious, of course; still, all the same, it doesn’t seem natural.’
Stephen said: ‘No—it doesn’t seem natural to you.’ And she suddenly flushed to the roots of her hair. Dear God, the outrage of this for Jamie!
But Jamie seemed quite unconscious of outrage. From time to time she stood in the doorway peering over at Barbara’s wasted face, listening to Barbara’s painful breathing, and then she would turn her bewildered eyes on the nurse, on Mary, but above all on Stephen.
‘Jamie—come back and sit down by the stove; Mary’s there, it’s all right.’
Came a queer, halting voice that spoke with an effort: ‘But . . . Stephen . . . we quarrelled.’
‘Come and sit by the stove—Mary’s with her, my dear.’
‘Hush, please,’ said the nurse, ‘you’re disturbing my patient.’
B ’ fight against death was so brief that it hardly seemed in the nature of a struggle. Life had left her no strength to repel this last foe— or perhaps it was that to her he seemed friendly. Just before her death she kissed Jamie’s hand and tried to speak, but the words would not come—those words of forgiveness and love for Jamie.
Then Jamie flung herself down by the bed, and she clung there, still in that uncanny silence. Stephen never knew how they got her away while the nurse performed the last merciful duties.
But when flowers had been placed in Barbara’s hands, and Mary had lighted a couple of candles, then Jamie went back and stared quietly down at the small, waxen face that lay on the pillow; and she turned to the nurse:
‘Thank you so much,’ she said, ‘I think you’ve done all that there is to do—and now I suppose you’ll want to be going?’
The nurse glanced at Stephen.
‘It’s all right, we’ll stay. I think perhaps—if you don’t mind, nurse . . .’
‘Very well, it must be as you wish, Miss Gordon.’
When she had gone Jamie veered round abruptly and walked back into the empty studio. Then all in a moment the floodgates gave way and she wept and she wept like a creature demented. Bewailing the life of hardship and exile that had sapped Barbara’s strength and weakened her spirit; bewailing the cruel dispensation of fate that had forced them to leave their home in the Highlands; bewailing the terrible thing that is death to those who, still loving, must look upon it. Yet all the exquisite pain of this parting seemed as nothing to an anguish that was far more subtle: ‘I can’t mourn her without bringing shame on her name—I can’t go back home now and mourn her,’ wailed Jamie; ‘oh, and I want to go back to Beedles, I want to be home among our own people—I want them to know how much I loved her. Oh God, oh God! I can’t even mourn her, and I want to grieve for her home there in Beedles.’