+ All Categories
Home > Documents > Java Ee Foundations

Java Ee Foundations

Date post: 06-Apr-2018
Category:
Upload: dgramma
View: 226 times
Download: 0 times
Share this document with a friend

of 229

Transcript
  • 8/2/2019 Java Ee Foundations

    1/229

    Java EE Foundations

    n + 1, Inc

  • 8/2/2019 Java Ee Foundations

    2/229

    Copyright (c) v1.0.0 2010 n + 1, Inc. Permission is granted to copy, distribute and/or modifythis document under the terms of the GNU Free Documentation License, Version 1.3 or any laterversion published by the Free Software Foundation; with no Invariant Sections, no Front-CoverTexts, and no Back-Cover Texts. A copy of the license is included in the section entitled GNU FreeDocumentation License.

    Page 2 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    3/229

    Contents

    1 Java EE Overview 13

    1.1 Java EE Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    1.1.1 Servlets and Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    1.1.2 Java Transaction API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    1.1.3 Java Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    1.1.4 Java Naming And Directory Interface . . . . . . . . . . . . . . . . . . . . . . . 17

    1.1.5 JavaMail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    1.1.6 Enterprise Java Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    1.1.7 Java IDL /RMI /RMI-IIOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    1.1.8 Java Messaging Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    1.1.9 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    1.2 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    1.2.1 Creating A Customer Annotation . . . . . . . . . . . . . . . . . . . . . . . . . 24

    1.2.2 Associating Annotations With A Class . . . . . . . . . . . . . . . . . . . . . . . 25

    1.2.3 Multiple Value Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    1.2.4 Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    1.3 Lab Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    2 Session Beans 33

    2.1 What Is A Session Bean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    3

  • 8/2/2019 Java Ee Foundations

    4/229

    CONTENTS

    2.1.1 Stateless Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    2.1.2 Stateful Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    2.2 How Session Beans Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    2.2.1 Proxy /Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    2.2.2 EJB Container Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    2.2.3 Bean Instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    2.3 Developing a Session EJB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    2.3.1 Remote and Local Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372.3.2 Session Bean POJO Implementation . . . . . . . . . . . . . . . . . . . . . . . . 38

    2.4 Building EAR Deployment File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    2.4.1 Compiling With ANT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    2.4.2 Packaging EJBs With ANT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    2.4.3 EAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    2.5 Accessing Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    2.5.1 JNDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    2.5.2 Accessing Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    2.6 Life Cycle Of Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    2.6.1 Stateless Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    2.6.2 Stateful Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    2.7 Lab Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    3 Entity Beans 53

    3.1 What is an Entity Bean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

    3.1.1 Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    3.1.2 Entity Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    3.2 Creating An Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    3.2.1 Mapping to Database Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

    3.3 Using An Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    Page 4 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    5/229

    Java EE Foundations

    3.3.1 Obtaining The Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    3.3.2 Entity Manager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

    3.3.3 Updating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

    3.4 Example Session Bean to Manage Employee Entity . . . . . . . . . . . . . . . . . . . . 73

    3.4.1 Employee Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    3.4.2 Employee Manager Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . 76

    3.4.3 Adding New Employee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

    3.4.4 Finding Employees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783.4.5 Removing Employees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    3.4.6 Updating Employee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

    3.4.7 Finding Multiple Employees . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    3.5 DataSources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

    3.5.1 Persistence Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

    3.6 Ant Build Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

    3.7 Lab Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

    4 Entity Beans 89

    4.1 Entity Bean Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

    4.1.1 One to One Unidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

    4.1.2 One to One Bidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

    4.1.3 One to Many Unidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

    4.1.4 Many to One Unidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

    4.1.5 One to Many Bidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

    4.1.6 Many to Many Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

    4.2 Multiple Relationship Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

    4.2.1 Lists and Ordered By . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

    4.2.2 Fetch Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

    4.2.3 Cascading Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

    Page 5 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    6/229

    CONTENTS

    4.3 Example Using Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

    4.3.1 Defining Entity Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

    4.3.2 Race Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

    5 Querying Entity beans 137

    5.1 Querying Entity Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

    5.1.1 Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

    5.1.2 Query Result Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

    5.1.3 Introduction to EJBQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

    5.1.4 Navigating Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

    5.2 WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

    5.2.1 EJBQL WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

    5.2.2 Dynamic WHERE Clause Values . . . . . . . . . . . . . . . . . . . . . . . . . . 148

    5.2.3 Comparison Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

    5.2.4 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

    5.2.5 Like Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

    5.2.6 Other Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

    5.2.7 Ordering Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

    5.2.8 Aggregates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

    5.3 Other Persistence Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

    5.3.1 Paging Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

    5.3.2 Named Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

    5.3.3 Native Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

    6 Transactions 167

    6.1 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

    6.1.1 ACID Transaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

    6.1.2 J2EE Container Provides Transaction Management . . . . . . . . . . . . . . . 170

    Page 6 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    7/229

    Java EE Foundations

    6.1.3 Six Transaction Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

    6.1.4 Exceptions and Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

    6.1.5 Isolation Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

    7 JMS And Message Driven Beans 179

    7.1 Java Messaging Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

    7.1.1 Publish /Subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

    7.1.2 Point to Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

    7.2 Message Delivery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

    7.2.1 Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

    7.2.2 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

    7.3 JMS Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

    7.3.1 Message Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

    7.3.2 JMS Message Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

    7.3.3 Sending JMS Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

    7.3.4 Receiving a JMS Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

    7.3.5 Using Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

    7.4 Message Driven Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

    7.4.1 Creating Message Driven Beans . . . . . . . . . . . . . . . . . . . . . . . . . . 202

    7.4.2 Deploying A Message Driven Bean . . . . . . . . . . . . . . . . . . . . . . . . 204

    7.4.3 Messaging MDB From Session Bean . . . . . . . . . . . . . . . . . . . . . . . . 205

    8 JavaMail 207

    8.1 JavaMail API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

    8.1.1 Mail Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

    8.1.2 Email Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

    8.1.3 MIME Email Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

    8.1.4 Message Recipients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

    Page 7 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    8/229

    CONTENTS

    8.1.5 Message Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

    8.1.6 Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

    8.1.7 Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

    Appendices 219

    A GNU Free Documentation License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

    Page 8 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    9/229

    List of Tables

    3.1 Common EntityManager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    3.2 Temporal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    3.3 Common EntityManager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

    4.1 Cascade Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

    5.1 EntityManager Query Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

    5.2 Query Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

    5.3 Temporal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

    5.4 Comparison Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

    5.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

    5.6 Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

    6.1 Isolation Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

    7.1 Mapping Of Topic To Queue Equivalents . . . . . . . . . . . . . . . . . . . . . . . . . 190

    7.2 JMS Header Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1937.3 JMS Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

    7.4 JMS Message Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

    9

  • 8/2/2019 Java Ee Foundations

    10/229

    LIST OF TABLES

    Page 10 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    11/229

    List of Programs

    1 Race Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

    2 TimeSplit Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1333 RaceManager Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1344 RaceManager Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

    11

  • 8/2/2019 Java Ee Foundations

    12/229

    LIST OF PROGRAMS

    Page 12 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    13/229

    Chapter 1

    Java EE Overview

    Objectives

    Understand the basic components contained within Java EE framework

    Understand what an annotation is

    Learn how to create custom annotations

    13

  • 8/2/2019 Java Ee Foundations

    14/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.1 Java EE Overview

    Java EE (Java Enterprise Edition) is a set of integrated services that allow developers to quicklycreate enterprise quality solutions. The focus of Java EE is to provide enterprise quality middle-ware services that allow the developers to focus on the business logic of the application and notthe development infrastructure. This allows applications to quickly scale with less work fromdevelopers.

    1.1.1 Servlets and Java Server Pages

    Servlets and Java Server Pages provide dynamic content for web servers and are an entry point intothe entire Java EE environment. The JSP and servlets provide a web based presentation layer for

    business applications.

    Client browsers send a HTTP request to the web server requesting a particular JSP or servlet. Theweb server can be any of the main web servers such as Apache and IIS. The web server takes theHTTP request and passes it along to the servlet container.

    The servlet engine takes the incoming HTTP request and transforms it into a HttpServletRequestobject to be handled by the servlets. The servlets then use access to the Java EE environmentto apply business logic to the incoming request. The resulting response is encapsulated withina HttpServletResponse object. The HttpServletResponse contains the data being sent back to theclient.

    The servlet engine takes the HttpServletResponse and translates it into a HTTP Response which isreturned to the browser. The browser then renders the HTML.

    At this point it is important to note that Java Server Pages become compiled into servlets so theyare treated identically as servlets within the servlet container.

    Page 14 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    15/229

    Java EE Foundations

    1.1.2 Java Transaction API

    The JTA provides an APIfor easilycreatingand managing transactions within the Java environment.It supports start, commit, abort, and rollback actions necessary for ACID compliant transactions.

    Atomic commands within a transaction either all succeed or all fail.

    Consistency the state of the database is in a consistent state at all times

    Isolation transactions are isolated from one another. Thus they can not step on each others toes.

    Durable Once a transaction is committed the the update will survive even if the system fails.

    One of the features that Java EE containers provide is integration of the JTA with Enterprise JavaBeans. Making it a trivial process to set up transaction capabilities for methods associated withenterprise beans.

    Page 15 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    16/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.1.3 Java Database Connectivity

    JDBC is a vendor independent API for connecting to SQL databases. Each database providesa concrete implementation of the JDBC API. Using a common interface means that applicationscan easily port from one database to another without having to re-write the source code of theapplication to deal with different SQL database programming interfaces.

    JDBC is a simple connection based API fro making single connections to the database. Java EEcontainers take this single connection technology and provides access to them through datasources.A datasource is a pool of database connections that can be shared across multiple applications.

    Page 16 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    17/229

    Java EE Foundations

    1.1.4 Java Naming And Directory Interface

    The JNDI provides an API for finding and accessing services which are organized into a hierarchicalstructure. The concrete implementations of the hierarchical database are provided by each Java EEcontainer.

    The important need for JNDI is that it allows developers to find resource across the network froma single location. It allows developers to find and access remote resources seamlessly within anapplication.

    JNDI can be used to gain access to a wide range of resource including both Enterprise Java beansand JDBC database connections. Thus developers do not have to hard code resource locationswithin the application. Allowing the system administrators the flexibility to move resources across

    machines and change the location only within the JNDI server.

    Page 17 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    18/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.1.5 JavaMail

    The Java EE platform includes an API for sending and receiving Internet email message from withinJava applications. JavaMail supports MIME encoded email, SMTP, POP, and IMAP protocols. Themail services are available through the JNDI interface.

    Page 18 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    19/229

    Java EE Foundations

    1.1.6 Enterprise Java Beans

    Enterprise Java Beans areone of the cornerstone technologies of the Java EE platform. Beans providethe heart of the business logic, messaging, and data storage of an enterprise application. The beansprovide the developer with key services to assist in creating enterprise solutions.

    The Java EE environment provides the bean with automatic transaction management, state manage-ment, resource pooling, and security. Allowing the developer to worry about the business processesand not the plumbing necessary to build large scale distributed applications.

    Session Beans Session beans are the containers for the business logic. Each bean provides aservice to the outside world. These services can inter-operate, perform transaction management,

    and other tasks necessary for building business processes.

    Entity Beans Entity beans are wrappers for the database layers of a system. Each bean providescontainer managed persistence allowing the developers to create class based representation of datafrom a data store. Such a mechanism simplifies the process of adding, updating, and deleting datafrom the database.

    Message Driven Beans Message driven beans are different from the other two beans. These beansmake it easy to be consumers of JMS messages. They allow developers to provide solutions thatare a asynchronous in nature.

    Page 19 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    20/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.1.7 Java IDL /RMI /RMI-IIOP

    Java IDL provides a utility for creating CORBA (Common Object Request Broker Architecture)objects in Java. CORBA is a platform and language independent method for communicatingacross the network to create distributed applications. CORBA services include naming, security,transaction, and management services necessary for effectively creating distributed environments.CORBA uses the Internet Inter-Orb Protocol (IIOP) for communicating data across the network.

    Java Remote Method Invocation (Java RMI) provides a protocol for communicating between Javaobjects on different Virtual Machines. This makes it simple to create distributed applications withinan all Java application.

    RMI-IIOP extends the Java RMIcommunication protocol to allow RMI method calls to communicate

    over the IIOP protocol. This allows Java applications to easily talk to CORBA object on the network.

    Page 20 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    21/229

    Java EE Foundations

    1.1.8 Java Messaging Service

    JMS is an API for communication between message oriented middleware. It is a messaging servicefor sending messages between applications across the network. It supports two types of deliv-ery mechanisms, a point-to-point and a publish-subscribe system. It is important to note that

    JMS guaranties the delivery of messages allowing developers to be confident about asynchronousdevelopment.

    Like JDBC, JMS is a vendor neutral API. The actual implementation of the messaging services isprovided by the Java EE container. This makes JMS messages platform independent meaning thatyou can easily interchange messaging systems without modifying the code using JMS.

    Page 21 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    22/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.1.9 Web Services

    Web services is another form of distributed computing. It utilizes established technologies tosimplify the process of create distributed applications. Web services make previous distributedenvironments like Java RMI, CORBA, and even Microsofts DCOM obsolete technologies. Theseolder technologies were to limiting (Java RMI only available between Java VMs and DCOM onlyavailable on Windows platforms) or to complicated (CORBA).

    XML The eXtensible Markup Language provides the foundational building blocks for web ser-vices. XML was created as a modular language to represent structured data. There are an extensiveset of tools for defining (XML Schema), parsing (SAX, DOM) and transforming XML data (XSL).All of these tools are license free and platform independent. Web services uses XML to describeservices and the interactions between these services.

    SOAP The Simple Object Access Protocol is the protocol used for web services communications.Generally SOAP messages travel over traditional Internet protocols like HTTP. SOAP messagesare XML documents that are broken into a Header and Body. This dichotomy allows for complexmessaging. The headers are processed by handlers that can provide additional protocol supportthrough third party applications (security, transactions, etc). The body is consumed by the SOAPserver for processing by the server application.

    WSDL The Web Service Description Language is used to describe service endpoints. It includes

    the location of the web service, supported transportation protocols, methods available from theservice, the parameters associated with the method and what the response message will looklike. Tools are available to take WSDL documents and generating code stubs making it easy fordevelopers to connect and consume web services.

    Page 22 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    23/229

    Java EE Foundations

    1.2 Annotations

    With the introduction of Java 5, a new mechanism was created that allowed developers to associatemeta data with Java objects within the source code. The meta data by definition does not effectthe compiled code. It is just information that is attached to a class. The new feature is calledannotations. These annotations provide a syntactical method for for assigning the custom metadata to a class, a classes method, or a classes attributes.

    If the code is not effected, what is the point of using annotations? While annotations do not effectthe compiled code, it is information that can be retrieved at runtime. The information can begathered by tools to perform some special function. The Java EE environment makes heavy use ofthis information to set up the container. The EJB3 specification uses the meta-data to define how

    the beans will interact with the container. It allows the developer to associate the meaningful datawith the actual class instead of being tucked away in one of many XML configuration files.

    Page 23 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    24/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.2.1 Creating A Customer Annotation

    While meta-data can represent a wide range of information, the annotation specification providesa mechanism for ordering the data into defined units. The developer is responsible for definingthe annotation and telling what type of meta-data can be associated with it. In this respect theannotation is a special kind of Java type.

    Java 5 accomplished this by making annotations an extension of the interface. The @ is used tomark the annotation data type. In the example below the Copyright annotation is being defined.

    public @interface Copyright {

    }

    After the annotation is defined, attributes representing the form of the meta-data is associated tothe annotation. In the copyright example, a value needs to be associated to the copyright.

    public @interface Copyright {

    String value();

    }

    One of the strange aspects of annotations is the representation of attributes as methods with a returntype. In this instance the attribute value is associated with the attribute Copyright and is a String.Since annotations are a data type, they must be packaged like any other type.

    package net.nplus1.myannotations;

    public @interface Copyright {

    String value();

    }

    Page 24 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    25/229

    Java EE Foundations

    1.2.2 Associating Annotations With A Class

    Using the annotation is simple. Specify the annotation and define any attributes to be associated.The copyright example has one attribute value. Below is an example of defining the annotation.

    @Copyright(value="2009 n + 1, Inc")

    The annotation can be applied to any class, attribute, or method by placing an instance of theannotation before the artifact.

    @Copyright(value="2009 n + 1, Inc")

    public class SimpleContainer {

    @Copyright(value="2008 n + 1, Inc")

    private Object data;

    public Object getData() {

    return data;

    }

    @Copyright(value="2001")

    public void setData(Object data) {

    this.data = data;

    }

    }

    Remember that annotations are a data type and thus they must be imported before using themwithin the destination class.

    package net.nplus1.containers;

    import net.nplus1.myannotations.Copyright;

    @Copyright(value="2009 n + 1, Inc")

    public class SimpleContainer {

    @Copyright(value="2008 n + 1, Inc")

    private Object data;

    public Object getData() {

    return data;

    }

    @Copyright(value="2001")

    public void setData(Object data) {

    Page 25 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    26/229

    CHAPTER 1. JAVA EE OVERVIEW

    this.data = data;}

    }

    Page 26 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    27/229

    Java EE Foundations

    1.2.3 Multiple Value Annotations

    An annotation isnt restricted to having one value associated with it. Annotations allow for multipleattributes to be defined. Below is an example of defining multiple attributes of varying data types.

    public @interface SummaryNote {

    int id();

    String summary();

    String date();

    }

    Each of these values would have to be defined if the annotation is associated with a particular class.

    @SummaryNote(id=55, summary="This is a test", date="1/13/2009")

    public class SimpleContainer {

    private Object data;

    public Object getData() {

    return data;

    }

    public void setData(Object data) {

    this.data = data;

    }

    }

    In addition to being able to define multiple properties, annotations have a way to provide multiplevalue attributes. It is done by defining the data type as an array. Below is a modification to the lastexample to allow for multiple authors to be defined.

    public @interface SummaryNote {

    int id();

    String summary();

    String date();

    String [] authors ();

    }

    When defining a multi-value attribute the same notation is used when creating an array throughdirect population. Recall how arrays can be initialized by setting the values.

    int [] data = {5, 3, 2, 1};

    In this example a data array of size four is created and it is pre-populated with the values of 5, 3,2, and 1. The same principal applies when setting the value of an annotation with an array. Theexample below defines the authors for the SummaryNote

    Page 27 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    28/229

    CHAPTER 1. JAVA EE OVERVIEW

    @SummaryNote(id=55, summary="This is a test", date="1/13/2009",authors = {"Brian", "Beth"} )

    Notice that the author values are a comma separated list of elements inside of brackets.

    Page 28 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    29/229

    Java EE Foundations

    1.2.4 Default Values

    It would be very cumbersome to work with annotations if a developer had to fill out every value ofthe annotation. Especially if some of the attributes could be set to a reasonable default that wouldonly need to be modified occasionally. Java provides such a mechanism by adding a new keyworddefault. default immediately follows the attribute along with the value to be used if the attributedoesnt exist within an annotation.

    public @interface SummaryNote {

    int id() default 1;

    String summary();

    String date() default "Unknown";

    String [] authors() default {};}

    With defaults set the only annotation attributes that must be defined are ones without a defaultvalue. In this case the summary field is the only mandatory field. Thus the annotation could beused as follows.

    @SummaryNote(summary="This is a test")

    The rest are the attributes are optional and can be defined if the default value is not appropriate.

    @SummaryNote(summary="This is a test", authors={"sarah"})

    It is also worth noting at this point that a single value in an array must be contained within thecurly braces.

    Page 29 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    30/229

    CHAPTER 1. JAVA EE OVERVIEW

    1.3 Lab Activity

    Part 1.

    The @Override annotation is used to ensure that a method is truly overriding a parents implemen-tation.

    Create a class called Test which contains two methods.

    public String toString()

    public String twoString()

    Markboth methods with the @Override annotation. What happens when the Test class is compiled?Why does only 1 method cause the compiler to fail?

    Part 2.

    The @Deprecated annotation can be applied to a method in a class to warn the compiler that theuser is trying to access a method which has been deprecated and should no longer be used.

    Create a class called Person. It should have one attribute name and the following methods:

    public void setName(String n)

    public String getName()

    public void printName()

    Provide an implementation for each of the methods. printName() should display the name on thescreen. Add a @Deprecated annotation to the printName() method.

    Create a second class called PersonTest and should be able to run as a Java application. In the mainmethod create an instance of the Person class and set its name. Call the printName() method toprint the name to the screen.

    Does an warning display when the application is compiled? What is the warning?

    Part 3.

    The @SuppressWarnings annotation is used by the compiler to ignore certain warnings and not

    display them.

    Modify the PersonTestsmain method in Part2 to include the annotation@SuppressWarnings(deprecated)

    What happens to the warning?

    Part 4. Another use for the @SupressWarnings annotation is to handle unchecked types. Create thefollowing Test class

    import java.util.LinkedList;

    Page 30 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    31/229

    Java EE Foundations

    public class ListTest {

    public static void main(String [] args) {

    LinkedList list = new LinkedList();

    list.add("test 1");

    list.add("test 2");

    for ( Object x : list ) {

    System.out.println(x);

    }

    }

    }

    What happens when theclassis compiled? What type of warning is issued? Adda @SupressWarningsannotation to the main method to remove the warning.

    Page 31 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    32/229

    CHAPTER 1. JAVA EE OVERVIEW

    Page 32 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    33/229

    Chapter 2

    Session Beans

    Objectives

    Understand how session beans work

    Learn how to create local and remote interfaces

    Learn how to create bean implementation

    Learn how to deploy session beans

    Learn how to access server side session beans

    Understand session bean state

    Learn how to use state transition annotations

    33

  • 8/2/2019 Java Ee Foundations

    34/229

    CHAPTER 2. SESSION BEANS

    2.1 What Is A Session Bean?

    A session bean is a special type of object that can be deployed into a Java EE environment. The roleof the session bean is to represent the business logic or the logical flow of the application. Session

    beans are good at organizing and executing what is necessary to perform some desired businessrule.

    What makes a session bean different from any other controller type logical mechanism is that it ismanaged by the Java EE container. The Java EE container is in charge of managing the instancesof the bean. The container pools the beans to maximize performance. Providing a highly scalablesolution.

    Their are two types of session beans available, stateless and stateful session bean. A stateless sessionbean does not maintain state between calls on the bean. The developer can not assume that anyattributes of a stateless session bean will be maintained between calls on the bean. A stateful session

    bean is an extension of the client application. It behaves like any other local object and its state,attributes, are guaranteed to be maintained between calls to the object.

    2.1.1 Stateless Session Beans

    The stateless session bean is a collection of independent business methods that are related to oneanother. For example, if a developer was tasked to write code to manage a todo list, a number ofactions would be necessary to manage the list. The developer would need to be able to add, edit,

    or delete items from the list. The code would also need to enumerate the items in the list. Each ofthese actions would be good candidates for compilation within a stateless session bean.

    Because each method is independent of one another, it is unnecessary to maintain stateful informa-tion between calls upon the bean. When developing stateless session beans any atomic method isa good candidate for inclusion within a stateless session bean.

    Why use a session bean? First offthey are easy to develop in EJB3. They require few server resourcesbecause they are not dedicated to a particular client. The solution scales very well.

    2.1.2 Stateful Session Beans

    Stateful session differ from stateless session beans in that they are dedicated to one client for the lifeof the bean. The methods have an interdependence that forces the bean to be associated with justthe single client.

    Take for example an ordering system manager. The ordering of products might be a multi-stepprocess that interacts with a user. The user has to select the items to order and then provideconfirmation for placing the order. The bean might have methods to add items, view items, andthe process order. Since these actions take place over time, the bean would need to store the items

    being ordered between calls and before final authorization.

    Page 34 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    35/229

    Java EE Foundations

    In this case all of the methods are interdependent upon each other for the completion of the businesscase. Therefore they make a good candidate for a stateful session bean. Stateful session beans are

    best used for managing complex tasks and transactions that are not atomic in nature.

    The downside to stateful session beans is the fact that they have a one to one relationship with theclient. Each stateful session bean can only be accessed by one client. Therefore unlike statelesssession beans which can share instances, there will have to be one stateful bean for every client. Ifthe system will interact with many clients, the system will have to manage a bean for each client.Stateful beans do not scale and should be used sparingly.

    2.2 How Session Beans Work

    Session beans are identified with specific annotations provided for the Java EE development envi-ronment. The @Stateless and @Stateful annotations defined in javax.ejb package mark the bean asa session bean. The Java EE environment recognizes classes with the annotations and marks themfor deployment as session beans. An EJB session bean is composed of three components. They arethe proxy/stubs, the EJB container, and the actual instance of the EJB.

    2.2.1 Proxy /Stub

    Session beans within a Java EE environment are based upon the client /server model. The beansreside on the server and the clients access these beans indirectly through a simple remote procedurecall. The proxy /stub design pattern provides the mechanism for session bean communication.

    The proxy is the server side component which handles incoming requests for the bean. Among itsresponsibilities is routing the call to an actual bean instance within the container. The stub resideson the client and is responsible for making the request upon the proxy. The Java EE container createsand manages the code necessary for the client to server communication. The developer does nothave to worry about managing connections. EJB provides two different proxy/stub mechanisms.

    The remote method uses Java RMI for handling communication across a network. In this case theclient virtual machine resides in a different one from the servers virtual machine. The only way tocommunicate is through the network. The Java RMI protocol is used to send and receive data to

    the bean.

    The local method provides direct access to the bean code. If the client and server reside within thesame virtual machine there is no need for network based communication. RMI would be overkillfor the communication layer. The local proxy/stub is nothing more than a simple pass though tothe bean.

    The obvious question, is when would a programmer use local rather than remote? This is mostlyuseful in a simple Java EE environment where the Servlet/JSP resides in the same container as thedeployed EJB. Since the Servlet or JSP page runs in the same container they share the same VM.

    Page 35 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    36/229

    CHAPTER 2. SESSION BEANS

    2.2.2 EJB Container Management

    The EJB container mentioned in previous sections is a construct used to represent the code whichmanages all EJB beans. It provides a number of services for managing bean instances.

    Creates and manages the proxy and stubs generated to handle communication.

    Instantiates and maintains life cycle for all beans

    Routes invocation on proxy to actual bean implementations

    Manages transactions for beans

    Manages security authorization for bean calls

    Pools stateless session beans for better performance and scalability

    All of the services provided are common elements found in any enterprise application. Ratherthan letting developers create their own session pooling and transaction management services, thecontainer provides these services. The advantage of such an arrangement is the fact that theseservices can be constructed and managed by the subject experts creating the Java EE containerrather than some home grown solution which is likely to be inferior.

    The Java EE environment makes it simpler to develop applications that are enterprise solutions.

    2.2.3 Bean Instance

    The final component is the actual instance of the bean. The container will take the class created bythe developer, instantiate it and then manage it within the Java EE environment. The bean instanceis where the actual business logic code resides.

    In the EJB3 specification the bean instance is a plain old Java object (POJO) that is registered with thecontainer through annotations. Once the Java EE container recognizes the annotations the objectscontrol is taken over by the container. It will instantiate the object as needed and pass through anylife cycle messages to the instance.

    Since the bean instance is managed by the server, it is never access directly by the client application.The proxy/stub communication mechanism is always used for communication.

    2.3 Developing a Session EJB

    Session beans are relatively easy to develop. The complexity is in making sure all of the right stepsare done to successfully deploy the bean. The first step in the process is to create the session beansinterface. The methods defined in the interface are the methods that will be exposed to the client

    Page 36 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    37/229

    Java EE Foundations

    application. In addition, the developer has to specify if the interface represents the local or theremote interface.

    Once the interface is created, the next step is to create the bean code. The bean must implementthe interface defined in the previous step. This step is logical because the generated proxy andstub code must map to an implementation of the session bean. The EJB3 specification makes theimplementation easy to create since it is a regular POJO.

    Those are the only steps necessary in defining a session bean. The only step left is to deploy thesession bean to the server. Deployment to the server is accomplished through the creation anddeployment of an EAR file. The EAR file is an enterprise archive.

    The first action necessary to create the EAR file is to compile the source class and interfaces intobyte code. These compiled classes are placed into the EAR file and are made available to the JavaEE container on deployment.

    The following sections walk through these steps in greater detail. It will use an example of a simplestateless calculator bean to explain the process.

    2.3.1 Remote and Local Interfaces

    The first step in development is to determine what actions the bean will be tasked with accom-plishing. The goal is to take each atomic action and define them as a series of methods. Javasinterface mechanism is perfect for capturing these method definitions. Theses methods defined bythe interface will ultimately be the ones exposed to the client application.

    There are two types of interfaces to define. The first is the remote interface. It informs the containerthat the generated proxy/stub must provide inter-VM communication. The container will createproxies and stubs that use RMI for the communication layer. Since RMI is used for communication,any objects that are passed to the session bean must implement the java.util.Serializable interface.Otherwise the call will throw a non serializable exception.

    The second interface is the local interface. It informs the container that the proxy/stub will residewithin the same VM. The container will create a proxy and stub that will provide a direct link

    between the client and session bean instance. Since network communication is not involved thereis no need for objects passed to implement the Serializable interface.

    The session bean can implement either or both interfaces.

    Creating The Interface

    A regular Java interface is used define the business methods which will be available to the client.The calculator interface will have two methods. The first will add two numbers and a second whichwill be tasked with subtracting two numbers.

    public interface Calculator {

    Page 37 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    38/229

    CHAPTER 2. SESSION BEANS

    public int addNumbers(int x, int y);public int subtractNumbers(int x, int y);

    }

    Once the interface is defined, it is time to specify which type of interface will be used to access thebean. This is done by annotating the interface with either the javax.ejb.Remote or javax.ejb.Localannotation. The @Remote annotation is used to mark a remote proxy/stub. The @Local annotationtells the server that it will be a local proxy/stub.

    Below shows how to mark the Calculator interface to use the remote proxy/stub mechanism.

    import javax.ejb.Remote;

    @Remote

    public interface Calculator {

    public int addNumbers(int x, int y);

    public int subtractNumbers(int x, int y);

    }

    This interface can be marked either local or remote. It is possible to create a second interface andmark it local. By applying both interfaces the client can access the bean either remotely or locally.Below is an example of a second interface marked for local access.

    import javax.ejb.Local;

    @Local

    public interface CalculatorLocal {

    public int addNumbers(int x, int y);

    public int subtractNumbers(int x, int y);

    }

    2.3.2 Session Bean POJO Implementation

    Once theinterface is definedfor thesession bean, thedeveloperneeds to provide the implementationof the business rules. This is accomplished by creating a simple Java class that implements the

    interface. The example below shows an implementation of the remote Calculator interface.

    public class CalculatorBean implements Calculator {

    public int addNumbers(int x, int y) {

    return x + y;

    }

    public int subtractNumbers(int x, int y) {

    return x - y;

    Page 38 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    39/229

    Java EE Foundations

    }}

    The next step is to provide information to the Java EE platform to signal that the class is meant tobe a session bean. The javax.ejb.Stateless and javax.ejb.Stateful annotations are used to signal whattype of session bean is being deployed. In the example, the CalculatorBean needs to be marked asa stateless session bean.

    import javax.ejb.Stateless;

    @Statelesspublic class CalculatorBean implements Calculator {

    public int addNumbers(int x, int y) {

    return x + y;

    }

    public int subtractNumbers(int x, int y) {

    return x - y;

    }

    }

    The fact that that the CalculatorBean implements an interface that is marked @Remote tells the JavaEE environment that the remote proxy/stub code needs to be made available at deployment time.If both a @Local and @Remote interface is associated with the bean implementation then the JavaEE environment will make the local and remote proxy/stubs available.

    import javax.ejb.Stateless;

    @Stateless

    public class CalculatorBean implements Calculator, CalculatorLocal {

    public int addNumbers(int x, int y) {

    return x + y;

    }

    public int subtractNumbers(int x, int y) {

    return x - y;

    }

    }

    The implementation and interfaces are all that are necessary for creating a session bean within thenew EJB3 specification.

    Page 39 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    40/229

    CHAPTER 2. SESSION BEANS

    2.4 Building EAR Deployment File

    EJBs are generally deployed to the Java EE server using an EAR file. The EAR file stands forenterprise archive. It is similar to a WAR file for web applications, but has a specific structure forenterprise deployment. This section steps the developers through the steps necessary to build anEAR file using the ANT build tool.

    2.4.1 Compiling With ANT

    The first step in creating an EAR file is the compilation of the beans and their respective interfaces.

    Since the annotations from the Java EE library are used to identify session bean components, theclasspath for these JAR files must be part of the build path.

    In JBoss, the Java EE jar files used for compilation can be found in the client directory of thedistribution. Thus to compile the files the JAR files from this directory must be included in theCLASSPATH designation.

    The ANT entry below provides an example of performing this operation.

    The first section describes the ANT pathinformation. The fileset defines the directory where the JARfiles reside. The include statement is used to include any JAR files within the directory structure.The id attribute used in the path task provides an identifier that can be used when defining aCLASSPATH in the compilation section.

    The target build above is a target used to compile the source code into class files. The javac taginvokes the javac compiler. The srcdir attribute determines where the .java files are located. It willcompile all files in the src directory and any sub-directories. The destination directory is wherethe .class files will be placed after compilation. The same directory structure used by the sourceis created in the build directory and the .class files are placed in the same directory as the sourcecounterparts. This occurs so the classes can maintain Java packaging compliance.

    The classpath tag inside the javac tag specifies additional locations to look for Java libraries. Inthis case, the id developed in the previous path section is used to add the Java EE JAR files to the

    Page 40 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    41/229

    Java EE Foundations

    classpath. If this isnt done then the compiler wont be able to find the annotations necessary forcompilation.

    2.4.2 Packaging EJBs With ANT

    The next step is to take all of the artifacts from compiling the session bean and group them intoan EJB centric jar file. The easiest way to accomplish this task is to make sure the elements of thesession bean are isolated into their own packages. The interfaces go into one package.

    package net.nplus1.app.services;

    public interface Calculator {// implementation here

    }

    The bean implementations generally go into another.

    package net.nplus1.app.beans;

    public class CalculatorBean implements Calculator {

    // implementation here

    }

    With the elements in package it becomes easy to create the jar file.

    In this example the JAR file acme-ejb.jar will be created. It is going to be composed of files from thebuild directory. It will include any files in the subdirectory of the beans or services directory. In thisexample the ** after beans and services means it will take any files within the directory or withinany subdirectory. The ** before means that the beans or services directory must exist somewhereunder the build directory.

    2.4.3 EAR File

    The deployment of a Java EE application is done using an EAR file. An EAR file is a JAR filewith a .ear extension. The EAR file contains all of the JAR files necessary to support the Java EE

    Page 41 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    42/229

    CHAPTER 2. SESSION BEANS

    application. These include the WAR file containing the web application, the EJB JAR file containingany necessary Session, Entity, or Message Driven beans, and any JAR files necessary to support theWAR or EJBs.

    In addition to the JAR files, the EAR file must contain an application.xml file. Similar to the web.xmlfile found in WAR files, it provides configuration information about the Java EE application. Theconfiguration file must be placed within the META-INF directory within the JAR file.

    application.xml

    The application.xml is a simple configuration file that contains two pieces of information. Adescription of the application and a list of modules (JAR) files that are included within the EAR file.

    The basic outline for the application.xml is shown below.

    Simple description of the application

    The application tag is the enclosing tag for the configuration file. The description is a tag that allowsthe developer to provide some information about the Java EE application. The description providesno value to the deployment. It is only useful for tools that read the EAR file.

    The module section on the other hand, provides important information about the Java EE applica-tion. There are three types of modules available: java, ejb, and web.

    The java module is used to specify any 3rd party JAR files that are going to be made available tothe Java EE application

    Simple description of the application

    third-party.jar

    The second type of module is the ejb module. It tells the Java EE container that the contents of theJAR file are session, entity, or message driven beans and to look for the annotations necessary todeploy the them.

    Simple description of the application

    third-party.jar

    acme-ejb.jar

    Page 42 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    43/229

    Java EE Foundations

    The web modules configuration is a bit more complicated than the other two types. The web taghas two child tags: web-uri and context-root. The web-uri is the path to the WAR file containingthe web application. The context-root is used to determine the path context for the web application.

    The path context is the path necessary to reach the web application after the root of the Java EEserver is reached. The best way to understand this is to review a couple of examples. For theseexample, the Java EE server has the domain name foobie.nplus1.net.

    /acme

    Web App URL: http://foobie.nplus1.net/acme

    /foobie/x

    Web App URL: http://foobie.nplus1.net/foobie/x

    /

    Web App URL: http://foobie.nplus1.net/

    The application below includes the web module.

    Simple description of the application

    third-party.jar

    acme-ejb.jar

    acme.war

    /acme

    The complete application.xml file including XML header information

    Simple description of the application

    third-party.jar

    acme-ejb.jar

    acme.war

    Page 43 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    44/229

    CHAPTER 2. SESSION BEANS

    /acme

    Creating EAR File With ANT

    Once the application.xml file is configured for the Java EE application, ANT can be used to buildthe EAR file. The ear tag is used to construct the file. It has two attributes. The destfile attribute isused to determine where the assembled EAR file will be placed. The appxml attribute tells whereANT can find the application.xml file.

    The fileset tag can be used within the ear tag to list the JAR files necessary for the application.

    Below is a complete example of a build.xml file that includes everything necessary to compile EJBsand the WAR file.

    My Build System Targets

    build - builds servlets and custom classes

    package - package web app into war file

    deploy - copy war file to deploy directory

    clean - cleans build and dist directories

    Page 44 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    45/229

    Java EE Foundations

    2.5 Accessing Session Bean

    Once the session beans are deployed to the server, they are accessible for use to outside applications.Access to the beans is controlled by the Java Naming and Directory Interface or JNDI server forshort. The user must query the JNDI server to gain a reference to the services remote/ local stub.Once the client has access to stub, calls can be made to the service as if it were a local method. Thestub handles all of the communication necessary to talk with the session bean on the server.

    Page 45 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    46/229

    CHAPTER 2. SESSION BEANS

    2.5.1 JNDI

    The Java Naming and Directory Interface provides a simple mechanism for accessing containermanaged resources. Each resource is associated with a name. All the developer needs to know isthe name and they can retrieve the resource from the JNDI server.

    JNDI uses a hierarchical structure to organize resources similar to a file system. In fact each layerof the hierarchy uses the same separator used by Unix/Linux file systems. The / character. Anexample of a JNDI look up is shown below.

    acme/CalculatorBean/remote

    acme/TransactionBean/local

    The JNDI server returns a reference to the resource associated with name. In the case of sessionbeans a reference to the stub the is returned to the end user. The developer can use JNDI to gainaccess to either the local or remote stub depending on the look up value. Since the stub implementsits respective interface the object can be cast to that interface. All subsequent calls to the object willmake the necessary calls to communicate with the bean residing on the server.

    Each Java EE container is required to provide an implementation of the JNDI API. The API isplatform independent whose concrete implementation is accessed through an initial context.

    Initial Context

    The InitialContext interface defined in the javax.naming package provides the entry point foraccessing the JNDI API. Like JDBC, the InitialContext can only be instantiated and invoked usinga process that is unique for each Java EE container.

    Below is an example of creating a the InitialContext using the JBoss Java EE container. JBoss usesthe Properties object in java.util to provide information about self instantiation and connecting tothe JNDI server.

    java.util.Properties props = new java.util.Properties();

    props.setProperty("java.naming.factory.initial",

    "org.jnp.interfaces.NamingContextFactory");

    props.setProperty("java.naming.provider.url",

    "jnp://localhost:1099");

    props.setProperty("java.naming.factory.url.pkgs",

    "org.jboss.naming:org.jnp.interfaces");

    javax.naming.InitialContext initialContext =

    new javax.naming.InitialContext(props);

    The java.naming.factory.initial option tells the InitialContext what factory to use when instantiatingan instance of itself. The java.naming.provider.url value tells the context where to connect whenmaking JNDI requests. In this instance the local machine is the JNDI server and listens to port 1099.

    Page 46 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    47/229

    Java EE Foundations

    This information is used by the InitialContext to instantiate an instance of the NamingContextconcrete class implemented by JBoss developers. Once the context is instantiated, it can be used toaccess the EJBs deployed to the server.

    2.5.2 Accessing Bean

    Once an InitialContext is constructed, it is a simple process of gaining access to the EJB. The first stepin the process is to determine the JNDI name for the EJB a developer wishes to access. The namingconventions for finding an EJB within is JNDI name store is different for each Java EE container.

    JBoss uses a simple mechanism based upon the EJBs implemented name, the EAR file it belongs to

    and the type (remote or local) of EJB being accessed.

    [EAR Name]/[Bean Name]/[remote | local]

    In previous sections, a Calculator bean was created. The implementation was CalculatorBean. Itwas created and deployed within the acme.ear file. It had both a remote and local interface. Thusthe two JNDI look ups for the remote and local interfaces are shown below.

    acme/CalculatorBean/remote

    acme/CalculatorBean/local

    The second step is to retrieve the object from the JNDI store. The task is accomplished by performinga look up on the JNDI store. The example below assumes the developer wants to return the remoteinterface.

    Object ref = initialContext.lookup("acme/CalculatorBean/remote");

    At this point a bit of an explanation about the communication protocols are necessary. The com-munication between the client and the session bean is set up to use Java RMI. But the underlyingcommunication protocol is not Java RMI. It is actually CORBA. CORBA stands for The CommonObject Request Broker Architecture. It is meant to be a platform and language independent mech-

    anism for communication between software programs. The protocol used for transportation inCORBA is IIOP or Internet Inter Object Protocol.

    Java created a RMI/IIOP to allow Java developers to use RMI for the interface and IIOP for theprotocol. Allowing Java objects to plug seamlessly into a CORBA architecture. Since IIOP islanguage independent, it doesnt support the concept of casting. Thus a special method is necessaryto do the object conversion. The javax.rmi.PortableRemoteObject provides a narrow method whichperforms the conversion. The narrow method takes two arguments. The object to convert and thedestination class. The method returns the converted object as type Object. Thus the result needs to

    be cast to the proper type.

    Page 47 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    48/229

    CHAPTER 2. SESSION BEANS

    Object ref = initialContext.lookup("acme/CalculatorBean/remote");Calculator calc = (Calculator)

    PortableRemoteObject.narrow(ref, Calculator.class);

    In this instance, the bean is being cast to the remote interface. The object can now be accessed asany other local object. All of the communication to the server is handled by the bean.

    Object ref = initialContext.lookup("acme/CalculatorBean/remote");

    Calculator calc = (Calculator)

    javax.rmi.PortableRemoteObject.narrow(ref, Calculator.class);

    int results = calc.addNumbers(215, 54);

    System.out.println("215 + 54 = " + results);

    Below is the complete client application.

    import java.util.Properties;

    import javax.naming.InitialContext;

    import javax.rmi.PortableRemoteObject

    import net.nplus1.app.services.Calculator;

    public class CalculatorApp {

    public static void main(String [] args) {

    Properties props = new Properties();

    props.setProperty("java.naming.factory.initial",

    "org.jnp.interfaces.NamingContextFactory");props.setProperty("java.naming.provider.url",

    "jnp://localhost:1099");

    props.setProperty("java.naming.factory.url.pkgs",

    "org.jboss.naming:org.jnp.interfaces");

    InitialContext initialContext = InitialContext(props);

    Object ref = initialContext.lookup("acme/CalculatorBean/remote");

    Calculator calc = (Calculator)

    PortableRemoteObject.narrow(ref, Calculator.class);

    int results = calc.addNumbers(215, 54);

    System.out.println("215 + 54 = " + results);

    }}

    The process for using a local interface is similar. The only difference is that the narrow() methodis unnecessary. Since the session bean resides in the same VM as the client application RMI/IIOPcommunication is unnecessary and not used. Thus it is possible to directly cast the object to thedesired type.

    Object ref = initialContext.lookup("acme/CalculatorBean/local");

    Page 48 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    49/229

    Java EE Foundations

    Calculator calc = (Calculator) ref;int results = calc.addNumbers(215, 54);

    System.out.println("215 + 54 = " + results);

    In this example the local interface is used in the JNDI look up.

    2.6 Life Cycle Of Session Beans

    While the developer doesnt control the creation of session beans or how they are managed, it isimportant to understand the life cycle of the two different types of session beans.

    2.6.1 Stateless Session Bean Life Cycle

    The stateless session bean has the simplest life cycle. It has two states: does not exist and method-ready. When the session bean is instantiated it transitions from not existing to a method-readypool for use by external client applications. Once the Java EE container no longer needs the bean itdestroys the object. The beans state transitions from the method-ready pool to the does not existstate in the process.

    Each of these transitions are marked by the container and alerts are available to the developerthrough the use of annotations. The Java EE specification provides annotation for each life cycle

    state change. The developer attaches the annotation to a method, and the method will be invokedwhen each life cycle event occurs.

    A method with the annotation @PostConstruct is invoked right after the bean is created by theJava EE container. The method must not have any arguments and can be used to initialize thestate of the stateless session bean. Since the bean is stateless, any state information should beautonomous. Remember that consecutive calls to the same bean is not guaranteed and is unlikely.A good candidate for the @PostConstruct for a stateless bean would be a connection to anothersystem resource such as a database, software system, etc

    The @PreDestroy annotation is associated with a method which will be invoked before the bean isdestroyed by the Java EE container. It is an ideal location to close any connections that are createdin the @PostConstruct method. Below is an example of how these annotations might be used.

    private MyConnection conn;

    @PostConstruct

    public void init() {

    conn = new MyConnection();

    conn.open();

    }

    @PreDestroy

    Page 49 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    50/229

    CHAPTER 2. SESSION BEANS

    public void destroy() {conn.close();

    }

    2.6.2 Stateful Session Bean Life Cycle

    The stateful session beans life cycle is considerably more complicated than the stateless sessionbean. It has the same states as a stateless bean, does not exist and method-ready, plan an additionalpassive state.

    When a stateful session bean is instantiated by the container, it transitions from the does not exist

    state to method-ready and is associated with a single client application. Once the client dissociateswith the bean, the Java EE container will destroy the object moving it into the does not exist state.In addition the stateful session bean can timeout if not used in a certain period specified by thecontainer. A timeout will also force the object into a does not exist state.

    The problem with stateful session beans are they are matched one to one with a client. Thereforeeach client will have its own unique instance of the stateful session bean associated with it. If a lotof clients use the service then a large number of stateful beans can be created. If the life span ofthose connections are relatively short, the scenario isnt a problem for the Java EE container. The

    bigger problem is if there are a lot of client connections and they hold onto those connections for anextended period of time and only call them occasionally. Such an instance would drain the Java EEcontainer of necessary system resources such as memory.

    The Java EE specification provides a mechanism for conserving resources by passivating statefulsession beans during a period of inactivity. Passivization is the process of storing the stateful beanoutside of physical memory. While the specification doesnt tell the container how to passivate, itis generally accomplished through serialization, but not always.

    The container provides two signals allowing the developer to handle transient data during thepassivization process. The @PrePassivate annotation marks a method which will be called beforepassivization takes place. Here the developer can clean up any transient data. A good exampleis a reference to an external log file. The connection can be closed before passivization. The@PostActivate annotation marks a methodwhich is calledonce thestateful bean leavespassivizationand before it enters the method-ready state. Here the transient state can be reset. In the log fileexample, the log file can be re-opened.

    The stateful session bean can also move from the passive to the does not exist state if the bean times

    out while passivated. If a bean is passivated when a timeout occurs, the the @PostActive methodnever fires. Instead the @PreDestroy annotation will be called.

    An additional annotation is available to the developer to signal that the stateful session bean isno longer needed. The @Remove annotation provides this functionality. When a method markedwith the @Remove annotation is invoked the Java EE container will remove the bean firing the@PreDestroy signal and moving the bean into the does not exist state.

    @Stateful

    Page 50 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    51/229

    Java EE Foundations

    public class MyBean implements LocalInterface {private ArrayList people;

    private FileWriter out;

    @PostConstruct

    public void initialize() {

    people = new ArrayList();

    out = new FileWriter("/tmp/foobie.log");

    }

    @PreDestroy

    public void destroy() {

    if ( out != null ) {

    out.close();}

    }

    @PrePassivate

    public void startPassivation() {

    out.close();

    out = null;

    }

    @PostActivate

    public void endPassivation() {

    out = new FileWriter("/tmp/foobie.log", true);

    }

    @Remove

    public void shutdown() {

    // signal to remove stateful bean

    }

    }

    In this example the stateful session bean has an ArrayList it used to keep track of People objects.In addition it has access to a FileWriter to use for logging. When the client application asks for an

    instance of MyBean, the bean is constructed and the @PostConstruct method initialize() is called torun by the container.

    Because the FileWriter is a transient variable, the session bean closes the file connection beforepassivization and re-instates it once passivization ends. Since the bean can be in a passivated statewhen it is destroyed the @PreDestroy method must make sure that the FileWriter exists beforeattempting to close the connection.

    The method annotated with @Remove can be called to alert the container to remove the beaninvoking the @PreDestroy method.

    Page 51 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    52/229

    CHAPTER 2. SESSION BEANS

    2.7 Lab Activity

    Part 1.

    Page 52 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    53/229

    Chapter 3

    Entity Beans

    Objectives

    Understand what an entity bean is

    Understand what an EntityManager is

    Learn how to create entity beans

    Learn how entity beans interact with the EntityManager

    Understand how to create a persistence unit

    Learn how to add entity beans to deployed EJB Jar file

    53

  • 8/2/2019 Java Ee Foundations

    54/229

    CHAPTER 3. ENTITY BEANS

    3.1 What is an Entity Bean?

    The Java EE standard provides for three types of Enterprise Java Beans, the Session Bean, the EntityBean, and the Message Driven Bean. The Message Driven Bean is used to handle asynchronousmessaging. The Session Bean and Entity Beans are used in tandem to provide an implementationof business rules. The Session Bean represent the business logic of an application. The Entity Beanis used to represent the data of an application.

    The Entity Bean defines a relationship between the bean and the data store. In most cases the datastore is a database. The method of mapping objects to data stores is known as Object Relational (OR)mapping. OR mapping is the process of mapping data between an Object Oriented framework anda relational database. The goal is to model the data of objects and the object relationships within in

    a flat relational table space.This module will walk the developer through the mapping process and then consider how to usethese entity beans to retrieve and store data within a relational database.

    Page 54 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    55/229

    Java EE Foundations

    3.1.1 Managed Persistence

    Java EE from the beginning was meant to be a system for providing enterprise class functionalityto the developer. One of the goals was to provide developers with a mechanism for managingpersistence of business data. From this concept, the entity bean was developed.

    The initial version of entity bean used bean managed persistence. In this instance the developerwas tasked with providing the logic for persisting the beans data to the data store. This included allof the SQL necessary to insert, update, and delete the data from the store. The Java EE environmentprovided transaction management, object pooling, and security for accessing the bean.

    This proved to be a very cumbersome and time consuming process. A lot of duplication of codinglogic was necessary between entity beans. The complexity and difficulty in using the entity bean

    meant few implemented the solution.

    The second version of the entity bean introduced container managed persistence. The Java EEcontainer continued to provide transaction management, object pooling, and security. Since muchof the persistence logic was duplicate code, the container managed the persistence logic for theentity bean. All the developer was left to do was map the entity bean to database.

    While this was a huge improvement on the first version, it still was overly complicated. The XMLdocuments used for the mapping were incredibly complex and unwieldy. A project that used a largenumber of entity beans would mean a configuration XML file that could be hundreds of kilobytesin size. Not something that could be easily managed.

    The third version of the entity bean introduced entity managed persistence. The method of persis-

    tence was defined in the Java Persistence 1.0 API. It took advantage of annotations introduced inJava 5 to be able to map each object to the database within the source code. Not only did it simplifythe complexity from version 2, but it moved all of the logic inside the source code for each bean.This development structure makes it much easier to manage a large number of entity beans becausethe mapping logic resides within each individual class.

    Another benefit to the third version of persistence was the ability to detach it from the Java EEcontainer. If the developer wants to use Java Persistence API in any Java application, it can be usedas a stand alone framework.

    The focus of this module will be to look at how to use persistence within the Java EE framework.

    Page 55 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    56/229

    CHAPTER 3. ENTITY BEANS

    3.1.2 Entity Managed Persistence

    Entity managed persistence is composed of four separate components. The first is the entity bean.The entity bean represents the data to be stored in the data store. The second component is theentity manager. Its role is to manage the collection of entities. It is charged with filling out theentity beans data and inserting, updating, and removing data from the data store based upon thecontents of the bean. The third component is the persistence context. It is charged with selectingdata from the database or updating the database with any changed values. The fourth componentis the database itself.

    Page 56 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    57/229

    Java EE Foundations

    Entity Beans

    Like their cousins the Session Bean, Entity Beans are plain old Java objects. Each instance of anentity bean represents a row in the database table. Take the following database table.

    Person Table

    -----------------------------------

    | id | first name | last name |

    -----------------------------------

    | 100 | John | Doe |

    | 101 | Jane | Doe |

    | 102 | Beth | Smith |

    -----------------------------------

    The developer would create an object that has the same characteristics of the table.

    public class Person {

    private int id;

    private String firstName;

    private String lastName;

    public void setId(int id) { this.id = id; }

    public void setFirstName(String name) { this.firstName = name; }

    public void setLastName(String name) { this.lastName = name; }

    public int getId() { return id; }

    public String getFirstName() { return firstName; }

    public String getLastName() { return lastName; }

    }

    Each row of the person table would represent an instance of the entity. The entity manager wouldbe in charge of creating the Person object an filling it with data from the table.

    Annotations are used to map the entity bean to the database table. The role of the developer increating an entity bean is to provide the annotations necessary to map the entity shown above to atable or series of tables within the database. This will be covered in greater detail later.

    Page 57 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    58/229

    CHAPTER 3. ENTITY BEANS

    Entity Manager

    The Entity Manager defined in the Persistence API provides two roles for the developer. It managesthe mapping of an entity to a database table. It is charged with filling in entity beans data fromthe database and is tasked with updating data in the database if values within the entity bean aremodified.

    The second role is to manage the persistence context. It is charged with making a connection to thedatabase and providing dialect specific information used by the persistence context to manage theconnection with the database.

    There is one aspect of the new persistence management that differentiates it from bean and containermanaged persistence in earlier versions of Entity Beans. That difference resides with how the beans

    are connected to the data source. With bean and container managed persistence each entity beanwas directly tied to the database. Each bean had logic embedded that made it dependent upon thedata source.

    Because the new persistence layer use POJOs, it doesnt have the same direct connection to the datastore. Thus the entity beans are not restrained to the Java EE container. For this to work each entity

    bean must be tracked by the entity manager and are grouped into one of two states, managed andun-managed.

    When an entity bean is in a managed state, the entity is tracked by the entity manager. It isconsidered attached to the manager. Whenever the entity changes state, the manager updates thedatabase with the changes. The entity manager will insert or delete managed entities as requested

    by the developer.

    When the entity bean leaves the scope of the entity manager, it becomes detached from the manager.In this un-managed state, the entity bean is no longer tracked by the entity manager. It becomes

    just another normal Java object.

    Page 58 c2010 n + 1, Inc All Rights Reserved

  • 8/2/2019 Java Ee Foundations

    59/229

    Java EE Foundations

    3.2 Creating An Entity Bean

    As stated in the previous section, an entity bean is a plain old Java object that has annotations whichmap the objects attributes to tables in the database. Table 3.1 provides a list of annotations used inmarking up an entity bean.

    Annotation Description

    @Entity Marks the class as an entity bean so it can be mapped

    @Table Ma


Recommended