Presentation is loading. Please wait.

Presentation is loading. Please wait.

IBM Labs in Haifa Distributed Applications in Java and Introduction to Enterprise Java Beans Michael Factor

Similar presentations


Presentation on theme: "IBM Labs in Haifa Distributed Applications in Java and Introduction to Enterprise Java Beans Michael Factor"— Presentation transcript:

1 IBM Labs in Haifa Distributed Applications in Java and Introduction to Enterprise Java Beans Michael Factor factor@il.ibm.com

2 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

3 IBM Labs in Haifa Introduction to Distributed Computing

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

5 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

6 IBM Labs in Haifa y= F(x) F(x) { return 5; } Network ClientServer 1 2 3 4 1.Send message to call F with parameter X 2.Receive message that F was called with the given parameter 3.Send message with the result of calling F 4.Receive message with the result of calling F Client Server Interactions

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

8 IBM Labs in Haifa y= F(x) F(x) { return 5; } Network ClientServer 1 4 5 6 1.Register "F" with name server 2.Lookup "F" using name server 3.Send message to call F with parameter X 4.Receive message that F was called with the give parameter 5.Send message with the result of calling F 6.Receive message with the result of calling F Name Server 2 3 Naming Services

9 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

10 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

11 IBM Labs in Haifa 1.Marshal X 2.Send Msg Network ClientServer 7.Receive Msg w/ Result 8.Unmarshal Result y= F(x) F(x) { return 5; } 3.Receive Msg 4.Unmarshal X 5.Marshal Result 6.Send Msg w/ Result Parameter Passing Flow

12 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

13 IBM Labs in Haifa 1.Marshall X 2.Send Msg Network ClientServer 8.Receive Result Msg 9.Unmarshal Result F(x) { // stub 3.Receive Msg 4.Unmarshal X 5.Call F(X) 6.Marshal Result 7.Send Msg w/ Result } F_skeleton() { } Stubs and Skeletons: Flow

14 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

15 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

16 IBM Labs in Haifa Dispatcher Worker Threads Call f_skel f g Call g_skel Server Clients network f g Server Architecture (continued)

17 IBM Labs in Haifa Java Object Serialization

18 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

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

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

21 IBM Labs in Haifa java.util.Hashtable java.lang.String java.lang.Integer A java.util.Hashtable java.lang.Stringjava.lang.Thread not serializable B writeObject(B) ==> throws java.io.NotSerializableException: java.lang.Thread writeObject(A) ==> succeeds Traversing The Graph

22 IBM Labs in Haifa 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); Serialization Example

23 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 ==.

24 IBM Labs in Haifa Java Remote Method Invocation (RMI)

25 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., inter- JVM call

26 IBM Labs in Haifa ClientServer call getCount inc. count display result 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

27 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

28 IBM Labs in Haifa public interface Count extends java.rmi.Remote { public int getCount() throws java.rmi.RemoteException; } ClientServer call getCount inc. count display result Remote Interface Sample Remote Interface

29 IBM Labs in Haifa ClientServer call getCount inc. count display result Remote Object Remote Interface 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 IBM Labs in Haifa 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++; } //... Sample Implementation Class

31 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

32 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

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

34 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

35 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

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

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

38 IBM Labs in Haifa Introduction to EJBs

39 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

40 IBM Labs in Haifa Architecture Client Interface Container Bean Instance Client Method invocation Method Delegation TX support Security Persistence...

41 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

42 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

43 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

44 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

45 IBM Labs in Haifa Architecture with Remote Interfaces Source: Enterprise JavaBeans TM Specification, Version 2.0, page 386

46 IBM Labs in Haifa Types of EJBs

47 IBM Labs in Haifa Types of Beans  Session  Client and application logic focus  Entity  Persistent data focus  Message  Asynchronous message processing

48 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

49 IBM Labs in Haifa How a Client Uses a Session Bean Home Client Component JNDI Server Bean Instance Container lookup create method

50 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

51 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

52 IBM Labs in Haifa Lifecycle of a Stateful Session Bean Container Perspective PassiveReadyDoes Not Exist create In Transaction commit or rollback start transaction timeout remove passivate activate

53 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

54 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

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

56 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

57 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

58 IBM Labs in Haifa Entity Beans and Database Tables Customer Key: Customer ID Product Key: Product ID Order Bean Key: Order ID Customer ID Product ID Invoice Key: Invoice ID Order ID * 1 1 1 1 Customer IDProduct ID... 1769 321212 Order Bean Table Invoice IDOrder ID... 10011 10033 Invoice Table Customer IDOrdersAddress... 761 10022 Customer Table

59 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 ClientDestination Msg Bean Instance Msg Bean Instance Msg Bean Instance

60 IBM Labs in Haifa Enterprise Attributes

61 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

62 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

63 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

64 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

65 IBM Labs in Haifa Putting it All Together

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

67 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

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

69 IBM Labs in Haifa Items not covered  APIs  Interoperability between servers  Relationship to CORBA

70 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

71 IBM Labs in Haifa Backup

72 IBM Labs in Haifa All classes in package java.rmi.server RemoteObject RemoteStub RemoteServer UnicastRemoteObject ClientServer extends remote object semantics of stubs abstract server run-time  access to concrete RMI server run-time for singleton, non- persistent, remote objects  this is the class remote objects typically extend  provides basic remote object semantics  redefines equals, hashCode and toString RemoteObject Hierarchy

73 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

74 IBM Labs in Haifa f(Remote b) { b.g() } AInterface a; a.f(new B()); Marshal B as a Stub System BSystem A Remote Interface A Client Stub A int f(Remote b) Remote Object A Remote Interface B Client Stub B int g() Remote Interface B Remote Object B Remote Objects as Parameters: An Example

75 IBM Labs in Haifa 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; } RMI Stubs and Skeletons Example Portion of machine generated CountImpl_Stub

76 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

77 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 ...


Download ppt "IBM Labs in Haifa Distributed Applications in Java and Introduction to Enterprise Java Beans Michael Factor"

Similar presentations


Ads by Google