You are on page 1of 286

Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Developing o @
8 ent
Applications For the
s
JavaarEE S tud
do 6 Platform
( a nc this
o s u seGuide • Volume 2
o Student
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

D65269GC20
Edition 2.0
June 2011
D73427
Pontifícia Universidade Católica do Rio Grande do Sul

Author Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Paromita Dutta Disclaimer

This document contains proprietary information and is protected by copyright and


Technical Contributors other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered
and Reviewers in any way. Except where your use constitutes "fair use" under copyright law, you
Tom Mc Ginn may not use, share, download, upload, copy, print, display, perform, reproduce,
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

publish, license, post, transmit, or distribute this document in whole or in part without
Matthieu Heimer the express authorization of Oracle.
Greg Stachnick
The information contained in this document is subject to change without notice. If you
Moises Lejter find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice


Editors
Arijit Ghosh If this documentation is delivered to the United States Government or anyone using
the documentation on behalf of the United States Government, the following notice is
Raj Kumar applicable:
s a
Daniel Milne
U.S. GOVERNMENT RIGHTS ) h a
c o m
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
Graphic Designer ฺ
ail ideฺ
disclose these training materials are restricted by the terms of the applicable Oracle

Rajiv Chandrabhanu m
license agreement and/or the applicable U.S. Government contract.
g Gu
Trademark Notice
o @
8 ent
Publishers s
do Stud
a r
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names
c his
may be trademarks of their respective owners.
Revathi Ramamoorthy
( a n t
Jayanthy Keshavamurthy
s o s e
a rdo e to u
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Contents
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 Preface
Course Goals 1-2
Course Map 1-3
Topics Not Covered 1-4
How Prepared Are You? 1-6
Introductions 1-7
Typographical Conventions 1-8 s a
) h a
1 Placing the Java™ EE Model in Context c o m

ail ideฺ
Objectives 1-2
m
g Gu
Requirements of Enterprise Applications 1-3
o @
8 ent
Java Technology Platforms 1-4 s
do Stud
a r
Enterprise Application Infrastructure Technologies 1-5
Java EE Technology Suite 1-7 ( a nc this
o s o use
Java EE Specifications and the Java Community ProcessSM
1-8
r d
a se t o
C
Component, API, and Service Layer 1-9
i licen
s
i d
Java EE Component Containers 1-10
c ola ble
Java EE Platform APIs and Services 1-13
i
r e N fera
Java EE Service Infrastructure 1-15
a n d rans
Java EE Platform Tiers and Architecture 1-17
x -t
Ale non N-Tier Architectural Model 1-18
Java EE-Tiered Architecture 1-19
Java EE Application Architecture 1-20
Java EE Web-Centric Architecture 1-21
Java EE EJB Component–Centric Architecture 1-22
Java EE Profiles 1-23
EJB 3.1 Lite 1-25
B2B Application Architecture 1-26
Java EE Web Service Architecture 1-27
Java EE Patterns 1-28
Java EE Pattern Tiers 1-29
Using Java EE Patterns 1-30

iii
Pontifícia Universidade Católica do Rio Grande do Sul

Java EE BluePrints 1-32


Summary 1-33
Quiz 1-35
Practice 1: Overview 1-43
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2 Java EE Component Model and Development Steps


Objectives 2-2
Principles of Component‑Based Development 2-3
Java EE Components 2-4
Java EE Component Characteristics 2-5
Component State and Properties 2-6
Encapsulated Components 2-7
s a
Component Proxies 2-8
) h a
c o m
Interaction of Java EE Application Components Through Interfaces 2-9
Distributable and Local Component Interactions 2-10

ail ideฺ
m
g Gu
Distributed Components and RMI 2-11
o @
8 ent
s
Calling Semantics for Local and Distributable Components 2-13
do Stud
a r
Advantages and Disadvantages of a Distributed Component Model 2-14
Location Transparency 2-15
( a nc this
o s o use
Naming Services in the Component Model 2-16
a rd e to
Use of the Java Naming and Directory Interface™ (JNDI) API in the Java EE
d is C licens
Component Model 2-17
i
i c ola ble
The Context Interface and the InitialContext Object 2-18

e N fera
Configuring the InitialContext Object 2-20
r
a n d rans
Using JNDI API as a Resource Locator 2-21
x -t
Ale non Narrowing and Remote Objects 2-22
Using a Component Context to Locate Components 2-23
Using Dependency Injection to Locate Components 2-24
Asynchronous as Compared to Synchronous Communication 2-26
Asynchronous Component-to-Component Interaction 2-27
Asynchronous Messaging 2-28
Advantages and Disadvantages of Asynchronous Interactions 2-29
Developing Java EE Applications 2-30
Java EE Roles 2-31
Steps for Developing a Java EE Application 2-34
Java EE Application Development Process 2-36
Development Tools 2-37
Configuring and Packaging Java EE Applications 2-38
Web Application Elements 2-40
Web Archive File Creation 2-41
Java Archive Files 2-42

iv
Pontifícia Universidade Católica do Rio Grande do Sul

Enterprise Archive Files 2-43


Deployment Descriptors 2-44
Summary 2-46
Quiz 2-48
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Practice 2: Overview 2-58

3 Web Component Model


Objectives 3-2
Role of Web Components in a Java EE Application 3-3
HTTP Request-Response Model 3-4
GET and POST Requests 3-6
Form Data 3-7
s a
Content Type and the Response Header 3-9
) h a
Comparison of Servlets and JSP Components 3-10
c o m
Life Cycle of a Web Component 3-11 ฺ
ail ideฺ
The service Method 3-12 m
g Gu
o @
8 ent
Servlet and JSP Component Examples 3-13
s
do Stud
Servlet Example 3-14
a r
JSP Component Example 3-15
( a nc this
s o use
Servlet and JSP Component Collaboration 3-16
o
a rd e to
Runtime Behavior of Servlets and JSP Components 3-17

i d is C licens
Web Component Thread Model 3-18

i c ola ble
Implications for the Developer 3-20

r e N fera
Web Context Root and Alias Mapping 3-22

a n d rans
Session Management 3-23
x -t
Ale non
Problems with Web-Tier Development 3-24
Model 1 and Model 2 Architectures 3-25
Traditional MVC Architecture 3-26
Model 2 Architecture as MVC 3-27
MVC in the Java EE Platform 3-28
Using Web-Tier Design Patterns 3-29
Service-to-Worker and Dispatcher View Patterns 3-30
Web-Tier Design Framework Construction 3-32
Some Available Web-Tier Frameworks 3-33
Business Delegate Pattern 3-34
Summary 3-35
Quiz 3-36
Practice 3: Overview 3-44

v
Pontifícia Universidade Católica do Rio Grande do Sul

4 Developing Servlets
Objectives 4-2
Basics of the Servlet API 4-3
Structure of the Servlet API 4-4
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Benefits of the Protocol-Specific API 4-5


Benefits of the HttpServlet Class 4-6
The service Method 4-7
Request-Handling Methods 4-8
Basic Servlet 4-9
Servlet Configuration 4-10
Deployment Descriptors 4-11
Deployment Descriptor Example 4-12
s a
Servlet Life Cycle 4-13
) h a
Using the Request and Response APIs 4-14
c o m
Request Object 4-15 ฺ
ail ideฺ
Response Object 4-16 m
g Gu
o @
8 ent
s
Example of Handling Form Data and Producing Output 4-17
do Stud
r
Forwarding Control and Passing Data 4-19
a
a nc this
The RequestDispatcher Interface 4-20
(
s o use
The RequestDispatcher Target and the Context Root 4-22
o
a rd e to
The forward and include Methods 4-23

i d is C licens
Transfer of Data in the Request Object 4-24

i c ola ble
Using the Session Management API 4-25

r e N fera
Java EE Platform Web-Tier Session Management Model 4-26

a n d rans
Session and Authentication 4-27
x -t
Ale non
Session Binding 4-28
Session Timeout 4-29
Session Lifetime 4-30
Retrieving a Session Object 4-31
Summary 4-32
Quiz 4-33
Practice 4: Overview 4-39

5 Developing with JavaServer Pages Technology


Objectives 5-2
JSP Technology as a Presentation Mechanism 5-3
Presentation Using JSP Pages Compared to Servlets 5-5
Presentation Using JSP Pages Compared To Servlets 5-6
Worker Beans, JSTL, and Custom Tags 5-7
JSP Page Deployment Mechanism 5-8
JSP Page Translation Procedure 5-9

vi
Pontifícia Universidade Católica do Rio Grande do Sul

Java Code Embedded in JSP Pages 5-10


Authoring JSP Pages 5-11
JSP Page Components 5-12
Syntactic Forms of JSP Tags 5-13
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

JSP Technology Directives 5-14


JSP Directives 5-15
The page Directive 5-16
JSP page Directives 5-18
The include Directive 5-19
Declarations, Expressions, and Scriptlets 5-21
Declaration Scripting Elements 5-23
Expression Scripting Elements 5-24
s a
Scriptlet Scripting Elements 5-25
) h a
Thread-Safety Implications 5-27
c o m
Processing Data from Servlets 5-28 ฺ
ail ideฺ
The jsp:useBean Action 5-29 m
g Gu
o @
8 ent
The jsp:useBean Scopes 5-34
s
do Stud
r
Request-Scope Beans and Collecting Data from Servlets 5-36
a
a nc this
Request-Scope Beans and Collecting Data from Servlets 5-37
(
s o use
The jsp:getProperty Action 5-39
o
a rd e to
Custom Tag Libraries 5-40

i d is C licens
The taglib Directive 5-41

i c ola ble
The tag-library Descriptor and Java Classes 5-43

r e N fera
The Expression Language (EL) 5-45

a n d rans
The JSTL Core Tag Library 5-46
x -t
Ale non
JSTL Examples 5-47
Packaging Tag Libraries in Web Applications 5-48
Summary 5-49
Quiz 5-50
Practice 5: Overview 5-56

6 Developing with JavaServer Faces™ Technology


Objectives 6-2
JavaServer Faces (JSF) 6-3
JavaServer Faces Benefits 6-4
JavaServer Faces 2.0 New Features 6-5
JavaServer Faces Development Tools 6-6
A Server-Side UI 6-7
JSF Hello World 6-8
JSF Implementations and Component Libraries 6-10
JSF Page Tags 6-11

vii
Pontifícia Universidade Católica do Rio Grande do Sul

JSF Tag Libraries 6-12


Managed Beans 6-13
The Unified Expression Language (EL) 6-14
JSF Forms 6-15
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Managed Bean Configuration 6-16


Managed Bean Names 6-17
Managed Beans and Forms 6-18
Managed Beans and Text Output 6-19
Managed Bean Life Cycle and Scope 6-20
JSF Page Navigation 6-21
Validation 6-22
Input Conversion 6-24
s a
Validation and Conversion 6-25
) h a
Validation and Conversion Errors 6-26
c o m
Error Messages 6-29 ฺ
ail ideฺ
Internationalization 6-30 m
g Gu
o @
8 ent
Internationalization Demo 6-31
s
do Stud
Summary 6-35
a r
Quiz 6-36
( a nc this
Practice 6: Overview 6-40
o s o use
a rd e to
7 EJB Component Model
i d is C licens
la le
Objectives o7-2
c
N
Role of
e
i r ab in a Java EE Application 7-3
EJB Components
f e
n r Component
dEJB n s Types 7-4
a r a
-t Application Tiers 7-5
x Enterprise
Ale non EJB Method Types 7-8
Analysis of the EJB Component Model 7-9
Role of the EJB Container 7-10
Embedded EJB Container 7-12
EJB Objects and Proxies 7-13
Local and Distributed Client Views 7-14
Elements of an EJB Component 7-15
EJB Life Cycle 7-17
EJB Timer Service 7-18
Timer Scheduling 7-19
@Schedule Syntax 7-20
@Schedule Examples 7-21
Calling EJB Components from Servlets 7-22
Initializing a Reference to a Stateless Remote Session Bean from a Servlet 7-23
Using Annotations to Obtain an EJB Reference in a Managed Component 7-24

viii
Pontifícia Universidade Católica do Rio Grande do Sul

EJB Lite 7-25


EJBs Before the Java EE 5 Platform 7-26
Summary 7-28
Quiz 7-30
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Practice 7: Overview 7-33

8 Implementing EJB 3.1 Session Beans


Objectives 8-2
Comparison of Stateless and Stateful Behavior 8-3
Stateless Session Bean Operational Characteristics 8-4
Stateless Session Bean Cardinality 8-5
Stateful Session Bean Operational Characteristics 8-6
s a
Stateful Session Bean Cardinality 8-7
) h a
Singleton Session Bean Characteristics 8-8
c o m
Creating Session Beans 8-9 ฺ
ail ideฺ
m
g Gu
Declaring a Business Interface for the Session Bean 8-10
o @
8 ent
s
Creating the Session Bean Class That Implements the Business Interface 8-11
do Stud
Declaring a Local Session Bean 8-13
a r
a nc this
Declaring a Remote Session Bean 8-14
(
s o use
Requirements for a Session Bean Class 8-16
o
a rd e to
Annotating the Session Bean Class 8-17

i d is C licens
Life Cycle of a Stateless Session Bean 8-18

i c ola ble
Life Cycle of a Stateful Session Bean 8-19

r e N fera
Example of a Callback Method in a Bean Class 8-20

a n d rans
The SessionContext Object 8-21
x -t
Ale non
Session Bean Packaging and Deployment 8-22
Session Bean Deployment Descriptor 8-23
EJB Packaging 8-25
Creating an EJB Bean Component Archive 8-26
Example of the EJB Module JAR File 8-28
Creating a Session Bean Client 8-29
Session Bean Client Reference Types 8-32
Portable JNDI Session Bean Clients 8-33
Global JNDI Names 8-34
Summary 8-35
Quiz 8-36
Practice 8: Overview 8-40

ix
Pontifícia Universidade Católica do Rio Grande do Sul

9 The Java Persistence API


Objectives 9-2
The Java Persistence API 9-3
Object Relational Mapping 9-4
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Normalized Data Mapping 9-5


Use of an Entity Component Across a Set of Database Tables 9-6
Entity Class Requirements 9-7
Entity Class Example 9-8
Persistent Fields as Opposed to Persistent Properties 9-10
Persistent Fields 9-11
Persistent Properties 9-12
Persistence Data Types 9-13
s a
The Concept of a Primary Key 9-14
) h a
Entity Component Primary Key Association 9-15
c o m
Persistence Units 9-16 ฺ
ail ideฺ
The persistence.xml file 9-17 m
g Gu
o @
8 ent
The Persistence Context 9-18
s
do Stud
The Entity Manager 9-19
a r
Entity Instance Management 9-20
( a nc this
s o use
Entity Instance Life Cycle and Entity Manager Methods 9-22
o
a
Entity Bean States 9-23 rd e to
i d is C licens
Entity Manager Methods 9-24

i c ola ble
Managed Entities 9-25

r e N fera
Deploying Entity Classes 9-26

a n d rans
Creating a Persistence Unit Using Default Settings 9-28
x -t
Ale non
Examining a Persistence Unit Using Nondefault Settings 9-30
Java SE JPA Applications 9-31
Java SE JPA persistence.xml Example 9-32
Java SE JPA EntityManager Example 9-33
Advanced Persistence Features 9-34
A Native Query Example 9-36
Summary 9-37
Quiz 9-38
Practice 9: Overview 9-41

10 Implementing a Transaction Policy


Objectives 10-2
Transaction Semantics 10-3
Atomicity 10-4
Locking and Isolation 10-6

x
Pontifícia Universidade Católica do Rio Grande do Sul

Transaction Models 10-7


Comparison of Programmatic and Declarative Transactions 10-9
Programmatic Scoping as Opposed to Reusability 10-10
Using JTA to Scope Transactions Programmatically 10-11
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Getting a Reference to the UserTransaction Interface 10-12


Using the begin,commit, and rollback Methods 10-13
Implementing a Container-Managed Transaction Policy 10-14
Container Interactions with the Transaction Management Infrastructure 10-15
How to Control the Container’s Behavior Using Transaction Attributes 10-17
Predicting the Effect of Transaction Scope on Application Performance 10-18
Transaction Scope and Entity Synchronization 10-19
Optimistic Locking and Versioning 10-20
s a
Implementing Versioning 10-21
) h a
Pessimistic Locking 10-22
c o m
Effect of Exceptions on Transaction State 10-23 ฺ
ail ideฺ
m
g Gu
Using the EJBContext Object to Check and Control Transaction State 10-24
o @
8 ent
JPA Transactions in Java SE Applications 10-25
s
do Stud
Summary 10-26
a r
Quiz 10-27
( a nc this
Practice 10: Overview 10-31
o s o use
a rd e to
C ns Using Messaging
is Applications
a le lice
11 Developing Java EE
i
Objectives ol11-2
d
N
Messagingic System
r abParticipants 11-3
r e
dAdministered f e
s Objects 11-4
a n r a n
-t Clients 11-5
x Messaging
Ale non Messages 11-6
Point-to-Point Messaging Architecture 11-7
Publish/Subscribe Messaging Architecture 11-8
Creating a Queue Message Producer 11-9
Example Code for Message Producer 11-12
Example Code for Message Producer 11-13
Queue Message Browser 11-15
Example Code for Queue Message Browser 11-16
Evaluating the Capabilities and Limitations of EJB Components as Messaging
Clients 11-19
Summary 11-20
Quiz 11-21
Practice 11: Overview 11-24

xi
Pontifícia Universidade Católica do Rio Grande do Sul

12 Developing Message-Driven Beans


Objectives 12-2
Introducing Message-Driven Beans 12-3
Java EE Technology Client View of Message‑Driven Beans 12-4
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Life Cycle of a Message-Driven Bean 12-5


Types of Message-Driven Beans 12-6
Creating a JMS Message-Driven Bean 12-7
Message-Driven Bean Example 12-9
Callback Methods in a Bean Class 12-10
Summary 12-12
Quiz 12-13
Practice 12: Overview 12-15
s a
) h a
13 Web Service Model
c o m
Objectives 13-2

ail ideฺ
m
g Gu
The Role of Web Services 13-3
o @
8 ent
Web Services as Remote Components 13-4 s
do Stud
a r
Web Services Compared to Remote EJBs 13-5
RESTful Web Services 13-6
( a nc this
SOAP Web Services 13-7
o s o use
a rd e to
Interoperability Requirements 13-8
d is C licens
SOAP Interoperability Standards 13-9
i
i c ola ble
Java APIs Related to XML and Web Services 13-13

e N fera
JAX-RS API 13-14
r
a n d rans
JAX-WS API 13-15
x -t
Ale non Summary 13-16
Quiz 13-17
Practice 13: Overview 13-22

14 Implementing Java EE Web Services with JAX-RS & JAX-WS


Objectives 14-2
Web Service Endpoint Types Supported by Java EE 6 14-3
JAX-RS Web Endpoints 14-4
Implementing a JAX-RS Web Endpoint 14-5
Simple JAX-RS Web Component Endpoint Example 14-6
JAX-RS Servlet Endpoint Configuration 14-7
JAX-RS URI Parameters 14-8
JAX-WS Web Endpoints 14-9
Implementing a JAX-WS Web Endpoint 14-10
Simple JAX-WS Web Component Endpoint Example 14-11
JAX-WS Servlet Endpoint Configuration 14-12

xii
Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Endpoint Life Cycle 14-13


JAX-WS Allowed Data Types 14-14
RESTful Web Service Clients 14-16
A RESTful Client Example 14-17
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Non-Java RESTful Web Service Clients 14-18


JAX-WS Web Service Clients 14-19
Developing JAX-WS Clients 14-20
A JAX-WS Client Example 14-21
Non-Java SOAP Web Service Clients 14-22
Summary 14-23
Quiz 14-24
Practice 14: Overview 14-26
s a
) h a
15 Implementing a Security Policy
c o m
Objectives 15-2 ฺ
ail ideฺ
Exploiting Container-Managed Security 15-3 m
g Gu
o @
8 ent
Security Concepts 15-4
s
do Stud
End-to-End Security Model 15-5
a r
Container-Managed Security 15-6
( a nc this
s o use
Container-Managed Authentication 15-7
o
a rd e to
Authentication in the Web Tier 15-8

i d is C licens
Web-Tier Authentication Challenge Methods 15-9

i c ola ble
Basic Authentication Dialog Box 15-10

r e N fera
Authentication from the Web Tier to the EJB Tier 15-11

a n d rans
Authentication of Non-Web Clients 15-12
x -t
Ale non
Interaction with the Security Infrastructure 15-14
User Roles and Responsibilities 15-15
Role-Based Java EE Security Model 15-16
End-to-End Roles 15-17
Creating a Role-Based Security Policy 15-18
Role Mapping 15-19
Role-Based Authorization in the Web Tier 15-20
Web Tier Security Annotations 15-21
Role-Based Authorization in the EJB Tier 15-22
EJB Tier Security Annotations 15-23
Using the Security API 15-24
Web-Tier Security API 15-25
EJB-Tier Security API 15-27
Configuring Authentication in the Web Tier 15-28
Selecting the Authentication Type 15-29
Creating an HTML Login Page for Form‑Based Authentication 15-30

xiii
Pontifícia Universidade Católica do Rio Grande do Sul

HTTP Security and JAX-WS clients 15-31


Summary 15-32
Quiz 15-33
Practice 15 Overview 15-35
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

xiv
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

EJB Component Model

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe the role of EJB components in a Java EE
application
• Describe the EJB component model
• Identify the proper terminology to use when discussing
EJB components and their elements s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Role of EJB Components in a Java EE Application

EJB components:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Are managed by an EJB container


• Provide business and messaging functions
• Are scalable, transactional, multiuser, and secure

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Component Types


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Enterprise JavaBeans
Technology

Session Message-Driven
s a
•Stateless
) h a
•Stateful
c o m
•Singleton ฺ
ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr ranTypes
EJB Component
a
s
x -t basic types of Java EE components that must be located in an EJB container:
AleTherenare
ontwo
• Session EJB components: A session EJB component provides a service to clients by
implementing business logic that runs in an EJB container. A session EJB component
might access the database and might also coordinate transactional work that involves
multiple entity classes.
• Message-driven beans: A message-driven bean is an asynchronous message
consumer that can execute server-side business logic based on messages received
from a variety of sources, such as legacy systems and Java EE clients. Although
message-driven beans are located in an EJB container, they have different operational
characteristics from session components.
Note: Previous versions of the Enterprise JavaBeans specification included an entity EJB
component. Entity EJB components are still supported for backwards compatibility, but have
been replaced by a non-EJB entity component outlined in the new Java Persistence API
specification.

Developing Applications for the Java EE 6 Platform 7 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Enterprise Application Tiers

Modern practice favors the division of enterprise components


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

into tiers:
• The services tier, which consists mostly of session beans
and message-driven beans
• The EIS-facing or object-relational mapping tier, which
consists mostly of entity classes and their supporting
classes s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
EJB Tiers
a dr rans
x -t “layer” is sometimes used in place of “tier.” In this lesson, tier does not
AleNote:nThe
onterm
designate a physical separation, instead it notes a logical partitioning of functionality.
An EJB application may have a large number of clients, and the clients may, in principle,
interact with both session bean services and entity components. However, in a multitiered
EJB application, it is considered bad design to have clients—that are not themselves EJB
components—interact directly with the database or entity components.
Session beans are common clients for entity components. It is common design practice to use
a session bean as a facade for a number of entity components, with most of the
computational logic encapsulated in the session bean.

Developing Applications for the Java EE 6 Platform 7 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

The two main reasons to use a session bean as a facade for a number of entity components
are:
1. Entity components in an EJB container do not provide remote access to clients:
The use of course-grained session bean interfaces minimize network overhead and
allow developers to leverage container-managed transactions.
2. To simplify the clients:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Clients of an EJB application expect to see services, which are provided by session
beans, not data, which is provided by entity beans. Clients must contain transaction
management code when directly using entity beans.
Note: This design practice is also called the Session Facade pattern, which is presented in
more depth in the following courses: Business Component Development with Enterprise
JavaBeans™ Technology and Java EE™ Patterns.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Enterprise Application Tiers

Entity Classes
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

TransactionLog

Client
Session Bean

AutomaticTeller ATMCustomer

Client
Ledger
s a
Session Bean ) h a
o m
Database
BranchTeller
Account
a ilฺc eฺ
Client
@ gm Guid
s o 8 ent
a r do Customer S tud
( a nc this
Client
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
EJB Tiers
a dr rans
x -tthe slide shows two session beans, AutomaticTeller and BranchTeller
AleThe figure
n o nin
that expose the business logic of a banking application.
In the figure in the slide, bank clients make deposits and withdrawals using the functionality
that is exposed by the ni session bean. Tellers create new accounts and perform other
banking functions using the BranchTeller session bean. The application session beans
connect with the back-end data store using a suite of entity classes that model the business
data.
Each entity class represents a different type of business entity. For example, an entity class
can represent transaction logs, ATM customers, ledgers, accounts, and customers. At the end
of a transaction, the data that is contained in entity components is typically written to the
database.

Developing Applications for the Java EE 6 Platform 7 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Method Types

Two basic categories of methods that are present in session


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJB components are:


• Lifecycle or callback methods
• Business methods

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Types
EJB Method
a r a n s
-t
x categories
AleThe two
n o n are:
• Lifecycle or callback methods: These methods are called by the container at various
points in the life cycle of an EJB component or associated implementation class. An EJB
component developer can implement these methods depending on the functionality
required from the EJB component.
• Business methods: Typically defined by a business interface, the bean class
implements business methods that execute the logic that EJB components require.
EJB Component Interfaces
The EJB component model provides some basic functionality using a few base interfaces that
are common to all EJB component types. These interfaces include:
• The EJBContext interface: This interface provides access to the container-provided
runtime context of an enterprise bean instance.
• The SessionContext and MessageDrivenContext interfaces extend the
EJBContext interface and provide additional methods that are specific to the enterprise
bean type. The EJBContext interface has several security, transaction-related, and
lookup methods that a component developer might find useful.

Developing Applications for the Java EE 6 Platform 7 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Analysis of the EJB Component Model

The EJB component model has the following characteristics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• A container encapsulates each component.


• The container provides proxies that allow clients limited
and controlled access to the EJB component.
• The proxies implement interfaces that are provided by the
EJB component developer.
• Clients make method calls on these interfaces. a
as ) h
o m
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Role of the EJB Container

Container
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Lifecycle Management

Client Client
Support

s a
Resource Management
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a dr EJB
Role ofnthe
r a n s
Container
x -t
AleThe EJB
n o n
container provides a number of important services to EJB components, as shown in
the figure in the slide.

Developing Applications for the Java EE 6 Platform 7 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Role of the EJB Container

The EJB container provides the following functionality:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Encapsulates access to external resources such as


databases and legacy systems
• Manages the life cycles of instances of the EJB
component’s implementation class
• Isolates the class that provides the implementation from its
clients s a
) h a
• Provides timer services, and can invoke methods at o certain
m
times, which allows the EJB component to perform
a ilฺc eฺ
scheduled tasks @ gm Guid
s o 8 ent
• Monitors, for message-driven beans,
a r tud
do aSmessage queue on
behalf of the EJB component nc his (a se t
o
os to u
r
a se d
s C
i © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d rans
a n
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Embedded EJB Container

Java applications, such as Java SE desktop or Java EE web-


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

type applications, may use an embedded EJB container instead


of a traditional application server EJB container. Embedded
EJB Containers:
• Are new to Java EE 6
• Support EJB Lite
A basic example: s a
) ha
m
EJBContainer ec =
ฺ c o
javax.ejb.embeddable.EJBContainer.createEJBContainer();
m ail ideฺ
Context ctx = ec.getContext();
@ g Gu
FooLocal foo = (FooLocal)ctx.lookup("java:global/foo/FooBean");
s o 8 ent
// use EJB
a r do Stud
ec.close();
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Objects and Proxies


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Client
Container

`
s a
) h a
EJB
c o m
Business
Object ฺ
ail ideฺ
Methods
Bean@
m
g Gu
Instance

s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr and
EJB Objects
a r a n sProxies
x -t
AleWhennanonEJB component client requests a session component, the container returns to the
client a reference to the EJB component’s EJB object, as shown in the figure.
The EJB object class is generated automatically by the server based on the definition of the
component or business interface. All subsequent client interactions are through the EJB
object.

Developing Applications for the Java EE 6 Platform 7 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Local and Distributed Client Views

You can provide a session EJB component with the following


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

four types of client access:


• Local
• Distributed (Remote)
• Web service based
• No-interface (new in EJB 3.1)
s a
Different interfaces are required because local and distributed
h a
)
interactions have different calling semantics. om
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Local and
a drDistributed
r a n s Client Views
x -t
AleBecause
n o n
the Java EE model enforces a strict separation between interface and
implementation, the client interacts with these objects by their interfaces. Consequently, the
business interface serves the following three purposes:
1. It provides an access point and type for clients.
2. It specifies to the server how to construct the EJB object.
3. It serves as a framework for the behavior of the EJB component.
You can provide a session EJB component with any combination of the following four types of
client views:
1. Local interfaces: The local interfaces are collectively known as the local client view.
2. Distributed interfaces: Together, the distributed interfaces form the distributed or
remote client view.
3. Web services interfaces: The web services interfaces for stateless session beans are
known as the Web Services view.
4. No-interface view: An EJB 3.1 variation of the local client view. The public methods of
the bean class specify the EJB component’s client API. No business interface is written.

Developing Applications for the Java EE 6 Platform 7 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Elements of an EJB Component

A message-driven EJB component has the following elements:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Implementation class
Distributable or locally accessible session EJB components
have the following elements:
• Business interface (optional for local EJB 3.1 components)
• Implementation class
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n
Elements drof araDistributable
n s EJB Component
e x - t
on Component Interface
Al • nRemote
The remote component interface provides access to the business methods of the EJB
component. The remote component interface is implemented by a stub or proxy on the
client side, and the EJB object on the server side.
For session EJB components, an EJB client uses dependency injection or JNDI lookups
to obtain a reference to the remote component interface. The EJB object is also called
the component object.
• Implementation Class
This class is marked with the javax.ejb.Stateless or javax.ejb.Stateful
annotation. The implementation class is often called the bean class, implementation
instance, EJB Instance, or EJB class. Clients do not have direct access to instances of
the implementation class. Implementation instances are always accessed through
remote or local interfaces.

Developing Applications for the Java EE 6 Platform 7 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Client View of a Distributable EJB Component


Note that message-driven beans do not follow this same model.
Because a client interacts with the EJB component through interfaces, the client view of an
EJB component is not that different from the client view of an ordinary Java object. The
process of obtaining a reference to an object was introduced in “Use of JNDI API in the Java
EE Component Model” in the lesson titled “Java EE Component Model and Development
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Steps.” The following code illustrates how a client connects to and uses a session EJB
component named bankMgr.
Client View of a Distributed Component
BankMgr bankMgr;
try {
InitialContext ic = new InitialContext();
bankMgr = (BankMgr) ic.lookup ("java:comp/env/ejb/BankMgr");
s a
} catch (...) { ) h a
c o m
// Handle exceptions ฺ
ail ideฺ
} m
g Gu
In the preceding code example, there is no indication about o @
8 ethe
whether n t client is using the
local view or the distributed view of the EJB component.
s
doIn fact, d client code is essentially
uthe
a r S t
identical in the local or distributed view of the EJB
a n c component.
h is However, it is conventional to
name the interfaces differently for the local ( t
the interface would conventionally d so view.
beocalled u sSo,e if this were a local client view interaction,
a r e to
BankMgrLocal.

i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Life Cycle

• An EJB component has a life cycle that is controlled by the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJB container based on the functionality requested by the


client and the operational requirements of the system.
• Each type of EJB component has specific lifecycle
operations and characteristics.
• Understanding the life cycle of the various EJB component
types may allow a component developer to optimize the s a
operation of the bean. ) ha m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Timer Service

• First appeared in Java EE platform 1.4, updated in Java


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EE 6
• Is a container-managed service
• Provides a callback service for modeling workflow-type
business processes that depend on notifications that
certain time-related events have occurred
• Can be configured to occur: s a
) h a
– At a specific time m
ฺ c o
– After a specific elapsed duration
m ail ideฺ
– At specific recurring intervals @ g Gu
t
– On calendar schedules similar todo so8cron
UNIX ud e n
(Java EE 6)
a r S t
– On all EJB types except a c
stateless
n is
hsession beans
( e t
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Timer Scheduling

Timer events can be scheduled in three ways:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Programmatically with the Timer API


• Automatically with a deployment descriptor
• Automatically with bean annotations
The bean annotation method uses @Schedule annotation.
This annotation uses a calendar-based syntax that is modeled
after the UNIX cron facility. A session bean might contain: as a
m )h
o
@Schedule(hour="1", dayOfMonth="1") a ilฺc eฺ
@ gm {G... uid }
public void generateMonthlyAccountStatements()
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Timer n
a dr rans
Scheduling
x cann-be t created for stateless session beans, singleton session beans, message-driven
AleTimers
n o
beans, and 2.1 entity beans. Timers cannot be created for stateful session beans.

Developing Applications for the Java EE 6 Platform 7 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

@Schedule Syntax

The @Schedule annotation accepts the following attributes:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• second
• minute
• hour
• dayOfMonth
• month
s a
• dayOfWeek
) h a
• year o m
a ilฺc eฺ
The second, minute, and hour attributes have
@ G uid
gma default
value of "0". The dayOfMonth, month,so 8 ent and
dayOfWeek,
year attributes have a default value
a r do"*".
of S tud
c a n his
( e t
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

@Schedule Examples

Every Monday at midnight:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

@Schedule(dayOfWeek="Mon")

Every Weekday morning at 3:15:


@Schedule(minute="15", hour="3", dayOfWeek="Mon-Fri")

Every minute of every hour of every day: s a


) h a
c o m
@Schedule(minute="*", hour="*") ฺ
ail ideฺ
m
g Gu
Every five minutes within the hour: o @
8 ent
s
do Stud
a r
@Schedule(minute="*/5", ( a nchour="*") t his
so us e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Calling EJB Components from Servlets

Servlets can freely call stateless and stateful session beans.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

However, the developer should observe the following


guidelines in using servlets with EJB components:

Guideline Rationale

Servlets should avoid calling entity The narrowness of the transaction


classes (direct database access). boundaries leads to inefficient s a
synchronization. ) h a
c o m
Servlets should generally make a few Reduce RMI overheads. ฺ
ail ideฺ
complex method calls, rather than m
g Gu
many simple method calls.
o @
8 ent
Stateless session beans can be JNDI lookups
s
doare expensive. ud
a r S t
located at initialization time.
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Initializing a Reference to a Stateless Remote


Session Bean from a Servlet
1 private BankMgr bankMgr = null;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2
3 public void init() {
4 try {
5 InitialContext ic = new InitialContext();
6
7 bankMgr = (BankMgr)ic.lookup
("java:comp/env/ejb/BankMgr"); s a
8 ) h a
o m
9 } catch (Exception e) {
a ilฺc eฺ
10 throw new ServletException(e);
@ gm Guid
11 } o8 ent os tud
r d
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr a Reference
Initializing
a r a n s to an EJB
x -t
AleThe code
n o n
snippet in the slide illustrates how a servlet can locate the EJB component at
initialization time and store it in an instance variable for future use.
You should note the following about the code in the slide:
• The InitialContext object is created using a default constructor and there are no
JNDI API properties.
The servlet uses a java:comp/env name to locate the EJB component in the web
module’s local namespace.
• The initialization can throw exceptions.
Your code should handle these exceptions in such a way that subsequent calls to the
service method fail gracefully. In the code example, if lookup fails, the bankMgr
reference remains null. It is easy to test for this condition in the service method.

Developing Applications for the Java EE 6 Platform 7 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Using Annotations to Obtain an EJB Reference in


a Managed Component
1 @EJB private BankMgr bankMgr;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Access to a session bean from normal Java classes must


be obtained with JNDI.
• Managed components, such as a servlet and other EJBs,
can use this technique to obtain an EJB reference.
• You should note the following about the code snippet:
— A JNDI lookup or context is not required.
s a
— The container assigns a value to the bankMgr reference ) ha
variable when the servlet is instantiated. c o m
il ฺ ฺ
The initialization does not throw exceptions. ma ide

@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Using n
a dr rans to Obtain an EJB Reference to a Managed Component
Annotations
x -tthat cause dependency injection of EJB components can only be used in a
AleAnnotations
n o n
managed component. A managed component is an enterprise component, such as a servlet
or session bean, that has its life cycle managed by a container. The snippet shown in the slide
illustrates how a servlet can locate the EJB component at initialization time using an EJB
annotation.
When you store a reference to a stateless session EJB component in an instance variable,
you do not compromise thread safety for two reasons:
• First, the variable is only written once when the servlet is initialized.
• Second, calls on the business methods of a stateless session EJB component are
guaranteed to be thread-safe.
There are circumstances in which it is safe to store a reference to the EJB component itself in
an instance variable, but this approach is not advised unless you are absolutely familiar with
the EJB component-thread model. Concurrent access to a stateful session bean will be
serialized in Java EE 6; previous versions could have possibly raised an
ConcurrentAccessException.

Developing Applications for the Java EE 6 Platform 7 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Lite

EJB 3.1 Lite is a subset of the full EJB specification for use in
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

embedded EJB containers and servers supporting the Java EE


web profile.
EJB 3.1 Lite supports:
• Stateless, stateful, and singleton session bean
components
• Local and no-interface view only s a
) h a
• Synchronous method invocations only o m
• Container-managed transactions and bean-managed a ilฺc eฺ
transactions @ gm Guid
s o 8 ent
• Declarative and programmatic security
a r do Stud
a nc this beans, the EJB
Notably not supported are message-driven
(
Timer service, and remote o s o use
EJBs.
rda se t o
C
is © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d rans
a n
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 25


Pontifícia Universidade Católica do Rio Grande do Sul

EJBs Before the Java EE 5 Platform

The following table lists the various names used for the EJB
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

component elements for version 2.1 of the EJB specification.


Term Description
Remote client view Includes both the remote home interface and the
remote component interface

Local client view Includes both the local home interface and the local
component interface
s a
Home interface Generic term for the factory interface for an EJB )h a
o m
component regardless of it being local ฺor
a il c remote
eฺ a
Local home interface Extends the EJBLocalHome interface m
g Gu and i d
provides
local home object
o @
8 ent
s
Remote home interface Extends the EJBHome
a r do interfaceS tud and provides a remote
home object
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr ransBefore the Java EE 5 Platform
EJB Components
a t
x arena-variety
AleTheren o of terms that are used to talk about EJB components. Before the EJB 3.0
specification, EJB components were more complex and many companies might wish to
convert Java EE projects to use EJB 3.0 or 3.1 to reduce the complexity of applications.
Before the existence of local client views, introduced in the EJB 2.0 specification, the
component interface was often referred to as the remote interface, or as the EJB object. With
the introduction of local client views, and associated new terminology, the term “remote” has a
more specific meaning when referring to interfaces.
Unfortunately, old terminology does not always fade from use as fast as new technology is
introduced. You might hear colleagues referring to a remote interface, when, in fact, they
mean to be referring to the component interface, regardless of its local or remote client view.
The table in the slide provides a list of EJB component terminology, along with their
descriptions and equivalents.

Developing Applications for the Java EE 6 Platform 7 - 26


Pontifícia Universidade Católica do Rio Grande do Sul

EJBs Before the Java EE 5 Platform

EJB 2.1 Entity beans have been replaced with the Java
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Persistence API and non-EJB Entity classes.

Term Description
Component interface Generic term for the business method interface
regardless of it being local or remote

s a
Local component interface Extends the EJBLocalObject interface and provides
) h a
a local EJB object
c o m
Remote component interface Extends the EJBObject interface and

ail provides
eฺ a
remote EJB object
m
g Gu i d
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 27


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The role of enterprise components in a Java EE


application
• The two main EJB component types
• The two major enterprise tiers that are typically found in a
Java EE application
• The two general classifications of methods found on an as a
EJB component m )h
o
• The characteristics of the EJB component model a ilฺc eฺ
@ gm Guid
• The terminology used to describe theoelements
8 ent of an EJB
s
component rdo tud
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Summary
a n dr rans
x -t
AleA JavanoEEnapplication uses a suite of components that is managed by the EJB container to
provide the business functionality that is required by an enterprise business application. An
application developer can create distributed business applications that are scalable,
transactional, multiuser, and secure using EJB components.
The two basic types of Java EE components that are located in the EJB container are session
EJB components and message-driven beans.
Modern practice favors the division of enterprise components into tiers. There are generally
two major tiers that might be further subdivided into the following tiers, depending on the
application design:
• Services tier, which is typically implemented by one or more session EJB components
based on the Session Facade design pattern
• EIS-facing or object-relational mapping tier, which is typically implemented by non-EJB
entity components

Developing Applications for the Java EE 6 Platform 7 - 28


Pontifícia Universidade Católica do Rio Grande do Sul

Two general classifications of methods found on an EJB component are lifecycle methods
and business methods.
The EJB component model has the following characteristics:
• The model uses containers to encapsulate the component.
• The container provides proxies that allow clients limited, controlled access to the EJB
component.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The proxies implement interfaces that are provided by the EJB component developer.
• Clients make method calls on these interfaces.
The terminology used to describe the elements of an EJB component has changed because
the EJB specification has evolved.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 29


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are the three functions provided by an EJB container?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Provides timer services


b. Manages the life cycle of EJB components
c. Encapsulates access to external resources
d. Optimizes the performance of the database

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a da,r b,rcans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 30


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which of the following is not a purpose of the business


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

interface of an EJB?
a. Manage the life cycle of the EJB object
b. Provide an access point and type for clients
c. Specify to the server how to construct the EJB object
d. Serve as a framework for the behavior of the EJB
component s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dar rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 31


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which three EJB components are not included in EJB Lite?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Interceptors
b. Remote EJBs
c. EJB Timer service
d. Message-driven beans

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a db,r c,rdans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 32


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 7: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Creating and deploying a simple EJB component


module
• Using annotations and dependency injection
• Running a simple EJB client application
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 7 - 33


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Implementing EJB 3.1 Session Beans

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Compare stateless and stateful behavior
• Describe the operational characteristics of a stateless
session bean
• Describe the operational characteristics of a stateful
session bean s a
) h a
• Create session beans o m
• Package and deploy session beans a ilฺc eฺ
@ gm Guid
• Create a session bean client o8 nt
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8-2


Pontifícia Universidade Católica do Rio Grande do Sul

Comparison of Stateless and Stateful Behavior

Session beans can be stateless or stateful. The statefulness of


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a bean depends on the type of business function it performs:


• In a stateless client-service interaction, no client-specific
information is maintained beyond the duration of a single
method invocation.
• Stateful services require that information obtained during
one method invocation be available during subsequent s a
method calls: ) h a
c o m
– Shopping carts ฺ
ail ideฺ
– Multipage data entry m
g Gu
o @
8 ent
– Online banking s
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr of
Comparison
r a n s
Stateless and Stateful Behavior
e x - t
nonEE applications that have user interfaces require the retention of state data. State
Al Most Java
can be stored in any number of places including:
• User tier: State can be stored in objects in Swing-based applications or in cookies with
web-based applications. This is typically avoided because of security and performance
reasons.
• Web tier: Web clients can have their state stored on the web tier in
javax.servlet.http.HttpSession objects. If the web and EJB business tiers are
running in the same application server, there is no drastic performance penalty if local
business components are used. State management should be done in a centralized
business tier if nonweb clients are used for reusability.
• Database tier: Sometimes used to achieve increased retention time of state. It can
provide increased failover capabilities when a vendor’s Java EE application server lacks
or has not been configured with advanced clustering and failover features.
• Business or EJB tier: Session EJBs can hold client state. Because both web and
Swing UI applications can store state in the EJB tier, this allows most state management
code to be written only once. This is typically easier and faster than storing state in a
database.

Developing Applications for the Java EE 6 Platform 8-3


Pontifícia Universidade Católica do Rio Grande do Sul

Stateless Session Bean Operational


Characteristics
With stateless session beans:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The bean does not retain client-specific information


• A client might not get the same session bean instance
• A large number of client requests can be handled at the
same time. This has a profound impact on performance.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n drSession
Stateless
a r a n sBean Operational Characteristics
x usage -t is decreased and performance increased when using stateless session beans,
AleMemory
n o n
when compared to unnecessarily configuring a session bean as stateful.
Note: A common misconception is that stateless session beans cannot have instance
variables. It is valid for stateless session beans to have instance variables; however, clients
might not get the same bean on every method call, so from a client’s perspective, the value of
the variables can appear to change.

Developing Applications for the Java EE 6 Platform 8-4


Pontifícia Universidade Católica do Rio Grande do Sul

Stateless Session Bean Cardinality


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Client `
AuctionManagerBean

AuctionManager

s a
Client AuctionManagerBean
) h a
c o m

ail ideฺ
EJB Object m
g Gu
o @
8 ent
Pool of EJB instances
Client
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8-5


Pontifícia Universidade Católica do Rio Grande do Sul

Stateful Session Bean Operational Characteristics

With stateful session beans:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The bean belongs to a particular client for an entire


conversation
• The client connection exists until the client removes the
bean or the session times out
• The container maintains a separate EJB object and EJB
instance for each client s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Stateful
r
dSession n s Operational Characteristics
Bean
x a t r a
on- common misconception is that stateless session beans scale better than
AleNote:nAnother
stateful session beans. There is always a cost to maintain client state and maintaining more
state than is needed, or using stateful session beans when a stateless bean would be
adequate, negatively impacts performance. If an application must store client state, stateful
session beans are an effective way to store the client state.

Developing Applications for the Java EE 6 Platform 8-6


Pontifícia Universidade Católica do Rio Grande do Sul

Stateful Session Bean Cardinality


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

`
AuctionManagerBean
AuctionManager

Client

AuctionManager AuctionManagerBean

s a
Client
) h a
c o m
AuctionManager AuctionManagerBean ฺ
ail ideฺ
m
g Gu
o @
8 ent
Client
s
do Stud
a r
EJB Objects
( a nc this EJB instances
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8-7


Pontifícia Universidade Católica do Rio Grande do Sul

Singleton Session Bean Characteristics

A singleton session bean has the following characteristics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The container maintains a single EJB instance for each


application. There will be an instance for each per JVM.
• The bean can belong to multiple clients simultaneously.
– Concurrent access is controlled using Container Managed
Concurrency by default.
• The bean does not retain state across server shutdown or s a
restart. ) ha
c o m

ail ideฺ
A singleton session bean uses the javax.ejb.Singleton
annotation.
m
g Gu
o @
8 ent
@Singleton s
do Stud
a r
public class CacheBean a{...} nc this ( se
s o
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Singleton
a drSession
r a n s Bean Characteristics
x -t session beans, a singleton session bean will maintain state across method
Alecalls. o n
Unlike stateless
nAdditionally, state is shared by all clients because all clients will access the same bean
instance.
The methods of a singleton session bean can be concurrently accessed by multiple clients.
By default, a singleton session bean’s concurrent access is controlled by the container using
Container Managed Concurrency. Container Managed Concurrency supports a multiple
reader, single writer locking strategy. Every method of a singleton session bean attempts to
obtain a Write lock by default. Methods can be annotated with either of the following:
@javax.ejb.Lock(javax.ejb.LockType.WRITE)
@javax.ejb.Lock(javax.ejb.LockType.READ)

Developing Applications for the Java EE 6 Platform 8-8


Pontifícia Universidade Católica do Rio Grande do Sul

Creating Session Beans

• Declare a business interface for the session bean (optional


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

for EJB 3.1 local beans).


• Create the session bean class that implements the
business interface if one exists.
• Configure the session bean by either annotating the
session bean class or providing a deployment descriptor.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8-9


Pontifícia Universidade Católica do Rio Grande do Sul

Declaring a Business Interface for


the Session Bean
A session EJB component’s business interface has the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following characteristics:

• Outlines the EJB component’s business methods


• Declares the session as a distributed component (optional)

s a
1 import javax.ejb.*;
) h a
2
c o m
3
@Remote ฺ
ail ideฺ
4
public interface HelloSession { m
g Gu
@
8 ent
public java.lang.String hello(); so
do Stud
5
a r
}6
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Creating the Session Bean Class That Implements


the Business Interface
A session EJB component’s class has the following
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

characteristics:
• Is often referred to as the bean class, implementation
instance, or EJB class
• Implements the component’s business interface (only if
one exists in EJB 3.1)
• Contains code that implements bean lifecycle methods s a
h a
(optional) m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Creating the Session Bean Class That Implements


the Business Interface
1 import javax.ejb.*;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2
3 @Stateless
4 public class HelloSessionBean implements HelloSession {
5
6 public java.lang.String hello() { return "Hello World!";}
7 }

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Declaring a Local Session Bean

• How can a session bean be designated as local?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

@Local
public interface Calculator {...}
@Stateless
public class CalculatorBean implements Calculator {...}

public interface Calculator {...}


@Local @Stateless
s a
public class CalculatorBean implements Calculator {...}
) h a
c o m
public interface Calculator {...} ฺ
ail ideฺ
@Stateless m
g Gu
o @
8Calculator n t {...}
public class CalculatorBean implements
s e
a r do Stud
@Stateless
( a nc this
public class CalculatorBean
o s o {...}u se
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Declaring
a drLocalr a n s Remote Session Beans
and
x -t frequently asked questions (FAQ) provide additional guidelines to assist you
AleThe following
n o n
with the task of declaring session beans.
1. What are the requirements for the session bean business interface?
A session bean’s business interface is a plain Java technology interface. The business
interface can have super interfaces. The business methods can throw arbitrary
application exceptions.
2. How are business interfaces classified?
A session bean can define both a local and a remote business interface. A business interface
to a session bean can be:
• A local interface
• A local interface providing access to code that executes on the same Java Virtual
Machine (JVM™) as the session bean component
• A remote interface
• A remote interface providing access to code that executes on a JVM that is different
(remote) from that of the session bean component

Developing Applications for the Java EE 6 Platform 8 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Declaring a Remote Session Bean

• How can a session bean be designated as remote?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

public interface Calculator {...}


@Remote @Stateless
public class CalculatorBean implements Calculator {...}

@Remote
public interface Calculator {...}
@Stateless
s a
public class CalculatorBean implements Calculator {...}
) h a
c o m
• Are there any additional requirements for remote ฺ
ail ideฺ
interfaces? m
g Gu
o @
8 ent
• Can a session bean have more than d o s one ubusiness
d
a r S t
interface?
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Declaring
a drLocal
r a n s Remote Session Beans (continued)
and
x -t a business interface be designated a local interface?
Ale 3. nHow
oncan
To specify an interface as a local interface, use the Local annotation on the interface or
the bean class. For example:
- @Local public interface Calculator {...}
- @Stateless public class CalculatorBean implements Calculator
{...}
Alternatively, you can use the Local annotation on the bean class. For example:
- public interface Calculator {...}
- @Local @Stateless public class CalculatorBean implements
Calculator {...}
• Or you use the default locality, which is local:
- public interface Calculator {...}
- @Stateless public class CalculatorBean implements Calculator
{...}

Developing Applications for the Java EE 6 Platform 8 - 14


Pontifícia Universidade Católica do Rio Grande do Sul
4. How can a business interface be designated a remote interface?
To specify an interface as a remote interface, use the Remote annotation on the
interface or the bean class. For example:
@Remote public interface Calculator {...}
@Stateless public class CalculatorBean implements Calculator
{..}
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Alternatively, you can use the Remote annotation on the bean class. For example:
public interface Calculator {...}
@Remote @Stateless public class CalculatorBean implements
Calculator {..}
What are the requirements for a no-interface local view session bean?
5. The bean class has the same requirements as in the examples of a local interface bean.
All EJB-related annotations must be placed on the bean class because no interface exists. a
@Stateless public class CalculatorBean {...} h a s
) m
6. Are there any additional requirements for remote interfaces?
ฺ c o
- The remote business interface is not required or expected to be a
m ail ideฺ
java.rmi.Remote interface.
@ g Gu
o 8interface
e n t timers, or timer
- A remote interface method must not expose local s
do Stud
types,
handles. a r
- The arguments and return types(of a nthec methods
t his must be of valid types for
RMI/IIOP. so us e
d o to of the interface should not include the
rthe methods
- The throws clauses a
of e
i d is C licens
java.rmi.RemoteException.
7. Can a session
a have
olbean le more than one business interface?
N i c a b
r class can implement multiple interfaces. To designate an interface
- reA sessionfe bean
d s
anbusiness interface of a bean class, use any of the following options:
e x an as - t rthe
Al n-onLocal or remote annotation on the interface
- Local or remote annotation on the implementing bean class
- Local or remote designation in the deployment descriptor associated with the bean
class

Developing Applications for the Java EE 6 Platform 8 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Requirements for a Session Bean Class

• The class must be a top-level class. In addition, the class


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

must be defined as public, must not be final, and must not


be abstract.
• The class must have a public constructor that takes no
parameters. The container uses this constructor to create
instances of the session bean class.
• The class must not define the finalize method. a
h a s
• The class must implement the methods of the bean’sm )
co ฺ
business interfaces, if any. ailฺ m uide
g
@ nt G
o 8
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rafor
Requirements
a n sa Session Bean Class
x -tbean class must comply with the design rules as stated in the slide.
AleThe session
n o n
Note: EJB 3.1 stateful session beans do not have a method to pass in initialization
parameters during lookup and creation. You must pass any initialization data as parameters
to a method call after lookup.

Developing Applications for the Java EE 6 Platform 8 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

Annotating the Session Bean Class


Annotation Applies to

Stateful Session bean class


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Stateless
Singleton
Local Session bean class or business
Remote interface

Remove Stateful session bean method

Other common annotations: a


h a s
• Transaction-related annotations m )
o
• Security-related annotations a ilฺc eฺ
• Lifecycle callback handler method annotations
@ gm Guid
s o 8 ent
• Resource-related annotations rdo
a S tud
( a nc the
When not specific to session beans, t his@EJB and @Resource
e
o us beans.
dosin session
annotations are often used o
ar se t
C
is © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i
N ferac
r e
d the n s
x a n
Annotating
t r a Session Bean Class
e -
n specification provides a number of annotations that you can use to supply
Al The EJB
no3.1
metadata about the session bean class. The following code shows an example of a stateless
session bean class that demonstrates the use of annotations. You can identify the
annotations by the leading @ character that prepends each annotation.
Examine below a session bean code with annotation:
@Stateless public class CalculatorBean implements Calculator {
public int add(int a, int b) {
return a + b;
}

public int subtract(int a, int b) {


return a - b;
}
}
The table in the slide contains a brief explanation of the most commonly used annotations
applicable to a session bean.

Developing Applications for the Java EE 6 Platform 8 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Life Cycle of a Stateless Session Bean

Does Not
Exist
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1. Dependency injection, if any


PreDestroy callbacks if any
2. PostConstruct callbacks, if any

s a
) h a
c o m
method Ready
Timeout
callback if any

ail ideฺ
m
g Gu
o @
8 ent
• PostConstruct callback s
a r d o
S t ud
• PreDestroy callback nc this
( a
o use
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Lifecycle
a drEventr a n s
Handlers
x -t
AleWith EJB
n o n
3.1, you are not required to provide lifecycle event handlers for session beans.
However, session beans do generate lifecycle events and you can optionally provide event
handlers for these methods.
A stateless session bean generates the following lifecycle events:
• PostConstruct
• PreDestroy
The stateless session bean lifecycle diagram shown in the slide provides the context for the
stateless session beans lifecycle events.

Developing Applications for the Java EE 6 Platform 8 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Life Cycle of a Stateful Session Bean

Does Not
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Exist Timeout

1. Dependency injection, 1. Remove method or


if any Timeout
2. PostConstruct 2. PreDestroy callbacks, if
callbacks, if any any

PrePassivate
callbacks, if any
method Ready Passive s a
) h a
PostActivate
c o m
callbacks, if any ฺ
ail ideฺ
• PostConstruct callback m
@ g Gu
• PreDestroy callback
s o 8 ent
• PostActivate callback a r do Stud
a n c his
• PrePassivate callback o ( e t
s s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr of raaStateful
Life Cycle
a n s Session Bean
x -tsession bean lifecycle diagram shown in the slide provides the context for the
AleThe stateful
n o n
stateful session bean’s lifecycle events.

Developing Applications for the Java EE 6 Platform 8 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Example of a Callback Method in a Bean Class

1 import javax.ejb.*;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2 import java.util.*;
3
4 @Stateful public class ShoppingCartBean implements
ShoppingCart {
5 private float total;
6 private List productCodes;
7 public int someShoppingMethod() {...}; s a
8 //... ) h a
9 o
c ฺm
@PreDestroy private void endShoppingCart()ilฺ{...};
a e
10 } gm uid @ nt G
o 8
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Example n r a Callback
dof n s Method in a Bean Class
x a -t r a
Ale(endShoppingCart)
o
The code
n nin the slide shows an example of a lifecycle event handler method
defined within a bean class.
A callback method defined in a bean class is required to have the following signature:
anyAccessModifier void methodName()
Note: The method can have any name and any access modifier. The method’s return type
must be void and it must have zero arguments.

Developing Applications for the Java EE 6 Platform 8 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

The SessionContext Object

Use the SessionContext object to access EJB objects,


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

obtain current transaction status, and obtain security


information.

1 import javax.ejb.*;
2 import javax.annotation.*;
3
s a
4 @Stateful
) h a
5 public class BankingBean implements Bank {
c o m

ail ideฺ
6 m
g Gcontext;
u
7 @Resource private javax.ejb.SessionContext
o8 den@ t
o s
8
c a rd Stu
9 }
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Session Bean Packaging and Deployment

Packaging and deployment tasks:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Optionally create a deployment descriptor file for the


session bean component
• Create a deployable session bean component archive
• Deploy the session bean component archive

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Session Bean Deployment Descriptor

1 <ejb-jar>
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2 <enterprise-beans>
3 <session>
4 <ejb-name>ReportBean</ejb-name>
5 <business-remote>services.Report</business-remote>
6 <ejb-class>services.ReportBean</ejb-class>
7 <session-type>Stateful</session-type>
8 <transaction-type>Container</transaction-type>
9 </session>
10 <!-- Deployment information for additional beans goes here-->
s a
11 </enterprise-beans>
) h a
12
c o m
13 <assembly-descriptor>

ail ideฺ
14 <!-- Add assembly information here--> m
g Gu
15 </assembly-descriptor> o @
8 ent
s
do Stud
16 </ejb-jar>
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Deployment
Introducing
a r a n s Descriptors
e x - t
non descriptor is an XML file that provides configuration information to the
Al A deployment
application server to configure the enterprise bean component during deployment.
There are two main types of deployment descriptors:
• Enterprise bean component deployment descriptors
An enterprise bean component deployment descriptors file is named
ejb-jar.xml. The ejb-jar.xml file contains deployment information for session,
entity (EJB 2.1), and message-driven beans. EJB component deployment descriptors
contain the following types of configuration information.
- Structural information
Structural information describes the structure of an enterprise bean and declares
an enterprise bean’s external dependencies.
- Application assembly information
Application assembly information describes how the enterprise bean (or beans) in
the ejb-jar.xml file is composed into a larger application deployment unit.

Developing Applications for the Java EE 6 Platform 8 - 23


Pontifícia Universidade Católica do Rio Grande do Sul
A single ejb-jar.xml file can contain deployment information for one or more enterprise
beans. Refer to chapter 19 of JSR 318: Enterprise JavaBeans, Version 3.1 EJB for the XML
schema for deployment descriptors associated with enterprise bean components.
• Java EE application deployment descriptors
The Java EE deployment descriptors file is named application.xml. It contains
deployment information for the Java EE application. Refer to The Java™ Platform,
Enterprise Edition Specification, v6.0, Chapter 8 for the XML schema for deployment
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

descriptors associated with Java EE applications.


As of EJB 3.0, you can embed configuration information for enterprise components using
metadata annotations in the bean component’s source code.
If all the configuration information needed for an enterprise bean is supplied using metadata
annotations, you are no longer required to supply a deployment descriptor. You are required
to supply a deployment descriptor if any of the required configuration information was not
supplied using metadata annotations. Optionally, you can use a deployment descriptor to
s
override any application assembly information originally embedded in the component’s source
a
) h a
code using metadata annotations. However, you must not override structural information.
c o m

ail ideฺ
The deployment descriptor for an enterprise bean is part of the component archive that
m
contains the bean. In addition to the deployment descriptor, an archive also contains all the
g Gu
enterprise bean classes.
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Packaging

Session beans must be packaged in an enterprise module to


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

be deployed. They may be packaged in:


• An EJB-JAR file. EJB-JAR files are typically bundled in a
EAR file.
• A WAR file. EJB 3.1 allows EJB components to be
packaged in a web module.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rans
EJB Packaging
a
x bean -t components must be packaged in a deployable enterprise module to be
AleSession
n o n
deployed. Java EE 5 and previous applications require EJB components to be packaged in an
EJB JAR file. The rules for EJB JAR files are outlined in the section, “Creating an EJB Bean
Component Archive.”
EJB 3.1 beans can be packaged in a WAR file which eliminates the need for both EJB JAR
and EAR files. When EJB components are packaged in a WAR file, the deployment descriptor
(ejb-jar.xml) is placed in the WEB-INF directory.

Developing Applications for the Java EE 6 Platform 8 - 25


Pontifícia Universidade Católica do Rio Grande do Sul

Creating an EJB Bean Component Archive

1. Create a working directory structure.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2. Copy the EJB component class files and helper classes


into their corresponding subdirectories.
3. Create a META-INF subdirectory off the root directory.
4. From a command line, execute the jar utility to create the
EJB JAR archive.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
r EJBnBean
dan s Component Archive
a -t
x component r a
AleAn EJB
n o n archive is an EJB module, which is sometimes referred to as an EJB JAR
file. You can create EJB JAR files using a GUI associated with an IDE or a Java EE
application server. Alternatively, you can create the EJB JAR file using a command-line tool
(utility), such as the Java technology archive tool jar. The following steps outline the process
of creating an EJB JAR file using the jar utility:
1. Create a working directory structure.
- Create a root directory.
Off the root directory, create the package directory structure corresponding to the
EJB component classes and helper classes.
2. Copy the EJB component class files and helper classes into their corresponding
subdirectories. For example, you should include the following classes:
- The enterprise bean implementation class, business interfaces, and their super
classes
- All classes referenced by the enterprise bean’s class, interfaces, and their super
classes

Developing Applications for the Java EE 6 Platform 8 - 26


Pontifícia Universidade Católica do Rio Grande do Sul
- An EJB module’s JAR file must not contain the following:
Java EE platform API classes and Java SE platform API classes
For example, the JAR file must not contain classes, such as: java.lang.String
or javax.ejb.EJBException.
3. Create a META-INF subdirectory off the root directory.
4. If a deployment descriptor is used to configure the enterprise bean, copy the deployment
descriptor file (ejb-jar.xml) for the EJB components into the META-INF directory.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

You must examine the deployment descriptor file to ensure that all required elements
have been supplied for the EJB components included in the EJB JAR archive.
Most application servers also require you to include a vendor-specific deployment
descriptor in the META-INF directory. For example, the GlassFish Application Server
names this file sun-ejb-jar.xml.
5. From a command line, execute the jar utility to create the EJB JAR archive.
If you examine the created EJB JAR archive, you see that it includes a manifest file
called MANIFEST.MF in the META-INF directory.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 27


Pontifícia Universidade Católica do Rio Grande do Sul

Example of the EJB Module JAR File


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

(/)Root
META-INF

ejb-jar.xml

MANIFEST.MF

auctionsystem
ejbs

AuctionManagerBean.class
s a
AuctionManagerRemote.class ) h a
c o m
AuctionManagerLocal.class

ail ideฺ
dtos
m
g Gu
BidStatusMessage.class
o @
8 ent
s
do Stud
PlaceBidMessage.class
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Examplen r the EJB
dof n s Module JAR File
x a -t r a
AleThe figure
n o nin the slide illustrates the directory structure and class files used to create the
auction system EJB module’s JAR file.
Deploying a Session Bean Component Archive
Deploying a session bean component archive, or for that matter any EJB module, is specific
to the application server. Most application servers provide the following two deployment
options:
- IDE-based deployment support
- Command-line based deployment support
For additional information on deployment, refer to the documentation associated with the
application server you are using.

Developing Applications for the Java EE 6 Platform 8 - 28


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Session Bean Client

Any managed component, such as a session EJB, message-


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

driven EJB, or servlet can use dependency injection to locate


an EJB using annotations and an instance variable.
Creating a client using container services:
1 import javax.ejb.*;
2
3 public class InternalClient { s a
4 @EJB // step 1 ) h a
o m
5 private static Calculator calc;
a ilฺc eฺ
6
@ gm Guid
7 o 8 en{t
public static void main (String sargs[])
8 int sum = calc.add(1, 2); a r udstep 2
do St//
9 } ( a nc this
o s o use
10 } d o
ar se t
C
is © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
da Session n s Bean Client
x a n
Creating
r a
t to the task of creating session bean clients, you should examine the
on-
AleBeforenproceeding
answers to the following questions.
What are some examples of session bean clients?
• Another enterprise bean, such as another session or entity bean
• A web component, such as a servlet
• A plain Java class, such as an application client
What factors should be considered when writing a session bean client?
The most important factor is the availability of standard container services, in particular
naming lookup and injection services. These services are supplied as standard by the
application server container for Java EE components.
What is an application client container?
In the case of a plain Java class, such as an application client, you can use an application
client container to provide these services. Alternatively, you can obtain the services an
application client requires from Java SE class methods, such as methods from the
javax.naming.InitialContext.

Developing Applications for the Java EE 6 Platform 8 - 29


Pontifícia Universidade Católica do Rio Grande do Sul
An application client container is a set of classes that work together to provide a hosting
environment for an application client. The hosting environment includes a JVM and a set of
services. These services include security, naming, injection, and communication (with the
application server container) services. A client using the application container executes in a
different JVM to that of the application server.
The packaging of the classes that make up the application client container is vendor specific.
Some vendors provide an application client container as a JAR file. Application client
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

containers are installed on the client machine.


Creating a Client Using Container Services
The following steps outline a process for creating a client that uses container services to
access the services of a session bean. Any managed component can use container services.
Managed components include Session EJBs, Message EJBs, and Servlets.
1. Use injection services of the container to obtain a reference to the session bean object.
2. Invoke the required services of the session bean object. a
a s
The code in the slide contains an example of a client that uses container services tohaccess a
session bean. m )
o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 30


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Session Bean Client

Creating a client without using container services:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 import javax.naming.*;
2 import javax.rmi.*;
3
4 public class ExternalClient {
5 public static void main (String args[]) {
6 // step 1 begin
7 Context ctx = new InitialContext(); s a
8 Object obj = ctx.lookup("ejb/Calculator"); ) h a
c o m
9 Calculator calc = (Calculator) ฺ
ail ideฺ
10 PortableRemoteObject.narrow(obj, Calculator.class); m
g Gu
11 // step 1 end
o @
8 ent
12 int sum = calc.add(1, 2); // step 2 s
do Stud
a r
13 }
( a nc this
14 }
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Client
r a n sWithout Using Container Services
x -t steps outline a process for creating a session bean client that is external to a
AleThe following
n o
container.
n
1. Use JNDI naming services to obtain a reference to the session bean object.
2. Invoke the required services of the session bean object.
The code in the slide contains an example of a client that uses JNDI naming services to
access a session bean.

Developing Applications for the Java EE 6 Platform 8 - 31


Pontifícia Universidade Católica do Rio Grande do Sul

Session Bean Client Reference Types

• If a session bean has a business interface(s), the client will


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

use the interface as the reference type to the session


bean.
• If a session bean has no business interface (no-interface
view), the client will use the bean class as the reference
type to the session bean.
• Clients do not instantiate the bean directly, regardless of s a
reference type. ) ha m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 32


Pontifícia Universidade Católica do Rio Grande do Sul

Portable JNDI Session Bean Clients

The EJB 3.0 and previous specifications do not require session


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

beans to have a standard JNDI name. To perform portable


JNDI lookups of a session bean requires editing the web.xml
file or the ejb-jar.xml file depending on the client type.
A web tier example:
<ejb-ref>
<ejb-ref-name>BrokerLookup</ejb-ref-name>
s a
<ejb-ref-type>Session</ejb-ref-type>
) h a
<remote>trader.BrokerModel</remote>
c o m
</ejb-ref> ฺ
ail ideฺ
m
g Gu
try {
o @
8 ent
s
do Stud
Context ctx = new InitialContext();
a
c his r
model =
( a n t
o
(BrokerModel)ctx.lookup("java:comp/env/BrokerLookup");
s s e
} catch(NamingException
a to u }
rdone)e {...
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 33


Pontifícia Universidade Católica do Rio Grande do Sul

Global JNDI Names

The Environmental Naming Context (ENC) is a JNDI context


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

that can be accessed via java:comp/env. This context is used


to create portable JNDI names for EJBs. Names in the ENC are
created with entries in a deployment descriptor.
EJB 3.1 specifies standard JNDI names for EJB components.
java:global[/<app-name>]/<module-name>/<bean-name>
java:app[/<module-name>]/<bean-name>
s a
java:module/<bean-name>
) h a
o m
a ilฺc JNDI
Dependency injection annotations can target a specific
eฺ
name. g m u i d
o 8 @ nt G
@EJB(mappedName="java:global/fooejb/FooBean")
r d os tude
FooRemote foo;
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 34


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Differentiate session bean types: stateful, stateless, and


singleton
• Declare the business interface for the session bean
• Create the session bean class that implements the
business interface
• Annotate the session bean class s a
) h a
m
• Add handling code for lifecycle callback events, if required
o
• Package the session bean a ilฺc eฺ
@ gm Guid
• Deploy the session bean s o 8 ent
• Create the client a r do Stud
c sa n hi
( e t
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 35


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are the two types of session beans?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Stateless and stateful


b. Stateful and synchronized
c. Stateless and synchronized
d. Synchronized and state ready

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dar rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 36


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are the three characteristics of a stateless session bean?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. It retains client-specific information.


b. It does not retain client-specific information.
c. A client may not get the same bean instance.
d. A large number of requests can be handled by the same
bean.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a db,r c,rdans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 37


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are the three characteristics of a stateful session bean?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. It does not retain client-specific information.


b. Bean belongs to a client for an entire conversation.
c. Connection exists until a timeout or the bean is removed.
d. It maintains a separate EJB object and EJB instance for
each client.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a db,r c,rdans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 38


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Identify a unique feature of a singleton session bean.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. The bean retains state across server restarts.


b. Bean methods can be accessed by only one client.
c. Bean methods can be accessed by multiple clients.
d. Only one bean of this type may be created in a container.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dcr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 39


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 8: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Coding a session EJB component


• Creating EJB references for web-tier clients
• Creating a Java SE EJB client
• Describing session beans
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 8 - 40


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

The Java Persistence API

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe the role of the Java Persistence API (JPA) in a
Java EE application
• Explain the basics of object-relational mapping
• Describe the elements and environment of an entity
component s a
) h a
• Describe the life cycle and operational characteristics
o mof
c
entity components ailฺ eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

The Java Persistence API

The Java Persistence API:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Replaces EJB 2.1 entity beans with non-EJB entity classes


• Is a standard API for specifying object-to-relational
mapping information
• Can be used with or without a Java EE Application Server
– Container-managed persistence
– Application-managed persistence s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
The Java
a drPersistence
r a n s API
x -tof Java persistence are defined in the Java persistence specification (JSR 317).
AleThe features
n o n
Data persistence is the mechanism used by applications to preserve application data (that
would be lost by application shutdown or computer power down) in a persistence store, such
as a database.
The Java persistence specification is the specification of the Java API for the management of
persistence and object/relational mapping with Java EE and Java SE. The technical objective
of the specification work is to provide an object/relational mapping facility for the Java
application developer using a Java domain model to manage a relational database.
All Java EE application servers are required to provide an implementation of the Java
Persistence API

Developing Applications for the Java EE 6 Platform 9 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Object Relational Mapping

Object-relational mapping (ORM) software:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Provides an object-oriented view of the database


• Examples include EclipseLink and Hibernate

s a
Customer
Entity ) h a
Component
c o m

ail ideฺ
m
g Gu
Customer
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
dr ransMapping Software
ObjectnRelational
a
x n-tpersistence mechanism used in most enterprise applications is a relational
AleThe denofacto
database. Object-oriented (OO) program design and relational database table structure might
not organize data in the exact same structure. A Java business domain object can:
• Encompass partial data from a single database table or
• Include data from multiple tables depending on the normalization of the relational
database
The figure in the slide shows a business concept having a one to one translate into a OO
domain object but having to span multiple tables in a relational database.
Object-relational mapping (ORM) software attempts to provide this mapping to OO software
developers without requiring much or any coding. Often just configuration information in the
form of code annotations or XML configuration files are supplied to ORM software.
Note: EclipseLink, http://www.eclipse.org/eclipselink/, is the continuation of Oracle’s open
source version of Toplink. Oracle donated the source code for Toplink, a JPA 1.0 provider, to
the Eclipse Foundation. EclipseLink is the reference implementation for the JPA 2.0
specification.

Developing Applications for the Java EE 6 Platform 9 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Normalized Data Mapping


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Customer

Customer

Account

s a
Account
) h a
c o m
Address

ail ideฺ
m
g Gu
o @
8 ent Address
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Mapping
One-to-One
a r a n s of Java Objects to Relational Tables
x -t
AleThe most
n o n
basic ORM software supports a simple mapping of Java objects to database tables,
as shown in the figure in the slide.

Developing Applications for the Java EE 6 Platform 9 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Use of an Entity Component Across a Set of


Database Tables
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Customer

Customer
Entity
Components
s a
Account
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent Address
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rMapping
One-to-Many a n s of a Java Object to Relational Tables
x ORM -t software has the ability to map Java objects to database table structures that do
AleModern
n o n
not have a simple one-to-one mapping as shown in the figure in the slide.
• J2EE 1.4 application servers provide EJB 2.1 container managed persistence (CMP)
EJBs as the standard ORM technique.
• Other ORM methods, such as Java Data Objects (JDO), also exist.
• The Java Persistence API attempts to combine the best features from existing ORM
technologies while removing the application server requirement of EJB 2.1 CMP EJBs.
- The JPA specification is just a specification for an API and for lifecycle behavior. It
is not usable ORM software.
- A Java Persistence API provider is required to use the Java Persistence API.
- Two examples of a Java Persistence API provider are EclipseLink and Hibernate.

Developing Applications for the Java EE 6 Platform 9 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Class Requirements

Entity classes are coded as standard Java classes with the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following requirements:
• javax.persistence.Entity annotation on the class
or declared as an entity in a deployment descriptor
• Must be a public class
• No-argument constructor with public or protected access
• Open to extension, that is, they are not final classes s a
) h a
• Implement Serializable if they are to be returned o mby
remote session beans a ilฺc eฺ
@ gm Guid
• Top-level class, entity classes cannotobe
8 innerntclasses
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Entity n
a dr Requirements
Class
r a n s
x -t steps outline a process that you can use to declare an entity class.
AleThe following
n o n
1. Collect information required to declare the entity class.
This step involves identifying the application domain object (identified in the object-
oriented analysis and design phase of application development) that you want to persist.
• Use the domain object name as the class name.
• Use the domain object field names and data types as the field names and types of
entity classes.
2. Declare a public Java technology class.
The class must not be final, and no methods of the entity class can be final. The class
can be concrete or abstract. The class cannot be an inner class.
3. If an entity instance is to be passed by value as a detached object through a remote
interface, ensure that the entity class implements the Serializable interface.
4. Annotate the class with the javax.persistence.Entity annotation.
5. Declare the attributes of the entity class.
Attributes must not have public visibility. They can have private, protected, or package
visibility. Clients must not attempt to access an entity classes’ attributes directly.

Developing Applications for the Java EE 6 Platform 9 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Class Example

1 import java.io.Serializable;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2 import javax.persistence.*;
3
4 @Entity @Table(name = "TABLE1")
5 public class MyEntity implements Serializable {
6
7 @Id @Column(name = "ID") private int id;
8 @Column(name = "MSG") private String message;
9
10 protected MyEntity() { }
11 public MyEntity(int id, String message) {
s a
12
13
this.id = id;
this.message = message; ) h a
c o m
14
15
}

ail ideฺ
16 public int getId() { return id; } m
g Gu
17 public String getMessage() { return message; }
o @
8 = message; n t }
s e
do Stud
18 public void setMessage(String message) { this.message
19 }
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Entity n
a dr Requirements
Class
r a n s (continued)
e x - t
Al 6. nYouoncan optionally declare a set of public getter and setter methods for every attribute
declared in the previous step.
7. Annotate the primary key field or the getter method that corresponds to the primary key
column with the Id annotation.
8. Declare a public or protected no-arg constructor that takes no parameters. The
container uses this constructor to create instances of the entity class. The class can
have additional constructors.
The code in the slide shows an example of an entity class.

Developing Applications for the Java EE 6 Platform 9 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Verifying and Overriding the Default Mapping


The following table outlines the default standard relationship between entity classes and
relational databases.
Object-Tier Element Database-Tier
Entity class Database table
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Field of entity class Database column


Entity instanceDatabase table record

The default database table name can be overridden using the Table annotation. The Java
Persistence API assigns the name of the entity class as the default name to the database
table. For example:
@Entity
s a
@Table(name = "Cust")
public class Client {
//Cust is the name of the database table
) h a
c o m
//... ฺ
ail ideฺ
} m
g Gu
The Java Persistence API assigns the name of the entity class
o @
8 ent (or field) name as the
property
s
default name to the database table column. Use the Column
a r tud to override the
do Sannotation
default setting. For example:
( a nc this
@Entity
o s o use
ard {se to
@Table(name = "Cust")
public class C
i d e n
is =lic"cname")
Client

ola String
@Column(name
i c a b le clientName;
r N private
e //... f er
d s
e x an -t}ran
Al non
You have several options available for generating the values of primary keys. The simplest of
these is to use the auto generation feature of the container, as shown in the following
example.
@Entity
@Table(name = "Cust")
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int clientReference;
//...
}
When using @GeneratedValue(strategy = GenerationType.AUTO), Toplink creates
a sequence table in the relational database. Other JPA providers can use different techniques
to create unique IDs.

Developing Applications for the Java EE 6 Platform 9 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Persistent Fields as Opposed to Persistent


Properties
Entity classes have their state synchronized with a database.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The state of an entity class is obtained from either its variables


(fields) or its accessor methods (properties).
• Field-based or property-based access is determined by the
placement of annotations.
• JPA 1.0 cannot have both field-based and property-based
access. s a
) h a
• JPA 2.0 can mix field-based and property-based access m
o
using the javax.persistence.Access annotation. ilฺc ฺ
g ma uide
o 8 @ nt G
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Persistent Fields

When using persistent fields, the persistence provider retrieves


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

an object’s state by reading its variables.


• Persistent fields cannot be public
• They should not be read by clients directly.
• Unless annotated with @Transient or modified with the
transient keyword, all variables are persisted regardless of
whether they have a @Column annotation. s a
@Id @Column(name = "ID") private int id; ) ha
m
ฺ c o
@Column(name = "MSG") private String message;
m ail ideฺ
@ g Gu
public int getId() { return id; } o8
e n t
s
public String getMessage() { return
a r domessage; S tud }
public void setMessage(String
( a ncmessage) t his { this.message =
message; }
so us e
r d o to
a e
i d is C©li2011,
c e s
nOracle
o l a le
Copyright and/or its affiliates. All rights reserved.

N ic rab
n d re nsfe
l e xa n-tra
A no

Developing Applications for the Java EE 6 Platform 9 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Persistent Properties

When using persistent properties, the persistence provider


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

retrieves an object’s state by calling its accessor methods.


• Methods must be public or protected.
• Methods follow the JavaBeans naming convention.
• Persistence annotations can only be on getter methods.
private int id;
private String message; s a
) h a
@Id @Column(name = "ID") public int getId() { return id; }
c o m
public void setId(int id) { this.id = id; }

ail ideฺ
m
g Gu
o @
8 ent
@Column(name = "MSG")
s
do }Stud
public String getMessage() { return message;
a r
public void setMessage(String message)
( a nc {ththis.message
is = message; }

o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Persistence Data Types

Persistence fields or properties can be of the following data


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

types:
• Java primitive types
• Java wrappers, such as java.lang.Integer
• java.lang.String
• byte[] and Byte[]
a
• char[] and Character[]
) has
• Any serializable types including but not limited to:ฺcom
– java.util.Date m ail ideฺ
@ g Gu
– java.sql.Date
s o 8 ent
– java.sql.TimeStamp a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Persistent
a dr Data
r a n s
Types
x Complex -t data types that do not have simple mapping, such as a java.lang.String
AleNote: n o n
to a VARCHAR or CHAR column might require additional annotations. These annotations are
described in the course titled Building Database-Driven Applications with Java Persistence
API .

Developing Applications for the Java EE 6 Platform 9 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

The Concept of a Primary Key

• An entity component distinguishes itself and the data it


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

represents from other entities by using a primary key.


• A primary key gives an entity instance its persistent
identity.
• They are typically a string or an integer, but can also be
custom classes that correspond to several database table
columns. s a
) h a
• Every entity class must have a primary key. m
c o
• They can be auto-incrementing. ailฺ eฺ
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@ gm Guid
@Column(name = "ID", nullable = ofalse) s o8 dent
c a rd Stu
his
private int id;
( a n t
so us e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Component Primary Key Association


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

`
<<customer>>
Primary Key 102 Database

Customer Table

102
<<customer>>
-
Primary Key 105 -
-

s a
105
-
) h a
-

c o m
<<customer>>
926
-

ail ideฺ
Primary Key 976 m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Entity n
a dr ransPrimary Key Association
Component
x -t
AleThe figure
n o nin the slide shows relationship between entity instances and tables rows.

Developing Applications for the Java EE 6 Platform 9 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Persistence Units

A persistence unit is a collection of entity classes stored in a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJB-JAR, WAR, or JAR archive along with a


persistence.xml file. A persistence unit:
• Defines what entity classes will be controlled by an entity
manager
• Is limited to a single datasource
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr andraOperational
Life Cycle n s Characteristics of Entity Components
e x - t
n classes, there are several key concepts that must be understood to begin
Al Besides
noentity
leveraging the Java Persistence API. They are:
• Entity manager
• Persistence context
• Persistence unit
• Persistent identity

Developing Applications for the Java EE 6 Platform 9 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

The persistence.xml file

The persistence.xml file:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Configures which classes make up a persistence unit


• Defines the base of a persistence unit
• Specifies the datasource used
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
s a
xmlns="http://java.sun.com/xml/ns/persistence">
) h a
<persistence-unit name="BrokerTool-ejb" transaction-
o m
type="JTA">
a ilฺc eฺ
gm Guid
<jta-data-source>StockMarket</jta-data-source>
@
s
<jar-file>BrokerLibrary.jar</jar-file>o 8 ent
<properties/> a r do Stud
</persistence-unit> ( a nc this
o s o use
</persistence> rd to
a se
s C
i © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d rans
a n
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

The Persistence Context

A persistence context can be thought of as a working copy of a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

persistence unit. Several persistence contexts using the same


persistence unit can be active at the same time. A persistence
context:
• Typically lasts the duration of a transaction
• Limits entity instances to a single instance per persistent
identity s a
h a
• Has a management API, known as the entity manager m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

The Entity Manager

An entity manager provides methods to control events of a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

persistence context and the life cycle of entity instances in a


persistence context. An entity manager:
• Provides operations, such as flush(), find(), and
createQuery(), to control a persistence context
• Replaces some of the functionality of home interfaces in
EJB 2.1 entity beans s a
h a
m)
It is obtained using dependency injection in managed classes.
o
@PersistenceContext private EntityManager em;
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Instance Management


1 import javax.persistence.*;
2 import javax.ejb.*;
3 @Remote @Stateless
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

4 public class BrokerModelImpl implements BrokerModel {


5 @PersistenceContext private EntityManager em;
6 public Stock getStock(String symbol) throws BrokerException {
7 Stock stock = em.find(Stock.class, symbol);
8 if(stock != null) {
9 return stock;
10 } else {
11 throw new BrokerException("Stock : " + symbol +
s a
12 " not found");
) h a
13 }
c o m
14 } ฺ
ail ideฺ
15
m
g G { u
16 public void addStock(Stock stock) throws BrokerException
o8 den@ t
17 try {
o s
18 em.persist(stock);
c a rd Stu
19 }catch(EntityExistsException
( a n exe) t{his
20 s o use
throw new BrokerException("Duplicate
o Stock : " +
d
ar se t o
C
is © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e s
d raManagement
n
Entity n
Instance
a
x n-t to an entity manager has been obtained, you use its methods to marshal
AleWhennaoreference
entity instance data into and out of the database.
Note: Many exceptions that can be thrown by the EntityManager methods are indirect
subclasses of java.lang.RuntimeException. IDEs and compilers do not require “try
catch” blocks around lines of code that cause a RuntimeException subclass, such as
javax.persistence.EntityExistsException, to be thrown.

Developing Applications for the Java EE 6 Platform 9 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Instance Management


21 stock.getSymbol());
22 }
23 }
24
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

25 public void updateStock(Stock stock) throws BrokerException {


26 Stock s = em.find(Stock.class, stock.getSymbol());
27 if(s == null) {
28 throw new BrokerException("Stock : " +
29 stock.getSymbol() + " not found");
30 } else {
31 em.merge(stock);
32 }
33 }
s a
34
35
public void deleteStock(Stock stock) throws BrokerException {
String id = stock.getSymbol(); ) h a
c o m
36
37
stock = em.find(Stock.class, id);
if(stock == null) {

ail ideฺ
38 throw new BrokerException("Stock : " + m
g Gu
39 stock.getSymbol() + " not found");
o @
8 ent
40 } else { s
do Stud
a r
nc this
41 em.remove(stock);
42 }
( a
o use
43 }
o s
44 }
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Instance Life Cycle and Entity Manager


Methods
persist
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

merge

persist
Managed
merge
persist remove
New

remove Removed s a
merge Serialization or
end of transaction
remove
) h a
c o m
merge ฺ
ail ideฺ
m
g Gu
Fails
o @
8 ent
s
do Stud
a r
( a ncDetached t his
so us
remove
e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Entity n
a dr rand
States a n sEntity Manager Methods
x -thave a transitional life cycle. An entity can exist in one of four states that are
AleJPA entities
n o n
controlled primarily by the entity manager.
The figure in the slide shows the possible states of an entity instance. The persist, merge,
and remove methods are part of the entity manager API.

Developing Applications for the Java EE 6 Platform 9 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Bean States

Entity beans have a transitional life cycle. An entity can exist in


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

one of four states:


• New: The entity instance is newly created and not
connected to a persistence context.
• Managed: The entity instance is connected to a
persistence context and has a unique entity identity. Only
one managed instance of a identity can exist in a s a
persistence context. ) h a
o m
• Detached: The entity instance is not connected a lฺca eฺ
ito
persistence context.
@ gm Guid
o 8 efor
n t
o s
• Removed: The entity instance is scheduled d deletion.
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Entity Manager Methods

Entity Manager Method Comment


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

flush Forces the synchronization of the database with


entities in the persistence context
refresh Refreshes the entity instances in the persistence
context from the database
find Finds an entity instance by executing a query by
primary key on the database
contains Returns true if the entity instance is in the a
persistence context. This signifies that the entity
h a s
instance is managed. m )
ฺ c o
merge Merges the state of the given entity
m ail intoidtheecurrent

persistence context
@ g Gu
Removes the entity s o 8 ent
instance
do Stud
remove
a r
persist Makes
( a nancentitythinstance
is managed and persistent
so us e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

Managed Entities

A managed entity will have any changes to its persistent fields


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

or properties persisted.

public void updateStock(Stock stock) throws


BrokerException {
Stock s = em.find(Stock.class,
stock.getSymbol());
s a
if(s == null) {
) h a
throw new BrokerException("Stock : " +
o m
stock.getSymbol() + " not found");ailฺc
m i d eฺ
} else {
@ g Gu
s o 8 ent
do Stud
//em.merge(stock);
a r
( a nc this
s.setPrice(stock.getPrice());
}
o s o use
} rd a seto
s C
i © l2011, n
i d i c e
ola ble
Copyright Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d rans
a n
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 25


Pontifícia Universidade Católica do Rio Grande do Sul

Deploying Entity Classes

• To deploy entity classes, you must create a persistence


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

unit.
• A persistence unit includes entity classes and a
persistence.xml configuration file.
• The persistence unit exists inside of Java EE modules,
such as EJB-JAR files and WAR files. Within these Java
EE modules, you can have persistence units that include s a
library jars. ) ha m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Deploying
a dr Entity
r a n s
Classes
x -t table shows the list of required components of a persistence unit.
AleThe following
n o n
Persistent Unit Component Comments
P
All managed (entity) classes These classes define what is persisted.

Object-relational mapping metadata This mapping defines the mapping


between the managed classes and
database tables.
Entity manager factory and entity manager This information specifies which entity
manager factory and which entity
managers are to be used.
Configuration information for the entity The configuration information defines how
manager factory and entity managers the entity manager factory and entity
managers are to be configured.
A persistence.xml file This file defines the persistence unit.

Developing Applications for the Java EE 6 Platform 9 - 26


Pontifícia Universidade Católica do Rio Grande do Sul

Default Locations for Persistence Unit 27

Persistent Unit Component Comments

All managed (entity) classes In directories that map the package structure of the
managed classes. The directory path root is the root of the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJB-JAR file.

Object-relational mapping These are included as annotations in the entity classes.


metadata An alternative default location is the XML deployment
descriptor file.
Entity manager factory and entity The default entity manager factory and default entity
manager managers are placed in a persistence provider–specific
location. These are known to the Java EE application
s a
server.
) h a
c o m
Configuration information for the ฺ
The default configuration information is known to the Java
ail ideฺ
entity manager factory and entity EE application server. m
managers @ g Gu
s o 8 ent
A persistence.xml file In the META-INF
a r S tudoff the root of the EJB-JAR file
dodirectory
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 27


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Persistence Unit


Using Default Settings
A persistence unit attempts to include all entity classes in the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

same EJB module as the persistence.xml file.


(/)Root
META-INF

ejb-jar.xml

MANIFEST.MF
persistence.xml
auctionsystem

s a
ejbs

) h a
entity AuctionManagerBean.class
c o m
AuctionManagerRemote.class ฺ
ail ideฺ
Auction.class
m
g Gu
AuctionManagerLocal.class
AuctionUser.class dtos
o @
8 ent
Bid.class s
do Stud
BidStatusMessage.class
a r
nc PlaceBidMessage.class
his
Item.class

( a e t
Persistence Components
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Persistence
r a n s Unit Using Default Settings
x -t
AleThe figure
n o nin the slide shows an example of persistence unit components in default settings
within an EJB-JAR. It also shows other components of an EJB-JAR archive.
The following steps outline a process that you can follow to create a persistence unit within an
EJB-JAR file, using the default settings for various components of the persistence unit. This
process assumes that the entity classes are fully annotated and all classes are placed in the
root directory.
1. If not already expanded, expand the EJB-JAR archive.
2. Create subdirectories that reflect the full qualified names of the managed classes that
you need to include in the persistence unit.
3. Copy all the classes that you need into the directories created in step 2
4. Create a minimal persistence.xml file. At a minimum, you must provide an XML file
with the following elements.
- The persistence element
- The persistence-unit element with a value for the name attribute

Developing Applications for the Java EE 6 Platform 9 - 28


Pontifícia Universidade Católica do Rio Grande do Sul

The code below shows the listing of the minimum content of the persistence.xml file.
<persistence>
<persistence-unit name="OrderManagement"/>
<persistence>
5. Copy the persistence.xml file into the META-INF directory off the EJB-JAR root
directory.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

6. Create (archive) the EJB-JAR module.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 29


Pontifícia Universidade Católica do Rio Grande do Sul

Examining a Persistence Unit


Using Nondefault Settings
A persistence unit can be made to include library jar files it
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

would not normally include.


1 <?xml version="1.0" encoding="UTF-8" ?>
2 <persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:// java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/ persistence_2_0.xsd">
3
4 <persistence-unit name="BrokerTool-ejb" transaction-type="JTA"> s a
5 <jta-data-source>StockMarket</jta-data-source> ) h a
c o m
6
7
<jar-file>BrokerLibrary.jar</jar-file>
<mapping-file>mapping.xml</mapping-file>

ail ideฺ
m
g Gu
8 <properties>
o @
8 ent
9
s
<property name="eclipselink.cache.type.default" value="NONE"/>
do Stud
10 </properties>
a r
11 </persistence-unit>
( a nc this
12 </persistence>
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Examining
a dr a rPersistence
a n s Unit Using Nondefault Settings
e x - t
Al • nThe onJAR files off root
The JAR files off the root are optional. They are an alternative method for the developer
to provide the managed set of entity classes. Every JAR file provided requires a
corresponding jar-file element in the persistence.xml file. The presence of the jar-
file elements in the persistence.xml file prompts the application server to load the
classes archived in the JAR file.
• The mapping XML files off root
The mapping XML files off the root are an alternative location for the object/relational
mapping information. These mapping files require a corresponding mapping-file element
in the persistence.xml file.
The mapping XML files are optional. All mapping information can be supplied through
the appropriate annotations in the entity class.
• <properties> are used to pass configuration information to the persistence provider.

Developing Applications for the Java EE 6 Platform 9 - 30


Pontifícia Universidade Católica do Rio Grande do Sul

Java SE JPA Applications

Using JPA in an EJB container has certain benefits:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Transactions are taken care of automatically. Transactions


are covered in more detail in the lesson titled
“Implementing a Transaction Policy.”
• There is less configuration because the persistent unit is
using a preconfigured DataSource for database access.
• Dependency injection is used to obtain an s a
EntityManager reference. h a
m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 31


Pontifícia Universidade Católica do Rio Grande do Sul

Java SE JPA persistence.xml Example


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://
www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="StockPU" transaction-type="RESOURCE_LOCAL">

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>trader.Stock</class>
<class>trader.Customer</class>
<class>trader.CustomerShare</class>
<properties>
<!-- useful log levels include OFF,FINE,SEVERE -->
<!-- useful ddl-generation values include create-tables and drop-and-create-tables --
s a
>
) h a
<property name="javax.persistence.jdbc.user" value="public"/>

c o m
<property name="javax.persistence.jdbc.password" value="public"/>

ail ideฺ
<property name="javax.persistence.jdbc.url" value="jdbc:derby:MyDB;create=true"/>
<property name="javax.persistence.jdbc.driver" m
g Gu
value="org.apache.derby.jdbc.EmbeddedDriver"/>
o @
8 ent
s
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>

do Stud
r
<property name="eclipselink.logging.level" value="SEVERE"/>
a
nc this
</properties>
</persistence-unit>
( a
o use
</persistence>
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Java SEn r Applications
dJPA n s
x a -t r a
AleWith just
n o n
a little extra work, JPA can be used in non-EJB applications such as Web
applications or Java SE desktop applications. The code examples in this slide and the next
show the important changes to JPA configuration and code in an SE application.
Note: The persistence.xml file example shown in the slide uses the embedded Derby
database driver, which automatically starts a database instance within the same JVM as the
application.

Developing Applications for the Java EE 6 Platform 9 - 32


Pontifícia Universidade Católica do Rio Grande do Sul

Java SE JPA EntityManager Example

The EntityManager is obtained programmatically instead of


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

with dependency injection.

EntityManagerFactory emf =
Persistence.createEntityManagerFactory("StockPU");
EntityManager em = emf.createEntityManager();
EntityTransaction entityTransaction =
s a
entityManager.getTransaction(); ) h a
o m
entityTransaction.begin();
a ilฺc eฺ
// ...
@ gm Guid
t
entityTransaction.commit(); so8 en do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Java SEn r Application
dJPA n s
a r a
x n-int a Java SE application, several JAR files must be added to a project. In the
AleTo usenoJPA
CLASSPATH, the application will require:
• The library JAR files that contain the persistence provider. Both Hibernate and
EclipseLink can be freely downloaded.
• The library JAR files to satisfy any required dependencies of the persistence provider.
There can be multiple dependencies that must be meet. Hibernate requires several
additional library JAR files.
• A running database and its JDBC driver. Derby, also known as the JavaDB, is a popular
choice for small databases because of its portability and embedded option.

Developing Applications for the Java EE 6 Platform 9 - 33


Pontifícia Universidade Católica do Rio Grande do Sul

Advanced Persistence Features

Advanced persistence features are covered in the course titled,


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Java Persistence API 2.0:


• Lifecycle callbacks: Entity classes can contain callback
methods that are executed by the JPA provider during
lifecycle events.
• Relationships: The Persistence API can be used to
manage foreign key tables and columns in an RDBMS. In s a
Java, these database relationships are modeled with ) ha
references and collections. c o m

ail ideฺ
• Java Persistence Query Language (JPQL):g It is G m au portable
database query dialect used to avoid
@ t
8 ennative SQL to
oadding
s
d Stud
o
Java applications. c a r
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 34


Pontifícia Universidade Católica do Rio Grande do Sul

Advanced Persistence Features

• Two types of queries:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

– NamedQueries
– NativeQueries
• Queries are used to execute JPQL or native SQL
statements on a database.
• The Criteria API is new to JPA 2.0. It:
– Provides a typesafe API to perform object-based queries a
has
– Is used in place of the JPQL m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 35


Pontifícia Universidade Católica do Rio Grande do Sul

A Native Query Example

Native queries:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Are easier to use because they do not require that you


learn JPQL or Criteria API.
• Should not be used extensively because they are
nonportable
Query query = em.createNativeQuery("SELECT *
FROM Customer", Customer.class); s a
h a
List customers = query.getResultList(); m)
o
a ilฺc eฺ
g m uid
Query query = em.createNativeQuery("SELECT 8 @ n t G *
s o e
FROM SHARES WHERE SSN = '" r+docustomerId
a S tud + "'",
CustomerShare.class); anc this
o ( se
s
rdo e to u
List shares = query.getResultList();
a
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
A Native
r
dQuery n s
Example
a
x query r a
-tusage should be kept at a minimum because the resulting code becomes tightly
AleNative
n o n
coupled with the underlying database structure.

Developing Applications for the Java EE 6 Platform 9 - 36


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The role of entity components


• The object-oriented data view provided by the Persistence
API
• The purpose of a primary key
• Field-based and properties-based entity classes
s a
• The relationship of a persistence unit, persistence context,h a
and entity manager m )
o
• The life cycle of entity components a ilฺc eฺ
m id g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 37


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What does object-relational mapping software attempt to do?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Simplify SQL statements


b. Optimize the database schema
c. Optimize memory related to data objects
d. Simplify the code needed to map an object to a database

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 38


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which of the following are examples of ORM software?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Derby
b. Maven
c. Hibernate
d. EclipseLink

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 39


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Where is the location of the datasource defined?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. web.xml
b. the persistence context
c. the persistence unit defined by web.xml
d. the persistence unit defined by persistence.xml

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 40


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 9: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Creating and configuring a persistence unit


• Using the basic functionality of the Java Persistence
API
• Describing the Java Persistence API
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 9 - 41


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Implementing a Transaction Policy

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe transaction semantics
• Compare programmatic and declarative transaction
scoping
• Use JTA to scope transactions programmatically
• Implement a container-managed transaction policy s a
) h a
• Support optimistic locking with the versioning of entity
o m
components a ilฺc eฺ
g m uid
@
• Support pessimistic locking using EntityManager
8 nt G APIs so ude
• Describe the effect of exceptions d o
r on transaction t state
n c a i s S
• Use JPA transactions ino a(aJavaeSE th environment
r d os to us
C a se
i d s
i © l2011,
c e n
ola ble
Copyright i Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d rans
a n
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Transaction Semantics

Three transaction concepts are important in the development of


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Java EE platform–compliant applications:


• Atomicity: Operations succeed or fail together
• Locking and isolation: Only one transaction at a time can
update a particular piece of data
• Flat transaction model: Only one transaction is in effect in
a particular thread at any given time s a
) ha
m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Atomicity
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

BEGIN

$$

Account1
$$ $$

s a
) h a
Account1 Account2 $$
c o m

ail ideฺ
m
g Gu
Account2 @
s o 8 ent
a r do Stud
( a nc COMMIT t his
so us e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Atomicity
a dr rans
x -t is atomic if it consists of a number of operations that must succeed or fail as a
AleA transaction
n o n
unit. For example, the figure in the slide shows the process of transferring money between
two bank accounts held on relational databases.
Because relational databases do not have a concept of transferring money, this operation
must be completed in two steps:
1. Reduce the amount of money in the account named Account1.
2. Increase the amount of money in the account named Account2.
There are three possibilities:
• If both of these operations succeed, there is no cause for concern.
• If both operations fail, there is cause for concern, but the data is left in a consistent state.
• If one operation succeeds and the other operation fails, there is likely to be trouble.

Developing Applications for the Java EE 6 Platform 10 - 4


Pontifícia Universidade Católica do Rio Grande do Sul
In a transaction:
• The scope extends from the start of its first operation, called the begin point, to the end
of its last operation, called the commit point.
• If any operation between these two points fails, then the system must be restored to the
state it had immediately before the begin point. Internally, the database engine uses
logs to store the original state and monitor the success of the operations.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Each change that is made during a transaction is logged, and if any operation fails, then
the logged operations are undone from the end of the log back to the beginning of the
log. This process is called rolling back.
In practice, few transactions are as simple as the transferring money example.
• Consider that the operation to reduce the amount of money in Account1 is not itself
atomic.
• The first step in transferring money probably consists of a number of steps that are
implemented in the application and a number of operations on the database.
s a
• The concept of scope is important because when you define a transaction in terms of its
) h a
o m
scope, rather than in terms of the number of operations it carries out, you get a much
c
more straightforward programming model. ฺ
ail ideฺ
In a complex transaction:
m
g Gu
o @
8a criticaln t For example, if the
• Not every operation that is carried out along the way s is e one.
transaction consists of 10 operations, one ofawhich r tud an email notification to the
do is toSsend
user, it is not necessarily the case that(a an
c hthis
failure of is notification should result in a
failure of the entire transaction. so e t
r d o to us
a design issue. Thisis Ca issue
• Regardless of whether a particular
design n s etypebe
must
of failure should cause a transaction rollback is
considered during implementation.
i d l i c e
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Locking and Isolation


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 2

s a
) h a
c o m
a il ฺ e ฺ
$$ m
g Gu i d
@
8 ent
3 Wait so
a r do Stud
Account2
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Locking
r Isolation
dand n s
x a t r a
on- allows the database to handle multiple concurrent transactions, while still
Ale • nLocking
ensuring that integrity is maintained.
• With locking, after a particular transaction has carried out an update on a particular data
item, other transactions are prohibited from updating or even reading that item again
until the first transaction commits.
• Subsequent transactions are then forced to wait, and they are said to be blocked by the
database. This process is called transaction isolation.
The figure in the slide shows an example of locking in a transaction.
The transaction shown in the slide has the following three steps:
1. The first transaction updates Account1 in the database. While the first transaction is in
process, Account1 is locked.
2. The second transaction attempts to update Account1, but cannot complete the update
because the account is locked.
3. When the first transaction completes, the lock on Account1 is released, which allows the
second transaction to continue.

Developing Applications for the Java EE 6 Platform 10 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Transaction Models

There are three types of transaction management models:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Transaction Model Description


Type
Nested A transaction consists of subtransactions that run in
parallel.
Chained A transaction consists of subtransactions that run in a
sequence. has
m)
Flat lฺco eฺ
A transaction cannot be made up of subtransactions.
a i
The flat transaction model:
• Is the only transaction model8 @ gm by
supported G utheidJava EE
o e n t
specification s
a rdo S
• Is supported by allcdatabase tud
vendors
his
(ansimple tAPI
• Leads to a very
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Models
Transaction
a r a n s
x -t
AleDifferent
n o n
database implementations support a variety of transaction management models. In
general, transaction management models can be divided into three types:
• Nested transaction model
If the main transaction fails, the subtransactions are rolled back. However, a failure in a
subtransaction does not necessarily roll back other subtransactions. For example, if
transaction 1 creates transaction 2, then in a nested transaction model, a failure in
transaction 1 rolls back transaction 1 and transaction 2. However, a failure in transaction
2 does not automatically role back transaction 1, because transaction 2 is subordinate to
transaction 1.
• Chained transaction model
If the main transaction fails, the subtransactions are rolled back. However, a failure in a
subtransaction only causes a rollback to the start of that subtransaction. For example, if
transaction 1 creates transaction 2, and transaction 2 creates transaction 3, then in a
chained model, a failure in transaction 3 only rolls back transaction 3. A failure in
transaction 2 rolls back transaction 2 and transaction 3. A failure in transaction 1 will roll
back all three transactions.

Developing Applications for the Java EE 6 Platform 10 - 7


Pontifícia Universidade Católica do Rio Grande do Sul
• Flat transaction model
In a particular thread, only one transaction is in effect at a time.
When a component issues a method call to commit a transaction, the component does
not have to specify which transactions to commit because only one transaction can be in
effect at a time. Flat transactions also allow for a simple declarative transaction model.
More complex transaction models can be simulated in code if necessary.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Comparison of Programmatic and


Declarative Transactions
The Java EE application developer’s concern is with scoping
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

transactions. Scoping can be programmatic (bean-managed


transactions) or declarative (container-managed transactions).
Programmatic Declarative

Operation Use JTA calls to specify which Specify the transaction


operations form a single properties in the deployment
a
transaction descriptor as ) h
Available In Servlets, JSP components, Session beans,cand o m
session beans, and message-driven a ilฺ beans,
eฺ but
message-driven beans
m
g GoruJSP
not in servlets i d
o @
8 ent
components
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n
Comparisondr of r a n s
Programmatic and Declarative Transactions
e x - t
n to the selection of which operations the developer wants to group into a
Al Scoping
n orefers
transaction. An alternative term is transaction boundary demarcation. The developer is never
concerned with the technicalities of transaction coordination. That is, matters, such as the
resource enlistment and log management, are the responsibility of the application server.
For some component types, the Java EE application developer can decide whether to use
programmatic transaction scoping or declarative transaction scoping. Some component types
only allow one method or the other. Where both methods are allowed, the decision about
which method to use operates at the component level. For example, a particular EJB
component cannot use both declarative and programmatic transaction scoping.

Developing Applications for the Java EE 6 Platform 10 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Programmatic Scoping as Opposed to Reusability

Programmatic transaction scoping is not preferred for EJB


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

components for two main reasons:


• Transaction scope cannot be changed at assembly time.
• The container cannot create a single transaction that
encompasses a mixture of programmatic and declarative
transaction scoping.
Declarative scoping avoids these problems. s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr raScoping
Programmatic n s as Opposed to Reusability
e x - t
on
Al A JTAntransaction is scoped by its begin() and end() calls, and is not affected by opening
and closing connections. Therefore, JTA transactions work against any number of back ends,
and do not require a connection to be held open for an extended duration.
Developers who are new to the Java EE platform frequently ask how JTA transactions are
different from Java™ DataBase Connectivity (JDBC™) transactions, and whether they can
interoperate. JDBC transactions have connection scope, which means that they operate
against a single back end and they commit when a connection is closed or committed.
• Although you can use JDBC transactions in application servers, provided their
limitations are accepted, there is seldom a good reason to do so.
• JTA is just as easy to use and, in a modern application server, just as efficient.
• In the old days, the use of JTA would imply a two-phase commit on every transaction,
even if there was only one back end.
• Modern products recognize this and silently convert JTA transactions into JDBC
transactions internally.

Developing Applications for the Java EE 6 Platform 10 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Using JTA to Scope Transactions


Programmatically
The JTA specification is relevant to developers of application
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

servers and database drivers. The code is independent of the


transaction infrastructure.
• Obtain a reference to the UserTransaction object from
the container.
• Scope the transactions using the begin and commit
methods. s a
• Fail a transaction using the rollback method. h a
m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Getting a Reference to the UserTransaction


Interface
Previous versions of Java EE required the use of JNDI or an
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJBContext to locate a UserTransaction. The preferred


method in Java EE 6 is to have the UserTransaction
injected by using an annotation.

import javax.ejb.*;
import javax.annotation.*;
import javax.transaction.*;
s a
) h a
@Stateful
c o m
public class MySessionBean implements MySession { ฺ
ail ideฺ
m
g Gu
@Resource UserTransaction ut; o @
8 ent
s
do Stud
a r
}
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Getting
a n da rReference
r a n s to the UserTransaction Interface
x use -tthe JNDI API to get a reference to the UserTransaction interface, as shown
AleYou can
n o n
in the following example:
import javax.transaction.UserTransaction;
InitialContext ic = new InitialContext();
UserTransaction ut = (UserTransaction)
ic.lookup("java:comp/UserTransaction");
An EJB component, servlet, or JSP page can use annotations to obtain a reference to the
UserTransaction interface as shown in the code in the slide.

Developing Applications for the Java EE 6 Platform 10 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Using the begin,commit, and rollback


Methods
Most uses of JTA to scope a transaction have the following
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

basic structure:

@Stateful
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource UserTransaction ut;

s a
public void method() {
) h a
try {
c o m
ut.begin(); // Transaction starts here ฺ
ail ideฺ
//... transaction operation 1, 2, 3
m
g Gu
ut.commit(); // Transaction finishes here
o @
8 ent
s
do Stud
} catch (Exception e) {
a r
ut.rollback(); // Oops: roll
( a ncback this
}
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Implementing a Container-Managed
Transaction Policy
Declarative or container-managed transaction scoping is the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

technique of choice in EJB components.


• No coding is necessary, but the transaction scope is
affected by the number and sequence of method calls.
• In many cases, you are required to do nothing. All of the
methods of CMT EJB components have a default of the
REQUIRED transaction attribute. a
h a s
) m
ฺ c o
ail ideฺ
import javax.ejb.*;
m
g Gu
@TransactionAttribute(TransactionAttributeType.REQUIRED)
o @
8 ent
public void someMethod () {...} s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raa nContainer-Managed
Implementing
a
s Transaction Policy
e x - t
on or container-managed transaction scoping is the technique of choice in EJB
Al Declarative
n
components. Declarative transaction scoping is portable, easy to apply, and does not limit the
reusability of EJB components. Annotations are the preferred way to implement declarative
scoping.
Note: The interaction between the containers, transaction infrastructure, and deployment
descriptor might seem complex. It might help to remember that in many cases you are
required to do nothing. All of the methods of CMT EJB components have a default of the
REQUIRED transaction attribute.

Developing Applications for the Java EE 6 Platform 10 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Container Interactions with the Transaction


Management Infrastructure
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 2

Container

5
s a
Commit/Rollback/Resume 6 3 Suspend/Join/Begin
) h a
c o m

ail ideฺ
g m u
4 o8@$$ nt G
r d os tude
a n ca his SDatabase
o ( se t
Transaction
s
rdo e to u
Coordinator
a
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Container
a drInteractions
r a n s with the Transaction Management Infrastructure
x -t transactions, the container makes adjustments:
AleWith declarative
n o n
• To the transaction state on entry to, and exit from, every method in every EJB
component
• In accordance with a set of transaction attributes that are defined in the deployment
descriptor
The figure in the slide shows the basic sequence that is used to define the transaction
attributes.
The figure in the slide illustrates the following basic sequence:
1. The client of the EJB component calls a business method. The client calls the business
method by way of the component object. At this point, either a transaction is in progress,
or it is not. Because the transaction model is flat, the container does not have to be
concerned about different transactions in the same thread of execution.
2. The container obtains the transaction attribute for this method from the information that
is supplied in the deployment descriptor. There are six possible attributes, which are
described in a subsequent slide.

Developing Applications for the Java EE 6 Platform 10 - 15


Pontifícia Universidade Católica do Rio Grande do Sul
3. Depending on whether a transaction was in progress, and also on the method’s
transaction attribute, the container adjusts the transaction state. It can either suspend
the current transaction, join the new method onto the current transaction, or begin an
entirely new transaction, which first suspends the original transaction. A transaction that
is suspended is on hold for the duration of the method call. It will not be rolled back if the
method fails, and the suspended transaction can be resumed later.
4. The transaction manager does whatever is necessary on the various databases and
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

other information sources to ensure that the container’s decision takes effect. The
transaction manager also sets up internal data structures in such a way that later access
to databases brings about the correct transactional operations.
5. The container calls the business method on the EJB component and the container might
then read or update the database.
6. On exit from the method, the container completes whatever it started on entry. For
example, if it began a new transaction, the container attempts to commit the transaction.
If the container suspended the existing transaction, the container resumes the s a
h a
transaction. The container can also roll back a transaction, either because the commit
)
o m
operation fails or because the rollback flag has been set by a business method within
c
the scope of a transaction. ฺ
ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

How to Control the Container’s Behavior Using


Transaction Attributes
Attribute Effect
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Required The method becomes part of the caller’s transaction. If the caller does not
have a transaction, the method runs in its own transaction.
RequiresNew The method always runs in its own transaction. Any existing transaction is
suspended.

NotSupported The method never runs in a transaction. Any existing transaction is


suspended.
s a
Supports
) h a
The method becomes part of the caller’s transaction if there is one. If the
caller does not have a transaction, the method does not run in a transaction.
c o m
Mandatory It is an error to call this method outside of a transaction. ฺ
ail ideฺ
m
g Gu
Never
o
It is an error to call this method in a transaction. @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr the
Controlling
r a n s
Container’s Behavior Using Transaction Attributes
e x - t
nonin the slide explains how the container uses the transaction attributes supplied by
Al The table
the developer or assembler to decide how to modify a transaction.

Developing Applications for the Java EE 6 Platform 10 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Predicting the Effect of Transaction Scope on


Application Performance
Transaction scope has two conflicting effects on performance
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

that you have to balance:


• Wider scope reduces the need for entity synchronization.
• Narrower scope increases database communication.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Scope
Transaction
a r a n s and Application Performance
x n-tEE applications, transaction scope has a significant effect on application
Ale • nInoJava
throughput.
• In the Java EE model, you must balance the additional factor of the effect of transaction
scope on database synchronization.
• The business rules of the application might themselves dictate the transaction scope. In
the example of transferring money from one bank account to another bank account, it is
clear that both operations must be part of the same transaction.
• No improvement in efficiency is likely to outweigh the risk of data corruption.
It takes considerable experience to be able to make the necessary design decisions to get
good throughput and avoid compromising the business rules. In this course, only a brief
outline can be given.

Developing Applications for the Java EE 6 Platform 10 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Transaction Scope and Entity Synchronization

Entity components must be synchronized with the underlying


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

database at least once per transaction.


• Entity classes do not declare transactions, they inherit the
transaction of the calling component.
• Entity classes can use optimistic locking. When a
transaction commits entity data, the transaction can fail to
commit because the data was modified by a concurrently s a
running transaction. ) ha
c o m
• JPA 2.0 applications may use pessimistic locking ฺ in
ail ideฺ
m
addition to optimistic locking. Pessimistic locking
g Gisu not
@ t
specified in entity classes. so8 den do Stu
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Optimistic Locking and Versioning

Optimistic locking provides better concurrency and scalability


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

by allowing multiple transactions to access the same data. In


read-only transactions this causes no problem but transactions
that update data might try to concurrently modify the same
entity identity. Versioning solves this problem by:
• Adding a version field or property to entity classes
• Using the version value to determine whether a entity’s s a
underlying data has been modified by another transaction ) h a
since the start of a transaction o m
a ilฺc eฺ
• Auto-incrementing the version value with every
@ G uid
gm committed
t
so8 den
data modification of an entity instance
do Stu
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Locking
Optimistic
a r a n s
x -t
AleEnterprise
n o n developers must concern themselves with scalability and concurrency while
maintaining data integrity. A standard approach to maintaining database integrity with many
concurrent users that access shared data is to use record locking.
Locking rows or tables for long periods of time to keep multiple records from being updated by
multiple users is referred to as pessimistic locking.
Optimistic locking tries to avoid acquiring long-term data locks. Data can be locked during a
read and during an update, but would not be locked in-between a read and update regardless
of the duration of the edit. This locking model scales better with a large amount of concurrent
users accessing the same data especially when database operations consist mostly of reads.
A drawback to optimistic locking is that it becomes easy to over-write another user’s changes.
Note: Transactions do not always lock database rows. A transaction simply means that
several operations will either commit or fail as a unit. If one operation fails all transacted
operations in the same transaction should fail. Without additional work there is very little that
will cause a JPA update to fail, even concurrent transactions updating the same records in a
database will complete successfully.

Developing Applications for the Java EE 6 Platform 10 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

Implementing Versioning

A basic implementation of versioning can use an integer


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

database column in the same table used for entity data. The
field or property used for the version should not be written to.
@Version
@Column(name = "VERSION")
private int version;

s a
public int getVersion() {
) h a
return version;
c o m
} ฺ
ail ideฺ
m
gnot match u the
When an entity is merged and its version does @ t G
stored version, the merge fails with ardos tude
o8 n
javax.persistence.OptimisticLockException. a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Pessimistic Locking

Pessimistic Locking was included in the JPA 2.0 specification.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Better for high write contention


• Can co-exist with optimistic locking and versioning
• javax.persistence.LockModeType.PESSIMISTIC

The EntityManager class has an overloaded find method


that can lock an entity instance during retrieval. a
as
) h
<T> T find(java.lang.Class<T> entityClass,
o m
ilฺc ฺ
java.lang.Object primaryKey, LockModeType lockMode)
g ma uide
8@after n t G
The EntityManager.lock method is sused
o o de retrieval.
r
a is S d t u
void lock(java.lang.Object entity,
n c LockModeType lockMode)
o (a se th
r d os to u
C a se
i d s
i © l2011,
c e n
ola ble
Copyright i Oracle and/or its affiliates. All rights reserved.

i
N ferac
r e
d Locking n s
a n
Pessimistic
r a
-t
x implementation
AleA basic
n o n of pessimistic locking would lock data when it is read and not unlock
until all modifications have taken place. Pessimistic locking does a good job of ensuring
predictable database updates. However, a potential issue with long-term record locking using
pessimistic locking is one of scalability. The more concurrent users there are of a database
application, the more likely it is that those users will request the same data causing
contention.
Many JPA 1.0 providers have proprietary methods to enable pessimistic locking in some form.
Code that uses pessimistic locking with a JPA 1.0 provider will not be 100% portable.
Methods for performing pessimistic locking are part of the EntityManger class. Additional
pessimistic locking capabilities are included in the Query and NamedQuery features of JPA.
If the lock cannot be obtained and the current transaction will be marked for rollback, a
PessimisticLockException will be thrown. When the lock cannot be obtained but the
current transaction does not require a rollback, a LockTimeoutException will be thrown.

Developing Applications for the Java EE 6 Platform 10 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Effect of Exceptions on Transaction State

Exception handling differs in programmatic and declarative


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

transaction scoping.
• With programmatic transaction scoping, you are
responsible for catching exceptions and failing
transactions.
• With declarative transaction scoping:
– The container automatically fails the current transaction if it s a
catches a runtime exception. OptimisticLockException ) ha
is a runtime exception. c o m
il ฺ
aobject eฺ
– An EJB component can use the EJBContext m
g Gu i dor
subclass to check whether the container
o @ n t a
8 hasefailed
s
transaction. rdo tud
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Runtime n r
dExceptions n s and Rollback Behavior
x a r a
t declarative transaction scoping, the container rolls back the current
-with
AleIn general,
n o n
transaction if it catches a runtime or unchecked exception.
Throwing a checked exception from a business method never, in itself, causes a rollback.
This is true no matter how catastrophic the failure might be. However, the failure that caused
the exception might itself have caused a rollback.
For example, consider a session bean that uses an entity class to insert a new data item.
Suppose the merge operation failed and threw an OptimisticLockException. This
example is an unchecked exception, so throwing it from the session bean to its client does roll
back the current transaction.
Most Java Persistence API–caused exceptions are unchecked exceptions because they
inherit from RuntimeException.
You should catch any subclasses of PersistenceException when using the Java
Persistence API within session beans to keep the current transaction from failing,

Developing Applications for the Java EE 6 Platform 10 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Using the EJBContext Object to Check and


Control Transaction State
The EJBContext object that is injected in EJB components at
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

runtime provides two methods that are useful for transaction


management and testing:
• getRollbackOnly()
This method returns true if the transaction has already
failed.
• setRollbackOnly() a
h a s
This method fails a container-managed transaction without
)
throwing a runtime exception. o m
ilฺc ฺ
g ma uide
o 8 @ nt G
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Using n
a drEJBContext
the
r a n s Object to Check and Control Transaction State
x -t declarative transaction scoping:
AleWhennyou
onuse
• Transaction failures are under the control of the container
• An EJB component might need to determine whether a transaction has failed
somewhere other than in the current method
- The usual reason for making this determination is to avoid carrying out operations
that are doomed to fail later.
- If the current transaction has already failed at an earlier point, perhaps as a result
of a database error, then there is no benefit in completing further work in the
current method, because the container will only have to roll it back on exit.
Typically, an EJB component calls getRollbackOnly before embarking on a lengthy
database operation.
The setRollbackOnly method:
• Sets the rollback flag, which might have the effect of making the transaction roll back
immediately, or of causing the container to roll it back later
- In either case, the transaction fails and can be rolled back at some point.
- The decision to set the rollback flag cannot be revoked later in the transaction.

Developing Applications for the Java EE 6 Platform 10 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

JPA Transactions in Java SE Applications

Java SE environments:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Typically will not have JTA


• Use resource-local entity managers
• Beginning, committing, and rolling back a transaction is
managed by the application developer
<persistence-unit name="StockPU" transaction-type="RESOURCE_LOCAL">
...
s a
</persistence>
) h a
c o m
EntityManagerFactory emf = ฺ
ail ideฺ
Persistence.createEntityManagerFactory("StockPU"); m
g Gu
EntityManager em = emf.createEntityManager();
o @
8 ent
s
do Stud
EntityTransaction entityTransaction = entityManager.getTransaction();
a r
nc this
entityTransaction.begin();
// ...
( a
o use
entityTransaction.commit();
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr ransin Java SE Applications
JPA Transactions
a
x -t entity manager is specified in the persistence.xml configuration file as
AleA resource-local
n o n
shown in the slide.
The EntityTransaction API controls transactions in an application using a resource-local entity
manager.
The code in the slide shows how to programmatically obtain an EntityManager and
manually control transactions.

Developing Applications for the Java EE 6 Platform 10 - 25


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Transaction semantics
• Programmatic and declarative transaction scoping
• The JTA API
• Container-managed transactions
• Transaction scope and application performance
a
• Optimistic locking and versioning of entity components) has
• Pessimistic locking APIs c o m

ail ideฺ
• The effect of exceptions on transaction state m
g Gu
o @
8 ent
o s
• JPA transactions in Java SE environments d
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 26


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Atomicity can be defined as:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Row in a table
b. A single SQL statement
c. A single object in a container
d. A number of transactions that succeed or fail as a unit

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 27


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Locking prevents which of the following?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Multithreaded thrash storms


b. Inefficient calls to the data store
c. Insecure access to a data element
d. Multiple processes overwriting the same data

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 28


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which three methods would demarcate a transaction?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. begin(), commit(), end()


b. begin(), end(), rollback()
c. begin(), end(), explode()
d. begin(), commit(), rollback()

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 29


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Select the goal of optimistic locking from the following:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. To not use locking at all


b. Avoid long-term data locks
c. Keep all database requests positive
d. Ensure optimum data write protection

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dbr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 30


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 10: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Determining when rollbacks occur given a specific


scenario
• Using the Java Persistence API versioning features to
control optimistic locking

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 10 - 31


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Developing Java EE Applications Using


Messaging
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe Java Messaging Service (JMS) API technology
• Write a message producer
• Write a queue message browser
• List the capabilities and limitations of enterprise
components as messaging clients a
as ) h
o m
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Messaging System Participants

JMS API
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Implementation
Session Message
Provider

Connection

Connection Queue Topic


Factory Destination Destination

Administrative Bind
s a
Tool
) h a
JNDI API
c o m
Namesake Connection
Factory
Queue
Destination
Topic
Destination

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
JMS API Client Lookup
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JMS APIn r
dTechnology n s
x a -t r a
AleThe figure
n o nin the slide shows the relationship among the main participants of the JMS API
messaging system.
The JMS API consists of a set of interfaces and classes. A JMS technology provider (JMS
provider) is a messaging system that provides an implementation of the JMS API. For an
application server to support JMS technology, you must place the administered objects
(connection factories, queue destinations, and topic destinations) in the JNDI technology
namespace of the application server. You use the administrative tool supplied by the
application server to perform this task.

Developing Applications for the Java EE 6 Platform 11 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Administered Objects
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Queue Connection Factory Queue Connection

Queue Destination

s a
) h a
c o m
Topic Destination ฺ
ail ideฺ
Topic Connection Factory
m
g Gu
Topic Connection

o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raObjects
Administered
a n s
x -t objects are objects that are configured administratively (as opposed to
AleAdministered
n o n
programmatically) for each messaging application. A JMS provider supplies the administered
objects. An application server administrator or application deployer configures these objects
and places them in the JNDI technology namespace.
The two types of administered objects are:
• Destinations: They are message distribution points. Destinations receive, hold, and
distribute messages. Destinations fall into two categories: queue and topic destinations:
- Queue destinations implement the point-to-point messaging protocol.
- Topic destinations implement the publish/subscribe messaging protocol.
• Connection factories: They are used by a JMS API client (JMS client) to create a
connection to a JMS API destination (JMS destination). Connection factories fall into two
categories: queue and topic factories.
The figure in the slide shows both types of administered objects supplied as part of a JMS
provider.

Developing Applications for the Java EE 6 Platform 11 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Messaging Clients
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Message Message Synchronous


Producer Queue Consumer
Client Sends Collects Client

Notifies
Message Asynchronous
s a
Producer
Client
Sends
Queue Consumer
) h a
Client
Collects
c o m

ail ideฺ
m
g Gu
Message 8
o @ n t
s e
a r do Stud
The synchronous client blocks(acommunication nc this until a message
o e
arrives. r d os to us
C a se
i d s
i © l2011,
c e n
ola ble
Copyright i Oracle and/or its affiliates. All rights reserved.

i
N ferac
r e
d Clients n s
x a n
Messaging
t r a
on- producer clients create and send messages to destinations.
Ale • nMessage
• Message consumer clients consume messages from destinations. Message consumers
can be either asynchronous or synchronous:
- Asynchronous consumer clients register with the message destination. When a
destination receives a message, it notifies the asynchronous consumer, which
then collects the message.
- Synchronous message consumer clients collect messages from the destination. If
the destination is empty, the client blocks until a message arrives.
The figure in the slide shows the three types of messaging clients, producer client,
asynchronous consumer client, and synchronous consumer client.

Developing Applications for the Java EE 6 Platform 11 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Messages
Header
• TextMessage
• MapMessage
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Properties • BytesMessage
• StreamMessage
• ObjectMessage
Body

Message Type Contents of the Message Body

TextMessage A java.lang.String object


s a
MapMessage A set of name–value pairs, for example, a hash table )h a
m
BytesMessage A stream of uninterpreted bytes or binaryildata
a ฺco eฺ
A stream of Java technology primitive gmvalues id
ufilled
StreamMessage
@
8 ent G
and read sequentially s o
a r do Stud
ObjectMessage A serializable Java
( a nctechnologyt h is object
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Messages
a dr rans
x -t
AleMessages
n o nare objects that encapsulate application information created by a message
producer. Messages are sent to a destination that distributes them to message consumers.
The figure in the slide shows the three parts of a JMS API message.
The following three characteristics apply to messages:
• The header contains standard information for identifying and routing the message.
• Properties provide a mechanism for the classification of messages.
- Properties are name-value pairs.
- You can set or read the value of any property.
- You can customize the property list by adding a name/value pair.
- Properties allow destinations to filter messages based on property values.
- Properties also provide interoperability with some message service providers.
• The body contains the actual message in one of several standard formats.

Developing Applications for the Java EE 6 Platform 11 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Point-to-Point Messaging Architecture


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Message Message
Client 1 Queue Client 2
Sends
Consumes
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr raMessaging
Point-to-Point n s Architecture
e x - t
nonin the slide illustrates the point-to-point messaging architecture, which is based on
Al The figure
the concept of a message queue.
A message queue retains all messages until they are consumed.
• The distinguishing factor between the point-to-point and publish/subscribe architectures
is that in most cases, each point-to-point message queue has only one message
consumer.
• There are no timing dependencies between the sender and receiver.
- A receiver gets all the messages that were sent to the queue, even those sent
before the creation of the receiver.
- The queue then deletes messages on the acknowledgement of successful
processing from the message consumer.

A message queue can have multiple consumers. When one consumer consumes a message
from the queue, the message is marked as consumed. Other consumers cannot also
consume the same message.

Developing Applications for the Java EE 6 Platform 11 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

Publish/Subscribe Messaging Architecture


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Message

Subscribes
Client 2

Delivers

Message Topic
Client 1
Publishes
s a
Message
) h a
Subscribes
c o m
Client 3

ail ideฺ
m
g Gu
Delivers
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rans Messaging Architecture
Publish/Subscribe
a
x -t
AleThe figure
n o nin the slide illustrates the publish/subscribe architecture, which is based on the
concept of a message topic.
• A topic can have multiple consumers. Message producers publish messages to a topic.
• The topic retains messages until the messages are distributed to all consumers.
• There is a timing dependency between publishers and subscribers. That is, subscribers
do not receive messages that were sent before their subscription to the topic or while
the subscriber is inactive.
The JMS API supports the concept of a durable subscriber. A topic retains all messages for
subsequent delivery to inactive durable subscribers.

Developing Applications for the Java EE 6 Platform 11 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Queue Message Producer

JNDI API Namespace


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 Lookup 2 Lookup

Test
Message
6 Creates
Queue Connection Factory
s a
3 Creates
4 Creates 5 Creates ) h a
Queue Queue
c o m
Session Sender
a i l ฺ Queue
eฺ
Queue Connection
m
g 7 Set i
uTextd
@ t G
s 8o8Send en
a r d Stud
o
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Queue
r a n sMessage Producer
x -t
AleThe figure
n o nin the slide illustrates the steps required to create a queue message producer.

Developing Applications for the Java EE 6 Platform 11 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Queue Message Producer

1. Obtain a connection factory using injection or the JNDI


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

API.
2. Obtain the message queue using injection or the JNDI API.
3. Create a Connection object using the connection factory.
4. Create a Session object using the Connection object.
5. Create a QueueSender or MessageProducer object
using the Session object. s a
) h a
6. Create one or more Message objects using the Session o m
object. a ilฺc eฺ
m id g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Queue
r a n sMessage Producer (continued)
x -t steps explain how you can create a message queue producer:
AleThe following
n o n
1. Obtain a connection factory using injection or the JNDI API.
A connection factory is an administered object. An instance of the
QueueConnectionFactory class is required. You use it to create the Connection
object in step 3.
2. Obtain the message queue using injection or the JNDI API.
A message queue is an administered object. A message queue implements the point-to-
point message protocol destination.
3. Create a Connection object using the connection factory.
A connection encapsulates a virtual connection with a JMS API provider enabling
messaging clients to send messages and to receive messages from destinations.
4. Create a Session object using the connection.
A Session object provides a single-threaded context for producing and consuming
messages.

Developing Applications for the Java EE 6 Platform 11 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Queue Message Producer

7. (Optional) Populate message with text using the setText


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

method of the TextMessage object.


– A TextMessage can be populated when it is created.
8. Send one or more Message objects using the
QueueSender or MessageProducer object.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Queue
r a n sMessage Producer (continued)
x t
on- a QueueSender or MessageProducer object using the Session object.
Ale 5. nCreate
A QueueSender object provides the API to send messages to a queue destination.
6. Create one or more Message objects using the Session object.
Use the session object to create the required type of message object. After creation,
populate the message with the required data.
7. (Optional) Populate the message with text using the setText method of the
TextMessage object.
A TextMessage can be populated when it is created.
8. Send one or more Message objects using the QueueSender or MessageProducer
object.
Use the send method of the QueueSender or MessageProducer to send the
messages to the queue destinations.

Developing Applications for the Java EE 6 Platform 11 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Message Producer


package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import java.io.IOException;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/JMSAddServlet")
public class JMSAddServlet extends HttpServlet { s a
) h a
c o m
@Resource(mappedName = "jms/QueueConnectionFactory")
javax.jms.QueueConnectionFactory queueConnectionFactory;

ail ideฺ
m
g Gu
@Resource(mappedName = "jms/DemoQueue")
o @
8 ent
javax.jms.Queue queue;
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Message Producer


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

String text = request.getParameter("text");


try {
Connection connection =
queueConnectionFactory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

s a
TextMessage message = session.createTextMessage(text);
) h a
MessageProducer producer = session.createProducer(queue);
c o m
producer.send(message);

ail ideฺ
m
g Gu
producer.close();
o @
8 ent
session.close(); s
do Stud
connection.close();
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Message Producer

response.sendRedirect("JMSListServlet");
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

} catch (JMSException ex) {


request.setAttribute("exception", ex);
RequestDispatcher dispatcher =
request.getRequestDispatcher("jms_error.jsp");
dispatcher.forward(request, response);
}
}
// doGet and doPost appear here ...
s a
}
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Code for
r
dMessage n sProducer
a r a
x n-t session bean, or message-driven bean can use resource injection services of
AleNote:nAoservlet,
the container to obtain references to administered objects, such as a
QueueConnectionFactory or a queue or a topic. Nonmanaged objects may use JNDI to
obtain references to JMS administered objects.
The code below shows how to use JNDI to obtain JMS administered objects:
try {
QueueConnectionFactory queueConnectionFactory =
(QueueConnectionFactory)jndiContext.lookup("QueueConnectionFactor
y");
Queue queue = (Queue) jndiContext.lookup(queueName);
} catch (NamingException e) {
//...
}

Developing Applications for the Java EE 6 Platform 11 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Queue Message Browser

A queue allows JMS clients to browse its messages. A


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

message browser:
• Does not consume messages
• Is read-only
• Does not work with topics

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Queue Message Browser


package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import java.io.IOException;
import java.util.*;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/JMSListServlet")
s a
public class JMSListServlet extends HttpServlet {
) h a
c o m
@Resource(mappedName = "jms/QueueConnectionFactory") ฺ
ail ideฺ
javax.jms.QueueConnectionFactory queueConnectionFactory; m
g Gu
@Resource(mappedName = "jms/DemoQueue")
o @
8 ent
javax.jms.Queue queue; s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Queue Message Browser


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

List<TextMessage> messages = new ArrayList<TextMessage>();


try {
Connection connection =
queueConnectionFactory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

QueueBrowser browser = session.createBrowser(queue);


Enumeration queueEnum = browser.getEnumeration();
s a
while (queueEnum.hasMoreElements()) {
) h a
Object obj = queueEnum.nextElement();
c o m
if(obj instanceof TextMessage) {

ail ideฺ
messages.add((TextMessage)obj); m
g Gu
} o @
8 ent
s
do Stud
}
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Example Code for Queue Message Browser

browser.close();
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

session.close();
connection.close();

request.setAttribute("messages", messages);
RequestDispatcher dispatcher =
request.getRequestDispatcher("jms_list.jsp");
dispatcher.forward(request, response);

} catch (JMSException ex) {


s a
request.setAttribute("exception", ex);
) h a
RequestDispatcher dispatcher =
c o m
request.getRequestDispatcher("jms_error.jsp"); ฺ
ail ideฺ
dispatcher.forward(request, response); m
g Gu
}
o @
8 ent
} s
do Stud
a r
nc this
// doGet and doPost appear here ...
} ( a
o use
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Evaluating the Capabilities and Limitations of EJB


Components as Messaging Clients
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Enterprise Beans Producer Synchronous Asynchronous


Consumer Consumer
Session bean Yes Not recommended Not possible

Message-driven Yes Not recommended Yes


bean
Servlet Yes* Not recommended Not possible
s a
) h a
• Servlets are able to act as message producers; however,
c o m

ail ideฺ
session beans are more typically used. m
@ g Gu
• Message-driven beans are the preferred
o 8 method
e n t to create
o s d
message consumers. ard Stu nc this
( a
o use
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n
Evaluatingdr theraCapabilities
n s and Limitations of EJB Components as Messaging
e x - t
Al non
Clients
The table in the slide shows the messaging capabilities of enterprise beans.
Using Enterprise Components as Message Producers
• Session and message-driven beans are capable of becoming message producers.
• To add this capability, you include code to invoke the required methods of the JMS API.
Using EJB Components as Message Consumers
• Synchronous message consumers block and tie up server resources. For this reason,
you should not use servlets or session and message-driven beans as synchronous
message consumers.
• Message-driven beans consume messages asynchronously and are the preferred
method to create message consumers.

Developing Applications for the Java EE 6 Platform 11 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned that:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The JMS API provides an abstraction on top of a


messaging system
• The two messaging models are:
– A point-to-point model using queues
– A publish-subscribe model using topics
• Any component can produce messages s a
h a
• Due to strict thread management enforced by an om)
application server, not all components are suited
a ilฺcto eฺ
consume messages @ gm Guid
8 t o den
o s
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What is JMS?
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Java Management Service, an API for managing Java EE


services
b. Java Mobile Service, an API for developing applications for
mobile devices
c. Java Macintosh Service, an API for developing
applications for Macintosh computers s a
) h a
d. Java Messaging Service, an API for creating, sending,
o m
c
receiving, and reading messages ailฺ eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are the two destination types?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Queue and topic


b. Topic and stack
c. Queue and stack
d. Queue and dequeue

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dar rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which of the following does a publish/subscribe architecture


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

have?
a. A topic and a single subscriber
b. A message and multiple copies
c. A topic and multiple messages
d. A topic and multiple subscribers
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 11: Overview

There are no practices for this lesson.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 11 - 24


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Developing Message-Driven Beans

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe the properties and life cycle of message-driven
beans
• Create a JMS message-driven bean
• Create lifecycle event handlers for a JMS message-driven
bean s a
) ha
m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Introducing Message-Driven Beans

Message-driven beans are intended as an asynchronous


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

message consumer.
Message-driven beans implement a message listener interface.
• For example, JMS message-driven beans implement the
JMS API MessageListener interface.
• The bean designer is responsible for the message listener
method code. s a
) h a
The deployer supplies information for the container to register
o m
the message-driven bean as a message listener with c ฺ
ilฺthe
a
m uide
destination. @ g G
o8 den t
o s
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Java EE Technology Client View of


Message-Driven Beans
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

JMS Send Notify <<message driven bean>>


Queue
Client onMessage

Remote interface
Local interface
Client transaction context
Client security context
s a
) h a
om
ilฺc eฺ
1. Containers can create and pool multiple instances of message-driven
a
beans to service the same message destination. gm
@ G uid
2. The operation of these instances are independento 8 of each
e n t other.
s
3. When a message arrives at a message a r o
S tudthe container
ddestination,
chooses the next available instance
( a ncassociated
t his with that destination
to service the message. so us e
a rdo e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Java EEn r
dTechnology n s Client View of Message-Driven Beans
x a -t r a
AleThe figure
n o nin the slide shows the Java EE technology client view of a message-driven bean.
Message-driven beans do not:
• Have remote component, or local component interfaces
• Provide Java EE components with a direct client interface. Java EE technology clients
communicate with a bean by sending a message to the destination (queue or topic) for
which the bean is the MessageListener object.
• Have client-visible identity. They do not hold client conversational state. They are
anonymous to clients.
• Not participate in a client’s transaction because they have no client. The message
sender’s transaction and security contexts are unavailable to a message-driven bean.
Consequently, message-driven beans must start their own transaction and security
context.

Developing Applications for the Java EE 6 Platform 12 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Life Cycle of a Message-Driven Bean


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Does Not
Exist

1. newInstance()
PreDestroy callbacks
2. Dependency injection, if any
if any
3. PostConstruct callbacks, if any

s a
) h a
c o m
message Timeout ฺ
ail ideฺ
listener
method
Method- callback
method m
g Gu
Ready
Pool
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr of raaMessage-Driven
Life Cycle n s Bean
e x - t
non in the slide shows the life cycle of a message-driven bean.
Al The figure
1. The container creates a message-driven bean by invoking the newInstance method.
2. After the bean instance is created, the container, if applicable, injects the bean’s
MessageDrivenContext instance, and performs any other dependency injection, as
specified by metadata annotations on the bean class or by the deployment descriptor.
3. The container then calls the bean’s PostConstruct callback method, if any.
4. Then the container adds the bean to the method-ready pool.
5. The bean is then ready to service the message notifications presented to it through the
message listener method.

Developing Applications for the Java EE 6 Platform 12 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Types of Message-Driven Beans

JMS message-driven beans:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• They are annotated with @javax.ejb.MessageDriven


and implement the javax.jms.MessageListener
interface.
• Application server can integrate support or use connector.
Non-JMS message-driven beans:
• They are annotated with @javax.ejb.MessageDriven s a
and implement a message listener interface specificm ha
to) the
o
messaging service.
a ilฺc eฺ
• Application server requires a connector.@gm Gui
d
o8 den t
o s
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a JMS Message-Driven Bean

1. Declare the message-driven bean class:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

– Class must be public but not final or abstract.


2. Annotate the message-driven bean class using the
MessageDriven metadata annotation.
– Specify values with the following attributes:

mappedName = nameOfMessageDestination
s a
) h a
c o m
activationConfig = {

ail ideฺ
@ActivationConfigProperty(propertyName = m
g Gu
"destinationType", propertyValue = "javax.jms.Queue")
o @
8 ent
} s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a JMS Message-Driven Bean

3. Optionally, use resource injection to obtain a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

MessageDrivenContext instance.
4. Include a public no-argument empty constructor.
5. Write the onMessage method of the MessageListener
interface.
6. Do not define a finalize method.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Creating
a n dar JMS r a n s
Message-Driven Bean
e x - t
on
Al In thenonMessage method of the MessageListener interface, supply the code to process
the received message. This code might include:
• Accessing entity instances and session beans executing in the same JVM machine
using their local interfaces
• Accessing session beans executing in another JVM machine using their remote
interfaces
• Sending messages to a message destination

Developing Applications for the Java EE 6 Platform 12 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Message-Driven Bean Example

1 package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2
3 import javax.ejb.*;
4 import javax.jms.*;
5
6 @MessageDriven(mappedName = "jms/DemoQueue", activationConfig = {
7 @ActivationConfigProperty(propertyName = "destinationType",
8 propertyValue = "javax.jms.Queue")
9 })
10 public class MDBExample implements MessageListener {
s a
11
) h a
12 public void onMessage(Message message) {
c o m
13 System.out.print("Consumed message."); ฺ
ail ideฺ
14 } m
g Gu
15 }
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr ranBean
Message-Driven
a
s Example
x -t
AleThe code
n o n
in the slide shows a simple example of a message-driven bean class.

Developing Applications for the Java EE 6 Platform 12 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Callback Methods in a Bean Class


1 import javax.ejb.*;
2 import javax.jms.*;
3 import javax.annotation.*;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

4
5 @MessageDriven(mappedName = "jms/DemoQueue", activationConfig = {
6 @ActivationConfigProperty(propertyName = "destinationType",
7 propertyValue = "javax.jms.Queue")
8 })
9 public class MessageBean {
10 @Resource private MessageDrivenContext mdc;
11
s a
12 public MessageBean() { } // constructor
) h a
13
c o m
14 @PostConstruct void obtainResources() { } ฺ
ail ideฺ
15 m
g Gu
16 @PreDestroy void releaseResources() { }
o @
8 ent
17 s
do Stud
a r
nc this
18 public void onMessage(Message inMessage) { }
19 }
( a
o use
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Adding n r
dLifecycle n sEvent Handlers
a
x EJB r a
-t 3.0 specification, you are not required to provide lifecycle event handlers for
AleWith the
n o n
message-driven beans. However, message-driven beans do generate lifecycle events and
you can optionally provide event handlers for these methods.
• PostConstruct
The PostConstruct callback occurs after the construction of the bean instance but
before the first message listener method invocation on the bean. This is at a point after
which any dependency injection has been performed by the container.
• PreDestroy
The PreDestroy callback occurs at the time the bean instance is removed from the
pool or destroyed.

Developing Applications for the Java EE 6 Platform 12 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Defining a Callback Handler in the Bean Class


To define a callback handler in a message-driven bean class, perform the following steps:
1. Declare, in the bean class, a callback method with the following signature:
public void methodName()
2. Ensure that the callback method conforms to the following rules:
- It can have any type of access modifier (public, default, protected, or private).
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

- It must not throw an application exception.


- It can throw a runtime exception.
- It must not use dependency-injected values.
- It must not rely on a specific transaction or security context.
3. Annotate the method with the appropriate lifecycle event handler metadata annotation.
For a PostConstruct method, use the PostConstruct metadata annotation. For a
PreDestroy method, use the PreDestroy metadata annotation.
s a
4. The code in the slide shows an example of lifecycle event handler methods ) ha
obtainResources and releaseResources defined within a bean class.
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The properties and life cycle of message-driven beans


• How to create a JMS message-driven bean
• Lifecycle event handlers for a JMS message-driven bean
The following are some interesting topics covered in the course
titled, Business Component Development with EJB
Technology: s a
) h a
• Message Selectors o m
• Acknowledgement modes a ilฺc eฺ
m id g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What are message-driven beans designed as?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Synchronous message consumers


b. Asynchronous message producers
c. Synchronous message providers
d. Asynchronous message consumers

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which two lifecycle events are generated by message-driven


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

beans?
a. postConstruct
b. UnConstruct
c. PreDestroy
d. postDestroy
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a da,r d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 12: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Implementing the message-driven bean


• Describing message-driven beans

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 12 - 15


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Web Service Model

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe the role of web services
• Distinguish between the two major types of web services
• List the specifications used to make web services platform
independent
• Describe the Java APIs used for XML processing and web s a
) h a
services om
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

The Role of Web Services

The W3C defines a web service as “a software system


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

designed to support interoperable machine-to-machine


interaction over a network.”
Web services are:
• Platform independent
• Designed to leverage existing technologies
• Interoperable across disparate programming languages s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
The Role
a drof Web
r a n s
Services
x t
on- exposes a remote service or executable procedure to a client application. Web
AleA webnservice
services are designed to be platform independent; however, this platform independence is not
without some cost. The cost of a web service’s platform independence is overhead, both in
network and CPU usage.
Some key features of web services are:
• Platform independent: No CPU, operating system, or programming language–specific
data or functionally is required for web services.
• Designed to leverage existing technologies: Web services make extensive use of
XML and HTTP technologies. Both of these technologies have large toolset and
knowledge bases.
• Interoperable across disparate programming languages: Web services use a
client/server model. It is possible to have a client written in one programming language
communicating with a server written in a different language.
The Java EE 6 platform enables the easy creation or addition of web services to your
applications.

Developing Applications for the Java EE 6 Platform 13 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Web Services as Remote Components

Web services provide a mechanism to remotely execute a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

business operation. Web services provide remote execution


similar to:
• CORBA
• RMI
• RPC
• DCOM s a
) h a
Web services differ from these technologies by leveraging
o m
HTTP and XML, both of which are well supportedmby
ฺc eฺ in
aillibraries
almost every programming language. @ g Guid
8 t o den
o s
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raasnRemote
Web Services
a
s Components
e x - t
on Object Request Broker Architecture (CORBA): A specification managed by
Al • nCommon
the Object Management Group (OMG). Provided bindings for the C programming
language and later C++ followed by Java. Seen by some as overly complex. Used
mainly in the 1990s. Beginning in 2000, web services started supplanting CORBA for
some applications.
• Remote Method Invocation (RMI): A Java technology remote object method invocation
technology. The preferred method for basic distributed Java components. Included as
part of the Java SE platform.
• Remote Procedure Call (RPC): A procedural remote execution protocol popularized by
Sun Microsystems. Not typically used in object-oriented software. Network File System
(NFS) is an example of an RPC program.
• Distributed Component Object Model (DCOM): The Microsoft equivalent to RMI,
which worked only on Microsoft platforms. DCOM has been replaced by Net Remoting
and web services.
Java libraries supporting web services are supplied in both the enterprise version of the Java
platform and the standard edition platform.

Developing Applications for the Java EE 6 Platform 13 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Web Services Compared to Remote EJBs

A web service consists of:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• A registry for publishing and looking up web services.


Registries implement the Universal Description, Discovery
and Integration (UDDI) standard. If the client already
knows the location of the desired service, the registry can
be bypassed.
• A transport protocol used to invoke operations, pass s a
arguments, and receive return values. In Remote EJBs, ) h a
this can be the Internet Inter-Orb Protocol (IIOP). o
In
m
web
a ilฺc eฺ
services HTTP is typically used.
@ gm Guid
• A sequence of data transferred between o n t and
8 theeclient
s
server. Remote session beans a r
use S tud object
do a serialized
whereas some web services ( a ncuse tXML.
his
o e
r d os to us
C a se
i d s
i © l2011,
c e n
ola ble
Copyright i Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e
d raCompared
n s
x a n
Web Services
t to Remote EJBs
e -
non architecture of remote EJBs is not that different from web services, with the
Al The overall
exception of the specific technologies used to make the web services platform independent.
Currently most implementations of web services are stateless so they are best compared to
stateless session beans.
Oracle offers a five day instructor-led training course dedicated to web services titled
Developing Web Services Using Java Technology.

Developing Applications for the Java EE 6 Platform 13 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

RESTful Web Services

A RESTful web service follows the Representational State


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Transfer architectural style. RESTful web services revolve


around resources.
Resources have URIs such as http://localhost/stocks/ORCL.
HTTP methods are used to perform operations relating to that
resource.
• HTTP GET: Retrieve a representation of the resource. a
• HTTP POST: Add a new element to a collection, such as adding h a s
m )
a stock to the http://localhost/stocks resource. o
a ilฺc eฺ
• HTTP PUT: Create or update the resource. gm
@ G uid
• HTTP DELETE: Delete the resource. so8 ent o d
Message format selection is left to S tu developer.
rd application
cathe s a n hi
( e t
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
RESTful
r Services
dWeb n s
a r a
x n-t many be any thing such as a stock, customer, or share of stock.
Ale • nA oresource
• The state of a resource is captured and transferred between a client and server.
Therefore, the architecture is called Representational State Transfer.
• The HTTP body content type may be any MIME type the developer wants to use.
• RESTful web services benefit from their simplicity and the wide adoption of HTTP.
Note: For more information on REST architecture see Roy Fielding’s dissertation,
Architectural Styles and the Design of Network-based Software Architectures, available at
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm.

Developing Applications for the Java EE 6 Platform 13 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

SOAP Web Services

A SOAP web service follows the Simple Object Access


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Protocol (SOAP) specification when exchanging XML-formatted


data. SOAP web services:
• Are more complex than RESTful web services
– Java libraries hide much of this complexity.
• Have a machine-readable API defined using WSDL
• Can use additional standard and specifications that are not s a
) h a
included in RESTful web services, such as security-related
m
c o
specifications. ailฺ eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
SOAP n
a dr Services
Web
r a n s
x -t in-depth analysis comparing RESTful web services to SOAP web services
AleNote:nFor
onmore
see RESTful Web Services vs. “Big” Web Services: Making the Right Architectural Decision,
http://www2008.org/papers/pdf/p805-pautassoA.pdf.

Developing Applications for the Java EE 6 Platform 13 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

Interoperability Requirements

Web services are designed to be platform and language


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

neutral. To make web services effective, they must:


• Support clients regardless of platform or language
• Be able to be implemented in any language regardless of
the platform
Just using HTTP as a transport protocol and XML as a data
format does not provide a high level of interoperability. To be s a
interoperable: ) ha
c o m

ail ideฺ
• The methods and headers used in the HTTP transport
protocol must be standardized
m
g Gu
o @
8 ent
s
• The format of messages must bedknowno tud ar is S
n c
o (a se th
r d os to u
C a se
i d s
i © l2011,
c e n
ola ble
Copyright i Oracle and/or its affiliates. All rights reserved.

i c
N fera
r e s
d ranRequirements
n
Interoperability
a
x -t
AleTwo ofnthe
onspecifications used to make web services interoperable are HTTP and XML. HTTP
is a transport protocol, typically used on top of Transmission Control Protocol/Internet
Protocol (TCP/IP), that can be used to transfer information in a request-response oriented
architecture. XML is a specification that is used to organize data in a machine-parsable text
file. Web services use HTTP to send formatted requests and responses, possibly as XML
messages.
There are many available data interchange formats such as Comma Separated Values
(CSV), JSON, and XML. These formats requires a document to follow a certain basic syntax
by themselves doe not specify a complete structure.
The World Wide Web Consortium (W3C) publishes the HTTP, XML, and SOAP specifications
at http://www.w3c.org.

Developing Applications for the Java EE 6 Platform 13 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

SOAP Interoperability Standards

• Extensible Markup Language (XML): A W3C standard


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

designed to store data in a format both readable to


humans and easily parsed by machines
• Hyper Text Transfer Protocol (HTTP): A W3C standard for
short-lived data communication
• Universal Description, Discovery and Integration (UDDI): A
publish and lookup standard sponsored by OASIS s a
) ha
m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

SOAP Interoperability Standards

• Simple Object Access Protocol (SOAP): A W3C standard


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

that enforces a more defined structure upon the XML


formatted messages used in web services
• Web Services Description Language (WSDL): A proposed
W3C standard that defines the functionality of a web
service. It is similar in purpose to the business interface of
a session EJB but formatted in XML. a
s
• Web Services Interoperability (WS-I) Basic Profile: A ) ha
profile that mandates the use of certain specifications,
c o m

ail ideฺ on
such as SOAP and WSDL, placing additiongm restrictions
u
@ t G
so8 web
them as needed, to provide interoperable en services
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
SOAP n
a dr rans Standards
Interoperability
x t
on- of a SOAP request:
AleCodenexample
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ns1="http://sample/">
<soapenv:Body>
<ns1:getGreeting>
<arg0>Duke</arg0>
</ns1:getGreeting>
</soapenv:Body>
</soapenv:Envelope>
<?xml version="1.0" encoding="UTF-8"?>

Developing Applications for the Java EE 6 Platform 13 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Code example of a SOAP response:


<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ns1="http://sample/">
<soapenv:Body>
<ns1:getGreetingResponse>
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

<return>Hello Duke</return>
</ns1:getGreetingResponse>
</soapenv:Body>
</soapenv:Envelope>
Example of a WSDL File:
<?xml version="1.0" encoding="UTF-8"?><definitions
xmlns="http://schemas.xmlsoap.org/wsdl/"
s a
xmlns:tns="http://sample/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" ) h a
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
c o m

ail ideฺ
targetNamespace="http://sample/" name="SayHelloService">
m
g Gu
<types>
o @
8 ent
<xsd:schema> s
do Stud
a r
<xsd:import namespace="http://sample/"
a nc this
schemaLocation="http://10.1.1.1:8080/WebService/SayHelloService/_
(
s o use
_contain er$publishing$subctx/WEB-
o
rd e to
INF/wsdl/SayHelloService_schema1.xsd"
a
is C licens
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
i d
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"/>

i c ola ble
</xsd:schema>

r e N</types>
f e ra
s
nd tra<message
n
e x a -
name="getGreeting">
Al non <part name="parameters" element="tns:getGreeting"/>
</message>

<message name="getGreetingResponse">
<part name="parameters" element="tns:getGreetingResponse"/>
</message>
<portType name="SayHello">
<operation name="getGreeting">
<input message="tns:getGreeting"/>
<output message="tns:getGreetingResponse"/>
</operation>
</portType>

Developing Applications for the Java EE 6 Platform 13 - 11


Pontifícia Universidade Católica do Rio Grande do Sul
<binding name="SayHelloPortBinding" type="tns:SayHello">
<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"
style="document"/>
<operation name="getGreeting">
<soap:operation soapAction=""/>
<input>
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>

</output>
</operation>
s a
</binding>
) h a
<service name="SayHelloService">
c o m

ail ideฺ
<port name="SayHelloPort" binding="tns:SayHelloPortBinding">
<soap:address m
g Gu
o @
8 ent
location="http://10.1.1.1:8080/WebService/SayHelloService"
s
do Stud
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
a r
( a nc this
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"/>
</port>
o s o use
</service>
a rd e to
is C licens
</definitions>
i d
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Java APIs Related to XML and Web Services

• Java DOM (JDOM)


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Java API for XML Processing (JAXP)


• Java Architecture for XML Binding (JAXB)
• Java API for XML-based Remote Process
Communications (JAX-RPC)
• Java API for XML Registries (JAXR)
s a
• SOAP with Attachments API for Java (SAAJ) h a
)
• Java API for RESTful Web Services (JAX-RS) ฺcom
il ฺ
• Java API for XML Web Services (JAX-WS)gma uide
o 8 @ nt G
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Java APIs
a drRelated
r a n sto XML and Web Services
-t in the following list can be used when providing or using a web service in
x specifications
AleThe n o n
the Java programming language.
• Java DOM provides an object-oriented Java model of an XML document.
• JAXP is a Java technology abstraction of the actual XML processing implementation.
• JAXB controls how to convert Java objects to XML schemas.
• JAX-RPC is the original high-level web services specification for Java technology,
replaced by JAX-WS. JAX-RPC is a proposed optional specification in Java EE 6.
• JAXR is a Java standard for using UDDI registries. JAXR is a candidate for pruning in
future versions of the Java EE platform.
• SAAJ is a Java standard for creating, sending, receiving, and parsing SOAP messages.
Used by JAX-WS.
• JAX-RS is a high-level Java web service API. JAX-RS implementations rely on HTTP as
the communication protocol.
• JAX-WS is a high-level Java web service API. JAX-WS implementations make use of
implementations of SAAJ, which in turn make use of JAXP and other Java XML
specifications.

Developing Applications for the Java EE 6 Platform 13 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-RS API

JAX-RS API is a high-level Java API for RESTful web services.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

JAX-RS:
• Was first included in the Java EE 6 platform
• Requires no specific data interchange format
• Developers may use JAXB or any other Java XML API if
they choose to produce or consume XML
• Provides only server APIs a
as )h
o m
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-RS n r
dAPI n s
a
x JAX-RS r a
-t on the server side does not require its use on the other side of the connection.
AleUsing n o n
If you are developing RESTful web services using Java technology, then you should use the
JAX-RS API.

Developing Applications for the Java EE 6 Platform 13 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS API

JAX-WS API is a high-level Java API for SOAP web services.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

JAX-WS:
• Replaces JAX-RPC
• Requires little or no XML or WSDL knowledge for basic
web services
• Uses JAXB to specify how Java and XML data types are
mapped s a
) h a
• Provides both client and server APIs om
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-WS n r
dAPI n s
a
x JAX-WS r a
-t on the client or server side does not require its use on the other side of the
AleUsingn o n
connection. If you are developing SOAP web service clients and servers using Java
technology, then you should use the JAX-WS API.
Web Service Benefits
The following are reasons to consider using web services:
• The flexibility of supporting unknown future client platforms.
• Not being tied to a particular server platform. For example, if the server platform does
not scale well, it can be replaced without affecting client applications.
• The use of HTTP as a communication technology allows the use of existing firewall
rules in many cases.

Developing Applications for the Java EE 6 Platform 13 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The types of web services in enterprise applications


• The specifications used to make web services platform
independent
• The Java APIs used for XML processing and web services

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

True or false: A web services provides a platform-independent


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

system for clients and servers to interact over a network.


a. True
b. False

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a dar rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What does REST stand for?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Recent State Transfer


b. Recombined State Transfer
c. Representational Size Testing
d. Representational State Transfer

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Answer:
a ddr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which web service technology relies on HTTP methods to


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

define operations?
a. RIA
b. WS-I
c. SOAP
d. REST
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dcr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which web service technology relies on HTTP methods to


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

define operations?
a. RIA
b. WS-I
c. SOAP
d. REST
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dcr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What is SOAP?
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Super Object Access Protocol


b. Simple Object Access Protocol
c. Simple Object Analysis Protocol
d. Super Object Analysis Protocol

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dbr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 13: Overview

There are no practices for this lesson.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 13 - 22


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Implementing Java EE Web Services with


JAX-RS & JAX-WS
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Describe endpoints supported by Java EE 6
• Describe the requirements of the JAX-RS POJO endpoints
• Describe the requirements of the JAX-WS POJO
endpoints
• Describe the requirements of JAX-WS EJB endpoints s a
) h a
• Develop web service clients om
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Web Service Endpoint Types


Supported by Java EE 6
A web service endpoint is the component that executes as a
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

result of sending a web service request to an application


server. Java EE 6 endpoints can be:
• POJO components (also called Servlet or Web)
• Stateless and Singleton session bean components (JAX-
WS)
Both JAX-RS and JAX-WS endpoints can be used in the Java s a
EE 6 platform. The choice between JAX-RS and JAX-WSmwill ) ha
co ฺ
largely depend on nonfunctional requirements. ailฺ e
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rEndpoints
Web Service
a a n s Supported by the Java EE 6 Platform
e x - t
n of components that can function as endpoints are as follows:
Al The two
notypes
• POJO components: Both JAX-RS and JAX-WS provide annotations that are used to
configure a plain Java class to function as a web service endpoint. In JAX-RS, an
endpoint is sometimes known as a resource class. In JAX-WS, this endpoint is
sometimes known as a servlet or web endpoint.
• Session bean components: Stateless and Singleton session bean components can
function as a web service endpoint. Stateful session beans cannot function as
endpoints.

Developing Applications for the Java EE 6 Platform 14 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-RS Web Endpoints

A JAX-RS endpoint is a POJO class, also known as a resource


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

class. When deployed to a web container, the JAX-RS


framework provides a servlet implementation used to handle
HTTP requests. A JAX-RS web endpoint:
• Is an annotated Java class created to provide web service
functionality
• Is instantiated per request s a
h a
• Does not require an EJB container m) o
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-RS n r Endpoints
dWeb n s
x a -t r a
AleThe Java
n o nAPI for RESTful Web Services (JAX-RS):
• Is a specification that, along with an implementation, supports the execution of remote
methods using the HTTP protocol for message transport. The messaging format used is
selected by the developer.
• Its reference implementation (RI) is named Jersey.
When a RESTful web service client wants to execute a remote method:
• It delivers a message to a server using the HTTP protocol methods
• It is the job of the JAX-RS implementation to convert the HTTP request to a Java
method call by using the request URI and HTTP method type
• You must supply the methods called by JAX-RS and these methods typically exist in an
endpoint component
Note: In JAX-RS, an endpoint component is also known as a resource class.
JAX-RS does not require an EJB container. This is the main benefit of this type of endpoint.
Servlet and JSP containers, such as Apache’s Tomcat, can be set up to support this type of
web service.

Developing Applications for the Java EE 6 Platform 14 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

Implementing a JAX-RS Web Endpoint

A JAX-RS web endpoint:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Has a @javax.ws.rs. path class annotation


• Has business methods that are public and are annotated
with a request method designator (for example, @GET)
• Uses the @Produces and/or @Consumes annotations at
the class or method level
• Cannot be an abstract s a
) h a
• Usually has a no-arg constructor om
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Simple JAX-RS Web Component Endpoint


Example
package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import javax.ws.rs.*;

@Produces("text/plain")
@Consumes("text/plain")
@Path("greeting")
public class GreetingResource {

private static String message = "Howdy";

public GreetingResource() {}
s a
) h a
@GET
c o m
public String getGreetingText() {

ail ideฺ
return message;
m
g Gu
}

o @
8 ent
@PUT s
do Stud
a r
nc this
public void putText(String content) {
message = content;
( a
o use
}
o s
}
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-RS Servlet Endpoint Configuration

The web.xml file in your web archive (WAR) must be updated


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

to provide a usable URL for the web service.


<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
s a
) h a
<servlet-mapping>
c o m
<servlet-name>ServletAdaptor</servlet-name> ฺ
ail ideฺ
<url-pattern>/resources/*</url-pattern> m
g Gu
</servlet-mapping>
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-RS n r
dServlet n s
Endpoint Configuration
x a - t r a
e
non
Al The <load-on-startup> element should be specified so that the web server loads this
class when starting up. When classes are loaded that contain a @Path annotation, the JAX-
RS provided servlet handles all HTTP requests for the configured URL.

Developing Applications for the Java EE 6 Platform 14 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-RS URI Parameters

The URI or path used to invoke a JAX-RS web service can


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

contain embedded parameters.

@Path("orders/{order_id}")
public class OrderResource {

@GET
Order getOrder(@PathParam("order_id") String id) {
s a
//...
) h a
}
c o m
} ฺ
ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Web Endpoints

The JAX-WS framework provides a servlet implementation


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

used to handle HTTP requests and process SOAP messages.


A JAX-WS web endpoint:
• Is a standard Java class created just to provide web
service functionality
• Is multithreaded
• Does not require an EJB container s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-WS n r Endpoints
dWeb n s
x a -t r a
AleThe Java
n o n
API for XML Web Services (JAX-WS) is a specification that, along with an
implementation, supports the execution of remote methods using an XML-based messaging
schema.
When a “big” web service client wants to execute a remote method, it delivers a SOAP
message to a server that, in this case, uses JAX-WS. It is the job of the JAX-WS
implementation to convert the SOAP message to method calls and arguments. You must
supply the methods called by JAX-WS and these methods only exist in an endpoint
component.

Developing Applications for the Java EE 6 Platform 14 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Implementing a JAX-WS Web Endpoint

A JAX-WS web endpoint:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Has a @javax.jws.WebService class annotation


• Contains business methods that are public and not final or
static
• Has exposed web service methods that are annotated with
@javax.jws.WebMethod
• Cannot be an abstract or final class s a
) h a
• Requires a default no-arg constructor o m
ฺ c
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Simple JAX-WS Web Component Endpoint


Example
package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import javax.jws.*;

@WebService
public class SayHello {

@WebMethod
public String getGreeting(String name) {
return "Hello " + name;
s a
}
) h a
}
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Servlet Endpoint Configuration

The web.xml file in your web archive (WAR) must be updated


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

to provide a usable URL for the web service.


<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>example.SayHello</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

s a
<servlet-mapping>
) h a
<servlet-name>hello</servlet-name>
c o m
<url-pattern>/sayhello</url-pattern> ฺ
ail ideฺ
</servlet-mapping>
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-WS n r
dServlet n s
Endpoint Configuration
x a - t r a
e
non
Al The <load-on-startup> element should be specified so that the web server loads this
class when starting up. When classes are loaded that contain a @WebService annotation,
the JAX-WS provided servlet handles all HTTP requests for the configured URL.

Developing Applications for the Java EE 6 Platform 14 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Endpoint Life Cycle

• JAX-WS endpoints, both web and EJB, can have optional


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

life- cycle methods that are automatically called if present.


• Any method can be used as a lifecycle method with the
correct annotation:
– @PostConstruct: Called by the container before the
implementing class begins responding to web service clients
– @PreDestroy: Called by the container before the endpoint a
is removed from operation h a s
) m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-WS n r
dEndpoint n sLife Cycle
x a r a
t endpoint follows the typical servlet threading model, which means that
on-
AleA webncomponent
typically there is one instance that is executed concurrently for each client. JAX-WS
implementations are free to leverage pools of bean instances to handle a request in a fashion
similar to stateless session EJB components.

Developing Applications for the Java EE 6 Platform 14 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Allowed Data Types

• Unlike the JAX-RPC, JAX-WS does not contain a Java-to-


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

XML binding specification for data types.


• JAXB is specified by JAX-WS as the way in which Java
data is converted back and forth to XML
• Basic Java types, such as String, is supported
automatically.
– However, to return or pass complex object instances, some s a
JAXB programming is required. ) ha m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
JAX-WS n r
dAllowed n sData Types
x a t r a
on- outside the scope of this course, you should know that JAXB is not used only
AleNote:nAlthough
with JAX-WS. You can use JAXB any time you need to convert a Java object to an XML
document. JAXB also supports generating classes from XML schemas, and XML schemas
from Java classes.

Developing Applications for the Java EE 6 Platform 14 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

Code Examples of Using JAX-B


Basic JAXB Annotated Class That Could Be Returned from a JAX-WS Method
import javax.xml.bind.annotation.XmlType;
@XmlType
public class Person {
private String name;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

private int age;

public Person() { }
public Person(String name, int age) {
this.setName(name);
this.setAge(age);
}
s a
) h a
public String getName() {
c o m
return name; ฺ
ail ideฺ
} m
g Gu
public void setName(String name) { 8@ n t
s o e
this.name = name;
a r do Stud
}
( a nc this
o s o use
a
public int getAge()rd e {to
i d is C age;
return
li c e ns
} la
c o l e
e N i public
f e r abvoid setAge(int age) {
a n dr rans this.age = age;
x -t }
Ale non }
SOAP Response of a JAXB Annotated Object
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope /"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ns1="http://server/">
<soapenv:Body>
<ns1:getPersonResponse>
<return>
<age>40</age>
<name>Bob</name>
</return>
</ns1:getPersonResponse>
</soapenv:Body>
</soapenv:Envelope>

Developing Applications for the Java EE 6 Platform 14 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

RESTful Web Service Clients

JAX-RS does not have a client API at this time. To write a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

RESTful web service client in Java:


• Use java.net.HttpURLConnection
• Use a client API not covered in the JAX-RS specification
Jersey, the reference implementation of JAX-RS, provides a
client API. Documentation is available at:
https://jersey.dev.java.net. s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rClients
Web Service a n s
x -t
AleJava web
n o n
service clients are programmed differently for RESTful and SOAP web services.

Developing Applications for the Java EE 6 Platform 14 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

A RESTful Client Example

package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Client {

public static void main(String[] args) throws Exception {


URL url = new URL("http://localhost:8080/JAXRSDemo/resources/greeting");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
s a
conn.setRequestMethod("PUT");
) h a
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
c o m
out.write("Hello"); ฺ
ail ideฺ
out.close(); m
g Gu
o @
8 ent
System.out.println("Response: " + conn.getResponseCode());
s
do Stud
a r
conn.disconnect();
( a nc this
}
}

o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Non-Java RESTful Web Service Clients

JAX-RS web services are platform neutral and can be called by


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

any client. To develop clients in other platforms, a developer


must:
• Have access to some type of documentation describing
the web service API
• Be able to produce and consume data in the format utilized
by the web service s a
) ha
m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

JAX-WS Web Service Clients

The key to creating a SOAP web service client, in any


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

language, is having a copy of the web service’s WSDL. The


WSDL describes the operations, arguments, and return values
used in a web service.
The WSDL definition for a JAX-WS web service can be
generated automatically when the web service is deployed.
s a
Although not part of the specification, to retrieve the generated ) h a
WSDL from the GlassFish Application Server, you can o m
a i lฺc eฺyour
use
browser by requesting a URL similar to: gm Guid
o @
8 ent
http://localhost:8080/WSApp-war/SayHelloService?WSDL
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Developing JAX-WS Clients

To access a web service from a JAX-WS client, you need:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The WSDL definition


• A Proxy object to handle the creation of SOAP messages
and HTTP communication. This proxy type class is know
as a Port in JAX-WS.
• A generated Port class or alternative source code and
any other required artifacts for the web service s a
) h a
The JAX-WS reference implementation bundled with the o m
GlassFish Application Server provides an application c ฺ as
ilฺknown
m a ide
wsimport to create all the required client code. g The
@ nt G u
o 8
wsimport application can also be runoas s an de task.
Ant
rd Stu
c a
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

A JAX-WS Client Example

In the following example:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The Service class is used to instantiate a Port or proxy


• The Port handles all SOAP message creation and
transmission
public class WSTest {

s a
public WSTest() { }
) h a
c o m
public static void main(String[] args) {

ail ideฺ
SayHelloService service = new SayHelloService();
m
g Gu
SayHello port = service.getSayHelloPort();
o @
8 ent
System.out.println(port.sayHello("Duke"));
s
do Stud
}
a r
}
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Non-Java SOAP Web Service Clients

A JAX-WS web service can be called by any client or platform.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The client must:


• Have access to the WSDL file
• Support the correct version of the SOAP specification
For maximum compatibility, the client should support the WS-I
Basic Profile 1.1.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Non-Java
a drSOAP
r a n s Service Clients
Web
x -t find additional information about WS-I and achieving interoperable web
AleNote:nYou
oncan
services at the Web Services Interoperability Organization’s web site http://www.ws-i.org/

Developing Applications for the Java EE 6 Platform 14 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Endpoints supported by the Java EE 6 platform


• The pros and cons of the different endpoint choices
• JAX-RS web service endpoints
• JAX-WS web service endpoints
• Web service clients
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

What is JAX-RS?
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Java API for Regular Web Services


b. Java API for RESTful Web Services
c. Java API for Real SOAP Web Services
d. Java API for Regular SOAP Web Services

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dbr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Which of the following web service standards does JAX-WS


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

use primarily?
a. REST
b. SOAP
c. HTTP
d. XML-RPC
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dbr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 25


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 14: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Creating a JAX-WS web service


• Creating a web service client
• Creating a JAX-RS web service
• Describing web services
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 14 - 26


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

Implementing a Security Policy

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Objectives

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following:
• Exploit container-managed security
• Define user roles and responsibilities
• Create a role-based security policy
• Use the security API
s a
• Configure authentication in the web tier h a
)m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 2


Pontifícia Universidade Católica do Rio Grande do Sul

Exploiting Container-Managed Security

The Java EE platform specification defines an end-to-end,


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

container-managed, role-based, vendor-neutral security model.


Your main task is to define roles and create the declarative
security policy.
• The security API relies on the container-managed security
model.
• The use of the security model in the Java EE platform is s a
all-or-nothing. ) ha
c o m
• For example, you cannot code authentication a and
il ฺ also
eฺ
declaratively specify authorization. m
g Gu i d
o 8 @ nt
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 3


Pontifícia Universidade Católica do Rio Grande do Sul

Security Concepts

• Authentication: Establishing that the user’s claimed identity


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

is genuine
• Authorization: Establishing that the user is allowed to carry
out the requested action
• Confidentiality: Protecting data from unauthorized viewing
during communication
• Integrity: Ensuring that the data received is the same as s a
the data sent ) ha
c o m
• Confidentiality and integrity are dealt with at the ฺ
ailtransport
eฺ
level using a low-level, public-key protocol,
m
gsuchGas i d
u secure
8 @ n t
sockets layer (SSL). oso de rd Stu
c a
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Security
r
dConcepts n s
x a -t r a
AleThe points
n o n listed in the slide are described below:
Authentication can be as simple as prompting for a username and password. More complex
systems might make use of a public-key infrastructure to manage the certificate exchange. In
the Java EE model, authentication is carried out by the containers and not by the
components.
Normally, it is necessary to authenticate a user before authorization can be checked, although
an unauthenticated user might be allowed to carry out certain operations. The Java EE model
primarily uses declarative authorization.
For confidentiality, the normal approach is to use encryption that is usually based on
public-key techniques.
Integrity is normally achieved by signing the data. That is, the security model encrypts a
checksum of the data and adds the encrypted checksum to the message to ensure that the
message has not been modified during transmission.
SSL is now formally known as transport layer security (TLS). The use of TLS for component
interactions is frequently standard in Java EE applications. Configuration of the transport is
part of the administration of the application server and is not normally visible to the application
developer.

Developing Applications for the Java EE 6 Platform 15 - 4


Pontifícia Universidade Católica do Rio Grande do Sul

End-to-End Security Model

Java EE Security Domain


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Web
Browser Components

EJB
s a
Components
) h a
c o m

ail ideฺ
m
g Gu
Application
o @
8 ent
s
a r doEE Security
Java
S tudDomain
( a nc this
o s o use
a rd e to
i d is C© 2011,
c e ns and/or its affiliates. All rights reserved.
c o la le li
Copyright Oracle

e N i
f e r ab
n dr Security
End-to-End
a r a n s
x -t examples illustrate what end-to-end security means in practice:
AleThe following
n o n
• If a user is authenticated at the web tier, the user’s identity is made available to an EJB
component when servlets in the web tier make method calls on an EJB component.
• If the EJB component has an access control restriction in place that allows a certain
user to execute a certain method, it is of no importance that the user was first
authenticated to execute a servlet. The user is still subject to the EJB component’s
access control restrictions.
• If a stand-alone Java application makes method calls on EJB components, and is
hosted by an application client container, the client container can authenticate the user
and pass the user’s identity on to the EJB component.
• In addition, if one component makes access control decisions based on whether the
user is a member of a particular security role, you can be sure that other components
that use the same roles will make consistent decisions, because role membership
information is propagated between containers.
• This membership propagation between containers makes development more
straightforward, because you do not have to be concerned about how security
information is passed from one part of a complex system to another.

Developing Applications for the Java EE 6 Platform 15 - 5


Pontifícia Universidade Católica do Rio Grande do Sul

Container-Managed Security

The security model in the Java EE platform is primarily an


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

authorization model.
• If required, the container authenticates the client.
• The container checks a client’s rights to carry out the
requested action on a component.
• After authorization is complete, the container invokes
application code. s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
Web Container
( a nc thiEJB s Container
so us e
r d o to
a e
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rans Security
Container-Managed
a
x -t server is responsible for the implementation of both authentication and
AleThe application
n o n
authorization, which leaves you to establish the policy that will be enforced.
This is possible because components in the Java EE model never interact directly, but only
through their containers. Therefore, it is the containers that enforce the security policy.
The figure in the slide shows how a security policy is enforced by the web containers and the
EJB containers.
• Each time a web operation is initiated by a browser that issues a request:
- The web container checks the user’s security privileges against the policy for the
requested operation
- If the operation is not allowed, the application code is never invoked
• With EJB components, whenever a method call is made through the home object or
component object, the caller’s security privileges are checked against the policy for that
method.
- If the method call is not allowed, the call is simply not made.

Developing Applications for the Java EE 6 Platform 15 - 6


Pontifícia Universidade Católica do Rio Grande do Sul

Container-Managed Authentication

When you use container-managed authentication, the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

containers and the server infrastructure implement


authentication procedures for login or certificate exchange.
Authentication considerations include:
• Authentication in the web tier
• Web-tier authentication challenge methods
• Authentication from the web tier to the EJB tier s a
) h a
• Authentication of non-web clients o m
• Interaction with the security infrastructure ma
ilฺc eฺ
id g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 7


Pontifícia Universidade Católica do Rio Grande do Sul

Authentication in the Web Tier


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

No Is resource
restricted?

Yes

Is the session Yes


authenticated?

No

Deliver challenge

s a
No
) h a
User credentials
Yes
c o m
accepted? ฺ
ail ideฺ
(Authorization) m
g Gu
o @
8 ent
Deliver requested
resource s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rainnsthe Web Tier
Authentication
a
x -t
AleThe figure
n o nin the slide shows the authentication process in the web tier. Web containers
typically use lazy authentication. Lazy authentication means that the user is only asked to
authenticate if the requested resource, such as a servlet or JSP component, is actually
subject to a security restriction.
Authentication completes the following basic sequence:
• If the resource is not restricted, the resource is delivered without challenge.
• If the resource is restricted, the container gets the session ID from the request and
checks in the session store to determine whether the user is already authenticated.
• If the user is authenticated, there is no need to authenticate again.
• The container checks whether the user has permission to request the specified
resource.
• If the user is not authenticated, instead of delivering the requested resource, the
container delivers an authentication challenge. The challenge very often consists of a
request to the user to supply a username and password.
• If the username and password are acceptable, the container moves on to the
authorization step.

Developing Applications for the Java EE 6 Platform 15 - 8


Pontifícia Universidade Católica do Rio Grande do Sul

Web-Tier Authentication Challenge


Methods
• HTTP Basic: The web browser prompts the user for a
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

username and password, and supplies this information in


the request header.
• Client Certificate: The client presents the user’s digital
certificate in response to a challenge from the server.
• Form-based: The developer controls the look and feel of
the authentication process by supplying HTML forms. s a
) h a
• Programmatic: Technically, this is not a challenge method.m
o
Java EE 6 includes programmatic servlet security,
a ilฺc which
eฺ
adds the ability to force a challenge in-code m i d
g or toGcollect
u
@ t
so8way.
authentication information in a custom den do Stu
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Web-Tier
a drAuthentication
r a n s Challenge Methods
e x - t
on authentication is the simplest method to use, and the least configurable. The
Al HTTPnbasic
appearance of the challenge is determined by the browser and not by the developer or the
application server.
Client certificate authentication is not widely used when the client is a web browser, because
end users tend to have certificates that the server is not prepared to trust. However, client
certificate authentication is important in a business-to-business context, where the client might
be another enterprise application.
When authentication is required, the container provides your HTML instead of the requested
resource. The actual authentication is completed by the container.

Developing Applications for the Java EE 6 Platform 15 - 9


Pontifícia Universidade Católica do Rio Grande do Sul

Basic Authentication Dialog Box


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rans
Basic Authentication
a
x -t
AleThe figure
n o nin the slide shows a basic authentication dialog box from a web browser.
It is a common misconception that basic authentication is less secure than the other types of
authentication.
In fact, both basic and form-based methods of authentication supply the credentials in
plaintext, unless a secure channel is established first.
The real problem with basic authentication is that after the user has logged in, it is difficult to
log out.
The reason for this problem is that after the browser has collected the username and
password, the browser can supply this information whenever the server asks for them.
So the removal of the user’s authenticated status at the application server only has the effect
of making the browser resupply the credentials and log the user right back in again.
There are solutions to this problem, but they are not entirely portable. Form-based
authentication is usually the preferred method when the client is a web browser.

Developing Applications for the Java EE 6 Platform 15 - 10


Pontifícia Universidade Católica do Rio Grande do Sul

Authentication from the Web Tier to the


EJB Tier
You should not attempt to supply authentication credentials to
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

the EJB tier in code. Authentication is passed from the web tier
to the EJB tier as follows:
• A client of an EJB component must pass a verifiable
security context with each method call that allows the user
to be identified.
• When the client is a web component in the same s a
application as the EJB component, it is the web container’s
) h a
o
responsibility to pass the user credentials to theilEJB
m
a ฺc eฺ
container. gm uid @ nt G
o 8
r d os tude
a n ca his S
o ( se t
s
a rdo e to u
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr rafrom
Authentication
a n s the Web Tier to the EJB Tier
x example,-t there is never a good reason to pass the identity of the current user as an
AleFor n o n
argument to a method of an EJB component.
If the server has been configured correctly, the EJB component is always able to find the
identity of the current user from the security context that is passed by the web container.
When the client of the EJB component is not a web component, additional steps are usually
required for authentication.

Developing Applications for the Java EE 6 Platform 15 - 11


Pontifícia Universidade Católica do Rio Grande do Sul

Authentication of Non-Web Clients

For stand-alone clients that are implemented in the Java


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

programming language:
• Consider using an application client container
• Remember that authentication remains the responsibility of
the container
• Explore the possibility of customizing the look and feel of
the login procedure s a
) ha m
ฺ c o
m ail ideฺ
@ g Gu
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raof
Authentication
a n sNon-Web Clients
x n-t makes a method call on an EJB component, the method call will either succeed
AleWhennaoclient
or fail. If the method call fails because the user is not identifiable, this failure cannot be
rectified in the EJB tier.

Developing Applications for the Java EE 6 Platform 15 - 12


Pontifícia Universidade Católica do Rio Grande do Sul

Authentication of Non-Web Clients

For clients that are not implemented in the Java programming


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

language:
• The client can use IIOP API calls directly to supply the
security context
• It has only been possible to use IIOP API calls portably
since the introduction of the CSIv2 protocol in J2EE 1.3
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raof
Authentication
a n sNon-Web Clients (continued)
x -tof IIOP API calls makes it possible for an application that is written in a software
AleThis support
n o n
language, such as C++, to make method calls on EJB components and to authenticate itself
by supplying a digital certificate. However, these procedures are beyond the scope of this
course.

Developing Applications for the Java EE 6 Platform 15 - 13


Pontifícia Universidade Católica do Rio Grande do Sul

Interaction with the Security Infrastructure

• Remember, the security model in the Java EE platform is


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

vendor-neutral and platform-independent.


• User credentials and permissions are stored in various
ways, such as directory servers and relational database
tables.
• The application server interacts with the security
infrastructure. Applications cannot do this without loss of s a
portability. ) ha
c o m
• The range of security infrastructures supported ฺ
by the
ail ideฺ
m
application server can be extended by the guse ofGu
JAAS/JACC modules. o 8 @ nt
s de r do Stu
a
nc this
( a
o use
o s
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr with
Interaction
a r a n s Security Infrastructure
the
x -t
AleThe Java
n o n
EE 6 specification mandates support for the Java Authentication and Authorization
Service (JAAS) and Java Authorization Service Provider Contract for Containers (JACC)
APIs. With these APIs, you can install new modules in the server to extend the server’s
authentication capability. This makes it possible to provide support for security infrastructures
that are not handled out-of-the-box by the application server without having to complete
authentication in the application itself.

Developing Applications for the Java EE 6 Platform 15 - 14


Pontifícia Universidade Católica do Rio Grande do Sul

User Roles and Responsibilities

A role is an abstraction of a set of user authorization privileges.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Users in the same role have broadly similar rights and


responsibilities.
• The role structure of the security model in the Java EE
platform is flat, not hierarchical.
• Individual users can, and often will, occupy more than one
role. s a
h a
• There is some correspondence between a role andoam)
ilฺc eฺ of
group in many security infrastructures, but theamapping
real users or groups to roles is platform @ gm Guid
specific.
o8 den t
o s
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 15


Pontifícia Universidade Católica do Rio Grande do Sul

Role-Based Java EE Security Model

Platform-Specific Security Infrastructure


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Show
Account
Customer
Gerald

s a
Create
) h a
Account
c o m
Vanessa Manager ฺ
ail ideฺ
m
g Gu
Java EE Security Domain
o @
8 ent
s
do Stud
a r
( a nc this
Erin
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
dr raand
Roles,nActors,
a n s Use Cases
x -t with UML modeling, you may find it helpful to think of a role as an actor in a
AleIf younare
onfamiliar
use-case model.
• An actor is not a user. Rather, an actor is a collection of users with similar
responsibilities.
• Each actor interacts with one or more use cases. A use case is a self-contained unit of
capabilities within the application. It follows that the actor must have some access rights
over that use case.
In the figure in the slide:
• The Customer role groups the rights and responsibilities that are shared by customers of
the application, which includes the right to see the contents of their bank accounts.
• The Manager role groups the rights of managers, which includes the right to create new
bank accounts, as well as to view existing bank accounts.

Developing Applications for the Java EE 6 Platform 15 - 16


Pontifícia Universidade Católica do Rio Grande do Sul

End-to-End Roles

Roles are typically defined for the application.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Roles are subsequently applied in the web tier and the


EJB tier.
• It is easier to ensure security when roles are consistent
across the application.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Roles
End-to-End
a r a n s
x -t at the application level, not at the level of components or tiers.
AleRolesnare
ondefined
Although an application can have different roles in the web tier and the EJB tier, in practice,
this is rarely useful.
More commonly, roles are end-to-end. That is, roles are defined for the whole application and
then applied in the web tier and EJB tier.
This makes it easier to ensure a consistent security policy across the application.

Developing Applications for the Java EE 6 Platform 15 - 17


Pontifícia Universidade Católica do Rio Grande do Sul

Creating a Role-Based Security Policy

Creating an end-to-end, role-based security policy is a


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

four-step procedure:
1. Clearly define the roles.
2. Assign roles to URL patterns in the web tier by editing the
web.xml file or use security annotations in Java EE 6.
3. Assign roles to methods in the EJB tier by editing the
ejb-jar.xml file or using the @RolesAllowed s a
h a
annotation on the EJB methods in Java EE 5 or 6. m)
o
4. Expose the roles you have used by editing theailฺc eฺ
application.xml file or by using the@ gm Guid
@DeclareRoles
t
so8 EEde5nor 6.
annotation in EJBs and servlets inoJava
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
a dar Role-Based
r a n s Security Policy
x example,-t you could have a role called manager in module 1 and a role called
AleFor n o n
administrator in module 2. Then, if the manager and administrator roles are broadly
compatible, you could assign all users that are in manager role to the administrator role as
well. There is nothing wrong with this grouping of roles, and sometimes it is necessary, but it
is generally easier to pick a simple set of overarching roles at the application level, and then
apply them at the component level.
The determination of the roles requires knowledge of the application’s overall structure and
the responsibilities of its users. This determination is part of the design process and is not a
development exercise. In practice, role assignments often come from use-case modeling, or
simply from a knowledge of the different ways in which the users interact with the system.

Developing Applications for the Java EE 6 Platform 15 - 18


Pontifícia Universidade Católica do Rio Grande do Sul

Role Mapping

Mapping application roles to the principal accounts or groups


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

that exist within the application server is done with a vendor


deployment descriptor file. The WEB-INF/sun-web.xml for
GlassFish:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application
Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/
sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">
s a
<security-role-mapping>
) h a
<role-name>user</role-name>
c o m
<group-name>customers</group-name> ฺ
ail ideฺ
</security-role-mapping> m
g Gu
</sun-web-app>
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 19


Pontifícia Universidade Católica do Rio Grande do Sul

Role-Based Authorization in the Web Tier


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 4
http://server/bank/ShowAccount

Web Container
Browser

2 3

s a
) h a
c o m

ail ideฺ
m
g Gu
Customer
o @
Session Store
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Authorization
Role-Based
a r a n s in the Web Tier
e x - t
nonin the slide shows the procedure that the web container uses to check the
Al The figure
authorization of each request.
The authorization procedure in the web tier involves the following steps:
1. The browser makes a request for a specific URL.
2. The URL of the request is matched against the patterns in the deployment descriptor
that are subject to security restrictions and to security annotations placed in servlet
classes.
3. If the URL is restricted, the server obtains the user’s role assignments from the session
store and the underlying security infrastructure.
4. The server checks the user’s allocated roles against the roles allowed for the resource.
If any of the user’s roles are in the allowed set, the request is allowed, and the web
component is invoked.

Developing Applications for the Java EE 6 Platform 15 - 20


Pontifícia Universidade Católica do Rio Grande do Sul

Web Tier Security Annotations


Servlet 3.0 added the @ServletSecurity annotation.
package com.example;
import java.io.IOException;
import javax.annotation.security.*;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.HttpMethodConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.EmptyRoleSemantic;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@DeclareRoles({"admin", "user"})

// all HTTP methods require "admin" or "user"


// @ServletSecurity(@HttpConstraint(rolesAllowed = {"admin", "user"}))
s a
// allow all HTTP methods except POST
) h a
o m
// @ServletSecurity(httpMethodConstraints = @HttpMethodConstraint(value="POST", emptyRoleSemantic =
c
EmptyRoleSemantic.DENY))

ail ideฺ
// GET requires "admin", other method are open
m
g Gu
"admin"))
o @
// @ServletSecurity(httpMethodConstraints = @HttpMethodConstraint(value = "GET", rolesAllowed =
8 ent
s
do Stud
// everything requires "admin" except GET
a r
nc this
// @ServletSecurity(value = @HttpConstraint(rolesAllowed = "admin"), httpMethodConstraints =
@HttpMethodConstraint("GET"))
( a
o use
o s
@WebServlet(name="SecurityServlet", urlPatterns={"/SecurityServlet"})

a rd e to
public class SecurityServlet extends HttpServlet {}

i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Web Tier
a drSecurity
r a n sAnnotations
x -t
AleThe code
n o nexample in the slide shows an example of using security annotations to restrict
access to a servlet component in Java EE 6. Java EE 5 and earlier versions require the use of
the web.xml deployment descriptor to configure security constraints.

Developing Applications for the Java EE 6 Platform 15 - 21


Pontifícia Universidade Católica do Rio Grande do Sul

Role-Based Authorization in the EJB Tier


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1 4
BankMgr.getAccount()

EJB Container

2 3

s a
) h a
c o m

ail ideฺ
m
g Gu
Customer
o @
8 ent
s
a r o Security
dProtocol S tud
( a nc thisContext
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr Authorization
Role-Based
a r a n s in the EJB Tier
e x - t
nonin the slide shows the procedure that the EJB container uses to check the
Al The figure
authorization of each request, which are listed below:
1. The client makes a specific method call on the EJB component.
2. The method call information is checked to determine whether this method has security
restrictions assigned to it in the deployment descriptor or with annotations.
3. If the method is restricted, the server obtains the user’s role assignments from the RMI
protocol and the underlying security infrastructure.
4. The server checks the user’s allocated roles against the roles that are allowed for the
restricted method. If any of the user’s roles are in the allowed set, the method is
invoked. Otherwise the EJB container throws an exception.

Developing Applications for the Java EE 6 Platform 15 - 22


Pontifícia Universidade Católica do Rio Grande do Sul

EJB Tier Security Annotations


A Java EE 5 or 6 compatible example of an EJB with security
annotations:
package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

@Stateless
@DeclareRoles({"admin", "user"})
public class SecurityBean {
s a
) h a
@Resource SessionContext ctx;
c o m

ail ideฺ
@RolesAllowed(value = {"admin", "user"})
m
g Gu
public String getText() {
o @
8 ent
String name = ctx.getCallerPrincipal().getName();
return name + ", your admin status is: " + o
s
d Stud
a r
}
ctx.isCallerInRole("admin");
( a nc this
}
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
EJB Tier
r
dSecurity n sAnnotations
a
x 5nand r a
-t 6 allow security constraints to be placed on EJB components using
AleJava EE
n o
annotations instead of using deployment descriptors.
The code in the slide shows a Java EE 5/6 EJB component using security annotations.

Developing Applications for the Java EE 6 Platform 15 - 23


Pontifícia Universidade Católica do Rio Grande do Sul

Using the Security API

The security API is only available to applications that use


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

container-managed authentication. The API provides two basic


facilities that you can use to determine identity and role
allocation.

Method Calls to Method Calls to


Determine User or Determine User Role
Client Identity Allocations s a
) h a
Web Tier getUserPrincipal isUserInRole
c o m
a il ฺ e ฺ
EJB Tier getCallerPrincipal isCallerInRole m
g Gu i d
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 24


Pontifícia Universidade Católica do Rio Grande do Sul

Web-Tier Security API

String user = request.getUserPrincipal().getName();


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

String message =
"Welcome to the on-line bank, " + user;

if (request.isUserInRole("manager")) {
//... show manager menu
}

s a
In this example, manager is a role reference, not a role. ) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Web-Tier
a drSecurity
r a n sAPI
x -t
AleThe web
n o n
container makes the security context of the current user available with the
HttpServletRequest object that is passed to the service method.
The code snippet in the slide shows the use of the getUserPrincipal method to determine
the user or caller identity:
The getUserPrincipal method returns a Principal object, which encapsulates the user
identity. The Principal.getName method renders a textual form of that identity, which will
be the username if authentication is HTTP basic or form-based.
The following code snippet shows the use of the isUserInRole method to determine
whether the user has been assigned to the manager role. A servlet might complete this
method to construct a display that was appropriate for a particular user.
if (request.isUserInRole("manager")) {
//... show manager menu
}

Developing Applications for the Java EE 6 Platform 15 - 25


Pontifícia Universidade Católica do Rio Grande do Sul
Role references are mapped onto real role names at deployment time. This process frees you
from needing to know the final role names that will be assigned across the application. This is
particularly important when components are supplied by different developers.
In the preceding code example, the developer who writes the code that refers to the role
called manager has no way to know that there will be a role called manager in the deployment
system. Only the deployer knows the name of the role, and might have made a decision to
call this role administrator. At deployment time, the deployer will map the coded role manager
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

onto the target role administrator.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 26


Pontifícia Universidade Católica do Rio Grande do Sul

EJB-Tier Security API


Using the EJBContext security API:
package com.example;
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

@Stateless
@DeclareRoles({"admin", "user"})
public class SecurityBean {

s a
@Resource SessionContext ctx;
) h a
c o m
@RolesAllowed(value = {"admin", "user"}) ฺ
ail ideฺ
public String getText() { m
g Gu
String name = ctx.getCallerPrincipal().getName();
o @
8 ent
return name + ", your admin status is: " +
s
do Stud
ctx.isCallerInRole("admin");
a r
}
( a nc this
}

o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
EJB-Tier
r
dSecurity n sAPI
a
x innthe r a
-t EJB tier is similar to the API in the web tier. However, the EJB components
AleThe API
n o
have callers instead of users, and the method names reflect this difference.
The security context of the current caller is made available to the EJB component by its
container through the EJBContext objects. An EJB component typically saves its context
object in an instance variable so it can be used later.
The code example in the slide shows an EJB component context object saved in an instance
variable.
There is also an isCallerInRole method, which corresponds to the web component’s
isUserInRole method, and is subject to the same deploy-time name resolution.
Note: Message-driven beans do not have callers in the same sense as session beans. You
cannot determine the identity of the client that posted the message to the message-driven
bean’s queue. Therefore, the security API is of limited value in message-driven beans.

Developing Applications for the Java EE 6 Platform 15 - 27


Pontifícia Universidade Católica do Rio Grande do Sul

Configuring Authentication in the Web Tier

Web-tier authentication is a complex topic. This course


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

addresses only:
• Selecting the authentication type
• Creating an HTML login page for form-based
authentication

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 28


Pontifícia Universidade Católica do Rio Grande do Sul

Selecting the Authentication Type

The web deployment descriptor can be used to specify the


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

authentication type.

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<login-config>
s a
<auth-method>BASIC</auth-method>
) h a
<realm-name/>
c o m
</login-config>

ail ideฺ
</web-app> m
g Gu
o @
8 e3.0 n t specification.
HTTP Basic is the default method in the s Servlet
a r do Stud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Selecting
a drtherAuthentication
a n s Type
e x - t
nonEE specification recognizes three types of authentication in the web tier. Each has
Al The Java
its own configuration requirements.
• HTTP Basic: Select this authentication method by specifying it in the web.xml
deployment descriptor. You can also use the IDE to perform this task.
• Client Certificate: Select this authentication method by specifying it in the web.xml.
You must also configure the web container’s certificate database and allocate
appropriate trust levels, but this process is specific to the particular application server.
• Form-based: Select this authentication method by specifying it in the web.xml. In
addition, you must create a login page and an error page in the HTML or JSP software.
These are the pages that are presented by the web container in response to a request
that requires authentication. The pages can have any names. Use the web.xml to
specify the names to the container.
• Programmatic: The Servlet 3.0 specification (Java EE 6) allows username and
password collection using application specific methods.
The code example in the slide shows how to select the authentication type in Java EE 6 with
a web.xml deployment descriptor.

Developing Applications for the Java EE 6 Platform 15 - 29


Pontifícia Universidade Católica do Rio Grande do Sul

Creating an HTML Login Page for


Form-Based Authentication
Minimal section of HTML:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

<form action="j_security_check" method="post">

<-- layout code not shown for clarity -->

Username:
<input name="j_username"/><br/>
Password: s a
<input name="j_password" type="password"/><br/> ) h a
c o m
<input type="submit" name="submit" value="Log in"/>

ail ideฺ
m
g Gu
o @
8 ent
</form>
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n
Creating
r HTML
dan n sLogin Page for Form-Based Authentication
x a -t r a
AleThe login
n o npage can have any appearance or layout, but the names of the form elements must
comply with the specification.
You usually create login and error pages that match the look and feel of the rest of the
application.
The use of a JSP component or a servlet for the login page allows it to contain dynamic
content, if necessary.
The action attribute should be j_security_check, and the username and password
fields should have the names j_username and j_password, respectively. It is these
names that signal to the web container that authentication data is being supplied.

Developing Applications for the Java EE 6 Platform 15 - 30


Pontifícia Universidade Católica do Rio Grande do Sul

HTTP Security and JAX-WS clients

A JAX-WS client may be required to supply HTTP authentication


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

credentials. The JAX-WS API can supply a username and


password if needed.

SayHelloService service = new SayHelloService();


SayHello port = service.getSayHelloPort();

((BindingProvider)port).getRequestContext().put(BindingProvider.USERNAME_PRO
s a
PERTY, "username");
) h a
((BindingProvider)port).getRequestContext().put(BindingProvider.PASSWORD_PRO
c o m
PERTY, "password"); ฺ
ail ideฺ
m
g Gu
Access to the URL of the WSDL should not o @
8 restricted
be n t unless a
s e
local WSDL is provided to clients. rdo
a S tud
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
n dr raand
HTTP Security
a n s JAX-WS Clients
x -t
AleThe code
n o n
in the slide shows a JAX-WS supplied username and password.
The username and password supplied to a JAX-WS client is sent to the web server when
calling the methods of a web service.
Before using the methods of a web service, you must have access to the service’s WSDL file.
If the WSDL file is password protected, you must configure a JAX-WS client with a local copy.

Developing Applications for the Java EE 6 Platform 15 - 31


Pontifícia Universidade Católica do Rio Grande do Sul

Summary

In this lesson, you should have learned:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Container-managed security
• User roles and responsibilities
• Role-based security policies
• The security API
• Configuration of authentication in the web tier
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Summary
a n dr rans
x -tmodel of the Java EE platform centers on providing a declarative security model
AleThe security
n o n
where the container does the work. The developer or application assembler specifies which
methods of EJB components, or which URL patterns, are accessible to various user roles.
Authentication, encryption, and certificate management are handled internally by the
containers, which leaves you free to concentrate on the access policy.

Developing Applications for the Java EE 6 Platform 15 - 32


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Select three common security concepts.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Scalability
b. Authorization
c. Authentication
d. Confidentiality

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n da,r b,rcans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 33


Pontifícia Universidade Católica do Rio Grande do Sul

Quiz

Roles are tied to which of the following?


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

a. Systems and users


b. Users and privileges
c. Systems and databases
d. Privileges and systems

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
Answer:
a n dbr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 34


Pontifícia Universidade Católica do Rio Grande do Sul

Practice 15 Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Using the EJB Security API to get the user’s identity in an


EJB component.
• Creating roles, users, groups, and a web-tier security
policy
• Describing Java EE security
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C© l2011,
c e ns and/or its affiliates. All rights reserved.
c o la le i
Copyright Oracle

e N i
f e r ab
a n dr rans
x -t
Ale non

Developing Applications for the Java EE 6 Platform 15 - 35


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

You might also like