Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

Search: 

  Tutorial: Design networked applications in RMI using the Adapter design pattern

Design networked applications in RMI using the Adapter design pattern

Tutorial Details:

Design networked applications in RMI using the Adapter design pattern
Design networked applications in RMI using the Adapter design pattern
By: By Dan Becker
A guide to correctly adapting local Java objects for the Web
f you use Java's Remote Method Invocation (RMI), you know that it's easy to understand and implement: The perfect recipe for creating remote objects and services. In fact, Sun's Java tutorial provides an excellent example for creating your first RMI server and client and for running a remote system. However, I've seen many designs that build upon the Sun example and become unwieldy as new functions are added. Novice programmers often resort to odd naming conventions to distinguish local behavior from remote behavior, and, with the addition of new remote services, the remote class can easily grow into a big mess that performs poorly under remote network traffic.
In this article I'll demonstrate how the Adapter pattern, one of the most common design patterns, can be used to adapt a local class to a remote class. Using this design technique, it's easy to distinguish local from remote behavior, and you'll be able to continue to use the local class for your non-networked applications. Also, as the number of remote services grow, it's easy to see which class must handle the request and which objects must be synchronized. Finally, with this technique, your design will be easier to understand and more amenable to changes and fixes from multiple developers.
What is the Adapter pattern?
The Adapter pattern is one of the structural patterns listed in the reference book Design Patterns by the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides). The Adapter pattern is very common not only to remote client/server programming but also to any situation in which you have one class that you wish to reuse, but the application interface doesn't match the class interface. For this reason, you use an adapter or wrapper to convert the application interface to the existing class interface. In software development, an adapter simply maps the interface of one class to that of another. Adapters are used continually throughout the software development process, hence the term Adapter pattern.
Figure 1, below, illustrates how an adapter works. In this diagram, Client wants to invoke the method request() in the Target interface. Since the Adaptee class has no request() method, it is the job of Adapter to convert the request to an available matching method. Here the Adapter converts the method request() call into the Adaptee method specificRequest() call. The Adapter does this conversion for each method that needs adapting, also known as wrappering.
Figure 1. Adapting an interface to an Adaptee class
This type of adapting is exactly what one needs when creating remote services for the Web. Think of the design process as taking a working local class and publishing its services for the Web. You publish the services not by adding to the local class, but by adapting the local class to the remote interface. In the following sections I'll show you how this is done.
Designing a networked application
As stated in the previous section, classes are best made Web-ready by adapting the local methods to a remote interface. Sun's Java tutorial tells us we have to follow certain steps to make RMI work. These steps are as follows:
Create a remote interface that extends the java.rmi.Remote interface
Provide an implementation of the remote interface
Invoke the remote method calls from the remote client
Serendipitously, these steps closely match the function of the Adapter pattern. The Adapter pattern is initiated when a remote client intends to use a method published in the remote interface. The remote interface extends the tagging interface java.rmi.Remote to let RMI know this interface implements RMI. Rather than forcing the local class to implement the remote method, which creates excessive class bloating and hurts performance and readability, one creates a remote adapter that services a remote method by invoking a similar method in the local class. The local class is unchanged and unaware that it's being adapted to service network requests. Figure 2 shows the relationships of the classes as you apply the Adapter pattern to RMI.
Figure 2. Adapting a Remote interface to a local class
Conceptually, we've created a picture of how we want to use the Adapter pattern in a Java RMI application. Now let's create a concrete implementation of this design. Let's assume we want to implement a remote collection that many remote clients can query or add and delete elements from over a network. For this example, I'll use the Hashtable class in the java.util package, which many Java programmers have used over and over again.
Design the local classes
The first step toward creating a remote collection is to design a local class that implements some function. Conveniently, Sun has created the java.util.Hashtable for us, and we'll use the class as-is with no extra function. I've omitted the synchronized keyword from the methods, but I will reintroduce it later when I discuss how to make the object thread-safe. For your convenience, Listing 1 contains the pertinent methods of the Hashtable class.
int size();
boolean isEmpty();
boolean contains( Object value );
boolean containsKey( Object key );
Object get( Object key );
Object put( Object key, Object value );
Object remove( Object key );
void clear();
Enumeration keys();
Enumeration elements();
Listing 1. The java.util.Hashtable class methods
Design the remote interface
The second step in this exercise is to create a remote interface that takes the services the remote class is offering and publishes them over the network. The interface RemoteMap , shown below, is based on the java.util.Map collection interface, which the hashtable implements in Java 2. Collectively, these methods form the interface that remote clients may call on our networked hashtable.
public interface RemoteMap extends java.rmi.Remote {
// Constants
public static final String SERVICENAME = "RemoteMap";
public int size() throws RemoteException;
public boolean isEmpty() throws RemoteException;
public boolean containsKey( Object key ) throws RemoteException;
public boolean containsValue( Object value ) throws RemoteException;
public Object get( Object key ) throws RemoteException;
public Object put( Object key, Object value ) throws RemoteException;
public Object remove( Object key ) throws RemoteException;
public void clear() throws RemoteException;
}
Listing 2. A RemoteMap interface: Our remote methods
There are a few details worth pointing out. To start with, all of the remote methods throw a java.rmi.RemoteException . This is nothing to worry about; it's simply a requirement of Java RMI. Also, the RemoteMap interface extends the java.rmi.Remote interface. This is a tagging interface that tells the Java rmic utility which interface is going to be shared over the network; this is another requirement of RMI. I've left out a few of the Map interface methods, such as keySet and valueSet , but these are easy to implement using the hashtable keys and elements enumerations. Finally, there is one constant in the interface -- the string SERVICENAME . This constant will be handy when servers publish an RMI service and clients query the RMI registry to find the name of our public services.
So, now we have a local object and a remote interface. We're now ready to adapt the local class to the remote interface.
Pitfalls of adaptation
Many designers fail to properly execute the next step, adapting the local class to the remote interface. It's tempting to create a new class that extends the java.util.Hashtable class and implements the RemoteMap interface (for example, RemoteHashtable ). This is a bad programming choice for several reasons:
It's preferable to design using composition rather than inheritance. Why? Because design by inheritance is normally used for adding new methods and attributes to an existing class. Here, we're simply adapting local methods to become remote methods, so design by composition and delegation is more appropriate.
Designing with inheritance uses up the single inheritance parent class. Since Java only allows single inheritance, this gives us the dubious choice of extending java.rmi.server.UnicastRemoteObject , as required by RMI, or extending java.util.Hashtable , as required when designing by inheritance. It's preferable to forgo design by inheritance and implement the RMI function.
Some local classes are final and may not be extended. For example, this design exercise won't work with the java.util.Vector class because that class is final. If a class is final, you cannot use design by inheritance.
Mixing local and remote functions overly complicates the class. This is especially problematic when the remote interface and the local class have similar method names. I've seen supposed solutions where programmers have changed the method names to help prevent this problem -- for example, sizeLocal and sizeRemote . This is ugly! Not to mention that two simple, single-function classes now become one big multifunction class. Even uglier!
To show you how easy it is to create an adapter, and how simple is its function, Listing 3 offers the entire code. Java RMI handles the marshalling and unmarshalling of all call parameters and return values as long as these objects are serializable and implement java.io.Serializable . So, you see, the adapter really is a very simple class, and we haven't made one change to our local implementation, the hashtable.
public class RemoteMapAdapter extends UnicastRemoteObject
implements RemoteMap {
// Constructors
// The owner publishes this service in the RMI registry.
public RemoteMapAdapter( Hashtable adaptee ) throws RemoteException {
this.adaptee = adaptee;
}
// RemoteMap role
public int size() throws RemoteException


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Design networked applications in RMI using the Adapter design pattern

View Tutorial:
Design networked applications in RMI using the Adapter design pattern

Related Tutorials:

Displaying 1 - 50 of about 2926 Related Tutorials.

Design patterns interview questions1
and used over and over becomes a design pattern. Q2. Can we always apply... in that design pattern is solely the discretion of the Project Manager who is handling... be provided by a design pattern? Ans. Design patterns should present a higher
 
Design Pattern
Design Pattern 1. Adapter Pattern 2. Bridge Pattern 3. Composite... Design Pattern Design Pattern  ... exists). This tutorial explains the design pattern in the following list
 
Design Patterns
; Adapter Design Pattern Bridge Design Pattern Composite Design Pattern Decorator...;      Factory Design Pattern Abstract Factory Design Pattern Singleton Design Pattern Builder Design Pattern Prototype Design Pattern
 
Creational Design Patterns
. Factory Design Pattern Abstract Design Factory Pattern Builder Design Pattern Prototype Design Pattern Singleton Design Pattern Factory Design Pattern : Let... Creational Design Patterns Creational Design Patterns
 
Factory Pattern
.  Factory Pattern:  One of the goals of object-oriented design..., not what kind of subclass to create. Creational design pattern , more...-specific classes into the code. It is an object oriented design pattern
 
Singleton Design Pattern
Singleton Pattern Java,Singleton Design Pattern,Java Singleton Design Pattern Example Singleton Design Pattern... in java. The Singleton design pattern ensures that only one instance
 
Design patterns interview questions2
. Q13. What is Service to Worker pattern? Ans. This is used in larger applications... Common Interview Questions Design patterns... pattern? Ans. Provides a solution for pre-processing and post-processing a request
 
Object-Oriented Design - Overview
-level concept, called design patterns, using combinations of classes to accomplish... Java: Object-Oriented Design - Overview Java: Object-Oriented Design - Overview Background
 
Design Patterns Training
. Design pattern is a indispensable part of Java and J2ee technologies. Course Curriculum: Design Patterns Training I. Creational Patterns. 1. Factory Pattern 2... Pattern II. Structural patterns 1. Adapter Pattern 2. Bridge Pattern 3. Composite
 
Design patterns interview questions
Common Interview Questions Design patterns...;      Design patterns interview questions1 A pattern is a proven (and recurring
 
Design patterns interview questions
Common Interview Questions Design patterns...;      Design patterns interview questions1 A pattern is a proven (and recurring
 
CORBA and RMI Books
CORBA and RMI Books CORBA and RMI Books... involved in choosing among sockets, HTTP/CGI, remote method invocation (RMI... applications. The book also explains how to use Enterprise JavaBeans to create large
 
How to design a frame of the picture.
Photoshop : How to design a frame of the picture. How to design a frame of the picture.     ... you can make a good design as of your wish. Let's start now New File: First take
 
How to design a remote of the game.
your designing skill? Then come forward to design a video game remote by using... Photoshop : How to design a remote of the game. How to design a remote of the game.      
 
Design patterns interview questions3
Design patterns interview questions3 Design...;ade pattern? Ans. This pattern hides the complexity of business components... which reduces the remote method overhead. This pattern fits well with declarative
 
JSF Architecture
;  JSF was developed integrating MVC design pattern so... we need to understand what is MVC design pattern, how MVC helps to design... design pattern splits an application design into three separate parts:  
 
Photoshop Tutorial : How to make a speaker design
How to make a speaker design. How to make a speaker design.          ...;    Get ready to learn my new design, in this tutorial you
 
Displaying Hello using RMI
Displaying Hello using RMI, RMI Tutorial Displaying Hello using RMI       ... to display Hello message using RMI. By RMI we mean Remote Method Invocation. RMI
 
Design By Contract
Java: Design By Contract Java: Design By Contract Bertrand Meyer formalized a programming methodology called Design by Contract, which has become popular in some groups
 
Design Express Realization Mode
Design Express Realization Mode Design Express.... It is a step by step tutorial to learn easily. I have just tried to design a stun... are going to make lips. Select the pen tool (P key) and use it to design mouth
 
RMI Plugin for Eclipse
for developing Java RMI systems using the Eclipse platform. Besides generation of the stub and skeleton files using the "rmic" compiler, the RMI Plug... Eclipse Plugin-Language RMI Plugin for Eclipse
 
User Interface Design
Java: User Interface Design Java NotesUser Interface Design Links Sun's Java Look and Feel Design... to start. AskTog - www.asktog.com User Interface Design for Programmers - Joel
 
Web 3.0 Design
Web 3.0 Design,Web 3.0 Development,Web 3.0 Tools,Web 3.0 Technologies,Rss Web Web 3.0 Design    ...;          Web 3.0 Design
 
Night Sky Design in Photoshop
Night Sky Design in Photoshop Night Sky Design...;    How to design a night sky scene? With this tutorial, you will learn to design a night sky scene. Some easy steps have been used
 
CD Logo Design Photoshop
CD Logo Design Photoshop CD Logo Design Photoshop...;  How to design a CD Logo by the Photoshop? This example will teach you to design about Compact Disc (CD) logo with some simple steps
 
Object-Oriented Design - Overview
Java: Object-Oriented Design - Overview Java: Object-Oriented Design - Overview Encapsulation.... Fowler is one of leading authors in the design area. His (with Kent Beck
 
Open Source Web Frameworks in Java
is the implementation of Model-View-Controller (MVC) design pattern for the JSP... Millstone is a user interface library for development of networked Java applications... using standard WYSIWYG HTML design tools. Dynamic content processing and form
 
How to design a face of the lady.
Photoshop : How to design a face of the lady. How to design a face of the lady.                    
 
Photoshop : Clouds design
and choose appropriate file size as your design. I have take here a (height
 
How to design a flash effect on the picture.
How to design a flash effect on the picture.< How to design a flash effect on the picture.                  
 
How to design a text button.
How to design a text button.< How to design a text button.          ... a design of the text button, mostly we use simple buttons of circle
 
How to design a water drop.
How to design a water drop.< How to design a water drop.                        
 
How to design a rainy season.
rainy season, rain, nature How to design a rainy season.                        
 
Design a picture of the sea water.
Design a picture of the sea water.< Design a picture of the sea water.                     
 
Matching Pattern using Regularexpression
Matching Pattern using Regularexpression Matching Pattern using Regularexpression      ... to match a pattern with the text by using Regularexpression.The steps involved
 
Eclipse plugin-Network
;   RMI Plugin for Eclipse Genady's RMI Plug-in for Eclipse is the comprehensive solution for developing RMI applications. Apart from the automatic generation of RMI stubs, the RMI Plugin makes it simple
 
EJB Books
-level design pattern descriptions into critical EJB-specific implementation issues..., transactions, and security Designing EJB applications using patterns.... Professional EJB shows how to develop and deploy EJB applications using both
 
WebOfPatterns
of knowledge about software design. WOP consists of two parts: a language neutral format to describe design patterns based on the W3C standards RDF and OWL , and a set of Eclipse plugins which use this format. How WOP can be used: Find pattern
 
Applications and Applets
Applications and Applets Applications and Applets...;  Now a days, Java is widely used for applications and applets... and is executed by a run-time interpreter. Applications are stand alone
 
Pattern resetting using regular expression
Pattern resetting using regular expression Pattern resetting using regular expression    ... describes the way to retrieve the String using regular expression. For this we
 
Struts IDEs
environments to enable you to develop web applications based on the MVC design pattern provided by the Jakarta Struts framework. Eclipse features... standalone Java Swing application for developing and managing Struts-based applications
 
Struts IDEs
environments to enable you to develop web applications based on the MVC design pattern provided by the Jakarta Struts framework. Eclipse features... standalone Java Swing application for developing and managing Struts-based applications
 
Easy Struts
development environments to enable you to develop web applications based on the MVC design pattern provided by the Jakarta Struts framework. Easy Struts
 
Photoshop Tutorial :background image
design as pattern and for this go to Edit > Define Pattern. A pop up menu... can learn and design your own background image. So let's try. Take a new file... design.  Fill Color: Go to tool bar and select Paint Bucket tool (G key
 
VoIP Adapters
; VoIP Analog Telephone adapter Inexpensive, easy-to-install... using IETF STUN and symmetric RTP  * Advanced Digital Signal Processing... * Ultra compact (wallet size) and lightweight design, great companionfor
 
Building Search Engine Applications Using Servlets !
Building Search Engine Applications Using Servlets... Search Engine Applications Using Servlets... of building search engine using Java Servlets. You can Download
 
How Struts Works
applications easier to design, create, and maintain. Struts is purely based on the Model- View- Contoller (MVC) design pattern. It is one of the best and most well developed design patterns in use. By using the MVC architecture we break
 
This series of progressive examples shows a typical pattern for building simple applications with a window.
NotesAbout Examples This series of progressive examples shows a typical pattern for building simple applications with a window. Example - First Window shows... beginning of the pattern that will be used in many examples in these notes
 
jACOB Designer
without using the design functions of jACOB. Activate the workflow option and any...; The latest version of jACOB  is faster, even easier to design with and has some  powerful  new features. Designing applications became more
 
Pattern and Matcher
Java: Pattern and Matcher Java: Pattern and Matcher In addition to the regular expression methods... pattern can be reused by many Matcher objects. Pattern pat
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.