Distributed Applications in Java and Introduction

Download Report

Transcript Distributed Applications in Java and Introduction

Distributed Applications in Java and
Introduction to Enterprise Java Beans
Michael Factor
[email protected]
IBM Labs in Haifa
IBM Labs in Haifa
Outline
 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
Introduction to Distributed Computing
IBM Labs in Haifa
IBM Labs in Haifa
Basic 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.
IBM Labs in Haifa
Basic 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
IBM Labs in Haifa
Client Server Interactions
Client
Server
2
y= F(x)
1
1.
2.
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
3
4
Network
F(x) {
return 5;
}
IBM Labs in Haifa
Finding 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?
IBM Labs in Haifa
Naming Services
Name Server
Client
Server
1
2
4
y= F(x)
F(x) {
return 5;
}
3
5
6
Network
1.
2.
3.
4.
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
IBM Labs in Haifa
Parameter 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
IBM Labs in Haifa
Marshaling/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
IBM Labs in Haifa
Parameter Passing Flow
Client
Server
y= F(x)
1.
2.
Marshal X
Send Msg
3.
4.
F(x) {
return 5;
}
Network
5.
6.
7.
8.
Receive Msg w/
Result
Unmarshal Result
Receive Msg
Unmarshal X
Marshal Result
Send Msg w/ Result
IBM Labs in Haifa
Stubs 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
IBM Labs in Haifa
Stubs and Skeletons: Flow
Client
Server
F(x) { // stub
1.
2.
Marshall X
Send Msg
F_skeleton() {
Network
3.
4.
5.
6.
7.
}
8.
9.
}
Receive Result Msg
Unmarshal Result
Receive Msg
Unmarshal X
Call F(X)
Marshal Result
Send Msg w/ Result
IBM Labs in Haifa
Where 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
IBM Labs in Haifa
Server 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
IBM Labs in Haifa
Server Architecture (continued)
Server
Clients
Dispatcher
Call f_skel
f
Call g_skel
network
g
g
f
Worker
Threads
Java Object Serialization
IBM Labs in Haifa
IBM Labs in Haifa
Goals 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
IBM Labs in Haifa
Serialization 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.
IBM Labs in Haifa
ObjectOutputStream
 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
 write<Type>(<Type> t) methods support writing primitives to stream
IBM Labs in Haifa
Traversing The Graph
writeObject(A) ==> succeeds
A
writeObject(B) ==> throws
java.io.NotSerializableException:
java.lang.Thread
B
java.util.Hashtable
java.lang.String
java.lang.Integer
java.util.Hashtable
java.lang.String
java.lang.Thread
not serializable
IBM Labs in Haifa
Serialization 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);
IBM Labs in Haifa
ObjectInputStreams
 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 ==.
Java Remote Method Invocation (RMI)
IBM Labs in Haifa
IBM Labs in Haifa
What 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., interJVM call
IBM Labs in Haifa
RMI 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
IBM Labs in Haifa
Remote 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
IBM Labs in Haifa
Sample Remote Interface
public interface Count
extends java.rmi.Remote
{
public int getCount()
throws java.rmi.RemoteException;
}
Client
Remote
Interface
Server
call getCount
inc. count
display result
IBM Labs in Haifa
Remote 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
Client
Remote
Interface
Server
call getCount
inc. count
display result
Remote
Object
IBM Labs in Haifa
Sample 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++;
}
// . . .
IBM Labs in Haifa
RMI 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
IBM Labs in Haifa
Remote 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
IBM Labs in Haifa
Passing 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)
IBM Labs in Haifa
RMI 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
IBM Labs in Haifa
Issues 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
IBM Labs in Haifa
RMI'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"
IBM Labs in Haifa
RMI'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.
Introduction to EJBs
IBM Labs in Haifa
IBM Labs in Haifa
Enterprise 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
IBM Labs in Haifa
Architecture
Client
Container
Method invocation
Client Interface
Method Delegation
TX support
Security
Persistence
...
Bean Instance
IBM Labs in Haifa
EJB 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
IBM Labs in Haifa
Local 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
IBM Labs in Haifa
Local 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
IBM Labs in Haifa
EJB 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 client’s 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 Bean’s component
interface
 Defined by the Bean Provider
 Client side implementations are generated when the Bean is deployed
Delegate invocations to Bean instance
IBM Labs in Haifa
Architecture with Remote Interfaces
Source: Enterprise JavaBeansTM Specification, Version 2.0, page 386
Types of EJBs
IBM Labs in Haifa
IBM Labs in Haifa
Types of Beans
 Session
 Client and application logic focus
 Entity
 Persistent data focus
 Message
 Asynchronous message processing
IBM Labs in Haifa
Session 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
IBM Labs in Haifa
How a Client Uses a Session Bean
JNDI Server
Container
Client
Home
Bean Instance
Component
IBM Labs in Haifa
Stateless 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
IBM Labs in Haifa
Stateful 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
IBM Labs in Haifa
Lifecycle of a Stateful Session Bean
Container Perspective
create
Does Not Exist
passivate
Ready
remove
activate
start
transaction
commit or
rollback
In Transaction
timeout
Passive
IBM Labs in Haifa
Entity 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
IBM Labs in Haifa
Persistence
 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
IBM Labs in Haifa
Persistence (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 Bean’s 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.
IBM Labs in Haifa
Container 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
IBM Labs in Haifa
EJB 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
IBM Labs in Haifa
Entity Beans and Database Tables
Order Bean Table
1 Customer
Key: Customer ID
*
Order Bean
1
Key: Order ID
Customer ID
Product ID
1 Product
Key: Product ID
1 Invoice
Order ID
1
3
Customer ID Product ID
76
9
2
1212
Invoice Table
Invoice ID
1001
1003
Order ID
1
3
...
Key: Invoice ID
Order ID
Customer Table
Customer ID Orders
76
1
1002
2
Address . . .
...
IBM Labs in Haifa
Message 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
Client
Destination
Msg Bean
Msg Bean
Instance
Msg Bean
Instance
Instance
Enterprise Attributes
IBM Labs in Haifa
IBM Labs in Haifa
Transactions
 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
IBM Labs in Haifa
Transaction 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 client’s 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
IBM Labs in Haifa
Transaction Attributes (Continued)
 Supports
Uses client’s 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
IBM Labs in Haifa
Security
 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
Putting it All Together
IBM Labs in Haifa
IBM Labs in Haifa
Deployment 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.
IBM Labs in Haifa
ejb-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
IBM Labs in Haifa
Making 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 Bean’s 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...)
IBM Labs in Haifa
Items not covered
 APIs
 Interoperability between servers
 Relationship to CORBA
IBM Labs in Haifa
Specifications
 RMI:
 http://java.sun.com/j2se/1.4.1/docs/guide/rmi/index.html
 Serialization:
 http://java.sun.com/j2se/1.4.1/docs/guide/serialization/index.html
 EJB
 ftp://ftp.java.sun.com/pub/ejb/947q9tbb/ejb-2_0-fr2-spec.pdf
Backup
IBM Labs in Haifa
IBM Labs in Haifa
RemoteObject Hierarchy
RemoteObject
provides basic remote object semantics
redefines equals, hashCode and toString
Client
extends
RemoteStub
remote object
semantics of stubs
Server
extends
RemoteServer
abstract server
extends
run-time
UnicastRemoteObject
access to concrete RMI server
run-time for singleton, nonpersistent, remote objects
this is the class remote objects
typically extend
All classes in package java.rmi.server
IBM Labs in Haifa
A Remote Object Implementation
Implements 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
IBM Labs in Haifa
Remote Objects as Parameters: An Example
Remote
Interface B
Remote
Interface A
int g()
int f(Remote b)
System B
AInterface a;
a.f(new B());
System A
Client
Stub A
Marshal B as a Stub
Remote
Object A
f(Remote b) {
b.g()
}
Remote
Object B
Client
Stub B
IBM Labs in Haifa
RMI Stubs and Skeletons Example
Portion 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.RemoteException {
// 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;
}
IBM Labs in Haifa
Characteristics of EJBs
 Contain business logic that operates on enterprise’s 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
IBM Labs in Haifa
EJB Goals
 For Bean Provider, Application Assembler and Deployer
 Simplicity
 Productivity
 Reuse
 Merchant market for components
 Enterprise qualities
Distribution
Integrity
Security
Transactions
. . .