Title: Distributed Applications in Java and Introduction to Enterprise Java Beans
1Distributed Applications in Java andIntroduction
to Enterprise Java Beans
- Michael Factor
- factor_at_il.ibm.com
2Outline
- Distributed Applications in Java
- Introduction to Distributed Computing
- Java Object Serialization
- Java Remote Method Invocation (RMI)
- Introduction to Enterprise Java Beans (EJB)
- Architecture
- Types of EJBs
- Enterprise Attributes
- Putting it all Together
3Introduction to Distributed Computing
4Basic Concepts
- Client-Server
- The client is the entity accessing the remote
resource and the server provides access to the
resource. Operationally, the client is the
caller and the server is the callee. - In Java terms
- The client is the invoker of the method and the
server is the object implementing the method.
5Basic Concepts (continued)
- The client and the server can be heterogeneous
- Different implementation languages
- Different operating systems
- The roles can be transient
- The definition is with respect to a particular
interaction. - Client and Server refer both to the code and the
system on which the code is running
6Client Server Interactions
Client
Server
F(x) return 5
2
y F(x)
1
3
4
- Send message to call F with parameter X
- Receive message that F was called with the given
parameter - Send message with the result of calling F
- Receive message with the result of calling F
Network
7Finding the Server
- How does the client find a server?
- One approach is a Name Service
- Associate a name with each server
- When server starts, it registers with a naming
service using the name - When the client wants to find the server, it asks
the naming service - Naming service can itself be a server
- How does the client find the naming server?
8Naming Services
Name Server
Client
Server
1
2
F(x) return 5
4
y F(x)
3
5
6
- Register "F" with name server
- Lookup "F" using name server
- Send message to call F with parameter X
- Receive message that F was called with the give
parameter - Send message with the result of calling F
- Receive message with the result of calling F
Network
9Parameter Passing
- Distribution complicates parameters passing
- Parameters are passed via a message and not via a
local stack - Issues include
- Different representations of primitive types
- convert representation
- Pointers are address space relative
- Composite Types (e.g., structures)
- embedded pointers
- need to be flattened and reconstructed
10Marshaling/Unmarshaling
- Marshaling
- done by client (i.e., caller)
- packing the parameters into a message
- flatten structures (e.g., objects)
- perform representation conversions if necessary
- also done by server (i.e., callee) for results
- Unmarshaling
- done by receiver of message to extract parameters
11Parameter Passing Flow
Client
Server
y F(x)
- Marshal X
- Send Msg
- Receive Msg
- Unmarshal X
F(x) return 5
Network
- Marshal Result
- Send Msg w/ Result
- Receive Msg w/ Result
- Unmarshal Result
12Stubs and Skeletons
- Encapsulate marshaling and communication
- Enable application code in both client and server
to treat call as local - Stub is on the client
- implements original interface
- contains information to find the server
- in an OO language, the stub object is a proxy for
the real object - Skeleton is on the server
- calls original routine
13Stubs and Skeletons Flow
Client
Server
F(x) // stub
- Marshall X
- Send Msg
F_skeleton()
- Receive Msg
- Unmarshal X
- Call F(X)
- Marshal Result
- Send Msg w/ Result
Network
- Receive Result Msg
- Unmarshal Result
14Where do Stubs and Skeletons come from?
- Writing (un)marshaling code is bug-prone
- communication code has many details
- structure of code is very mechanical
- Answer
- Stubs and Skeletons can be generated from a
description of the code to be remotely invoked - A separate Interface Definition Language (IDL)
- Description can be generated from code to be
distributed
15Server Architecture
- Servers can typically handle concurrent requests
from multiple clients - Typically the same address spaces provides
multiple interfaces - A common server architecture
- accept a request (i.e., a call from a client)
- determine which routine is being invoked
- dispatch request to a thread of execution
- start the thread executing in the appropriate
skeleton
16Server Architecture (continued)
Server
Clients
Dispatcher
Worker Threads
Call f_skel
f
Call g_skel
network
f
g
g
17Java Object Serialization
18Goals of Serialization
- Provide a means of writing/reading the state of
an object to/from a stream - Preserve inter-object relationships
- Enable marshaling/unmarshaling
- Do not require per-class implementation
- Allow per-class customization
19Serialization Basic Concepts
- All primitive types can be saved in a stream
- The class of an object to be saved in a stream
must implement one of - java.io.Serializable
- java.io.Externalizable
- Externalizable allows a high degree of
customization - Not discussed further
- Not all standard Java classes are serializable
- Classes that provided access to system resources
are not serializable - most of java.io., java.net., etc.
20ObjectOutputStream
- java.io.ObjectOutputStream is used to save the
state of an object - writeObject(Object o) method on the stream which
writes the indicated object to the stream - traverses references to other objects
- referenced objects must also be serializable
- in event of a cycle an object is only written to
stream once - default does not write static or transient data
- writeltTypegt(ltTypegt t) methods support writing
primitives to stream
21Traversing The Graph
writeObject(A) gt succeeds
A
java.util.Hashtable
java.lang.Integer
java.lang.String
22Serialization Example
import java.net. import java.io. // . . . //
Create the ObjectOutputStream Socket s new
Socket(host, port) ObjectOutputStream oos
new ObjectOutputStream(s.getOutputStream()) //
Call writeObject on the Stream to write a Date
object oos.writeObject(new java.util.Date()) //
Call writeInt to write an int oos.writeInt(3)
23ObjectInputStreams
- java.io.ObjectInputStream is used to restore the
state of an object - readObject() returns next object in the stream
- creates a new object graph
- structurally equivalent to the graph that was
originally written to the stream - objects in graph are distinct from original
graph, i.e., don't compare .
24Java Remote Method Invocation (RMI)
25What is RMI?
- Java Remote Method Invocation is a mechanism that
allows calls between objects in different JVMs - Basic concepts
- Remote Interface
- defines the methods that a client can invoke on a
server - Remote Object
- an object whose methods can be invoked from
another JVM - Remote Method Invocation
- invoking a method of a remote interface on a
remote object, i.e., inter-JVM call
26RMI Running Example
- To motivate this discussion, we will use a simple
running example of a count server. - server supports a single method, getCount(), that
returns the number of times it has been called - client calls the method and displays the results
Client
Server
call getCount
inc. count
display result
27Remote Interface
- Extends java.rmi.Remote
- java.rmi.Remote is an empty interface
- Flags methods that can be called remotely
- Client is coded to remote interface
- Invoking a remote method uses normal Java syntax
- All methods of a remote interface must throw
java.rmi.RemoteException - Thrown when a remote invocation fails, e.g., a
communications failure - Used in generating stubs and skeletons
28Sample Remote Interface
public interface Count extends java.rmi.Remote
public int getCount() throws
java.rmi.RemoteException
29Remote Object
- Implements a remote interface
- Can add additional methods
- Typically extends (a subclass of)
java.rmi.server.RemoteObject - Client uses a stub to refer to remote object
- Never access remote object directly
30Sample Implementation Class
public class CountImpl extends
java.rmi.server.UnicastRemoteObject implements
Count private int count public
CountImpl() throws java.rmi.RemoteException
super() count 0 public int
getCount() throws java.rmi.RemoteException
return count // . . .
31RMI Parameter Passing
- There are two types of parameters to consider
- Remote objects, i.e., implement java.rmi.Remote
- Non-remote objects
- This applies both to inputs and return results
32Remote Objects as Parameters
- The target receives a reference to the client
stub implementing the remote interface - Enables access to unnamed remote objects
- Client creates a remote object and passes it as a
parameter on a remote method - Server returns a remote object as the result of a
remote method - Enables peers and not just client-server
- Client invokes a remote method, passing a remote
object that it implements as a parameter - When server invokes a method on this parameter it
is using a client stub, this results in a
callback to original client
33Passing Non-Remote Objects as Parameters
- Objects are passed by value
- A copy of object is sent to the server
- Java Object Serialization used to copy
parameters - Non-remote-object parameters of a remote
interface must be Serializable - Use of Serialization gives different semantics
than normal Java parameter passing - given remote method
- Object identity(Object o) return o
- then
- o ! remote.identity(o)
34RMI Stubs and Skeletons
- Stubs and skeletons are mechanically generated,
e.g., by rmic (RMI Compiler) - input is a class file containing a remote object,
e.g., CountImpl.class - output is class files for stub and skeleton for
the remote object - CountImpl_Stub and CountImpl_Skel
- optionally can keep Java source files
- stub class extends RemoteStub
- stub thus has remote semantics for equals,
toString and hashCode
35Issues We Did Not Discuss
- Partitioning an application
- Where is the dividing line between client and
server - Security
- Class Loading, Firewalls, RMI over HTTP, etc.
- Remote Object Activation
- Socket Factories
- RMI Runtime Architecture
- Distributed Garbage Collection
- Class Loading
- RMIClassLoader
- JavaIDL
- Mapping of Java to CORBA IDL
36RMI's Strengths
- Relatively easy to develop a distributed
application - But harder than a non-distributed application
- No need to learn a separate language or object
model - But need to learn subtle differences
- A pure Java solution
- "Write Once, Run Anywhere"
37RMI's Weaknesses
- Loss of object identity
- If an object is passed by value, a new copy of
the object is created - Performance
- If one is not very careful, the use of
serialization can result in sending very large
messages - Potential for Deadlock if Callbacks are used
- System A makes a remote call to system B
- B makes a callback to A
- The thread that will process the callback in A is
not the thread that made the original call to B - If A was holding a lock when it made the initial
call, deadlock may result.
38Introduction to EJBs
39Enterprise Java Beans Components and Containers
- An Enterprise Java Bean (EJB) is a component the
provides reusable business logic functionality
and/or a representation of a persistent business
entity - An EJB Container executes an EJB due to a client
request. - Provides the plumbing necessary to execute the
EJB including - non-business logic related functionality such as
transactions, security, concurrency, remote
access, etc. - life cycle functions, e.g., creating, destroying,
etc. - Client uses an interface to access the Bean
indirectly - A deployment descriptor describes the structure
of the Bean and how to execute the Bean as part
of an application
40Architecture
Client
Container
Client Interface
TX support Security Persistence . . .
Bean Instance
41EJB Roles
- Bean Provider
- Produces a component of reusable business logic
in an ejb-jar file - Application Assembler
- Combines multiple beans into an application
described by a deployment descriptor - Deployer
- Customizes the application for a specific
server/container - E.g., map security roles defined in deployment
descriptor to real users - Server and Container Provider
- Provides the tools to allow deploying an
application and the runtime support to execute
the application according to the deployment
descriptor - System Administrator
42Local vs. Remote Interfaces
- Entity and Session Beans can support local and
remote interfaces - Client is written to a specific interface
- Interface(s) supported is not transparent to Bean
provider - Local interface
- Not location independent
- Client and EJB run in the same JVM
- Example A Bean always accessed by other Beans
- Parameter passing is by reference (same as
standard Java) - Supports fine grained access
- Remote interface
- Location independent
- Parameters passed by value (RMI semantics)
- Supports coarse grain access
43Local vs. Remote Interfaces (Continued)
- Reasons for Choosing Local vs. Remote Access
- Type of client
- If client is always a Web Component or another
EJB, choose local - Coupling
- If tightly coupled, choose local
- Scalability requirements
- If strong scalability requirements, choose remote
44EJB Interfaces
- Home Interface
- Can be viewed as a collection of Beans
- Lifecycle functions, e.g., create, remove, find
- Home business methods
- Business methods that are not instance specific
- Component Interface
- Business logic
- Define clients view of the Bean
- Client never directly access Bean instance
- Client finds home interface via JNDI
- Client uses home interface to obtain a reference
to the Beans component interface - Defined by the Bean Provider
- Client side implementations are generated when
the Bean is deployed - Delegate invocations to Bean instance
45Architecture with Remote Interfaces
Source Enterprise JavaBeansTM Specification,
Version 2.0, page 386
46Types of EJBs
47Types of Beans
- Session
- Client and application logic focus
- Entity
- Persistent data focus
- Message
- Asynchronous message processing
48Session Beans
- Executes on behalf of a single client
- Focus on functionality, application logic and
application state - May be transaction aware
- May access shared data in an underlying DB but
does not directly represent this shared data - Is relatively short-lived
- Is removed when the EJB Container crashes
- Typically have state maintained across multiple
requests from the same client - Stateless session beans are a special case
49How a Client Uses a Session Bean
JNDI Server
Container
Client
Home
Bean Instance
Component
50Stateless Session Beans
- Not tied to any particular client
- Can use instance variables only if they are not
client related - All Stateless Session Beans are equivalent
- A container can choose
- To serve the same instance of a Bean to multiple
clients - To serve difference Bean instances to the same
client at different times - A container may maintain a pool of Stateless
Session Beans - No necessary relation between when a client
creates the Bean and when the Container creates
the Bean - Provide very high scalability
51Stateful Session Beans
- Assigned to a particular client
- Maintain per client state across multiple client
requests - May be passivated allows a degree of pooling
- The container serializes the state of a Bean non
currently being used and writes state to
secondary storage - Frees JVM resources held for Bean
- When a new request arrives for Bean, it must be
activated - State read from secondary storage and
deserialized - Can only passivate a Bean if it is not in a
transaction - More on transactions later
52Lifecycle of a Stateful Session BeanContainer
Perspective
create
passivate
Passive
Ready
Does Not Exist
remove
activate
commit or rollback
start transaction
In Transaction
timeout
53Entity Beans
- Represent persistent data
- Typically represent a row from a database
- Can also represent entities implemented by legacy
applications - Can be shared across multiple users
- Long lived
- Lifetime is tied to life of data and not to a
particular client - Entity objects (not Beans) can be created outside
of a Container, e.g., from a pre-existing
database. - Data persistence can managed either by Bean or
Container - Client can either create a new Entity Bean of
find an existing Bean - Home interface provides finder methods
- findByPrimaryKey unique key within a home
- Application specific finder methods
54Persistence
- Two kinds
- Bean Managed
- Programmatic
- Container Managed
- Declarative
- Bean Managed
- Bean provider must write routines to access the
data store - Declares instance variables to contain the
persistent data - Finder method implementation written by Bean
provider - Container invokes these routines at an
appropriate times in lifecycle - More common when underlying store is an
application
55Persistence (Continued)
- Container Managed
- Allows Bean to be logically independent of data
source - e.g., same code for relational database, IMS
database, etc. - Container generates code to access the data store
- Deployer maps the fields of the Bean to the
columns of the database - Bean provider describes Beans fields and
relationships to other Beans in deployment
descriptor - Container may use lazy access methods and caching
- Finder methods are described in the deployment
descriptor - Description is in EJB QL
- Implementation is generated when Bean is deployed
- Virtual fields are used in the Bean to contain
the persistent data - Access is via getXXX/setXXX methods.
56Container Managed Relationships
- Relationship between Beans
- Similar to foreign keys in relational databases
- Types of relationships
- One to one
- Many to one
- One to Many
- Many to Many
- Allows container to ensure referential integrity
- e.g., setting a Bean in field for a one to one
relationship will atomically remove the Bean from
a prior relationship
57EJB QL
- A query language
- Similar to a subset of SQL
- Used in the deployment descriptor to describe the
behavior of finder (and other) methods for Beans
with Container Managed Persistence
58Entity Beans and Database Tables
Order Bean Table
1
Order ID Customer ID Product ID . . .
1 76 9
3 2 1212
1
1
Invoice Table
Invoice ID Order ID . . .
1001 1
1003 3
1
Customer Table
Customer ID Orders Address . . .
76 1
1002 2
59Message Beans
- Executes upon receipt of a client JMS message
- Asynchronous
- No return value
- Stateless and short lived
- May access persistent data but does not represent
persistent data - Not tied to a client
- A single Message Bean can process messages from
multiple clients - Has neither Home nor Component interface
Msg Bean Instance
Msg Bean Instance
Msg Bean Instance
Client
Destination
60Enterprise Attributes
61Transactions
- Ensure all-or-nothing semantics
- In EJB only addresses persistent data
- Application code required to rollback changes in
application variables - Either Bean or Container Managed Transaction
Demarcation - Bean Managed
- Explicit use of the Java Transaction API by the
Bean - Container Managed
- Completely declarative in deployment descriptor
- Container invokes business method in specified
scope - Entity Beans must use Container Managed
transactions - Session and Message Beans may use Bean Managed
- Clients can also establish transactional scope
62Transaction Attributes
- Associated with methods in deployment descriptor
- Specifies how container manages transaction when
client invokes a method - Types of attributes
- NotSupported
- Method never called within a transaction
- Container suspends client context if it exists
- Required
- Runs in clients context if it exists otherwise
Container create a new context - Used for a method that requires transaction, but
can participate in a broader unit of work - Example depositing money in an account
- Can be atomic by itself or part of a greater
transaction involving other operations
63Transaction Attributes (Continued)
- Supports
- Uses clients context if it exists otherwise runs
without a context - Needs to be used with caution
- RequiresNew
- Container always runs the method in a new
transaction - Useful for work that commits regardless of
results of outer unit of work - Mandatory
- Client must invoke the method from within a
transaction - Container uses this context
- Never
- Client must not invoke the method from within a
transaction - Container does not provide transaction context
64Security
- Transport
- Secure Socket Layer
- Transport Layer Security
- Application assembler and deployer specify
security in deployment descriptor - Security Roles
- Logical roles defined by application assembler
- Mapped to principles by deployer
- Method Permissions
- Set of methods that can be invoked by a security
role - Run-as
- Specifies identity (security role) a Bean uses
when it calls other EJBs
65Putting it All Together
66Deployment Descriptor
- Captures declarative information
- Well-formed XML
- Contains
- Structural information
- Name of Bean, class, interfaces, Bean type,
persistence type, container managed fields, . . .
- Not all combinations of structural information
make sense - Application assembly information
- Security roles, method permissions, transaction
attributes, etc.
67ejb-jar
- Standard format for packaging enterprise Beans
- Contains
- Deployment descriptor
- Class files
- Bean
- Interfaces
- . . .
- Does not contain subs generated by container
- ejb-client jar
- Jar file for client visible files
68Making This More Real 8 Steps
- Trivial stateless Session bean, that prints on
server console outputError(String s) - To implement a bean, you (or tools!!) need to
- Specify (not implement) the Remote interface
- Specify (not implement) the Home interface
- Specify (and implement!) the Beans
Implementation class - Compile the above
- Create a Deployment Descriptor, in this case a
Session Descriptor for a Session bean - Create a Manifest/EJB-jar file
- Run the deployment tool, which processes the
ejb-jar file and processes and stores the code,
etc - Start the server.
- Develop the client (no different than any other
client...)
69Items not covered
- APIs
- Interoperability between servers
- Relationship to CORBA
70Specifications
- RMI
- http//java.sun.com/j2se/1.4.1/docs/guide/rmi/inde
x.html - Serialization
- http//java.sun.com/j2se/1.4.1/docs/guide/serializ
ation/index.html - EJB
- ftp//ftp.java.sun.com/pub/ejb/947q9tbb/ejb-2_0-fr
2-spec.pdf
71Backup
72RemoteObject Hierarchy
RemoteObject
- provides basic remote object semantics
- redefines equals, hashCode and toString
Client
Server
extends
extends
RemoteStub
RemoteServer
remote object semantics of stubs
abstract server run-time
extends
UnicastRemoteObject
- access to concrete RMI server run-time for
singleton, non-persistent, remote objects - this is the class remote objects typically extend
All classes in package java.rmi.server
73A Remote Object ImplementationImplements remote
interface(s)
- Can add additional methods
- If does not extend UnicastRemoteObject
- must redefine equals, hashCode and toString
- must explicitly tell RMI run-time about object
- UnicastRemoteObject.exportObject(Object o)
- Client never uses implementation class
74Remote Objects as Parameters An Example
75RMI Stubs and Skeletons ExamplePortion of
machine generated CountImpl_Stub
public final class CountImpl_Stub extends
java.rmi.server.RemoteStub implements Count,
java.rmi.Remote // Removed lots of code
public int getCount() throws java.rmi.RemoteExcep
tion // Removed the code to make the
call int result try
java.io.ObjectInput in call.getInputStream()
result in.readInt() catch
(java.io.IOException ex) throw new
java.rmi.UnmarshalException("Error
unmarshaling return", ex) // Removed
Additional Error Handling Code return
result
76Characteristics of EJBs
- Contain business logic that operates on
enterprises data - Bean provider defines a client view
- Client view is independent of of the container in
which the bean is deployed - Beans are created and managed at runtime by a
Container which mediates client access - Client never directly accesses the Bean
- Since container involved in path between client
and Bean instance it can implement pragmatics and
lifecycle functions - If Bean uses only services defined by EJB Spec.,
it can be deployed in any compliant Container - Specialized containers with extended
functionality can be defined - Can be assembled into an application without
requiring source code
77EJB Goals
- For Bean Provider, Application Assembler and
Deployer - Simplicity
- Productivity
- Reuse
- Merchant market for components
- Enterprise qualities
- Distribution
- Integrity
- Security
- Transactions
- . . .