Distributed Applications in Java - PowerPoint PPT Presentation

1 / 94
About This Presentation
Title:

Distributed Applications in Java

Description:

Marshall X. Send Msg. Network. Client. Server. Receive Result Msg. Unmarshal Result. F ... Marshalls the return objects. Sends the response back to the client ... – PowerPoint PPT presentation

Number of Views:119
Avg rating:3.0/5.0
Slides: 95
Provided by: bitterroot
Category:

less

Transcript and Presenter's Notes

Title: Distributed Applications in Java


1
Distributed Applications in Java
  • CS 420 Spring 2006

2
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

3
Introduction to Distributed Computing
4
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.

5
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

6
Client 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
7
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?

8
Naming 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
9
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

10
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

11
Parameter 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

12
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

13
Stubs 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


14
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

15
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

16
Server Architecture (continued)
Server
Clients
Dispatcher
Worker Threads
Call f_skel
f
Call g_skel
network
f
g
g
17
Java Object Serialization
18
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

19
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.

20
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( t) methods support writing
    primitives to stream

21
Traversing The Graph
writeObject(A) succeeds
A
java.util.Hashtable
java.lang.Integer
java.lang.String
22
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)
23
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 .

24
Java Remote Method Invocation (RMI)
25
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., inter-JVM call

26
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
27
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

28
Sample Remote Interface
public interface Count extends java.rmi.Remote
public int getCount() throws
java.rmi.RemoteException
29
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

30
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 // . . .
31
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

32
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

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

34
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

35
Lab Review (1)
  • The remote object's codebase is specified by the
    remote object's server by setting the
    java.rmi.server.codebase property. The RMI server
    registers a remote object, bound to a name, with
    the RMI registry.
  • The RMI client requests a reference to a named
    remote object. The reference (the remote object's
    stub instance) is what the client will use to
    make remote method calls to the remote object.
  • The RMI registry returns a reference (the stub
    instance) to the requested class. If the class
    definition for the stub instance can be found
    locally in the client's CLASSPATH , which is
    always searched before the codebase, the client
    will load the class locally. However, if the
    definition for the stub is not found in the
    client's CLASSPATH, the client will attempt to
    retrieve the class definition from the remote
    object's codebase.

36
Lab Review (2)
  • The client requests the class definition from the
    codebase. The codebase the client uses is the URL
    that was annotated to the stub instance when the
    stub class was loaded by the registry. Back in
    step 1, the annotated stub for the exported
    object was then registered with the RMI registry
    bound to a name.
  • The class definition for the stub (and any other
    class(es) that it needs) is downloaded to the
    client.
  • Now the client has all the information that it
    needs to invoke remote methods on the remote
    object. The stub instance acts as a proxy to the
    remote object that exists on the server, the RMI
    client uses the remote object's codebase to
    execute code in another, potentially remote JVM.

37
Starting the Server
  • Likewise the drive name may be required in the
    path. "file///h/" should work for this. (Note
    three front slashes, the drive letter, a colon,
    and another front slash.) The red slash is part
    of the path. This is particularly important if
    your source and class files are on a non-system
    drive, such as H or M.

38
Lessons Learned
  • The drive name may be required in the path.
    "file///h/" should work for this. (Note three
    front slashes, the drive letter, a colon, and
    another front slash.) This is particularly
    important if your source and class files are on a
    non-system drive, such as H or M.

39
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"

40
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.

41
Introduction to EJBs
42
Why Enterprise JavaBeans?
  • Server side re-usable components that enable
    rapid application development
  • Factor out common services from application
    development
  • Distribution and remote invocation (interface
    with other services)
  • Transaction management (one unit of work)
  • Thread management
  • Persistence (related to database)
  • Security (JAAS)
  • Scalability
  • You can just concentrate on application code!

43
The three types of Beans
  • Session Beans (service layer)
  • Provide synchronous (request-response
    conversation) client access to business services
  • Can be stateless (shared) or stateful (one per
    client)
  • Have NO persistent state
  • Entity Beans
  • Represent persistent components in the business
    model (database tables and columns)
  • Students, employees, documents, etc.
  • Shared between clients, but access is
    synchronized
  • Message Driven Beans (not efficient for
    real-time)
  • Provide asynchronous access to business services
    (a queue)
  • Invoked by messages instead of distributed method
    call
  • Clients do not interact directly with them

44
Stateless Session Beans
  • Execute on behalf of one client at a time
  • Re-entrant, executes logic that does not keep
    state across invocations
  • When done servicing one client, gets released so
    it can service another
  • A small pool of beans can be created to service
    many clients scalable!
  • A client may make multiple concurrent invocations
    each invocation will get a different instance
    from the pool to process the request

45
Stateful Session Beans
  • Converse with clients across invocations and time
  • Are managed by one and only one client
  • Can not be switched between invocations
  • Can hold state of the conversation (like the
    contents of a shopping cart)
  • May be passivated (serialized, moved to secondary
    storage) as required
  • State may not be maintained across server
    restarts
  • Not as scalable, can only process one invocation
    at a time and may or may not be clustered
  • Note should always have _at_remove annotation at
    the end.

46
What is a Container? (application container)
  • The fundamental part of an EJB server
  • Manages the Beans
  • Deployment
  • Lifecycles instantiation and pooling
  • Execution threads
  • All client access goes through it
  • Provides integration of services (naming,
    transactions, etc.)
  • Intercepts calls and injects the service
    infrastructure
  • Client invocations are decoupled through a proxy
  • The proxy routes all calls through the container
  • The service code is applied before the business
    code is executed (JBoss interceptors)
  • The container calls the bean implementation
    directly
  • Supplies the bean implementation with a
    EJBContext object which provides details of the
    environment and current invocation

47
What is a Proxy?
  • Similar to a middleman, a person in the middle
  • Provides a special object which implements your
    business interface
  • The object is used as a replacement for the
    actual service implementation to hide the
    complexity
  • Marshalling the call parameters
  • Sending the invocation to the server
  • Injects the service code (transactions, etc.)
  • Calls the business logic
  • Completes the service code (commit)
  • Marshalls the return objects
  • Sends the response back to the client
  • Is the object bound into JNDI
  • Client never sees the bean implementation and
    does not have to!
  • JBoss dynamically builds proxy at deployment,
    other containers may require a separate static
    compilation step

48
Deployment Descriptor ejb-jar.xml
  • Now optional in EJB3
  • Can be used to complement or override information
    provided by annotations
  • Contains metadata for the beans
  • Type of bean
  • Name of class
  • Environment properties
  • Transactional and security requirements
  • Portable across vendors part of the JEE
    specification

49
Deployment Descriptor jboss.xml
  • Optional JBoss specific extension
  • Connect local bean name to global JNDI context

50
EJB Packaging
  • myApplication.jar
  • META-INF
  • ejb-jar.xml (optional)
  • jboss.xml (optional)
  • class files in package subdirectories

51
Java Annotations
  • EJB3 adds the ability to use runtime
    annotations instead of deployment descriptors
    (Note These are different from javadoc
    annotations)
  • Allows self-describing code
  • Formalizes the code generation that was being
    done by tools like xdoclet
  • Must recompile if changed
  • Best of both worlds - can still be overridden by
    XML descriptors
  • http//www.fnogol.de/ejb-annotations-cheat-sheat

52
Goals of EJB3 Persistence
  • Remove EJB3 framework from Domain Objects (for
    example tables in a database)
  • Take advantage of the new Java annotations
    feature
  • Reduce the amount of deployment descriptors
  • Provide sensible default values for deployment
  • Simplify environmental dependencies with
    Dependency Injection (via the proxy to ensure
    that at runtime the reference is not null null
    pointer exception)
  • Increase the reusability of EJB components by
    moving closer to JavaBeans or POJO models
  • Overhaul the persistence model
  • Enable lightweight domain object models
  • Support inheritance and polymorphism
  • Address O/R(object to relational database)
    mapping configuration
  • Enhance support for EJB-QL(query language),
    dynamic queries (on an object) and native SQL

53
Enterprise Bean Business Interfaces
  • Define normal Java interfaces
  • Define a class that implements one or all of the
    interfaces
  • Annotate the interface or implementation bean
    with _at_Local or _at_Remote to explicitly define your
    local and remote business interfaces
  • If your implementation bean declares a single,
    non-annotated interface it is assumed to be the
    business interface and _at_Local
  • Annotate any callback methods that are required
  • _at_PostConstruct, _at_PreDestroy (SLSB, SFSB, MDB)
  • _at_PostActivate, _at_PrePassivate (SFSB)
  • Code any XML descriptor overrides that may be
    needed usually found in subdirectory for
    example
  • \source\resources\deployment\code\ejb\META-INF\ejb-jar.xml or
    \persistence.xml
  • \source\resources\deployment\code\metadata\application.xml

54
Example
  • _at_Remote
  • public interface MyService
  • public void validateName( String name ) throws
    DataValidationException
  • _at_Stateless
  • public class MyServiceBean implements MyService
  • public void validateName( String name ) throws
    DataValidationException
  • if( name null )
  • throw new DataValidationException( Name
    can not be null)
  • if( name.length() 35 )
  • throw new DataValidationException( Name
    35 characters)

55
EJB3 Client Example
  • Default global JNDI proxy name based upon
    interface (global - MyService)
  • public class client
  • public static void main( String args ) throws
    Exception
  • Context naming new InitialContext()
  • MyService service (MyService) naming.lookup(
    MyService/remote )
  • service.validateName( Patrick Murphy )

56
Dependency Injection (at time of deployment)
  • Allows removal of code to do JNDI lookups
  • Container initializes fields or calls setter
    methods
  • _at_Stateless
  • public class MyServiceBean
  • _at_EJB( nameSomeOtherService )
  • private otherService
  • _at_Resource
  • private EJBContext ejbContext
  • _at_Resource( namejava/D6501DS )
  • private dataSource
  • public void validateName( String name ) throws
    DataValidationException
  • if( name null )
  • throw new DataValidationException( Name
    can not be null)

57
EJB3 Interceptors
  • public class ServiceLogger
  • _at_AroundInvoke
  • public void log( InvocationContext ctx ) throws
    Exception
  • log.info( ctx.getMethod().getName() called
    )
  • return ctx.proceed()
  • _at_Interceptors(ServiceLogger.class )
  • _at_Stateless
  • public class MyServiceBean
  • public void validateName( String name ) throws
    DataValidationException
  • if( name null )
  • throw new DataValidationException( Name
    can not be null)

58
Transactions
  • Transaction is a unit of work
  • Beans are enrolled in transactions by the
    container
  • Transaction requirements can be set for the whole
    bean or per method
  • Possible Transaction Attributes
  • Required always runs in a transaction (either
    enrolls in an existing one or will start a new
    one), this is the default if not specified
  • RequiresNew always runs in a new transaction
    (any existing transaction is suspended while the
    method is called)
  • Supports enrolls in a transaction if one
    already exists
  • Mandatory must be called within an existing
    transaction
  • NotSupported can not be run in a transaction
    (any existing transaction will be suspended while
    the method runs)
  • Never can not be called within a transaction

59
Transaction Example
  • _at_Stateless
  • _at_TransactionAttribute( TransactionAttributeType.RE
    QUIRED )
  • public class MyServiceBean
  • public void validateName( String name ) throws
    DataValidationException
  • if( name null )
  • throw new DataValidationException( Name
    can not be null)
  • if( name.length() 35 )
  • throw new DataValidationException( Name
    35 characters)

60
Transactions Continued
  • Commit happens automatically if nothing forces a
    rollback
  • If an error occurs, you can force a rollback by
    getting the EJBContext reference and calling the
    setRollbackOnly() method
  • Checked Exceptions can be annotated to cause
    automatic rollback
  • Runtime Exceptions always force rollback but can
    be annotated to be unwrapped
  • You can use the XML descriptors to add the
    attribute to existing Exception classes
  • _at_ApplicationException ( rollbacktrue )
  • public class MyException
  • public MyException( String message )
  • super( message )

61
Transactions Continued...
  • External XML descriptors can be used to add
    additional metadata to existing classes.
  • MyException
  • true

62
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

63
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

64
Types of EJBs
65
Types of Beans
  • Session
  • Client and application logic focus
  • Entity
  • Persistent data focus
  • Message
  • Asynchronous message processing

66
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

67
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

68
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

69
Lifecycle of a Stateful Session BeanContainer
Perspective
create
passivate
Passive
Ready
Does Not Exist
remove
activate
commit or rollback
start transaction
In Transaction
timeout
70
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

71
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

72
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 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.

73
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

74
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

75
Entity Beans and Database Tables
Order Bean Table
Customer
1
Key Customer ID

Order Bean
1
Product
Key Order ID Customer ID Product ID
Invoice Table
1
Key Product ID
Invoice
1
Key Invoice ID Order ID
Customer Table
76
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

Msg Bean Instance
Msg Bean Instance
Msg Bean Instance
Client
Destination
77
Enterprise Attributes
78
Transactions
  • Ensure all-or-nothing semantics
  • In EJB only applicable to 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

79
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 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

80
Transaction 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

81
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

82
Putting it All Together
83
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.

84
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

85
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 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...)

86
Items not covered
  • APIs
  • Interoperability between servers
  • Relationship to CORBA

87
Specifications
  • 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

88
Backup
89
RemoteObject 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
90
A 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

91
Remote Objects as Parameters An Example
92
RMI 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
93
Characteristics 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

94
EJB Goals
  • For Bean Provider, Application Assembler and
    Deployer
  • Simplicity
  • Productivity
  • Reuse
  • Merchant market for components
  • Enterprise qualities
  • Distribution
  • Integrity
  • Security
  • Transactions
  • . . .
Write a Comment
User Comments (0)
About PowerShow.com