View
222
Download
0
Tags:
Embed Size (px)
Citation preview
CSE333
JRMI-1.1
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Paul C. BarrThe Mitre Corporation
145 Wyckoff Road145 Wyckoff RoadEatontown, NJ 07724
Prof. Steven A. Demurjian, Sr.Computer Science & Engrg. Dept.
The University of ConnecticutStorrs, CT 06269-3155
[email protected]://www.engr.uconn.edu/
~steve(860) 486 - 4818
CSE333
JRMI-1.2
IntroductionIntroduction
The Core Java Classes That Made the Success of The Core Java Classes That Made the Success of Java Provides the Basic Building Blocks for Creating Java Provides the Basic Building Blocks for Creating Robust Networked Applications.Robust Networked Applications.
Those Classes Are All the Ones Included in the Those Classes Are All the Ones Included in the Following Packages: Following Packages: java.applet, java.awt, java.io, java.lang, java.net and java.util.
They Form the Base of the Java Framework That They Form the Base of the Java Framework That Was Shipping in the Java Development Kit, Version Was Shipping in the Java Development Kit, Version 1.0. 1.0.
CSE333
JRMI-1.3
IntroductionIntroduction
The 1.1 Version of the JDK, Was an Essential The 1.1 Version of the JDK, Was an Essential Improvement As the Kit Contained a Set of New Improvement As the Kit Contained a Set of New API’s Specific to Distributed Computing: API’s Specific to Distributed Computing: java.security, java.sql with sun.jdbc, java.beans, and java.rmi.
CSE333
JRMI-1.4
Introduction (Concluded)Introduction (Concluded)
The Next Version JDK 1.2 Extends the Set of New The Next Version JDK 1.2 Extends the Set of New API's Specific to Distributed Computing:API's Specific to Distributed Computing: Enterprise Java Beans (EJB), javaRMI Extensions java Naming and Directory Interface (JNDI), java IDL, java Transaction Systems (JTS), java Messaging Systems (JMS)
CSE333
JRMI-1.5
RMI definedRMI defined
Java Remote Method Invocation (RMI) Is an Inter-Java Remote Method Invocation (RMI) Is an Inter-process Protocol for Java, Allowing Java Objects process Protocol for Java, Allowing Java Objects Living in Different Java Virtual Machines to Living in Different Java Virtual Machines to Invoke Transparently Each Other's Methods. Invoke Transparently Each Other's Methods.
Since These Virtual Machines Can Be Running on Since These Virtual Machines Can Be Running on Different Computers Anywhere on the Network, Different Computers Anywhere on the Network, RMI Enables Object-oriented Distributed RMI Enables Object-oriented Distributed Computing. Computing.
Java RMI Provides the Java Programmers With an Java RMI Provides the Java Programmers With an Efficient, Transparent Communication Mechanism Efficient, Transparent Communication Mechanism That Frees Them of All the Application-level That Frees Them of All the Application-level Protocols Necessary to Encode and Decode Protocols Necessary to Encode and Decode Messages for Data Exchange. Messages for Data Exchange.
CSE333
JRMI-1.6
RMI CORBA metaphorRMI CORBA metaphor
Remote Objects Written in Java RMI Interact Remote Objects Written in Java RMI Interact Approximately in Much the Same Way CORBA Approximately in Much the Same Way CORBA Objects Do: Objects Do:
Server Objects Publish Their Interfaces to Make Server Objects Publish Their Interfaces to Make Them Available to RMI Clients; Them Available to RMI Clients;
Stub Classes Deal With Binding to the Remote Stub Classes Deal With Binding to the Remote Objects and Do the Client-side Data Marshaling; Objects and Do the Client-side Data Marshaling;
Skeleton Classes on the Server-side Handle Skeleton Classes on the Server-side Handle Incoming Calls. Incoming Calls.
The Communication Mechanism Is Shown in the The Communication Mechanism Is Shown in the Next Slide . Without Any Surprise, This Looks Next Slide . Without Any Surprise, This Looks Very Much Like the Elementary ORB Structure of Very Much Like the Elementary ORB Structure of CORBA. CORBA.
CSE333
JRMI-1.7
RMI CORBA Block DiagramsRMI CORBA Block Diagrams
RMI Block Diagram
CORBA Block Diagram
CSE333
JRMI-1.8
Extensions included in RMIExtensions included in RMI
Java RMI Introduces a New Object Model to Java RMI Introduces a New Object Model to Programmers: Programmers: The Java Distributed Object Model, Which
Naturally Extends the Pre-JDK1.1 Object Model.
A Few New Features or Divergence's Were A Few New Features or Divergence's Were Added. Added. The Results of a Remote Invocation, As Well
As the Arguments That Came Along With the Initial Request, Are Passed by Value Rather Than Reference. This Is Because Object References Are Only
Useful Within the Same Virtual Machine.
CSE333
JRMI-1.9
Extensions included in RMIExtensions included in RMI
New Features (Continued)New Features (Continued) Instead, Ordinary Objects Are Passed by Value, by
Copy, Between Two Different Virtual Machines. To Do This Copy Operation, RMI Uses the New Object Serialization Service, Which Flattens a Local Java Object's State Into a Serial Stream That It Can Then Pass As a Parameter Inside a Message.
A Remote Object, an Object That Implements the A Remote Object, an Object That Implements the java.rmi.Remote Interface, Can Nevertheless Be java.rmi.Remote Interface, Can Nevertheless Be Passed by Reference and Not by Copying the Passed by Reference and Not by Copying the Actual Implementation. Clients of Remote Objects Actual Implementation. Clients of Remote Objects Interact With Remote Interfaces, Never With the Interact With Remote Interfaces, Never With the Implementation Classes of Those Interfaces. Implementation Classes of Those Interfaces.
CSE333
JRMI-1.10
Extensions included in RMI (Concluded)Extensions included in RMI (Concluded)
Clients That Invokes Methods on Remote Objects Clients That Invokes Methods on Remote Objects Have to Deal With Additional Interfaces and Have to Deal With Additional Interfaces and Classes, but Also With a Whole New Set of Classes, but Also With a Whole New Set of Exceptions. Exceptions.
Extra Security Mechanisms Are Now Introduced Extra Security Mechanisms Are Now Introduced to Reinforce the Control of the Behavior of Java to Reinforce the Control of the Behavior of Java Classes, and Most of All Stubs Classes. Classes, and Most of All Stubs Classes.
If a SecurityManager Is Not Explicitly Installed by If a SecurityManager Is Not Explicitly Installed by Server Objects, No Remote Invocation Will Be Server Objects, No Remote Invocation Will Be Possible. Possible.
CSE333
JRMI-1.11
RMI PresentationRMI Presentation
Remote Method Invocation Is the Action of Remote Method Invocation Is the Action of Invoking a Method of a Remote Interface on a Invoking a Method of a Remote Interface on a Remote Object. Therefore, We Must Provide Our Remote Object. Therefore, We Must Provide Our Server Object With the Interface Implementation Server Object With the Interface Implementation and Class Inheritance It Needs. We Must Also and Class Inheritance It Needs. We Must Also Obtain the Stubs and Skeleton Classes Needed for Obtain the Stubs and Skeleton Classes Needed for the Communication Between Remote Objectsthe Communication Between Remote Objects
The Development Process Is Show in Next Slide The Development Process Is Show in Next Slide Where Bob Is the Server Developer and Alice the Where Bob Is the Server Developer and Alice the Client One. Client One.
CSE333
JRMI-1.12
RMI Block Diagram for HelloWorld RMI Block Diagram for HelloWorld ApplicationApplication
Unmarshall UnmarshallMarshall Marshall
NDR NDR NDR NDR
Stub Stub Skel Skel
Transport Transport Transport Transport
HelloApplet HelloImpl
Hello
1 2 3
4
5
ServerClient
RMI Layer
Start rmiregistery
rmic HelloImpl.java
CSE333
JRMI-1.13
Hello.javaHello.java
package examples.hello;
import java.rmi.Remote; import java.rmi.RemoteException;
public interface Hello extends Remote { String sayHello() throws RemoteException; }
CSE333
JRMI-1.14
HelloImpl.javaHelloImpl.javapackage examples.hello;
import java.rmi.Naming;import java.rmi.RemoteException;import java.rmi.RMISecurityManager;import java.rmi.server.UnicastRemoteObject;public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { super(); } public String sayHello() { return "Hello World!"; } public static void main(String args[]) { // Create and install a security manager if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager()); } try {
HelloImpl obj = new HelloImpl(); // Bind this object instance to the name "HelloServer" Naming.rebind("HelloServer", obj); System.out.println("HelloServer bound in registry");
} catch (Exception e) { System.out.println("HelloImpl err: " + e.getMessage()); e.printStackTrace();
} }}
CSE333
JRMI-1.15
HelloApplet.javaHelloApplet.javapackage examples.hello;
import java.applet.Applet;import java.awt.Graphics;import java.rmi.Naming;import java.rmi.RemoteException;public class HelloApplet extends Applet { String message = "blank"; // "obj" is the identifier that we'll use to refer // to the remote object that implements the "Hello" // interface Hello obj = null; public void init() {
try { obj = (Hello)Naming.lookup("//" +
getCodeBase().getHost() + "/HelloServer"); System.out.println("Host = "+getCodeBase().getHost()); message = obj.sayHello();} catch (Exception e) { System.out.println("HelloApplet exception: " +
e.getMessage()); e.printStackTrace();}
} public void paint(Graphics g) {
g.drawString(message, 25, 50); }}
CSE333
JRMI-1.16
RMI StepsRMI Steps
The Different Steps That Must Follow to Get a The Different Steps That Must Follow to Get a Server Implemented and Running Are: Server Implemented and Running Are:
1. Define the Server Interface. The Server Object Declares Its Service Via a Remote Interface, That Must Therefore Extends the java.rmi.Remote Interface.
2. Write the Server Code. HelloImpl Must Provide the Java File Containing the Server Class That Implements Its Server Interface, and That Inherits From the java.rmi.UnicastRemoteObject Class.
CSE333
JRMI-1.17
RMI StepsRMI Steps
Different Step (Continued)Different Step (Continued)
3. You Need to Also Include the Code That Will Install a SecurityManager and That Will Register the Server Interface Within the RMI Naming Context Using the Naming.Bind (or Rebind) Method. The Daemon Program That Is in Charge of the Naming Service Is RMIregistry, and It Must of Course Be Running for the Interface Registration to Succeed.
CSE333
JRMI-1.18
RMI Steps (Concluded)RMI Steps (Concluded)
Different Step (Continued)Different Step (Continued) 4. Compile the Server Class. First, Uses the
Javac Compiler to Produce the Server .class File, and Secondly, Run the rmic Compiler to Obtain the Stub and Skeleton .class Files.
5. Execute the Server Program. If the RMIRegistry Daemon Is Not Already Running, It Must Be Launched. He Can Then Run the Java Interpreter With His Server .class File.
6. Distribute the Stub Class. In Order to Get Clients Calling the Methods of the Server, the Stub Class That Has Been Generated Needs to be Provided . This Will Enable Client Code to Make Successful Requests to Server Object.
CSE333
JRMI-1.19
Java, JavaBeans and Java RMIJava, JavaBeans and Java RMI
Java Is "A Simple, Object Oriented, Distributed, Java Is "A Simple, Object Oriented, Distributed, Interpreted, Robust, Secure, Architecture Neutral, Interpreted, Robust, Secure, Architecture Neutral, Portable, High-performance, Multithreaded and Portable, High-performance, Multithreaded and Dynamic Language". Dynamic Language".
Javabeans Is the Specification for Building Reusable Javabeans Is the Specification for Building Reusable Software Components (on the Client Side) Using Java. Software Components (on the Client Side) Using Java.
Java-RMI Ensures Communication Between Java-RMI Ensures Communication Between Distributed Program-level Java Objects Residing in Distributed Program-level Java Objects Residing in Different Address Spaces by Assuming a Different Address Spaces by Assuming a Homogeneous Java Virtual Machine Environment.Homogeneous Java Virtual Machine Environment. It Thus Takes Advantage of the Java Object Model
Whenever Possible to Support Distributed Objects in the Java Environment.
CSE333
JRMI-1.20
Enterprise Java BeansEnterprise Java Beans
Enterprise Javabeans (EJB) (for the Server Side) Enterprise Javabeans (EJB) (for the Server Side) Provides a Fully-scaleable, Distributed, and Cross-Provides a Fully-scaleable, Distributed, and Cross-platform Architecture That Makes the Most of platform Architecture That Makes the Most of Your Business Resources. Your Business Resources.
Not Only Can These Components Run on Any Not Only Can These Components Run on Any Platform, but They Are Also Completely Portable Platform, but They Are Also Completely Portable Across Any Vendor's EJB Component Execution Across Any Vendor's EJB Component Execution System. System.
The EJB Environment Automatically Maps the The EJB Environment Automatically Maps the Component to the Underlying Vendor-specific Component to the Underlying Vendor-specific Execution Services. Execution Services.
CSE333
JRMI-1.21
Java Remote Method InvocationJava Remote Method Invocation
Remote Method Invocation (RMI) Is the Object Remote Method Invocation (RMI) Is the Object Equivalent of Remote Procedure Calls (RPC). Equivalent of Remote Procedure Calls (RPC). While RPC Allows You to Call Procedures Over
a Network, RMI Invokes an Object's Methods. In the RMI Model, In the RMI Model,
The Server Defines Objects That the Client Can Use Remotely.
The Clients Can Now Invoke Methods of This Remote Object As If It Were a Local Object Running in the Same Virtual Machine As the Client.
RMI Hides the Underlying Mechanism of Transporting Method Arguments and Return Values Across the Network.
CSE333
JRMI-1.22
Java Remote Method InvocationJava Remote Method Invocation
In Java-RMI, an Argument or Return Value Can In Java-RMI, an Argument or Return Value Can Be of Any Primitive Java Type or Any Other Be of Any Primitive Java Type or Any Other Serializable Serializable Java Object. Works Over a Network.Java Object. Works Over a Network.
CSE333
JRMI-1.23
Java-RMI and comparison with otherJava-RMI and comparison with otherMiddleware SpecificationsMiddleware Specifications
Java-RMI Is a Java-specific Middleware Spec That Java-RMI Is a Java-specific Middleware Spec That Allows Client Java Programs to Invoke Server Java Allows Client Java Programs to Invoke Server Java Objects As If They Were Local.Objects As If They Were Local.
Java-RMI Is Tightly Coupled With the Java Language. Java-RMI Is Tightly Coupled With the Java Language. There Are No Separate IDL Mappings That Are There Are No Separate IDL Mappings That Are Required to Invoke Remote Object Methods. Required to Invoke Remote Object Methods.
This Is Different From DCOM or CORBA Where IDL This Is Different From DCOM or CORBA Where IDL Mappings Have to Be Created to Invoke Remote Mappings Have to Be Created to Invoke Remote Methods.Methods.
CSE333
JRMI-1.24
Java-RMI and comparison with otherJava-RMI and comparison with otherMiddleware SpecificationsMiddleware Specifications
Since Java-RMI Is Tightly Coupled With the Java Since Java-RMI Is Tightly Coupled With the Java Language, Java-RMI Can Work With True Sub-Language, Java-RMI Can Work With True Sub-classes.classes. Neither DCOM nor CORBA Can Work With
True Subclasses Since They Are Static Object Models.
Because of This, Parameters Passed During Because of This, Parameters Passed During Method Calls Between Machines Can Be True Method Calls Between Machines Can Be True Java Objects. Java Objects. This Is Impossible in DCOM or CORBA at
Present.
CSE333
JRMI-1.25
Java-RMI and comparison with otherJava-RMI and comparison with otherMiddleware Specifications (Concluded)Middleware Specifications (Concluded)
If a Process in an RMI System Receives an Object If a Process in an RMI System Receives an Object of a Class That It Has Never Seen Before, It Can of a Class That It Has Never Seen Before, It Can Request That Its Class Information Be Sent Over Request That Its Class Information Be Sent Over the Network.the Network.
Over and Above All This, Java-RMI Supports Over and Above All This, Java-RMI Supports Distributed Garbage Collection That Ties Into the Distributed Garbage Collection That Ties Into the Local Garbage Collectors in Each JVM.Local Garbage Collectors in Each JVM.
CSE333
JRMI-1.26
Workings of Java-RMIWorkings of Java-RMI
Since Both the Client and the Server May Reside Since Both the Client and the Server May Reside on Different Machines/processes, There Needs to on Different Machines/processes, There Needs to Be a Mechanism That Can Establish a Be a Mechanism That Can Establish a Relationship Between the Two. Relationship Between the Two.
Java-RMI Uses a Network-based Registry Java-RMI Uses a Network-based Registry Program Called Program Called RMIRegistry RMIRegistry To Keep Track of the To Keep Track of the Distributed Objects. Distributed Objects. (Note: The RMI Registry Is an RMI Server
Itself!!!)
CSE333
JRMI-1.27
The RMI RegistryThe RMI Registry
The Server Object Makes Methods Available for The Server Object Makes Methods Available for Remote Invocation by Binding It to a Name in the Remote Invocation by Binding It to a Name in the RMI RegistryRMI Registry. .
The Client Object, Can Thus Check for the The Client Object, Can Thus Check for the Availability of a Certain Server Object by Looking Availability of a Certain Server Object by Looking up Its Name in the Registry. up Its Name in the Registry.
The The RMI RegistryRMI Registry Thus Acts As a Central Thus Acts As a Central Management Point for Java-RMI. Management Point for Java-RMI. The RMI Registry Is Thus a Simple Name
Repository. It Does Not Address the Problem of Actually Invoking Remote Methods.
CSE333
JRMI-1.28
Stubs and SkeletonsStubs and Skeletons
Since the Two Objects May Physically Reside on Since the Two Objects May Physically Reside on Different Machines, a Mechanism Is Needed to Different Machines, a Mechanism Is Needed to Transmit the Client's Request to Invoke a Method Transmit the Client's Request to Invoke a Method on the Server Object to the Server Object and on the Server Object to the Server Object and Provide a Response. Provide a Response.
Java-RMI Uses an Approach Similar to RPC in Java-RMI Uses an Approach Similar to RPC in This Regard. This Regard. The Code for the Server Object Must Be
Processed by an RMI Compiler Called rmic, Which is Part of the JDK.
CSE333
JRMI-1.29
Rmic CompilerRmic Compiler
The The rmic rmic Compiler Generates Two Files: Compiler Generates Two Files: A Stub and a Skeleton.
The Stub Resides on the Client Machine and the The Stub Resides on the Client Machine and the Skeleton Resides on the Server Machine.Skeleton Resides on the Server Machine. When a Client Invokes a Server Method, the
JVM Looks at the Stub to Do Type Checking. The Request Is Then Routed to the Skeleton on
the Server, Which in Turn Calls the Appropriate Method on the Server Object. In Other Words, the Stub Acts As a Proxy to the Skeleton and the Skeleton Is a Proxy to the Actual Remote Method.
CSE333
JRMI-1.30
Java RMI InternalsJava RMI Internals
The RMI Server Creates an Instance of the 'Server The RMI Server Creates an Instance of the 'Server Object' Which Extends Object' Which Extends UnicastRemoteObjectUnicastRemoteObject
The Constructor for The Constructor for UnicastRemoteObjectUnicastRemoteObject "exports" the Server Object - Basically Making It "exports" the Server Object - Basically Making It Available to Service Incoming RMI Calls. Available to Service Incoming RMI Calls. A TCP Socket Which Is Bound to an Arbitrary
Port Number Is Created and a Thread Is Also Created That Listens for Connections on That Socket.
CSE333
JRMI-1.31
Java RMI InternalsJava RMI Internals
The Server Registers the Server Object With the The Server Registers the Server Object With the RegistryRegistry This Operation Actually Hands the Registry the
Client-side "Stub" for That Server Object. This Stub Contains the Information Needed
to "Call Back" to the Server When It Is Invoked (Such As the Hostname/port of the Server Listening Socket).
CSE333
JRMI-1.32
Java RMI Internals (Continued)Java RMI Internals (Continued)
A Client Obtains This Stub by Calling the A Client Obtains This Stub by Calling the Registry, Which Hands It the Stub Directly. Registry, Which Hands It the Stub Directly. (This Is Also Where the “codebase” Comes In:
If the Server Specified a “codebase” to Use for Clients to Obtain the Class File for the Stub, This Will Be Passed Along to the Client Via the Registry.
The Client Can Then Use the codebase to Resolve the Stub Class - That Is, to Load the Stub Class File Itself).
The The RMIRegistryRMIRegistry Holds Onto Remote Object Holds Onto Remote Object Stubs Which It Can Hand off to Clients When Stubs Which It Can Hand off to Clients When Requested.Requested.
CSE333
JRMI-1.33
Java RMI Internals (Continued)Java RMI Internals (Continued)
When the Client Issues a Remote Method Invocation When the Client Issues a Remote Method Invocation to the Server, the Stub Class Creates a "RemoteCall" to the Server, the Stub Class Creates a "RemoteCall" Which Basically Which Basically (A) Opens a Socket to the Server on the Port
Specified in the Stub Itself, and (B) Sends the RMI Header Information As
Described in the RMI Spec. The Stub Class Marshals the Arguments Over the The Stub Class Marshals the Arguments Over the
Connection by Using Methods on Connection by Using Methods on RemoteCall to Obtain the Output Stream Which RemoteCall to Obtain the Output Stream Which Basically Returns a Subclass of Basically Returns a Subclass of ObjectOutputStreamObjectOutputStream Which Knows How to Deal With Passing Objects Which Knows How to Deal With Passing Objects Which Extend java.rmi.Remote, Which Serializes Which Extend java.rmi.Remote, Which Serializes Java Objects Over the SocketJava Objects Over the Socket
CSE333
JRMI-1.34
Java RMI Internals (Continued)Java RMI Internals (Continued)
The Stub Class Calls The Stub Class Calls RemoteCall.executeCallRemoteCall.executeCall Which Causes the RMI to Happen.Which Causes the RMI to Happen.
On the Server Side, When a Client Connects to the On the Server Side, When a Client Connects to the Server Socket, a New Thread Is Server Socket, a New Thread Is Forked to Deal With the Incoming Call. Forked to Deal With the Incoming Call. The Original Thread Can Continue Listening to
the Original Socket So That Additional Calls From Other Clients Can Be Made.
The Server Reads the Header Information and The Server Reads the Header Information and Creates a Creates a RemoteCallRemoteCall Of Its Own to Deal With Of Its Own to Deal With Unmarshalling the RMI Arguments from the Unmarshalling the RMI Arguments from the Socket. Socket.
CSE333
JRMI-1.35
Java RMI Internals (Concluded)Java RMI Internals (Concluded)
The Server Calls the “dispatch” Method of the The Server Calls the “dispatch” Method of the Skeleton Class (the Server-side ”stub" Generated bySkeleton Class (the Server-side ”stub" Generated by rmicrmic), Which Calls the Appropriate Method on the ), Which Calls the Appropriate Method on the Object and Pushes the Result Back Down the Wire Object and Pushes the Result Back Down the Wire (Using the Same ‘RemoteCall Interface Which the (Using the Same ‘RemoteCall Interface Which the Client Used to Marshall the Arguments). Client Used to Marshall the Arguments). If the Server Object Threw an Exception Then the
Server Catches This and Marshals That Down the Wire Instead of the Return Value.
Back on the Client Side, the Return Value of the RMI Back on the Client Side, the Return Value of the RMI Is Unmarshalled (Using the RemoteCall as Created Is Unmarshalled (Using the RemoteCall as Created Above) and Returned From the Stub Back to the Client Above) and Returned From the Stub Back to the Client Code Itself.Code Itself.
If an Exception Was Thrown from the Server that's If an Exception Was Thrown from the Server that's Unmarshalled and Re-thrown From the Stub. Unmarshalled and Re-thrown From the Stub.
CSE333
JRMI-1.36
Java 1.1 Event ModelJava 1.1 Event Model
Paul C. BarrPaul C. [email protected]@mitre.org
CSE333
JRMI-1.37
The Java 1.1 Event ModelThe Java 1.1 Event Model
Event-handling Code Is the Heart of Every Useful Event-handling Code Is the Heart of Every Useful Application. Application.
All Event-driven Programs Are Structured Around All Event-driven Programs Are Structured Around Their Event-processing Model. Java Events Are Their Event-processing Model. Java Events Are Part of the Java Abstract Windowing Toolkit Part of the Java Abstract Windowing Toolkit Package (AWT for Short)Package (AWT for Short)
CSE333
JRMI-1.38
The Java 1.1 Event ModelThe Java 1.1 Event Model
People Who Are Familiar With the Ms-windows People Who Are Familiar With the Ms-windows or X-windows SDK Programming, Remember or X-windows SDK Programming, Remember That the Windows Procedure Was Braced Against That the Windows Procedure Was Braced Against a Flood of Events and Then a Giant ‘Switch’ a Flood of Events and Then a Giant ‘Switch’ Statement Was Used to Sort Through These Statement Was Used to Sort Through These Events. Events.
Similarly, in The Microsoft Foundation Classes Similarly, in The Microsoft Foundation Classes Programming Model or The Motif Programming Programming Model or The Motif Programming Model, Each Component Has to Be Over-ridden to Model, Each Component Has to Be Over-ridden to Make It Do What You Want It to Do - Something Make It Do What You Want It to Do - Something Similar to the Older Java 1.0 Inheritance Event Similar to the Older Java 1.0 Inheritance Event Model.Model.
CSE333
JRMI-1.39
The Java 1.1 Event Model (Continued)The Java 1.1 Event Model (Continued)
The First Approach Is the Easiest to Implement, but The First Approach Is the Easiest to Implement, but Any Time You Use a Switch Statement, You Any Time You Use a Switch Statement, You Somehow Have This Nagging Feeling That Perhaps Somehow Have This Nagging Feeling That Perhaps There Is Something Un-object-oriented in the Design There Is Something Un-object-oriented in the Design or That a Different Class Hierarchy and Design or That a Different Class Hierarchy and Design Would Have Made This Go Away.Would Have Made This Go Away.
The Second Approach Is More Object-oriented, but The Second Approach Is More Object-oriented, but Involves a Great Deal of Work.Involves a Great Deal of Work.
With the New 1.1 Delegation Event Model, a With the New 1.1 Delegation Event Model, a Component Can Be Told Which Object or Objects Component Can Be Told Which Object or Objects Should Be Notified When the Component Generates Should Be Notified When the Component Generates a Particular Type of Event. a Particular Type of Event. If a Component Is Not Interested in an Event
Type, Then Events of That Type Will Not Be Propagated.
CSE333
JRMI-1.40
The Java 1.1 Event Model The Java 1.1 Event Model (According to Sun)(According to Sun)
Simple and Easy to LearnSimple and Easy to Learn Support a Clean Separation Between Application Support a Clean Separation Between Application
and GUI Code and GUI Code Flexible Enough to Enable Varied Application Flexible Enough to Enable Varied Application
Models for Event Flow and PropagationModels for Event Flow and Propagation For Visual Tool Builders, Enable Run-time For Visual Tool Builders, Enable Run-time
Discovery of Both Events That a Component Discovery of Both Events That a Component Generates As Well As the Events It May ObserveGenerates As Well As the Events It May Observe
Support Backward Binary Compatibility With the Support Backward Binary Compatibility With the Old ModelOld Model
Facilitate the Creation of Robust Event Handling Facilitate the Creation of Robust Event Handling Code Which Is Less Error-prone (Strong Compile-Code Which Is Less Error-prone (Strong Compile-time Checking)time Checking)
CSE333
JRMI-1.41
The 1.1 Delegation Event ModelThe 1.1 Delegation Event Model
The 1.1 Event Model Is Based on the Concept of The 1.1 Event Model Is Based on the Concept of an ‘Event Source’ and ‘Event Listeners’. an ‘Event Source’ and ‘Event Listeners’. Any Object That Is Interested in Receiving
Messages (or Events ) Is Called an Event Listener.
Any Object That Generates These Messages (or Events ) Is Called an Event Source.
CSE333
JRMI-1.42
The 1.1 Delegation Event ModelThe 1.1 Delegation Event Model(Pictorial Representation)(Pictorial Representation)
CSE333
JRMI-1.43
The 1.1 Delegation Event Model The 1.1 Delegation Event Model (Continued)(Continued)
The Event Source Object Maintains a List of The Event Source Object Maintains a List of Listeners Who Are Interested in Receiving Events Listeners Who Are Interested in Receiving Events That It Produces. That It Produces.
The Event Source Object Provides Methods That The Event Source Object Provides Methods That Allow the Listeners to Add Themselves Allow the Listeners to Add Themselves ( ‘Register’ ) or Remove Themselves From This ( ‘Register’ ) or Remove Themselves From This List of ‘Interested’ Objects. List of ‘Interested’ Objects.
When the Event Source Object Generates an When the Event Source Object Generates an Event, or When a User Input Event Occurs on the Event, or When a User Input Event Occurs on the Event Source Object, the Event Source Object Event Source Object, the Event Source Object Notifies All the Listeners That the Event Has Notifies All the Listeners That the Event Has Occurred.Occurred.
CSE333
JRMI-1.44
Event Source Object ImplementationEvent Source Object Implementation
//This is one typical Event Source Object implementation public class EventSource extends Applet { public Label m_Label; public Button m_Button; public int m_nCounter;
public void init() { m_Label = new Label( "Go ahead and click away." ); m_Button = new Button( "Click Here" ); EventListener listenerObject = new EventListener( this ); //Register with event source using addXListener m_Button.addActionListener( listenerObject );
add( m_Label ); add( m_Button ); }
}
CSE333
JRMI-1.45
Event Listener ObjectEvent Listener Object
//This is one typical Event Listener Object implementation class EventListener implements ActionListener { private EventSource m_sourceObject;
public EventListener( EventSource sourceObject ) { m_sourceObject = sourceObject; }
//This method handles the EventObjects fired by the EventSource Object//Note: An ActionEvent is an EventObject public void actionPerformed( ActionEvent e ) { m_sourceObject.m_Label.setText( "That was click " + ( ++m_sourceObject.m_nCounter ) + " buddy." ); }
}
CSE333
JRMI-1.46
Event Object InteractionsEvent Object Interactions
An Event Source Object Notifies an Event Listener An Event Source Object Notifies an Event Listener Object by Invoking a Method on It and Passing It Object by Invoking a Method on It and Passing It an EventObject ( An Instance of a Subclass of an EventObject ( An Instance of a Subclass of java.util.EventObject ). java.util.EventObject ). In Order for the Source to Invoke a Method on
a Listener, All Listeners Must Implement the Required Method.
This Is Ensured by Requiring That All Event Listeners for a Particular Type of Event Implement a Corresponding Interface.
CSE333
JRMI-1.47
Event Delegation ModelEvent Delegation Model
The Java 1.1 Event Delegation Model Is Based on The Java 1.1 Event Delegation Model Is Based on Four Concepts:Four Concepts: The Event Classes The Event Listeners Explicit Event Enabling Adapters
CSE333
JRMI-1.48
Event ClassesEvent Classes
CSE333
JRMI-1.49
Event Class SpecificsEvent Class Specifics
Every Event Is a Subclass of java.util.EventObject. Every Event Is a Subclass of java.util.EventObject. It Is a Very General Class With Only One Method of
Interest: Object getSource()
This Method Returns the Object That Originated the Event. Every Event Has a Source Object, From Which the Event Originated. This Method Returns a Reference to That Source.
AWT Events, Which Is What We Are Concerned With Here, AWT Events, Which Is What We Are Concerned With Here, Are Subclasses of java.awt.AWTEvent. Are Subclasses of java.awt.AWTEvent. This Is the Superclass of All the Delegation Model
Event Classes. The Most Interesting Method in This Class is int getID()
This Method Returns the ID of the Event. An Event’s ID is an int That Specifies the Exact Nature of the Event. This Value is Used to Distinguish the Various Types of Events That Are Represented by Any Event Class.
CSE333
JRMI-1.50
AWT EventsAWT Events
java.awt.event - The Subclasses of java.awt.event - The Subclasses of java.awt.AWTEvent Represent The Various Event java.awt.AWTEvent Represent The Various Event Types That Can Be Generated by the Various Types That Can Be Generated by the Various AWT Components. AWT Components. All the Various Types of AWT Events, Are
Placed in a Separate Package Called java.awt.event for the Sake of Convenience.
CSE333
JRMI-1.51
Types of EventsTypes of Events
ActionEvent Generated by Component ActivationActionEvent Generated by Component Activation AdjustmentEvent Generated by Adjustment of Adjustable AdjustmentEvent Generated by Adjustment of Adjustable
Components Such As Scroll BarsComponents Such As Scroll Bars ContainerEvent Generated When Components Are Added to ContainerEvent Generated When Components Are Added to
or Removed From a Containeror Removed From a Container FocusEvent Generated When a Component Receives Input FocusEvent Generated When a Component Receives Input
FocusFocus ItemEvent Generated When an Item Is Selected From a List, ItemEvent Generated When an Item Is Selected From a List,
Choice or Check BoxChoice or Check Box KeyEvent Generated by Keyboard ActivityKeyEvent Generated by Keyboard Activity MouseEvent Generated by Mouse ActivityMouseEvent Generated by Mouse Activity PaintEvent Generated When a Component Is PaintedPaintEvent Generated When a Component Is Painted TextEvent Generated When a Text Component Is ModifiedTextEvent Generated When a Text Component Is Modified WindowEvent Generated by Window Activity Like WindowEvent Generated by Window Activity Like
Minimizing or MaximizingMinimizing or Maximizing
CSE333
JRMI-1.52
Handling EventsHandling Events
There Are a Number of Ways to Handle the Events There Are a Number of Ways to Handle the Events Listed Above.Listed Above. Object. Another Way Is to Explicitly Enable the
Originating Component to Handle Its Own Events.
CSE333
JRMI-1.53
The Event ListenersThe Event Listeners
Event Listeners Are Objects That Are Responsible Event Listeners Are Objects That Are Responsible for Handling a Particular Task of a Component. for Handling a Particular Task of a Component. The Listener Typically Implements the
Interface That Contains Event-handling Code for a Particular Component. For Instance, When the Component Experiences
Input, an EventObject of the Appropriate Type Is Constructed and Is Passed As a Parameter to a Method Call on the Listener:
CSE333
JRMI-1.54
//This is one typical Event Listener Object implementation class EventListener implements ActionListener { private EventSource m_sourceObject;
public EventListener( EventSource sourceObject ) { m_sourceObject = sourceObject; }
//This method handles the EventObjects fired by the EventSource Object //Note: An ActionEvent is an EventObject public void actionPerformed( ActionEvent e ) { m_sourceObject.m_Label.setText( "That was click " + ( ++m_sourceObject.m_nCounter ) + " buddy." ); }
}
CSE333
JRMI-1.55
The applet code that forms the Event The applet code that forms the Event SourceSource
//This is one typical Event Source Object implementation public class EventSource extends Applet { public Label m_Label; public Button m_Button; public int m_nCounter;
public void init() { m_Label = new Label( "Go ahead and click away." ); m_Button = new Button( "Click Here" ); EventListener listenerObject = new EventListener( this ); //Register with event source using addXListener m_Button.addActionListener( listenerObject );
add( m_Label ); add( m_Button ); }
}
CSE333
JRMI-1.56
If You Notice the Code Fragment Above, an If You Notice the Code Fragment Above, an Instance of the EventListener Class Is Created. Instance of the EventListener Class Is Created. This Instance listenerObject, is Set As One of
the Button's Action Listeners Using the addActionListener() Method Call. All in All, You Will Find a Standard Pattern Followed for Giving a Listener to a Component. It Can Be Summarized As Follows Create a Listener Class That Implements
the ...Listener Interface Construct the Component Construct an Instance of the Listener Interface Call Add...Listener() on the Component, Passing in
the Listener
CSE333
JRMI-1.57
EventListener RemovalEventListener Removal
An Event Listener May Be Removed From an An Event Listener May Be Removed From an Event Source's List of Interested Listeners by Event Source's List of Interested Listeners by Calling a Remove...Listener() Method, Passing in Calling a Remove...Listener() Method, Passing in the Listener Object to Be Removed. For Example, the Listener Object to Be Removed. For Example, in the Above Code Fragment, the Code Below in the Above Code Fragment, the Code Below Removes the Action Listener Object listenerObject Removes the Action Listener Object listenerObject From the Button m_Button.From the Button m_Button.
m_button.Removeactionlistener( listenerObject );m_button.Removeactionlistener( listenerObject );