0% found this document useful (0 votes)
59 views

Module 5-Notes

The document discusses distributed systems and client-server architectures. It defines distributed systems and outlines their advantages and drawbacks. It then describes the basic architecture of client-server systems, including how clients send requests to servers which process the requests and return results. The document focuses on using Java Remote Method Invocation (RMI) to implement client-server systems with distributed objects.

Uploaded by

abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Module 5-Notes

The document discusses distributed systems and client-server architectures. It defines distributed systems and outlines their advantages and drawbacks. It then describes the basic architecture of client-server systems, including how clients send requests to servers which process the requests and return results. The document focuses on using Java Remote Method Invocation (RMI) to implement client-server systems with distributed objects.

Uploaded by

abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Software Architecture and Design Patterns (18CS731)

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

a. It is more economical and efficient to process data at the point of origin.


b. Distributed systems make it easier for users to access and share resources.
c. They also offer higher reliability and availability: failure of a single
computer does not cripple the system as a whole.
d. It is also more cost effective to add more computing power.

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.

Client server system

Distributed systems can be classified into :


1. Peer-to-Peer systems :
Every computer system (or node) in the distributed system runs the same set
of algorithms; they are all equals, in some sense
2. Client-Server systems :
There are two types of nodes: clients and servers. A client machine sends
requests to one or more servers, which process the requests, and return the
results to the client.

Basic Architecture of Client/Server Systems

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 2


Software Architecture and Design Patterns (18CS731)

➢ The server hosts an object-oriented system.


➢ Like any other client/server system, clients send requests to the server, these requests
are processed by the object-oriented system at the server, and the results are returned.
➢ The results are then shown to end-users via the user interface at the clients.

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,

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 3


Software Architecture and Design Patterns (18CS731)

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

This difficulty can be handled in one of two ways:


1. By using object-oriented support software:
The software solves the problem by the use of proxies that receive method calls on
‘remote’ objects, ship these calls, and then collect and return the results to the object that
invoked the call. The client could have a custom-built piece of software that interacts with the
server software. This approach is the basis of Java Remote Method Invocation.

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.

Java Remote Method Invocation


The goal of Java RMI is to support the building of Client/Server systes where the server hosts
an object-oriented system that the client can access programmatically.
The objects at the server maintained for access by the client are termed remote objects.
A client accesses a remote object by getting what is called a remote reference to the
remote object.
After that the client may invoke methods of the object.
The basic idea behind RMI is to employ the proxy design pattern.
Java RMI employs proxies to stand in for remote objects. All operations exported to
remote sites (remote operations) are implemented by the proxy. Proxies are termed
stubs in Java RMI. These stubs are created by the RMI compiler.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 4


Software Architecture and Design Patterns (18CS731)

The set-up is shown in above figure:


When the client calls a remote method, the corresponding method of the proxy object
is invoked. The proxy object then assembles a message that contains the remote
object’s identity, method name, and parameters. This assembly is called marshalling.
In this process, the method call must be represented with enough information so that
the remote site knows the object to be used, the method to be invoked, and the
parameters to be supplied.
➢ When the message is received by it, the server performs demarshalling, whereby the
process is reversed.

Setting up a remote object system is accomplished by the following steps:


1. Define the functionality that must be made available to clients. This is accomplished by
creating remote interfaces.
2. Implement the remote interfaces via remote classes.
3. Create a server that serves the remote objects.
4. Set up the client.

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.

Remote method invocations can fail due to a number of reasons:

a. The remote object may have crashed,


b. the server may have failed, or
c. the communication link between the client and the server may not be operational, etc.

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 5


Software Architecture and Design Patterns (18CS731)

Implementing a Remote Interface

1. The next step is to implement via remote classes.


➢ Parameters to and return values from a remote method may be of primitive type, of
remote type, or of a local type.
➢ All arguments to a remote object and all return values from a remote object must be
serializable. Thus, they must implement the java.io.Serializable interface.
➢ Parameters of non-remote types are passed by copy;
➢ Intuitively, remote objects must somehow be capable of being transmitted over
networks. A convenient way to accomplish this is to extend the class
java.rmi.server.UnicastRemoteObject.

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:

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 6


Software Architecture and Design Patterns (18CS731)

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

Creating the Server

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 7


Software Architecture and Design Patterns (18CS731)

➢ 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 process of creating and binding the name is given below.

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 8


Software Architecture and Design Patterns (18CS731)

2. It can get a reference as a return value from another method call.

In the following code, the getters of the Book Interface object are called and displayed.

Setting up the System

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

3. This command creates the stub file Book_ Stub.class.


4. Copy the client program into client and compile it.
5. Run RMI registry and the server program using the following commands

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 9


Software Architecture and Design Patterns (18CS731)

➢ The first command starts the registry and


➢ The second causes the Book instance to be created and registered with the
name MyBook.

6. Finally, run the client as below from the client directory.

7. The client code starts, looks up the object with the name MyBook, calls the object’s
getter methods, and displays the values.

Implementing an Object-Oriented System on the Web

HTML and Java Servlets

➢ 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 header contains code like the following:

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 10


Software Architecture and Design Patterns (18CS731)

➢ 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

Entering and Processing Data

The complete code that allows us to enter some piece of text in the web page is given below.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 11


Software Architecture and Design Patterns (18CS731)

The code that begins with the line :

<form action="/servlet/apackage.ProcessInput" method="post">

➢ 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

<td><input type="text" name="userInput"></td>

➢ a button of type "submit", which when clicked causes the form data to be sent to the
server. The button has the label Process.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 12


Software Architecture and Design Patterns (18CS731)

<td><input type="submit" value="Process"></td>

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

➢ The server-side code ProcessInput is an example of a servlet, which uses the


request- response paradigm.
➢ Servlets can process data sent using the HTTP protocol via a form.
➢ They can handle multiple requests concurrently.
➢ We create a servlet by extending the class HttpServlet as below.

public class ProcessInput extends HttpServlet {

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

public void doPost(HttpServletRequest request, HttpServletResponse response) throws


IOException, ServletException {

➢ Data sent by the client through the form is retrieved using the request object as

below: String input = request.getParameter("userInput");

➢ Afterthedataiscapturedandprocessed,theservletcreatesanHTMLpageusing the
response object as below.

➢ The first line states that the data is HTML and the second line begins the HTML code.

➢ The complete code for the servlet is given below

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 13


Software Architecture and Design Patterns (18CS731)

Deploying the Library System on the World-Wide Web

Figure 5.1: How servlets and HTML cooperate to serve web pages

Developing User Requirements


First task is to determine the system requirements : Example Library system
1. The user must be able to type in a URL in the browser and connect to the library system.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 14


Software Architecture and Design Patterns (18CS731)

2. Users are classified into two categories:


a. super users :
➢ Superusers are essentially designated library employees, and ordinary
members are the general public who borrow library books. superusers can
execute any command when logged in from a terminal in the library.
b. Ordinary members.
➢ Ordinary members are the general public who borrow library books.
➢ Ordinary members cannot access some ‘privileged commands’.

In particular, the division is as follows:


a. Only superusers can issue the following commands: add a member, add a
book, return a book, remove a book, process holds, save data to disk, and
retrieve data from disk.
b. Ordinary members and super users may invoke the following commands:
issue and renew books, place and remove holds, and print transactions.
c. Every user eventually issues the exit command to terminate his/her session.
3. Some commands can be issued from the library only. These include all of the
commands that only the superuser has access to and the command to issue books.
4. A superuser cannot issue any commands from outside of the library. They can log in,
but the only command choice will be to exit the system.
5. Superusers have special user ids and corresponding password. For regular members,
their library member id will be their user id and their phone number will be the
password.

Logging in and the Initial Menu

Figure below shows the process of logging in to the system.

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 15


Software Architecture and Design Patterns (18CS731)

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

The State transition diagram for adding book is shown below:

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 16


Software Architecture and Design Patterns (18CS731)

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

Add Member, Return Book, Remove Book

➢ 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

State transition diagram for saving 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

A book may be checked out in two different


ways:

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 17


Software Architecture and Design Patterns (18CS731)

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

State transition diagram for issuing books

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 18


Software Architecture and Design Patterns (18CS731)

➢ 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

Design and Implementation

To deploy the system on the web, we need the following:

1. Classes associated with the library


2. Permanent data (created by the save command) that stores information about
the members, books, who borrowed what, holds, etc.
3. HTML files that support a GUI for displaying information on a browser and
collecting data entered by the user. For example, when a book is to be returned, a
screen that asks for the book id should pop up on the browser. This screen will
have a prompt to enter the book id, a space for typing in the same, and a button to
submit the data to the system.
4. A set of files that interface between the GUI ((3) above) and the objects that
actually do the processing ((1) above). Servlets will be used to accomplish this
task

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 19


Software Architecture and Design Patterns (18CS731)

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.

We attempt to combine the two approaches so as to utilize the advantages

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.

First, it reduces the number of files somewhat and

Avoids duplication of files.

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.

Examples of HTML file fragment

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.

<form action="GOTO_WITH_BOOKID" method="post">

➢ By simply changing the string GOTO_WITH_BOOKID in the servlet, we


can use the same HTML file in multiple situations

A similar approach is taken for accepting member ids.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 20


Software Architecture and Design Patterns (18CS731)

➢ 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

<h3> RESULT <br></h3>

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

➢ Servlets typically deal with multiple users.


➢ When a servlet receives data from a browser, it must somehow figure out which user
sent the message, what the user’s privileges are, etc.
➢ Each request from the browser to the server starts a new connection, and once the
request is served, the connection is torn down.
➢ However, typical web transactions involve multiple request–response pairs. This
makes the process of remembering the user associated with a connection somewhat
difficult without extra support from the system.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 21


Software Architecture and Design Patterns (18CS731)

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

HttpSession session = request.getSession();

➢ When the user logs out, the session is removed 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

A session object can be used to store information about the


session.

1. void setAttribute(String name, Object value)

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.

2. Object getAttribute(String name)

The attribute value associated with name is returned.

3. void removeAttribute(String name)

This method deletes the specified attribute from this session.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 22


Software Architecture and Design Patterns (18CS731)

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:

➢ We store the HTML files in a directory named Library, which is a subdirectory of


webapps, which, in turn, is a subdirectory of the home directory of Tomcat.

➢ The servlets are in the package library, which is stored in Library/WEB-INF/classes.

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 23


Software Architecture and Design Patterns (18CS731)

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

Structure of servlets in the web-based library system


➢ A servlet receives data from a browser through a HttpServletRequestobject. This
involves parameter names and their values, IP address of the user, and so on.
For example, when the form to add book is filled and the Add button is clicked,
the servlet’s doPost method is invoked. As we have seen earlier, this method has
two parameters: a request parameter of type HttpServletRequest and a response
parameter of type HttpServletResponse.
➢ Each command is organized as a combination of one to three servlets.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 24


Software Architecture and Design Patterns (18CS731)

➢ The methods and doPost and doGet are collected into a class named LibraryServlet.
➢ This class has the structure shown in Figure below.

Most of the methods of LibraryServlet fall into one of five categories:

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 25


Software Architecture and Design Patterns (18CS731)

Execution flow

Processing a request sometimes involves simply generating an HTML page,


The course of the execution of the command is shown in Figurebelow:

The URL associated with the text is as below:

<a href="removebookinitialization">Remove book</a>

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:

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException
{
response.setContentType("text/html"); String page = run(request, response); if (!notLoggedIn(requ
{
setAttribute(request, "page", page);
}
response.getWriter().println(page);
}

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 26


Software Architecture and Design Patterns (18CS731)

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 27


Software Architecture and Design Patterns (18CS731)

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.

The HTML code for entering the book id is given below.

<form action="GOTO_WITH_BOOKID" method="post">


<table>
<tr>
<td align="right">Id:</td>
<td><input type="text" name="bookId"></td>
</tr>
<td><br><input type="submit" value="Enter Book Id"></td>
</tr>
</table>
</form>

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"

method="post"> in the HTML file and the line

htmlFile = htmlFile.replace("GOTO_WITH_BOOKID", "removebook");

in the servlet. The place holder GOTO_WITH_BOOKID is replaced by the URL


removebook. Therefore, when the user submits the form, the RemoveBook servlet is
initiated.

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

<td valign="top" width="160">

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 28


Software Architecture and Design Patterns (18CS731)

<a href="issuebookinitialization">Issue book</a>

<br></td>

The click on Issue bookcauses the servlet IssueBookInitializationto execute.


This servlet checks if the user is a superuser, and if so, a screen to accept the
member id is displayed; otherwise, the member to whom the book should be
issued is known and a screen to accept a book id is displayed.
The code is given below.

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 ("").

From the above discussion, clearly,

String memberId = getAttribute(request, "currentUserId");

would be the empty string if the user is a superuser and the logged-in-member’s id

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 29


Software Architecture and Design Patterns (18CS731)

otherwise.
The servlet IssueBookGetMemberId retrieves the id of the member to whom books
should be issued:

String memberId = request.getParameter("memberId");

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 30


Software Architecture and Design Patterns (18CS731)

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.

The code, given below,

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 31


Software Architecture and Design Patterns (18CS731)

First gets an iterator for the books checked out.


The HTML file is built up from the file renewBook.html
The strings TITLEand DUE_DATEare respectively replaced by the book’s title
and due date.
A unique name for the checkbox is generated by replacing the string RENEWby
the concatenation of renewand a counter that is incremented once per loop iteration.
The RenewBooksservlet must somehow discover the book id and other details of
the books that are to be renewed.
Also, we list the title and due date (possibly changed) of each book to be renewed
and a status message that says whether the book was renewed or not.
This demands that we remember the details of all the books in the order we
displayed them.
These are stored in the attributes bookId, title, and dueDate, each concatenated with
the value of the counter.
Also, the number of books displayed is also stored in the attribute numberOfBooks.

Logging in and logging out

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

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 32


Software Architecture and Design Patterns (18CS731)

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.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 33


Software Architecture and Design Patterns (18CS731)

The final step is to return the appropriate menu.


This is done bythe method getMenu that has three parameters.
The code assembles the HTML page by reading from four different files in
addition to the files for beginning and ending the page.
These meet the requirements we set forth under ‘Developing User Requirements’.
If the user has logged in from the library, the Issue Book command is inserted into
the menu.
For privileged users, commands such as Add and Remove Book are inserted.
Ordinary members always get to issue commands such as placing a hold and
removing a hold.
These commands are also available to superusers who log in from a library terminal.
Finally, the exit command is available to all users from anywhere.

Prof. SHIVAKUMAR, CSE DEPT., KNSIT Page : 34

You might also like