Вы находитесь на странице: 1из 72

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 (java.io)
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

Bean.method
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 bean.method(); }
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: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/images/ejbcon-statefulSessionBeanLifeCycle.gif

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) {


System.out.println("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

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/images/ejbcon-statefulSessionBeanLifeCycle.gif

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) {
this.acct = acct;
}
public void addAddress(AccountAddress addr) {
this.addr = 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(AccountCreator.class)
@Stateless
public class AccountCreatorEJB implements AccountCreator {
private Account acct;
private Address addr;
public void addAccount(Account acct) {
this.acct = acct;
}
public void addAddress(AccountAddress addr) {
this.addr = 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)
" http://www.fluxcorp.com/
! Quartz (OSS)
" http://www.opensymphony.com/quartz/

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
javax.ejb.TimerService ts;
public void startTimer() {
MyTimerData mtd = new MyTimerData();
mtd.msg = "Pick me!";

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


ts.createTimer(sInterval, 2000, mtd);

public void stopTimer() {


Collection<Timer> list = ts.getTimers();
for (Timer t : list) {
if (t.getInfo() != null && t.getInfo() instanceof MyTimerData)
t.cancel();
}
}
@Timeout
public void TimeHandler(Timer timer) {
MyTimerData mtd = (MyTimerData)timer.getInfo();
System.out.println(new Date().toString() + " - " + mtd.msg);
}

27
3/4/14

Copyright 2013, Gash

Timer example (EJB v3.1)


@Stateless
public class TimerTestEJB implements TimerTestRemote {
@Resource
javax.ejb.TimerService ts;

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


public
TimeHandler(Timer timer) {
MyTimerData mtd = (MyTimerData)timer.getInfo();
System.out.println(new Date().toString() + " - " + mtd.msg);
}

@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/application.xml


!
!
!
!

Optional since J EE 5
Contains a complete application (beans + web)
Resources META-INF/ra.xml
EJBs META-INF/ejb-jar.xml, META-INF/persistence.xml
" Annotations have simplified what is placed in the ejb-jar.xml file

! Web META-INF/web.xml
" 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
ejb-jar.xml

EAR (v3.1)
WAR
WEB-INF

" EJBs

web.xml
ejb-jar.xml
classes
EJBs

! WAR
" WEB-INF
web.xml

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 ejb-jar.xml (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 (ejb-jar.xml)


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)
! http://www.jboss.org/jbossas/downloads

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/jboss.sh, ~/.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/standalone.sh)


Combine java class with annotations (behavior, resource, etc)
Fold in Ant
Deploy to your app server
" cp myapp.jar $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
!http://localhost:9990
!Create user first: bin/add-user.sh
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 build.xml for examples
Below jars are as of 7.1 (differs from 7.1.1 in our example
projects)
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
AS7_HOME/modules/javax/transaction/api/main/
jboss-ejb-api_3.1_spec-1.0.1.Final.jar
AS7_HOME/modules/javax/ejb/api/main/

jboss-ejb-client-1.0.0.Beta10.jar
AS7_HOME/modules/org/jboss/ejb-client/main/
jboss-marshalling-1.3.0.GA.jar

AS7_HOME/modules/org/jboss/marshalling/main/
xnio-api-3.0.0.CR5.jar

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

jboss-remoting-3.2.0.CR6.jar

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

jboss-logging-3.1.0.Beta3.jar

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

xnio-nio-3.0.0.CR5.jar

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

jboss-sasl-1.0.0.Beta9.jar

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

jboss-marshalling-river-1.3.0.GA.jar
AS7_HOME/modules/org/jboss/marshalling/river/main/

41
3/4/14

Copyright 2013, Gash

References
Tutorials and References
! http://download.oracle.com/javaee/6/tutorial/doc/
javaeetutorial6.pdf
! http://www.perfdynamics.com/Test/gcaprules.html
! http://www.oracle.com/technetwork/java/javaee/documentation
http://community.jboss.org/wiki/EJB31inAS600M2

JBoss 7
!
!

http://www.mastertheboss.com/jboss-application-server.html
https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using
+JNDI

Source code
! Apache OpenEJB (supports EJB 3.0) - http://openejb.apache.org/
" 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) {
authImpl.authenticate(user, cred);
}

manage internal use of


resources (start & end)

public void endSession() {}


private validate() {}

public doTask(String arg) {


validate();
txImpl.begin();
try {
Object work = persistImpl.find();
doSomething(work);
persistImpl.save(work);
} catch (Exception ex) {
txImpl.rollback();
}
txImpl.end();
}

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();
txImpl.begin();
try {
// delegate work to the implementation
// class (MyService)
Service svc = getInstance();
svc.doTask();
} catch (Exception ex) {
txImpl.rollback();
}
txImpl.end();
}

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 = persistImpl.find();
doSomething(work);
persistImpl.save(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
! run.sh
! shutdown.sh (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 jboss-client.jar
7.1 will offer a similar jar
! For now (7.0,7.1) you will have to include the dozen or so
jars

Using jboss-client.jar in your client (via ant):


<target name="demo6" depends="init">
<copy file="${basedir}/resources/log4j.properties"
toDir="${classes.dir}" />
<java classname="gash.ejb.echoclient.Client">
<classpath>
<pathelement location="${jboss.home}/client/jbossall-client.jar" />
<pathelement location="${classes.dir}" />
</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(EchoPoint.class)
@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