100% found this document useful (1 vote)
331 views72 pages

Ejb Tutorial

The document discusses Java Enterprise Edition (JEE) and Enterprise Java Beans (EJBs). It introduces JEE as a framework for building scalable systems using standards and tools. It describes EJBs as a capability within JEE for managing distributed components and their interactions. It also discusses session beans, stateless beans, stateful beans, and message-driven beans.

Uploaded by

aditi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
331 views72 pages

Ejb Tutorial

The document discusses Java Enterprise Edition (JEE) and Enterprise Java Beans (EJBs). It introduces JEE as a framework for building scalable systems using standards and tools. It describes EJBs as a capability within JEE for managing distributed components and their interactions. It also discusses session beans, stateless beans, stateful beans, and message-driven beans.

Uploaded by

aditi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Math is easy; design is hard.

- Jeffrey Veen

CmpE 275
Section: Java EE (JEE) - Enterprise Java Beans

Part 1: EJB Intro, Session Beans, Timer service

Java Enterprise Edition (Java EE)


Distributed Objects

2
3/4/14

Copyright 2013, Gash

Method call latency is not a factor in POJO/JavaBeans (single JVM)


however, it is a concern with distributed objects that
communicate over the network
Fine grain access pattern

Singe JVM/Process
Remote: Container + Object

getFirstName()

Requesting
Object

getLasttName()

Person

getAddressName()
getID()

id : Long
lastName : String
firstName: String

Application space ( single JVM): Access time per method ~0 msec


Distributed space: The connection between the requestor and remote
system introduces a tax (time and load) to marshal / unmarshal data and
transmit across the network.
Assume access time per method is ~1000 msec
(example requires ~4000 msec per object)
3
Copyright 2011, Gash

What is Java EE and EJBs?

Enterprise Java Beans (EJBs) is a capability within the Java


Enterprise Edition (Java EE) for managing components and
their interactions

How to describe Java EE?


An application
A framework for building scalable systems
Standards
A set of tools for web development

4
3/4/14

Copyright 2013, Gash

Java Enterprise Edition (JEE)

Application Servers implement


the Java EE standards. They
are applications for managing
lifecycle, transactions, and
resources for running of other
peoples code
! Modules
"
"
"
"

Application Client Modules


Web Modules (e.g., JSPs)
EJB Modules
Resource Adapter Modules

! Framework
" Standards and software to
build applications
" Includes tools for transactions,
database access, security, etc.

5
3/4/14

Copyright 2013, Gash

JEE is a collection of standards


and tools

Java Enterprise Edition (currently Java EE 6) is a set of best of


technologies, standards and practices built upon the Java SE. This
includes lifecycle management, transactions, security, and
deployment configuration. A partial listing:
Technologies
!
!
!
!

Enterprise Java Beans (EJB) 3.1


Java Persistence (JPA) 2.0
Java Message Service (JMS) 1.1
Java Transaction API (JTA) 1.1

(JSR
(JSR
(JSR
(JSR

318)
317)
914)
907)

Web Services
!
!
!

SOAP (JAX-WS) 2.2


REST (JAX-RS) 1.1
XML Binding (JAXB) 2.2

Web Application


(JSR 224)
(JSR 311)
(JSR 222)

" Java Servlet 3.0


" JavaServer Pages (JSP) 2.2
" JavaServer Faces (JSF) 2.0

(JSR 315)
(JSR 245)
(JSR 314)

Misc.
!

JavaMail, JMX, StAX, XML, JDBC, HTTP,

6
3/4/14

Copyright 2013, Gash

Comparing POJOs, JavaBeans


and EJBs

Plain Old Java Object (POJO)


! To put it simply, a class - Person, String
! Basic object oriented representation of a feature, process, or behavior

JavaBean
! POJO plus naming, metadata, and access rules
" Getter/Setter methods:
void setName(String name)
void setCool(boolean yes)

String getName()
boolean isCool()

" Bean Info

Enterprise Java Beans (EJBs)


!
!
!
!

Requires objects to implement Serializable why?


Lifecycle and interceptors
Dependency Injection (DI) of EJB attributes
Local and remote concept

7
3/4/14

Copyright 2013, Gash

JEE/EJBs provide distributed


design support by
The Application Server (AS) is a framework that provides an
integrated environment for objects that includes:
!
!
!
!

Lifecycle management
Transaction support
Security
Discovery

Object types (EJBs) supported:


"
"
"
"
"

Session Bean (Stateless and Stateful)


Message Driven Bean (MDB)
Timer service (simple scheduling service)
Persistence (JPA)
Resource Adapters (RA)
Transactional integration of external systems/services

8
3/4/14

Copyright 2013, Gash

What does this mean to you?


The EJB container acts as a functional programming
container
Solves
! Threading is complex
! Transactions are invasive
! Resource management is error prone

Isolating (minimizing) these concerns from the


developer, helps to increase productivity and
lessens errors resulting from concurrency and
distributed codes
Hadoop is another framework that supports a functional programming model
9
3/4/14

Copyright 2013, Gash

EJB Restrictions

or what you cannot (should not) do

Restrictions are placed on EJBs to ensure behavior and management


of resources that may be accessed by multiple instances (across
JVMs), compromise security safeguards, does not disrupt container
control

Key Restrictions applicable to EJBs and classes they use


!
!
!
!

Static fields for read & write (read only okay - final)
Java UI classes (awt, swing, etc)
Prompt for information from the stdin or redirect stdin, stdout, stderr
Create or manage threads
" Thread synchronization primitives

!
!
!
!
!
!

Stop the JVM


Native library access
Override/Use object substitution features of the Java serialization API
Directly read or write from/to a file descriptor ([Link])
Use sockets
Modify class loaders
10

3/4/14

Copyright 2013, Gash

Why the restrictions?

The EJB container acts as a lifecycle container. This means the


container manages the creation, lifecycle, and interceptor calls to an
EJB bean (class instances).
! Resources are managed by the container. If a bean allocates resources
and does not release them when done, the server may run out of
resources (e.g., file descriptors)
! Other containers that you may come across include Hadoop (MapReduce)

EJB Container
(from pool)

Transaction
JNDI (for DI)
Timer

[Link]
Security
11
3/4/14

Copyright 2013, Gash

The EJB container manages TX, lifecycle,


interceptors, and invoking the method
What happens when a method is called
! Get container and bean:
"
"
"
"

create bean through instance manager (pool of containers)


create TX policy
create interceptor stack
invoke post create methods (declared by @PostCreate or XML)

! Method execution
" invoke interceptors (declared by @AroundInvoke or XML)
" try { execute [Link](); }
catch (Exception e) { handle(TX policy); }
finally { after TX policy }

12
3/4/14

Copyright 2013, Gash

Three general types of EJB


components
Session beans
! Business logic
! Session beans can be declared as Local and
Remote (why?)

Message-driven beans
! Decouple direct interaction (delay response)

Entities
! Persistence
Note all EJBs are classes, all classes are not EJBs
13
3/4/14

Copyright 2013, Gash

EJB: Stateless

!
!

v2.x:

v3.x
Annotations:
@PostConstruct,
@PreDestroy

No conversational data between calls


Old EJB 2.x requires two classes (home,
bean)

Lookup, create, destroy methods (home)


Object implementation (bean)

EJB 3.0 simplified declaration and lifecycle


methods (no ejbCreate(),)
EJB 3.1 annotation replaces interfaces
Annotation: @Stateless
Best for handling blocking requests
Instance pooling, timer capable, WS
capable

Note from the image (EJB 2.x) we can see the evolution of the EJB specification from
a required method-based framework to a casual (use if needed) design (v3.1) to a
more developer friendly through annotations to designate lifecycle methods. Does this
really created separation of the lifecycle of an object?
ejbCreate(), ejbRemove() are EJB 2.x methods that in EJB 3.x are replaced by lifecycle annotation
image: [Link]

14
3/4/14

Copyright 2013, Gash

EJB v3.0: Local and remote interfaces for


session beans (Stateless, Stateful)
Session beans can run in a local container
for optimization within the same JVM
Annotations (limit external exposure)
! @Remote
! @Local
@Local
public interface EchoPointLocal extends EchoPoint
@Remote
public interface EchoPointRemote extends EchoPoint
15
3/4/14

Copyright 2013, Gash

EJB v3.0: Stateless example


public interface EchoPoint extends Serializable {
String echo(String what);
}

@Local
EchoPointLocal

@Remote
EchoPointRemote

@Stateless
public class EchoPointEJB implements EchoPointLocal, EchoPointRemote {

public String echo(String what) {


[Link]("Echo: " + what);
return what;
}

16
3/4/14

Copyright 2013, Gash

EJB: Stateful
v3.x lifecycle
@PostConstruct
@PreDestroy
@PrePassivate
@PostActivate

Retains information between calls


! Conversational data (must be serializable)
! Client to Object (one-one mapping)

v2.x ejbLC()

EJB 3.0 simplified declaration and lifecycle


methods (no ejbCreate(),)
EJB 3.1 annotation replaces interfaces
Annotation: @Stateful
Best for mult-part (steps) input without
persisting data between steps
No pooling, not timer capable, not WS capable

[Link]

17
3/4/14

Copyright 2013, Gash

Stateful passivation
Unlike stateless which can be limited to the number
of instances (pooled), a stateful is created per
client, which can create a memory burden on the
server.
The lifecycle includes passivation and activation of
a stateful instance
! Invoked when the server is experiencing heavy memory
usage or the instance is idle for a period of time
(configurable)
! Data contained in the instance is saved to disk or database
! A passivated object is activated before removing
(More on lifecycles in the next lecture)
18
3/4/14

Copyright 2013, Gash

EJB v3.0: Creating stateful EJBs


public interface AccountCreator extends Serializable {
void addAccount(Account acct);
void addAddress(Address addr);
}

@Local
AccountCreatorLocal

@Remote
AccountCreatorRemote

Not required
in EJB v3.1

@Stateful
public class AccountCreatorEJB implements AccountCreatorRemote {
. . .

19
3/4/14

Copyright 2013, Gash

Detailed look at the stateful


implementation
Remote interface - EJB v3.0 only

@Stateful
public class AccountCreatorEJB implements AccountCreatorRemote {
private Account acct;
private Address addr;
public void addAccount(Account acct) {
[Link] = acct;
}
public void addAddress(AccountAddress addr) {
[Link] = addr;
}
@Remove
public void cancelCreation() {
acct = null;
}

Annotation to indicate that


once this method is
called, the stateful EJB
instance can be removed.

. . .
20
3/4/14

Copyright 2013, Gash

EJB v3.1: Further simplification


yields the following
@Remote([Link])
@Stateless
public class AccountCreatorEJB implements AccountCreator {
private Account acct;
private Address addr;
public void addAccount(Account acct) {
[Link] = acct;
}
public void addAddress(AccountAddress addr) {
[Link] = addr;
}
}

. . .

21
3/4/14

Copyright 2013, Gash

Summarizing stateful v. stateless


uses
Technical differences

Usage differences

22
3/4/14

Copyright 2013, Gash

Let us consider for the moment stateless session


beans. Do we need stateful session beans?

Stateful beans introduce several drawbacks


that we must consider
What cases must we consider?
! Long-lived stateful data
! Multi-device access (remember stateful data is
tied to the clients connection)
! Resource conservation (data is not committed
until the stateful interaction ends)

23
3/4/14

Copyright 2013, Gash

Architecting stateful out of existence


How would you design a system to
provide stateful behavior using
stateless calls?

24
3/4/14

Copyright 2013, Gash

@Singleton (EJB v3.1)

Implementation of a GoF Singleton pattern


! Supports declarative TX, lifecycle (@PostConstruct, @PreDestroy), concurrency,
security, - same features available to a session bean

Motivation
! Manage information that does not lend itself to copies.
" E.g., Caching across tiers

Is this really required?


! Negative perceptions of the singleton pattern as an anti-pattern
! JPA/ORM/JDBC or cache services
@ConcurrenyManagement(CONTAINER)
@Singleton
public class SingleLookupBean {
@Lock(WRITE)
public void setData(String key, String value) {}

@Lock(READ)
public String getData(String key) {}

25
3/4/14

Copyright 2013, Gash

EJB timer service

Simple scheduling service (time delayed callbacks)


! Easy to use scheduling
! Supported by the standard and implemented by application servers means no
additional configuration and management needed (beyond the AS)
! Provides scheduling through
" Single - called once
" Interval - multiple

! Annotation: @Timeout
" Specify a the callback method within a stateless or message beans
" Container invoked method
" Transactional - can rollback

! Weaknesses
" Programmatic scheduling of tasks only (v3.0)

Full featured scheduling services


! Flux (Commercial)
" [Link]
! Quartz (OSS)
" [Link]

EJB v3.1: Enhances the


timer service by adding
declarative scheduling and
with @Startup the timer can
be automatically started by
the container
26

3/4/14

Copyright 2013, Gash

Timer example (EJB v3.0)


@Stateless
public class TimerTestEJB implements TimerTestRemote {
@Resource
[Link] ts;
public void startTimer() {
MyTimerData mtd = new MyTimerData();
[Link] = "Pick me!";

// start a timer with an initial delay and an interval of sInterval


[Link](sInterval, 2000, mtd);

public void stopTimer() {


Collection<Timer> list = [Link]();
for (Timer t : list) {
if ([Link]() != null && [Link]() instanceof MyTimerData)
[Link]();
}
}
@Timeout
public void TimeHandler(Timer timer) {
MyTimerData mtd = (MyTimerData)[Link]();
[Link](new Date().toString() + " - " + [Link]);
}

27
3/4/14

Copyright 2013, Gash

Timer example (EJB v3.1)


@Stateless
public class TimerTestEJB implements TimerTestRemote {
@Resource
[Link] ts;

@Schedule(second=0, minute=0, hour=0, dayOfMonth=1, month=*, year=*)


public
TimeHandler(Timer timer) {
MyTimerData mtd = (MyTimerData)[Link]();
[Link](new Date().toString() + " - " + [Link]);
}

@Schedule(expression="0 0 0 1 * * *")

Programmatic time out still supported

seconds, minutes as
hour as

dayOfMonth as

month as

dayOfWeek as

year as

0-59
0-23
1-31
1-12
0-7 or Sun,
yyyy

@Timeout
public void TimeHandler(Timer timer)

wildcard

28
3/4/14

Copyright 2013, Gash

Deployment

29
3/4/14

Copyright 2013, Gash

Configuration by exception
EE 5 (EJB 3.0) introduced many
changes we have seen session
declarations (annotations)
The second significant simplification is
in deployments
!deployment descriptors are optional

We will revisit this more when we talk about interceptors and lifecycles
30
3/4/14

Copyright 2013, Gash

Deploying to the application server


(beans and web applications)
We know the application server (AS) hosts EJBs, web services,
and web applications.
! These are declared through annotations and can be extended using
deployment descriptors

EAR (enterprise archive) META-INF/[Link]


!
!
!
!

Optional since J EE 5
Contains a complete application (beans + web)
Resources META-INF/[Link]
EJBs META-INF/[Link], META-INF/[Link]
" Annotations have simplified what is placed in the [Link] file

! Web META-INF/[Link]
" Servlet 3.0 fragments

31
3/4/14

Copyright 2013, Gash

EAR (zip files)


Besides deploying a simple EJB-jar for just EJBs,
EARs are used to configure EJB & web deployments
EAR
! EJB-JAR
" META-INF
[Link]

EAR (v3.1)
WAR
WEB-INF

" EJBs

[Link]
[Link]
classes
EJBs

! WAR
" WEB-INF
[Link]

JSP files

" JSP files

32
3/4/14

Copyright 2013, Gash

Deploying session beans

Java EE 5 and 6 (EJB 3.0 and 3.1) deployment has been greatly
simplified through the use of annotations
! Deployment configuration files (Deployment Descriptors) are optional for
session beans

Deployment Descriptors
! XML file defining what is being deployed
" Jars
" Declarative transaction statements for methods
" Security

! Examples where DD are applied


" Enterprise Archive (EAR)
" Web Application Archive (WAR)
" EJBs [Link] (JAR)

Deploying a EJB package consisting of session beans


! Create an archive (.jar) of the EJB classes
! Copy to the application servers deployment directory (JBoss)
33

3/4/14

Copyright 2013, Gash

EJB descriptor ([Link])


The EJB deployment descriptor overrides values declared in
code (annotation)
Overriding allows for deployment customization (e.g., testing,
beta, vendor changes)
What you can control (basically everything you can do with
annotations)
!
!
!
!
!

resources used
security and transaction levels
interceptors and lifecycle methods
persistence
queues

For instance
! @stateless maps to <session-type>stateless</session-type>
34
3/4/14

Copyright 2013, Gash

Tutorial: Configuring JBoss Application Server (AS)

35
3/4/14

Copyright 2013, Gash

Stepping through configuration


and deployment
JBoss community edition (v6.x)
! [Link]

JBosss initial EJB3.1


support started with
AS version 6.0.0 M2
(current release is 6.1.0 Final)

36
3/4/14

Copyright 2013, Gash

JBoss Setup
Install JBoss AS (6.x, 7.0, 7.1)
! Choose an easy to get to location
" E.g., /opt, /usr/local

! Create symbolic link to protect you from version changes


ln s /opt/jboss-as-7.1.0.CR1b jboss

! Create an environment variable $JBOSS_HOME pointing to


your symbolic link (/opt/jboss)
" e.g., /etc/profile.d/[Link], ~/.bashrc

37
3/4/14

Copyright 2013, Gash

Building an EJB3.1 project is a


simple recipe of steps
Ingredients
! One large IDE
" A simple Java project from Eclipse or NetBeans will do

! One application server


! Dash of Ant build and deploy
! A pinch of an idea

Instructions
!
!
!
!

Pre-heat JBoss ($JBOSS/bin/[Link])


Combine java class with annotations (behavior, resource, etc)
Fold in Ant
Deploy to your app server
" cp [Link] $JBOSS/standalone/deployments

Is that it?
38
3/4/14

Copyright 2013, Gash

Building and deploying through ant


(Can you isolate dependencies? Avoid the IDE)
Build outside of the IDE enables separation of
the IDE dependencies from the projects
! Better control over
technologies
! Scriptable (cron)
builds
! Can encourage
reactive code as it
helps identify
configuration
problems hidden by
IDEs and increases
deployment
awareness
39
3/4/14

Copyright 2013, Gash

JBoss 7.x deployment


Changes to 7.x require a few changes
to our 6.x deployment
!AS can be configured in standalone mode
or domain (cluster)
!Client (non-AS, i.e. not Web or WS)
requires

Console
![Link]
!Create user first: bin/[Link]
40
3/4/14

Copyright 2013, Gash

JBoss 7.x remote client


Multiple jars (in theory allows for better control, in practice
its a pita)
7.1 will simplify with a single jar
See stateless [Link] for examples
Below jars are as of 7.1 (differs from 7.1.1 in our example
projects)
jboss-transaction-api_1.1_spec-[Link]
AS7_HOME/modules/javax/transaction/api/main/
jboss-ejb-api_3.1_spec-[Link]
AS7_HOME/modules/javax/ejb/api/main/

[Link]
AS7_HOME/modules/org/jboss/ejb-client/main/
[Link]

AS7_HOME/modules/org/jboss/marshalling/main/
[Link]

AS7_HOME/modules/org/jboss/xnio/main/

[Link]

AS7_HOME/modules/org/jboss/remoting3/main/

[Link]

AS7_HOME/modules/org/jboss/logging/main/

[Link]

AS7_HOME/modules/org/jboss/xnio/nio/main/

[Link]

AS7_HOME/modules/org/jboss/sasl/main/

[Link]
AS7_HOME/modules/org/jboss/marshalling/river/main/

41
3/4/14

Copyright 2013, Gash

References
Tutorials and References
! [Link]
[Link]
! [Link]
! [Link]
[Link]

JBoss 7
!
!

[Link]
[Link]
+JNDI

Source code
! Apache OpenEJB (supports EJB 3.0) - [Link]
" Start exploring from container/openejb-core/src/main/java/org/apache/openejb/core

42
3/4/14

Copyright 2013, Gash

Reading

Books
!
!
!
!
!

Beginning EJB 3 Application Development, Kodali, et. al (2006)


EJB3 In Action, panda, Rahman, Lane (2007)
Enterprise JavaBeans 3.1, Rubinger, Burke, Haefel (Sep 2010)
Pro EJB 3: Java Persistence API, Keith, Schincariol (2006) old but good
Pro JPA 2, Keith, Schincariol, 2009

Pattern Books
! Java Enterprise Design Patterns, Grand (2002)
! Core J2EE Patterns 2nd Ed., Alur, Crupi, Malks (2003)
! EJB Design Patterns, Marinescu (2002)

43
3/4/14

Copyright 2013, Gash

Backup slides:
1. Example of the effects of fine grain processing
2. Use of proxies to decouple implementation
3. JBoss 6.x notes

44
3/4/14

Copyright 2013, Gash

Examining latency in JMS


OpenJMS latency (1000 messages)

Flooding the JMS queue

2500.0

2000.0

1500.0

No Wait
.5 Wait
.25 Wait

1000.0

500.0

0.0
1

112

223

334

445

556

667

778

889

1000

Solution was to control how fast


messages were placed on the queue
(graphed in yellow and red)
45
Copyright 2011, Gash

Milliseconds

I/O Latency: Network saturation of


when copying files

Files transferred
46
Copyright 2011, Gash

As we try to make sense of the world (classify, define


(map), order and structure layers), the world resists
Classically, we try to understand the world (systems) as a
model of layers (MVC). Certainly, much has been written
about tiers (2, 3, 4, N). Most of it is _____

Presentation
Business
Persistence
Database
47
3/4/14

Copyright 2013, Gash

The common Interface pattern


(simple let fundamental to most patterns)
Interfaces hide concrete providers
! Defines contractual/expected behavior through
methods
! Hides technology used to provide the behavior
! Examples
" Persisting data (Stream, ActiveRecord, JDBC, JPA)
" Logging (SLF4J)

class [classname] implements [interface] {


String addJob(Job job);
void removeJob(String id);
Job findJob(String id);
}
48
3/4/14

Copyright 2013, Gash

Interface (cont)
Beyond simple decoupling, interfaces
are the fundamental concept behind
scalable and strategic patterns
!Why? What is it about this simple pattern
that is so neat?

49
3/4/14

Copyright 2013, Gash

The importance of Interfaces


Interfaces (proxies and facades)
! Define expectations (sometimes referred to as a
contract) between the integrator and provider
! For instance:
" Feature/Service contracts
Typically describes a real-world feature (e.g., person, store)

" Communication contracts


Data transfer (e.g., sockets, message services)

" Common traits


Attributes - data structures
Behavior (methods) - pre and post conditions (input/output)

50
Copyright 2011, Gash

Proactor design pattern for highly


scalable systems
Proactor is an asynchronous processing model that
provides non-blocking behavior to both the
inbound request and the outgoing response
! The dual decoupling allows the server to control resources
and servicing of accept-process-respond independently

Request

Accept
(async)

Process
(async)

Dispatch

Respond
(handler(reply))

op + handler
reply

51
3/4/14

Copyright 2013, Gash

Lets work through an example to improve a POJO OO


design: A server (object) implementation
(pseudo code to illustrate core concepts)

public MyService{
private Authentication authImpl = new BlankAuthentication();
private Transaction txImpl = new BlankTransaction();
private Persistence persistImpl = new BlankPersistence();

private attributes isolate


implementation

// setters and getters not shown


public void startSesion(User user, Credentials cred) {
[Link](user, cred);
}

manage internal use of


resources (start & end)

public void endSession() {}


private validate() {}

public doTask(String arg) {


validate();
[Link]();
try {
Object work = [Link]();
doSomething(work);
[Link](work);
} catch (Exception ex) {
[Link]();
}
[Link]();
}

Invoke semaphores for


ACID behavior & use
resources

Commit and handle


exceptions
52

Copyright 2011, Gash

POJOs sequence of events (simple)


MyService

Client
startSession(u,c)

Authentication
Transaction

doTask()

begin()
validate()

Persistence

find/save()
end()

endSession(u)

Directly owned by the service


53
Copyright 2011, Gash

Reduce repetitive motion: A


better framework
Goal: simplify server development
! Reduce repetitive code of the server implementation
" Hide explicit start and end session calls
" Hide authentication and transaction
public ServiceBase implements Service {
private String serviceClassname;

Service
(Interface)

// initialization, setter/getter methods not shown


private Service getInstance() {}

public doTask(String arg) {


validate();
[Link]();
try {
// delegate work to the implementation
// class (MyService)
Service svc = getInstance();
[Link]();
} catch (Exception ex) {
[Link]();
}
[Link]();
}

Base

Impl

54
Copyright 2011, Gash

Benefits of further refactoring


The redesigned implementation hides the implementation/
technologies for persisting data we are left with only the
code to perform the work
! Delegating transaction and authentication responsibility to the
framework
" Centralizes management and technologies
" Consistent application of TX and authentication allows for further simplification
and declarative configuration

! Simplifies by eliminating service specific functionality


public MyService implements Service {

public doTask(String arg) {


Object work = [Link]();
doSomething(work);
[Link](work);
}

55
Copyright 2011, Gash

Resulting design: Isolating/Decoupling functionality


from communication (infrastructure) - Delegation
Infrastructure

ServiceBase

Client
startSession(u,c)

Authentication
Transaction

doTask()

begin()

Core functionality
isolated from service /
communication
infrastructure

Functionality
MyService

validate()

Persistence

delegates doTask()
end()

endSession(u)

Isolates the functionality

56
Copyright 2011, Gash

Solution: decouple along communication paths and


resources Container, Faade, and proxy patterns in
distributed architectures
Newer frameworks (JEE, Spring) rely these patterns to isolate
behavior and tools/features
! E.g., the container pattern is used to hide redundant operations

! Transactions, Security, Lifecycle, Logging/Auditing

Applicable to both client-side and server-side uses

Discovery
Remote object

Isolate technology

Local object

Client

Service
Framework
(w/ predefined
interfaces to a set of
custom services)

Authentication
Transaction
Persistence
57

Copyright 2011, Gash

JBoss 6.x Overview

58
3/4/14

Copyright 2013, Gash

Jboss (6x) directory organization


cd /usr/local/jboss (where you installed it)
$JBOSS_HOME/bin
! [Link]
! [Link] (Ctrl-C works)

$JBOSS_HOME/server
! Runtime configurations
" Defines what services are started (e.g., JMS)
" You should use default

! $JBOSS_HOME/server/default/deploy
" Where you copy your applications (jars) to you deploy

! $JBOSS_HOME/server/default/deploy/message
59
3/4/14

Copyright 2013, Gash

JBoss 6.x remote client


Single jar [Link]
7.1 will offer a similar jar
! For now (7.0,7.1) you will have to include the dozen or so
jars

Using [Link] in your client (via ant):


<target name="demo6" depends="init">
<copy file="${basedir}/resources/[Link]"
toDir="${[Link]}" />
<java classname="[Link]">
<classpath>
<pathelement location="${[Link]}/client/[Link]" />
<pathelement location="${[Link]}" />
</classpath>
</java>
</target>
60
3/4/14

Copyright 2013, Gash

Old Slides

61
3/4/14

Copyright 2013, Gash

Consider: Business Delegate


Minimize coupling
Hide location (local vs. remote)
! Communication optimization
" minimize resource utilization (sockets, memory)

! Exception handling
" Connection retries, failover (location transparency)
" Translate communication exceptions to domain
exceptions

! Lifecycle (resource management)

62
3/4/14

Copyright 2013, Gash

Consider: Session Locator


(Factory)
Locate services and objects
Centralize and optimize lookup
mechanisms
Encapsulate provider differences
(registry JNDI, File, )

See also Dependency Injection (DI)


63
3/4/14

Copyright 2013, Gash

Brief timeline of the EJB


specification

EJB v1
!

1998-1999
"
"
"
"

EJB v2
!

BEA WebLogic (bought by Oracle, 2008)


IBM WebSphere
Sun/Oracle Glassfish (Free)
Apache OpenEJB
JBoss Application Server (Free/Com)
Oracle Application Server
Caucho (Free - limited use)

CORBA compatible protocols (IIOP)


Object lifecycle management
Timer and Message-driven beans

EJB v3
!
!

2006 -
Simplify development
"

Annotations (JDK 1.5)

Java Persistence API (JPA)


"

Examples

2001 - 2003-ish
"
"
"

XML Deployment descriptors


RMI over IIOP
Entity, Stateless, and Stateful beans
Role-based security

Replaces Entity Bean concept of earlier EJBs

EJB v3.1
!
!
!
!
!

2008 (really 2010)


Simplifies v3 removes the need for interfaces
Singletons
Web service support for stateful session beans
Timer services declarations (cron-like)

64
3/4/14

Copyright 2013, Gash

Evolution of the EJB


Early beliefs (2.x): Desire for flexibility (explicit declaration)
results in code complexity and poor maintenance
Reworked (3.0): JDK 1.5 annotations allow for simplification.
EJB 3.0 revises interfaces declarations using annotations
! Must declare either local or remote interfaces in the bean class (if using both)

Relaxed (3.1): No longer need to declare local and remote


interfaces
EJB 2.x (3 classes)

EJB 3.0 (2 classes)

public interface EchoPoint


extends EJBObject

@Remote([Link])
@Stateless
public class EchoPointEJB {

public interface EJBPointHome


extends EJBHome
public class EchoPointEJB
implements SessionBean

. . .

65
3/4/14

Copyright 2013, Gash

Factors: Availability
Defining availability
! Two perspectives host and application
" Uptime of a machine/software
" Accessible for use

! Nines
" How to describe the level of availability
" Percent the system is available (accumulative)
Down Mon, Tue, Wed, Thu is bad
7.2 hours of planned maintenance and upgrades per month is okay

Availability (%)

Down/Year

Down/Month

90%

36.5 days

72 hrs

99%

3.65 days

7.2 hrs

99.9%

8.76 hrs

43.2 min

99.99%

52.6 min

4.32 min

99.999%

5.26 min

25.9 sec

66
3/4/14

Copyright 2013, Gash

Distributed systems provide


replication to solve availability

Perspective of the software


! Many units of a service are deployed
! At unit can answer a request
! units can call other units

There are many architecture solutions, some of them are


! Messaging - routing strategies allow for the lookup, and routing of requests

- who watches the routing service?
! Duplicate servers - deploying to multiple application servers
! Clustering servers - synchronizing session data between servers

Complexity
! Cost to build, cost to support
! Synchronization of data requires bandwidth and cycles
! Where to apply replication?
" Web, middle, data?
" Database?
" Network, power
" Centers (installations)

67
3/4/14

Copyright 2013, Gash

Why is designing for scalability


is so hard?

Causes
! Expansion exceeds original purpose (design)
" Mission changes, increased load

! Expansion that is cost prohibitive


" Upgrade costs (e.g., hardware)

Issues
!
!
!
!
!

Unable to support complexity or costs


Aging software and/or hardware
Increased support effort (out paces growth)
Decreased efficiency
Behavior is hard to predict or completely model (anticipate) all possible
problems before they happen

Scalability should
! Not change consistency (reliability)
! External latency does not decrease
! Code base does not change
68

3/4/14

Copyright 2013, Gash

Scalability (and availability)


design examples
Examining hardware solutions, we can create scalable software designs.

Cluster, Blade, Shard


Cluster - N/2 (like) systems offer a platform for
scaling and availability

Pattern for two should allow for many more - up to a point where issues of
replication and caching become a factor to the design

Software updates are easier - redirect all to one, bring down other to
update, switch procedure and then reset (assumes all hosts are identical)

Shared data with symmetric services is easy to implement.

However, the use of local caching will prevent failover consistency this may not be a problem if the system and consumers agree to
occasional break in continuity of service
69

3/4/14

Copyright 2013, Gash

Design (cont.)
Blade - linear scalability with nearly unlimited
expansion

Symmetric architecture that is not interconnected like a cluster

Semi-self contained mini systems - cluster may distribute subsystems in


disproportionate deployment to reduce hot spots

Data replication or centeralized access is an issue - todays HA storage


systems remove much of this problem.

Load balancer is required to distribute load - use of sticky sessions,


content, QoS, customer-based, etc

70
3/4/14

Copyright 2013, Gash

Designs (cont.)
Shard - a bladed architecture with no collective
memory - truly independent.

Finding data is important if shards do not share databases

Hops to find the data may be a performance issue

Separation of data is a referential integrity (RI) defeating design breaks optimization and reduction of duplication of normal form
database design

Minimizes hot spots - file system, database, or key subsystems


Why?

71
3/4/14

Copyright 2013, Gash

Comparing concepts of the cluster, blade,


and shard design approaches
Logical v. physical how to view your
design and distinguish from the hardware
topology
What does it mean to be
! Pure
" Conceptual

! Project
" Measurable
" ROI
" Realistic time, money, resources
72
3/4/14

Copyright 2013, Gash

Common questions

Powered by AI

Stateless session beans are advantageous in scenarios where the application requires handling of requests independently without the need for client-specific state retention between calls. They are ideal for high-throughput situations where the logic is the same for any client or operation, such as simple operations that do not require data persistence between calls (e.g., authentication checks, calculation services). Stateless beans allow for greater scalability and resource efficiency since they can be pooled and reused across different client invocations, unlike stateful beans which consume more memory due to the one-to-one mapping with clients . This makes stateless beans more suitable for applications requiring high concurrency and low-latency response times where session-specific data is not needed .

Dependency Injection (DI) within EJBs supports application development by simplifying the management of dependencies and resources within applications. DI allows developers to define dependencies directly in annotations or XML configuration files, enabling the container to inject required resources automatically at runtime. This reduces the need to write boilerplate code for resource lookup and instantiation, promoting clean and modular code structure. DI enhances testability and maintainability of the application by decoupling the configuration and bean logic, facilitating the injection of mock services or resources during testing without changing the actual code . It streamlines the development process by allowing developers to focus on implementing business logic rather than worrying about the initiation and management of dependencies .

The transition from EJB 2.x to EJB 3.0 improves the developer experience by replacing complex method-based lifecycle management with simplified annotations. In EJB 2.x, developers needed to implement methods like ejbCreate() and ejbRemove(), leading to more boilerplate code and increased complexity. EJB 3.0 introduces annotations such as @PostConstruct and @PreDestroy, which streamline lifecycle management and reduce the need for specific method implementations, allowing developers to focus more on business logic rather than boilerplate code . This simplification reduces errors and increases productivity by providing a more intuitive way to define how beans should be managed by the container .

Key restrictions imposed on EJBs include prohibitions on using static fields for read and write operations (except final fields), managing threads or thread synchronization primitives, accessing native libraries or modifying classloaders, and performing direct I/O operations. These restrictions are necessary to ensure that EJBs do not interfere with the container's control over resources and lifecycle management . The container must maintain the integrity and security of the resources it manages while ensuring that multiple instances of beans do not lead to concurrency issues or security breaches. These restrictions enable the container to provide robust lifecycle management, such as pooling beans and managing transactions, without interference from the bean's internal logic .

Stateful session beans manage client-specific state by retaining conversational data across multiple method calls for the same client. This means a stateful bean instance is tied to a single client session, retaining data such as user input or session-specific objects, which must be serializable. This client-specific instance management results in a potential memory burden on the server since a new instance must be created and maintained for each client, reducing scalability compared to stateless beans which are pooled and shared . The container can mitigate these resource demands through strategies like passivation, which allows idle stateful instances to be written to persistent storage and reactivated when needed, balancing the trade-off between retaining state and conserving server resources .

Resources are managed by the EJB container to prevent resource leaks and ensure efficient utilization within an application server. If a bean manages its own resources, there is a risk that resources such as file descriptors and database connections may not be released properly, which could deplete the server's resources and lead to performance degradation or failure . The container provides a controlled environment, managing the lifecycle of beans and intercepting method calls to apply transaction policies, thereby reducing error-prone code and improving developer productivity .

The EJB timer service in EJB 3.1 enhances scheduling capabilities by introducing the support for declarative scheduling in addition to programmatic scheduling available in previous versions. In EJB 3.1, developers can use annotations like @Schedule to define scheduled callbacks directly within the bean code, eliminating the need for complex external scheduling configurations. This improvement allows developers to easily manage recurring tasks, such as maintenance routines or periodic data processing, within the EJB framework . The timer service provides a standardized, container-managed solution for task scheduling that integrates seamlessly with the transactional capabilities of EJBs, enabling reliable and fault-tolerant execution of scheduled methods, which can rollback in case of transactional failures .

Singleton session beans in EJB 3.1, which implement the GoF Singleton pattern, are utilized for managing shared global state or configuration across multiple clients. They are beneficial for tasks like caching or shared resource management without the overhead of creating multiple instances. Singleton session beans support declarative transactions, lifecycle management, and concurrency control, making them suitable for centralized logic implementations . However, their potential drawbacks include the risk of becoming a bottleneck due to their shared nature if not properly synchronized for concurrent access, leading to contention issues. Additionally, singleton patterns can be considered an anti-pattern in some cases because they introduce global state which can complicate unit testing and reduce the flexibility of the application architecture .

The EJB container plays a critical role in managing the lifecycle and transaction of EJBs. It automates various tasks, such as the creation, pooling, and destruction of bean instances, ensuring that resources are efficiently managed and available for client requests when needed. The container also intercepts method calls to enforce transaction policies, which simplifies transaction management for developers by isolating it from the business logic. This allows developers to focus solely on business logic, as the container ensures that transactions are started, committed, or rolled back as appropriate based on the application's configuration or annotations such as @TransactionAttribute . By centralizing these management responsibilities, the container provides a robust and consistent environment for executing distributed transactions while minimizing transactional complexity for developers .

Annotations in EJB 3.0 and 3.1 enhance the deployment process and developer productivity by reducing the dependency on cumbersome XML deployment descriptors. Early versions like EJB 2.x required developers to define bean configurations in verbose XML files, complicating the deployment process and increasing the likelihood of configuration errors. Annotations simplify this process by allowing programmers to define lifecycle, transaction, and resource references directly in the source code, thus providing greater immediacy in development and reducing configuration overhead . This shift also aligns with modern development practices by improving code readability and maintainability, making it easier for developers to make changes and understand bean configurations quickly without navigating through complex XML files .

You might also like