Module 5-Notes
Module 5-Notes
MODULE 5
Designing with Distributed Objects
Definition: Businesses usually install multiple computer systems that are
interconnected by communication links, and applications run across a network of
computers rather than on a single machine. Such systems are called distributed
systems.
Advantages
Drawbacks
a. The software for implementing them is complex.
Distributed systems must coordinate actions between a number of
possibly heterogeneous computer systems; if data is replicated, the copies
must be made mutually consistent.
b. Data access may be slow because information may have to be
transferred across communication links.
c. Securing the data is a challenge.
As data is distributed over multiple systems and transported over
communication links, care must be taken to guarantee that it is not lost,
corrupted, or stolen.
➢ Figure below shows a system with one server and three clients.
➢ Each client runs a program that provides a user interface, which may or not
be a GUI.
There is a basic difficulty in accessing objects running in a different Java Virtual Machine
(JVM). Let us consider two JVMs hosting objects as in Fig. below.
➢ A single JVM has an address space part of which is allocated to objects living in it.
For example,
• Objects object 1 and object 2 are created in JVM 1 and are allocated at
addresses A1 and A2 respectively. Similarly, objects object 3 and object 4 live
in JVM 2 and are respectively allocated addresses A3 and A4.
• Code within Object 2 can access fields and methods in object 1 using address
A1. However, addresses A3 and A4 that give the addresses of objects object 3
and object 4 in JVM 2 are meaningless within JVM 1.
2. By avoiding direct use of remote objects by using the Hyper Text Transfer Protocol
(HTTP).
The system sends requests and collects responses via encoded text messages. The
object(s) to be used to accomplish the task, the parameters, etc., are all transmitted via these
messages. This approach has the client employ an Internet browser, which is, of course, a
piece of general-purpose software for accessing documents on the world-wide web.
Remote Interfaces
1. In the case of RMI, the functionality exported of a remote object is defined via what is
called a remote interface. A remote interface is a Java interface that extends the
interface java.rmi.Remote.
2. Clients are restricted to accessing methods defined in the remote interface. We call
such method calls remote method invocations.
NOTE: Java RMI encapsulates such failures in the form of an object of type
java.rmi.RemoteException; as a result, all remote methods must be declared to throw this
exception.
2. Since it is a remote class, Book must be compiled using the RMI compiler by
invoking the command rmic as below.
Rmic Book
The compiler produces a file named Book_Stub.class, which acts as a proxy for calls
to the methods of BookInterface. The stub contains a reference to the serialized object
and implements all of the remote interfaces that the remote object implements. All
calls to the remote interface go through the stub to the remote object.
3. Remote objects are thus passed by reference. This is depicted in Figure below:
➢ Here , we have a single remote object that is being accessed from two clients.
➢ Both clients maintain a reference to a stub object that points to the remote object that
has a field named a.
➢ Suppose now that Client 1 invokes the method setA with parameter 5.
➢ The call goes through the stub to the remote object and gets executed changing the
field a to 5. any changes made to the state of the object by remote method invocations
are reflected in the original remote object.
➢ If the second client now invokes the method getA, the updated value 5 is returned to it.
NOTE: parameters or return values that are not remote objects are passed by value. Thus,
any changes to the object’s state by the client are reflected only in the client’s copy, not in the
server’s instance.
Before a remote object can be accessed, it must be instantiated and stored in an object
registry, so that clients can obtain its reference. Such a registry is provided in the form of the
class java.rmi.Naming. The method bind is used to register an object and has the following
signature:
The first argument takes the form //host:port/name and is the URL of the object to be registered;
➢ host refers to the machine (remote or local) where the registry is located,
➢ port is the port number on which the registry accepts calls, and
➢ name is a simple string for distinguishing the object from the other objects in the registry.
➢ Both host and port may be omitted if its in localhost and port no is 1099.
The complete code for activating and storing the Book object is shown below.
The Client
A client may get a reference to the remote object it wants to access in one of two ways:
1. It can obtain a reference from the Naming class using the method lookup.
In the following code, the getters of the Book Interface object are called and displayed.
1. To run the system, create two directories, say server and client, and copy the files
BookInterface.java, Book.java, and BookServer.java into server and the file
BookUser.java into client.
2. Then compile the three Java files in server and then invoke the command
rmic Book
7. The client code starts, looks up the object with the name MyBook, calls the object’s
getter methods, and displays the values.
➢ System displays web pages via a browser has to create HTML code.
➢ HTML code displays text, graphics such as images, links that users can click to
move to other web pages, and forms for the user to enter data.
➢ An HTML program can be thought of as containing a header, a body, and a trailer.
➢ The first four lines are usually written as given for any HTML file.
➢ observe words such as html and head that are enclosed between angled brackets (< and
>). They are called tags.
➢ HTML tags usually occur in pairs: start tag that begins an entry and end tag that
signals the entry’s end. For example, the tag <head> begins the header and is ended
by </head>.
➢ The text between the start and end tags is the element content.
➢ In the fifth line we see the tag title, which defines the string that is displayed in the
title bar.
As a sample body, let us consider the following.
➢ The body contains code that determines what gets displayed in the browser’s window.
➢ Some tags may have attributes, which provide additional information.
For example
<span style="color: rgb(0, 0, 255);">
➢ The tag span has its attribute style modified, so that the text will be in blue colour.
➢ Attributes always come in name/value pairs of the form name="value".
➢ They are always specified in the start tag of an HTML element.
➢ The body contains code to display the string An Application in the font Lucida
bright, bolded, italicised, and in blue color.
➢ The last line of the file is : </html> it ends the HTML file
The complete code that allows us to enter some piece of text in the web page is given below.
➢ The tag form begins the specification of a set of elements that allow the user to enter
information.
➢ The action attribute specifies that the information entered by the user is to be
processed by a Java class called ProcessInput.class, which resides in the package
apackage.
➢ The tag <table> begins the creation of a table.
➢ Each row of the table is described using the tag <tr>, and the tag <td> defines a cell in
the table.
➢ <input> tag has two attributes : type and name
• type: which specifies what is the type of input : "text", which means plain text or
"password", which makes the entry unreadable on the screen.
• name: must be given a unique value
➢ a button of type "submit", which when clicked causes the form data to be sent to the
server. The button has the label Process.
There are two primary ways in which form data is encoded by the browser:
1. GET : GET means that form data is to be encoded into a URL
2. POST: POST makes data appear within the message itself.
Server-Side Code
➢ Since we transmitted form data using the POST method, we need to override a
method called doPost.
o This method has two parameters, request and response that respectively
encapsulate the data sent by the client and the response to the client.
➢ The header of the doPost method is given below.
➢ Data sent by the client through the form is retrieved using the request object as
➢ Afterthedataiscapturedandprocessed,theservletcreatesanHTMLpageusing the
response object as below.
➢ The first line states that the data is HTML and the second line begins the HTML code.
Figure 5.1: How servlets and HTML cooperate to serve web pages
➢ When the user types in the URL to access the library system, the log in screen that
asks for the user id and password is displayed on the browser.
➢ If a valid combination is typed in, an appropriate menu is displayed.
➢ What is in the menu depends on whether the user is an ordinary member or a
superuser and whether the terminal is in the library or is outside.
1. The Issue Book command is available only if the user logs in from a terminal in the
library.
2. Commands to place a hold, remove a hold, print transactions, and renew books are
available to members of the library (not superusers) from anywhere.
3. Certain commands are available only to superusers who log in from a library terminal:
these are for returning or deleting books, adding members and books, processing holds,
and saving data to and retrieving data from disk.
Add Book
➢ When the command to add a book is chosen, the system constructs the initial screen to
add a book, which should contain three fields for entering the title, author, and id of
the book, and then display it and enter the Add Bookstate.
➢ By clicking on a button, it should be possible for the user to submit these values to
system.
➢ The system must then call the appropriate method in the Library class to create a
Book object and enter it into the catalog.
➢ The result of the operation is displayed in the Command Completed state
➢ From the Command Completed state, the system must allow the user to add another
book or go back to the menu.
➢ In the Add Book state, the user has the option to cancel the operation and go back to
the main menu.
➢ We need to accept some input (member details or book id) from the user,
access the Library object to invoke one of its methods, and display the
result.
Save Data
➢ When the data is to be written to disk, no further input is required from the user.
➢ The system should carry out the task and print a message about the outcome.
Issue Book
First, a member is allowed to check it out himself/herself. Here the system already has the
user’s member id, so that should not be asked again.
Second, he/she may give the book to a library staff member, who checks out the book for the
member. Here the library staff member needs to input the membered to thesystem followed
by the book id.
➢ After receiving a bookid, the system must attempt to check out the book.
➢ Whether the operation is successful or not, the system enters the Book Id Processed
state. Complexity arises from the fact that any number of books may be checked out.
Thus, after each book is checked out, the system must ask if more books need to be
issued or not.
➢ The system must either go to the Get Book Id state for one more book id or to the
Main Menu state.
➢ As usual, it should be possible to cancel the operation at any time.
Renew Books
➢ The system must list the title and due date of all the books loaned to the member.
➢ For each book, the system must also present a choice to the user to renew the book.
➢ After making the choices, the member clicks a button to send any renew requests to
the system.
➢ For every book renewal request, the system must display the title, the due date
(possibly changed because of renewal), and a message that indicates whether the
renewal request was honoured.
➢ After viewing the results, the member uses a link on the page to navigate to the main
menu.
The state transition diagram is given in Figure below
Structuring the files HTML code for delivery to the browser can be generated in
one of two ways:
1. Embed the HTML code in the servlets. This has the disadvantage of making the
servlets hard to read, but more dynamic code can be produced.
2. Read the HTML files from disk as a string and send the string to the browser.
This is less flexible because the code remains static.
1. Create a separate HTML file for every type of page that needs to be displayed. For
example, create a file for entering the id of the book to be returned, a second file for
displaying the result of returning the book, a third file for inputting the id of the book
to be removed, a fourth one for displaying the result of removing the book, etc.
2. Exploit the commonalities between the commands and create a number of HTML
code fragments, a subset of which can be assembled to form an HTML file suitable
for a specific context.
❖ The first option has the advantage of simplicity. However a rough calculation shows
that at least 28 files are needed.
❖ Although the second option is more involved because of the need to assemble a big
file from several fragments, we find that it presents some advantages over the first.
For example, to change the way the library’s name is displayed in the screens,
every one of the HTML files will need to be updated! We thus opt for the second
choice.
Consider the two commands, one for returning and the other for removing books
➢ In both, the user must be presented with a web page that asks him/her to enter
a book id. We have just one file that displays this page.
➢ However, the servlet that needs to be invoked will change depending on the
context. Therefore, we code the servlet name as below.
➢ For every webpage, the header should display a title that depends on the
context. We maintain just one file for the header. This file has a string TITLE
that stands for the title of the web page. Depending on which page is being
displayed, TITLE is replaced by an appropriate string, which gets displayed in
the title bar.
➢ When a command is completed, we need to display a web page.
➢ we employ just one file, commandCompleted.html, to carry out this task. This
file is adapted, however, in two different ways.
1. The result to be displayed will vary on the command as well as whether the operation
was successful. To take care of this, the file has a string called RESULT
Pseudocode
2. To reduce the number of mouse clicks, the user may be given the option to repeat the
command whose result is displayed by the commandCompleted.html file. For
example
,after completing the Add Book command, we need to give an option to issue the
command once again so that the user can add another book.
<a href="REPLACE_JS">REPLACE_COMMAND</a><br>
How to remember a
user
➢ The system provides the necessary support by means of what are known as sessions,
which are of type HttpSession.
➢ When it receives a request from a browser, the servlet may call the method
getSession() on the HttpServletRequest object to create a session object, or if a
session is already associated with the request, to get a reference to it.
➢ To check if a session is associated with the request and to optionally create one, a
variant of this method getSession(boolean create) may be used.
➢ If the value false is passed to this method and the request has no valid HttpSession,
this method returns null. When a user logs in, the system creates a session object as
below.
session.invalidate();
➢ The following code evaluates to true if the user does not have asession: that is, the
user has not logged in:
request.getSession(false) == null
This command binds value, the object given in the second parameter, to the attribute
specified in name. By setting the second parameter to null, the attribute can be removed.
Configuration
➢ The server runs with the support of Apache Tomcat, which is a servlet container.
➢ A servlet container is a program that supports servlet execution.
➢ The servlets themselves are registered with the servlet container.
➢ URL requests made by a user are converted to specific servlet requests by the servlet
container. The servlet container is responsible for initializing the servlets and
delivering requests made by the client browser to the appropriate servlet.
➢ The directory structure is as in Figure below:
➢ The implementation of the backend classes such as Member, Catalog, etc. is in the
package basicImplementation.
➢ Our implementation requires that the user create an environment variable named
LIBRARY-HOME that has as value the absolute path name of the directory that
houses the HTML files.
➢ The deployment descriptor elements are defined in a file called web.xml. While this
file permits a large number of tags, our use of them is limited to mapping the URLs to
servlets. To understand how this is done, first examine the following lines of XML
code.
➢ Thus when we write code such as URL=login in the HTMLfile, the string
login is mapped to the servlet name LoginServlet.
➢ But the servlet name given by the tag <servlet-name> is just a name that is mapped to
the fully-qualified class name of the servlet as below.
➢ The list of superusers and their passwords is stored in a file named Privileged Users.
➢ The IP addresses of all client machines located in the library are listed in a file named
IPAddresses.
➢ Both files are to be stored in the same directory that has the HTML files.
➢ To run the system, first Tomcat needs to be started and then the library system needs
to be accessed from a browser by typing in the URL of the Tomcat home
concatenated with
/Library.
➢ The file index.html in the library directory is then accessed; this file directs the request
to the servlet Login.
➢ The methods and doPost and doGet are collected into a class named LibraryServlet.
➢ This class has the structure shown in Figure below.
1. One group contains methods that store information about the user. This information
includes the user id, the type of terminal from which the user has logged in, etc. and
are stored in attributes associated with the session object. The methods are
addAttribute, setAttribute, getAttribute, and deleteAllAttributes.
2. Methods to validate users and help assess access rights. The validateSuper
Usermethod checks whether the user is a superuser and validateOrdinary Member does
the same job for ordinary members. The method library Invocation returns true if and
only if the user has logged in from a ter- minal located within the library.
3. The getFilemethod reads an HTML file and returns its contents as a String object.
4. The fourth group of methods are used for handling users who may have invoked a
command without actually logging in. The method notLoggedIn returns true if and
only if the user has not currently logged in. The method noLoginError Message
returns HTML code that displays an error message when a person who has not logged
in attempts to execute a command.
5. The final group of commands deal with processing the request and responding to it.
The doGet message calls doPost, which does some minimal processing needed for all
commands and then calls the abstract runmethod, which individual servlets override.
Execution flow
The URL for the servlet is removebookinitialization; recall that this corresponds to the
class RemoveBookInitialization, so when the link is clicked, the doPost method of that
servlet is invoked. The code for this method is in LibraryServlet and is as follows:
The first line in the method specifies the type of the file for the response object:
whatever is written to the response object is treated as HTML.
The run method is invoked, which is implemented within the subclass. This
method returns HTML code as a String object and is saved in the attribute named
page of the session. This helps in the following way.
o The system always remembers the last page displayed. If the user tries to
login from a different window of the browser, that page is redisplayed.
o It also helps when the user overwrites the current page by visiting some
other site and wants to come back to the library system.
o Finally, the page is written out and gets displayed in the browser.
The code for removing a book begins with the servlet RemoveBook Initialization, whose
run method is given below.
The first three lines in the runmethod check if the user has actually logged in and is
not here via some othermeans.
This can actually occur if the user has two windows connected to the library and
the exit command is issued from one of the two.
If that is indeed the case, the method noLoginErrorMessage() is called. This
method simply generates an HTML page that displays ‘Not logged in’ and supplies
a link to the log in screen.
In the case that the user is actually logged in, the HTML page is assembled. It
includes reading four files: one to begin the HTML page and the other to end it.
In between, a form to enter the book id and a link to cancel the command are inserted.
As a consequence, the browser at the client displays a page that either requires the
user to enter the id of a book that should be removed or click on a link to cancel
the command and return to the main menu.
In the normal course of action, the user would enter a book id and click the button
labelled Enter Book Id. Notice the lines
<form action="GOTO_WITH_BOOKID"
Issuing books
An ordinary member may self-issue a book or may ask a library staff member, a
superuser, to issue the book for himself/herself. In the former case, we need to skip
asking the member’s id and in the latter case, the system must present a screen for entering
the member id.
Like all other commands, the user clicks on a link to issue books; the HTML file
contains the lines
<br></td>
We now discuss how we remember the member for whom the book is to be issued.
The session object can store attributes and that commands such as issuing a book
and placing a hold are always carried out for a specific member.
That member’s id is stored in the attribute currentUserId.
If the session was for an ordinary member, the value for this attribute is the
member’s id itself. Otherwise, when a superuser is logged in, the value changes
depending on the member for whom the command is being carried out; when the
command does not involve a member , the value of this attribute is the empty
string ("").
would be the empty string if the user is a superuser and the logged-in-member’s id
otherwise.
The servlet IssueBookGetMemberId retrieves the id of the member to whom books
should be issued:
If the member id is invalid, the HTML file consists of an error message and a form to
accept the member id. In this case, note that control will come back to the same servlet.
The IssueBookGetBookIdservlet gets the book id from the form, retrieves the value of
the attribute currentUserId to get the member id and calls the issueBook method of
Library.
The result is then used to replace the string RESULT in the commandCompleted
HTML file.
The result of invoking issueBookis stored in the string RESULT as has been the case for other
commands.
Renewing books
The member id needs to be accepted if the user is a superuser; otherwise, that step can
be bypassed.
To allow renewal, the title and due date all of the books checked out to the user must be
displayed.
Also, for each book a checkbox needs to be shown, so the user can check it if he/she
wants the book to berenewed.
The HTML code, stored in the file renewBook.html, for this part of the process is
given below.
The type checkboxdenotes a checkbox control, which the user can click to indicate
that a book should be renewed.
The three strings, TITLE, DUE_DATE, and RENEW are placeholders for the
book title, book id, and the name of the checkbox control. T
The idea is that the above five lines of code will be replicated as many times as the
number of books checkedout.
The list of books must be assembled from two servlets: RenewBooks Initialization
if the user is an ordinary member and RenewBooksGet MemberId if the user is a
superuser.
Since the code to perform this task is a bit lengthy, it is extracted into LibraryServlet.
When the class LibraryServlet is loaded, it reads the files PrivilegedUsers and
IPAddressesand copies the information to main memory.
When a user logs in, we have seen that control goes to the Login servlet.
It assembles the log in screen for display by the browser.
Assume now that the user types in a user id and password and sends them to the
server.
The Indexservlet reads in the user id and password and calls a method named
getMenu in the class MenuBuilder.
This class is responsible for checking the validity of the user and returning the
appropriate menu. The class MenuBuilder itself is not a servlet, so to utilise the
methods of LibraryServlet, it needs the reference to the Indexservlet.
To call some of these methods, MenuBuilder also needs the request object. For
uniformity, we also pass the response object, although it is not currently used.
The method thus has 5 parameters: a reference to the Index servlet, the request and
response objects, and the user-id andpassword.
First, the code checks if the user is a superuser by calling the method validate
SuperUser of LibraryServlet, and if so, the attribute userType is given the value
Privileged.
Otherwise, the LibraryServletclass’s validate OrdinaryMembermethod is called to
see if the user is a member of the library; in that case, the userType attribute is set
as Ordinary.
Also, note the use of the boolean variables privilegedand validated.
In the event of an invalid user- id–password combination, a null value is returned
to the Index servlet, which redisplays the log-in screen with an error message.
With a successful log-in, the method checks whether the terminal used is within
the library premises or outside.
The attribute locationreflects this assessment.
The currentUserIdis set to the user’s id for ordinary users and to the empty string
("") for privileged users.