Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
CHECK GRAMMARTHROUGHOUT DOC. + OTHER INFO BELOW.
RELIABLE, SECURE, ON-LINE BOOKSTORE IMPLEMENTATION VIA
JAVA RMI AND TOMCAT
Wenping Peng
PROJECT
Submitted in Partial satisfaction of
the requirements for the degree of
MASTER OF SCIENCE
in
COMPUTER SCIENCE
at
CALIFORNIA STATE UNIVERSITY, SACRAMENTO
FALL
2003
ii
RELIABLE, SECURE, ON-LINE BOOKSTORE IMPLEMENTATION VIA
JAVA RMI AND TOMCAT
A Project
by
Wenping Peng
Approved by:
______________________________________________________, Professor
Dr. Isaac Ghansah
Date: __________________
______________________________________________________, Second Reader
Dr. Richard Smith
Date: __________________
iii
Student: Wenping Peng
I certify that this student has met the requirements for format contained in the University
format manual, and that this Project is suitable for shelving in the Library and credit is to
be awarded for the Project.
__________________________________________________
Dr. Cui Zhang, Graduate Coordinator
Department of Computer Science
__________________
Date
4
Abstract
Of
RELIABLE, SECURE ON-LINE BOOKSTORE IMPLEMENTATION VIA JAVA
RMI AND TOMCAT
by
Wenping Peng
During the recent e-commerce and e-business boom, building web-based applications has
become more and more demanding in the marketplace. Many companies and individuals
spend tremendous time and effort in building efficient Internet applications and
implementing many e-commerce features such as search engines, on-line ordering, secure
transactions, and password protection to be more competitive.
The goal of this project is to simulate a real on-line bookstore and build a reliable, secure
web application of an on-line book ordering system, using Tomcat as the web server.
Tomcat provides support for Java Servlet and JSP technologies. It has become the most
popular web server of Internet services with many advantages such as open source,
efficiency, security, and multi-platform. This project was written in Java and JavaScript.
Java was chosen in this project as the programming language because it’s object-oriented
nature is perfect for server-side programming. Java also provides a huge number of builtin network capabilities that make it easy to develop Internet-based and web-based
applications. Java RMI (Remote Method Invocation) technology was implemented in
5
this project for multiple server and client communication. All the application servers:
Primary name server, Replication name server, Authentication Server, Book Server,
Credit Card server, and Book Administrator Server can be located on different machines,
they will work as a whole to provide services to the clients through the Internet.
__________________________, Committee Chair
__________________________, Date
6
ACKNOWLEDGMENTS
I would like to thank my project advisers Dr Ghansah, and my project second reader: Dr.
Dick Smith for their genuine advice and help.
I would also like to thank all the professors in CSUS in computer science. Their
dedicated work and knowledge made it possible for me to get my degree in computer
science.
7
TABLE OF CONTENTS
List Of Figures................................................................................................................... 9
CHAPTER 1: INTRODUCTION AND BACKGROUND
1.1 Motivation and Background .................................................................................... 10
1.2 Purpose....................................................................................................................... 11
1.3 Brief application Description ................................................................................... 11
1.4 Document Organization ........................................................................................... 12
CHAPTER 2: TECHNOLOGY IMPLEMENTATION
2.1 Java RMI ................................................................................................................. 14
2.2 Java Servlet................................................................................................................ 17
CHAPTER 3: PROJECT ARCHITECTURAL DESIGN
3.1 The Top-Level Schema. ............................................................................................ 20
3.2 Client Server Communication. ................................................................................ 22
3.3 Reliability Consideration: Replicate name servers. ............................................... 24
3.4 Security Consideration: Password Encryption. ..................................................... 25
3.5 Implementation environment and languages ......................................................... 26
CHAPTER 4: PROJECT FUNCTION DESIGN
4.1 Logical flow for user login ........................................................................................ 30
4.2 Logical flow of book searching services .................................................................. 31
4.3 Logical flow for purchase book ............................................................................... 33
4.4 Logical flow for book Administrator ...................................................................... 36
CHAPTER 5: SYSTEM CONFIGURATION
5.1 Install Java JDK Package ........................................................................................ 40
8
5.2 Install and Configure Tomcat .................................................................................. 40
5.3 Install Servlet............................................................................................................. 42
5.4 Create Application Directory................................................................................... 42
CHAPTER 6: RESULTS AND CONCLUSION
6.1 Summary and Results ............................................................................................. 46
6.2 Problems encountered and solutions ....................................................................... 46
6.3 Other Chanlleges ....................................................................................................... 47
6.4 Future Enhancements ............................................................................................... 49
BIBLIOGRAPHY .......................................................................................................... 50
APPENDIX A USER MANUAL ................................................................................... 51
APPENDIX B LIST OF JAVA PROGRAMS.............................................................. 59
APPENDIX C LIST OF JSP PROGRAMS ............................................................... 107
9
LIST OF FIGURES
Figure 1 Connections made when client uses RMI ...................................................... 14
Figure 2: Client to servlet process flow ......................................................................... 18
Figure 3 Application Structure Chart........................................................................... 20
Figure 4 Client server model diagram .......................................................................... 23
Figure 5 JSP page work flow ......................................................................................... 29
Figure 6 Logical View of User login .............................................................................. 30
Figure 7 User login interface .......................................................................................... 31
Figure 8 Logical View of book searching ...................................................................... 32
Figure 9 Book searching interface ................................................................................. 33
Figure 10 Logical View of credit card services ........................................................... 34
Figure 11 Interface of book purchasing services ......................................................... 35
Figure 12 Interface of book purchasing confirmation................................................. 35
Figure 13 Logical View of Book Administration ......................................................... 36
Figure 14 Interface of book Administration ................................................................. 37
Figure 15 User interface of entering edit information ................................................. 38
Figure 16 User interface of book edited confirmation ................................................. 39
Figure 17 Tomcat web application directory structure............................................... 42
10
CHAPTER 1: INTRODUCTION
1.1 Motivation and Background
The recent e-commerce and e-business boom has created a great demand for on-line
applications. This has led to the development of many very sophisticated web-based
applications, providing many e-commerce features such as: Search engines, On-line
ordering, secure transactions, and Password protection. The effectiveness and efficiency
of the web-based application is dependent on the development and implementation of
these features, which will provide the competitive edge in the current market place.
E-Commerce has provided an opportunity for many companies to find more cost
effective ways of conducting their existing business and attracting new business. The
companies are now able to conduct real-time secure transactions on-line, generating more
income with lower costs, and promoting their products on-line to attract new customers.
E-Commerce also provides new and exciting opportunities to reach the global market on
a real-time basis 24 hours a day and is available to millions of potential customers across
the globe. Business analysts across the world are now predicting that by 2005, nearly one
billion people worldwide will be shopping on-line, spending more than $5 trillion. The
increasing needs for efficient web based applications and the challenges involved in
building a powerful web application, was the motivation for this project.
1.2 Purpose
11
The purpose of the project is to design and build a web-based on-line application for a
bookstore with multiple server and client communication, implementing new web
technologies such as Tomcat, Java RMI and Java Servlet, which are very popular in
network application development.
This application simulates a real on-line bookstore, like a minor version of Amazon.com.
The main development tools used in this project are the following:
The web server in this project is Tomcat.
The programming language is Java. The multiple server and client
communication feature will be implemented via Java RMI and Java servlet.
The web interface will be written in JSP.
The on-line bookstore is built to be a secure, reliable and flexible web application. It
applies replications to improve the application’s reliability and applies encryption to
enhance network security.
1.3 Brief Application Introduction
On-line bookstore is a web-based application that handles users’ general requests on line
and provides services ranging from book searching, book purchasing to book inventory
updating on line through different servers. The servers can be located on different
computers.
12
The on-line bookstore’s functionalities include the following:
1) Verify the user/administrator’s login by the Authentication server.
2) Allow users to search for books on line by book id, book name, or book author through
Bookshop Server.
3) Allow users to purchase books on-line by using their credit card information through
Credit Card Server.
4) Allow book administrators to edit book inventory information on line through Book
Admin Server.
5) Name server is replicated to increase the reliability and availability of this application.
1.4 Document Organization
The rest of this document is organized as follows:
Chapter 2 - Discusses the technologies: Java RMI and Java Servlet implemented
in this project for network communication.
Chapter 3 - Describes the high-level architectural design of this project, explains
the structure and functionalities of this application and the reasons for choosing
these software and development tools.
Chapter 4 - Discusses the functional design and describes all the possible data
flows with page interface design in this project.
Chapters 5 - Introduces the system setup, software installation and configurations.
Chapter 6 - Summarizes the results, conclusion, challenges and future
enhancement work of this project.
13
APPENDIX A – User Manual, Program lists and Test cases.
APPENDIX B – List of Java Programs.
APPENDIX C – List of JSP Programs
14
CHAPTER 2: TECHNOLOGIES IMPLEMENTATION
Java RMI and Java Servlet are the main technologies implemented in this application for
network communication. This chapter talks about these two implementations in detail.
2.1 Java RMI
Introduction
Java RMI technology was implemented in this project for client-server communication.
RMI (Remote method invocation) allows applications call object methods located
remotely, sharing resources and processing load across systems. RMI allows any Java
object type to be used as parameter. Remote Method Invocation (RMI) facilitates object
function calls between Java Virtual Machines (JVMs) which can be located on separate
computers.
RMI
REGISTRY
RMI
SERVICE
1
2
CLIENT
WEB SERVER
3
Figure 1: Connections made when client uses RMI
15
Figure 1 shows the connections made by the client when using Java RMI, The client must
contact to RMI registry, and request the name of the service. This part must come before
figure. Do it for all figures.
1. The client calls the RMI service and processes the response.
2. The client calls the RMI service and processes the response.
3. The Client sends the response to web server and displays the response.
Steps for creating Java RMI
1) Define the remote interface.
The interface must extend the java.rmi.Remote and all methods must be declared to
throw java.rmi.RemoteException . It specifies the characteristics of the methods
provided by the server that are visible to its clients.
For example, in this project, the nameServer.java is the interface of name server.
2). Define the remote object implementation.
Remove all periods after close parenthesis in entire doc.
Write the implementation of the interface services. The class must be a subclass of
(extend) java.rmi.server.UnicastRemoteObject and must implement the remote interface.
The class is also required to define the constructor for the remote object and implement
the methods that can be invoked remotely. For example, nameServerImpl.java should
implement nameServer.java. This implementation will include a static main method to
make this class a complete application. It creates a single instance of remote objects and
registers the remote objects with the RMI registry.
16
3). Compile the interface and remote object implementation.
javac nameServer.java
javac nameServerImpl.java
4). Generate the skeletons and stubs.
rmic nameServerImpl
The stubs and skeletons are generated by the RMI’s rmic compiler, In this case,
it will generate nameServerImpl_Skel.class and nameServerImpl_Stub.class
The stubs and skeletons are interface between the application layer and the rest
of the system. It transmits data to the remote reference layer.
They communicate with each other through the transport layer by marshalling
and unmarshalling parameters between client and the remote objects.
5). Write client
Developing a client that uses the remote interface that calls the services defined in the
implementation. In this project, a helper class ConnectNS.java was created to connect to
the name server on behalf of other application servers. All the other application server or
servlet need to be a client when it registers to name server or get server name. For
example, AuthenServerImpl.java will be the client when it register to name server.
6). Start Rmiregistry
Before start any server, rmiregistry need to be started in a new shell command window
and left running... (UNIX and Windows)
rmiregistry <port-number>
On UNIX, a port number can be ranging from 5000 and 32767; On Windows, the default
port is 1099.
17
7). Start the server and client application
In a new shell command window, run the server application:
java nameServerImpl
and in anther new shell command window, run the client application:
java AuthenServerImpl 4998
The messages will be displayed in the shell screen and indicated that the name server and
client is running successfully.
2.2 Java Servlet
Introduction
Java Servlet technology provides web developers with a simple, consistent mechanism
for extending the functionality of a web server and for accessing existing business
systems. Servlets are precompiled Java programs that are executed on the server side.
Servlets are the Java platform technology of choice for extending and enhancing web
servers. Java servlet have made many web applications possible. It provides a
component-based, platform-independent method for building web-based applications,
without the performance limitations of CGI programs. And unlike proprietary server
extension mechanisms (such as the Netscape Server API or Apache modules), servlets
are server and platform independent.
Servlets have access to the entire Java family, including the JDBC API to access
enterprise databases. Servlets can also access a library of HTTP-specific calls and receive
all the benefits of the mature Java language, including portability, performance,
18
reusability, and crash protection. In recent web development, servlets are a popular
choice for building interactive web applications.
Figure 2: client to servlet process flow
Client to servlet process
Figure 2 shows the process flow when servlet handles requests from client. Servlet can
user client input passed by an HTML form and return response. It dynamically builds a
HTML document based on the client’s request. Servlet is written in Java, hence it has all
the advantages of java programming language: platform independent, object oriented,
network communication and multithreaded features etc.
Servlets/JSP require a Container, and Apache Tomcat is the reference implementation of
the Servlet/JSP Specs. That’s one reason why Tomcat was chosen to be the JSP and
servlet container in this application. When properly installed and configured, Tomcat will
handle servlet requests at port 8080. Servlet can be accessed at
http://localhost:8080/BS/servlet/servletexamples.
Servlet Methods
Servlet interacts between client and server. It has some basic methods such as:
doGet, if the servlet supports HTTP GET requests
19
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
init and destroy, to manage resources that are held for
When Servlet building a dynamic web page according to the response??, it will get a
PrintWriter associated with the webserver’s output stream and write response data via
this PrintWriter with all necessary the HTML formats.
20
CHAPTER 3 APPLICATION ARCHITECTURAL DESIGN
LOGIN PASSWORD GOES TO jsp IN THE CLEAR. IT MUST BE ENCRYPTED TO
PROVIDE PROPER SECURITY.
This chapter discusses the high-level architectural design of this application, address the
design logic and functionalities of each server, and explain the client-server model which
is the fundamental of network communication.
3.1 The Top-Level Schema.
Book Store Client
(login.jsp)
login
Get Service
Authentication
Server
( Decrypt)
Register
Primary
Name
Server
Authentication Servlet
Secret Key Encrypt
Administrator
Login
Get server name
User
Bookshop Servlet
Get Service
Book Server
(Search books)
Register
Get Server Name
Payment
Credit Card Servlet
Credit card
Get Service server
Register
Get Server Name
Book Admin Servlet
Administration
Get Service Server
Get Server Name
Figure 3 Application Structure Chart
Register
Replicate
Name
Server
21
Figure 3 above demonstrates the architectural design of the bookstore application. This
Application is composed of six servers. The purpose and the data flow of each server is
described as follows:
1). Name Server: primary name server and replicated name server
All the application servers (Authentication Server, Book Server, Credit Card Server,
Book Administrator Server) should register themselves to the name server before they
can be up and running and provide services. The name server stores all the physical
addresses of other running servers and provides the server’s name when requested. Name
server was replicated to increase the availability to the clients. (for detailed explanation of
replication, please refer to section 3.3 “Reliability Consideration”).
2). Authentication Server
The purpose of Authentication server is to verify user/administrator login information.
Authentication servlet forwards the login request from JSP page and connects to name
server to find out the Authentication server’s address and then connects to the
Authentication server to get the login verification.
3). Book Server
The purpose of Book Server is to provide the user ability to search for books by different
criteria. Bookshop servlet first captures the search criteria and then connects to name
server to find the Bookshop server’s address and then connects to the Bookshop server to
get the search result.
22
4). Credit Card Server
The purpose of Credit Card Server is to facilitate the application to process the payment
for user’s on-line book purchases. Creditcard servlet first captures all the purchase
information and then connects to name server to find the credit card server name and then
connects to the Credit card Server to put charges into customer’s credit card balance.
5). Book Administration Server
The purpose of Book Administration Server is to provide the administrator the ability to
edit the book inventory on-line. BookAdmin servlet first connects to name server to find
the BookAdmin server name and then connects to the Book Administration Server to
process client’s “Edit”, “Add” or “Delete” request.
Having considered that the client-server model was the main concept of network
communication implemented in the architectural design.?? We will talk about clientserver communications in detail.
3.2 Client Server Communication
3.2.1 Introduction
Multiple client/server communication within one web application is very common in web
development. For example, some on-line shops take advantage of other on-line services
such as a Payment Service Provider helps a small e-business offering their customers the
ability to conveniently purchase goods and services directly from a small on-line shop.
23
Using a credit card payment process, transactions will have security protection and are
completed online in seconds, which a small on-line shop cannot provide on its own.
3.2.2 Client Server Model
Typically, a client sends a request to a server, and the server returns a response to the
client. Client/server describes the relationship between two computer programs in which
one program, the client, makes a service request from another program, the server, which
fulfills the request. In a network, the client/server model provides a convenient way to
interconnect programs that are distributed efficiently across different locations. Computer
transactions using the client/server model are very common. The functionality of this
model, can be demonstrated by the following (figure #?)diagram:
Figure 4 Client server model diagram
Information can pass in either or both directions between a client and a server.
The client/server model has become one of the central ideas of network computing. Most
business applications being written today use the client/server model. In the usual
24
client/server model, one server, sometimes called a daemon, is activated and awaits client
requests. Typically, multiple client programs share the services of a common server
program. Both client programs and server programs are often part of a larger program or
application relative to the Internet. For example, the web browser is a client program that
requests services (the sending of Web pages or files) from the web server (which
technically is called a Hypertext Transport Protocol or HTTP server) in another computer
somewhere on the Internet.
3.2.3 Client/Server Model Concept implementation in the bookstore project
The web is an example of distributed system where web servers act as resource
managers. In on-line bookstore application, Client/Server Model is very important
concept for network communication. With users searching books on-line, the client
program in local computer forwards the request to the Book Server program. Book
Server processes the request and sends the results back to the client in local computer,
which displays the information on the web. Book server can be both server and client.
When book server registers itself to name server, name server is the server and book
server is the client. When the user search for books through book server, Web browser is
the client and book server is the server.
3.3 Reliability Consideration: Replicate Name Servers
25
In complex network environments, performance and high availability is the greatest
concern. Replication has the potential to improve both availability and performance and
therefore this methodology was incorporated in design of this project.
Since all the communication in this application relies on name server, if the name server
failed, the whole application will not be able to function, To overcome this problem, we
designed two name servers in this project: Primary name server and replicate name
server. Primary name servers store host name and IP address information, and the
replicate name server replicate this information. Both servers will provide the same
services and either server can start first. The client will connect to primary name server
first. If the connection fails, the client will be able to connect to replicate name server for
the same service. The service to the user will not be interrupted and therefore they will
not be aware of which server provided the service as long as one of the name servers is
functional. Replicate name server is to eliminate the single point of failure for name
servers. It will provide more fault tolerance for the whole application.
3.4 Security Consideration: Password Encryption.
Introduction
For security reason, we rely on encryption on the Internet more than ever before. For
shopping, paying bills, banking online, and many other purposes, it's (it is) important that
the Internet transactions remain as secure as possible. Encryption is an especially popular
and effective technique for maintaining Internet security. To protect sensitive or
confidential information on both server and client's computer, the data should remain
confidential (despite wiretapping).
26
Encryption is extremely important for passwords. Sending an unencrypted password
across the network gives an open invitation to hackers. For password protection, the
sender encrypts the password before it sends out; the recipient decrypts data and recovers
the content. Storage at both ends, and the transmission between, is all fully encrypted.
With the encryption, the typical login scenario will be: before storing the data, a one-way
hash of the password is created and transferred into encrypted format and stored into the
database, When the user logs in again, the password hash is created in this session and is
compared to the one stored in the database. The user can successfully login if both values
are equal.
Encryption implementation in the bookstore project
In this project, In order to implement the encryption algorithm, CEncrypt.java was
created. This program uses One-way hash encryption method to protect the users’
password, which will use a single secret key to encrypt data. The Authenservlet class
capture the user’s login name and password, it convert user’s password into another
string by Cencrypt class and send the value to the Authentication server to evaluate the
password.
3.5 Implementation Environment and Languages (Which and why)
This section discusses the software tools and environment chosen to implement the
application.
A) Tomcat as Web Server
27
Tomcat is an open-source project, which provides the official reference implementation
of the Java Server Pages (JSP) and Java Servlets technologies. Users can create JSP
codes or java servlets. HTML or JSP web pages will be able to reference these JSP and
servlets through their web locations. A project under Tomcat can be deployed
(Encapsulated in a container) to be a web application. The official website for tomcat is at
http://jakarta.apache.org/tomcat
Tomcat was selected for this project for the following reasons:
Tomcat can be used as a small stand-alone web server for web sites to handle web
page requests and servlet requests.
Tomcat provides an environment for Java-based dynamic web content; in other
words, a container for servlets.
Tomcat is free software available for download from the Internet. It is small and
easy to be installed.
Tomcat has a large active user community and therefore its easy to get help
online.
Possibility for free upgrades in the future.
B) Java as the programming language
Java is a programming language expressly designed for use in the distributed
environment of the Internet. Java was selected for this project for the following reasons:
Java's object-oriented nature and native network protocol handlers make it well
suited for the web, especially for developing web applications.
28
Java can be combined with Java servlets. Java servlets are extensions to a server,
usually an HTTP (web) server, that allows developers to create custom dynamic
applications, which is the method implemented in this application.
Java can be used to create complete applications that may run on a single
computer or be distributed among servers and clients in the network.
C) JSP and servlet for the web page.
Web pages are the start point of web application, there are two types of web pages: static
and dynamic contect. JSP is a simplified, fast way to create dynamic web content. It is
HTML or XML pages with embedded Java Code or Java Beans. A JSP file is complied to
Java Servlet automatically by the Servlet container, then cached under tomcat work
directory.
JavaScript technology is an extension of the Java Servlet technology. Servlets are
platform-independent, 100% pure Java server-side modules that can be used to extend the
capabilities of a web server with minimal overhead, maintenance, and support. Together,
JSP and servlets technology provides an attractive type of dynamic web scripting
/programming that offers platform independence, enhanced performance, separation of
logic from display, ease of administration, extensibility into the enterprise and most
importantly, easy to use and it’s compatible with Java. These are the reasons why it was
selected for this project.
29
Figure 5 JSP page work flow
Figure 5 shows how JSP pages works. The client send it’s request in JSP source from
web browser to Web application server, Web application server process the request of
JSP or servlet and dynamically build the response page and send to web browser again.
30
CHAPTER 4: PROJECT FUNCTIONAL DESIGN
The purpose of this chapter is to further clarify and expand the High-Level design to
produce a robust set of detail functional design specifications for each possible data flow
and web interfaces implemented in this application.
4.1 Logical flow for user login
4.1.1 Diagram for user login (specify fig?? REPEAT THROUGHOUT DOC)
User login
Find AuthenServer
Register self
Authentication
Servlet
(check login)
Name
Servers
Register Service
Authentication
Server
NO
Yes
Login
failure
Page
(return to
login)
Bookpage.jsp
(send request)
Figure 6 Logical View of User login
4.1.2 Description of data flow
31
Users access login.jsp page, enter login name and password and click submit;
Servlet capture the login information and pass it to the Authentication Server.
Authentication Server processes the login content and responds with login result.
If login is successful, user will be directed to the Bookpage.jsp.
If login fails, user will be directed to the login_user.jsp page again.
4.1.3 User interface for login is as below:
Figure 7 User login interface
4.2 Logical flow of book searching services:
4.2.1 Diagram for book searching:
32
Bookpage.jsp
(send request)
BookShop Servlet
(pass the request)
BookShop
Server
(process the request)
Find Book Server
Name
Server
Register Services
Response from
Servlet
(BookResult)
If want to purchase
Credit Card.jsp
Figure 8 Logical View of Book Searching
4.2.2 Description of data flow
User enter search criteria through Bookpage.jsp and send it to the servlet.
33
BookShop Servlet captures the search criteria and passes it to the Bookshop
Server.
Bookshop Server processes the search condition and responds with book details.
User can click on “Go Back” button to do another search or click on “Purchase”
button to continue other actions.
4.2.3 User interface for book searching is as below:
Figure 9 Book searching interface
4.3 Logical flow for book purchase
4.3.1 Diagram for purchasing books with credit card:
34
Credit Card.jsp
(send request)
Credit Card Servlet
(pass the request)
Response Credit Server Name
Name
Server
Credit Card
Server
(process the request)
Register Credit Services
Response from
Servlet
(Purchase detail)
Thank you page or
Purchase more
Figure 10 Logical View of credit card services
4.3.2 Description of data flow
Order.jsp sends book order to creditcardservlet.
CreditcardServlet captures the order and passes it to the Credit card Server.
Creditcard Server processes the purchase information and responds with purchase
confirmation.
35
4.3.3 User interface for book purchase page:
Figure 11 Interface of book purchasing services
If the purchase is executed successfully, the user will get a confirmation as below:
Figure 12 Interface of book purchasing confirmation
36
4.4 Logical flow for book Administrator
4.4.1 Logical flow for book administration:
Login.jsp
(Admin
login )
Find AuthenServer
Authentication
Servlet
login)
Register (check
itself
Name
Server
Authentication
Server
NO
Login
failure
Page
(return)
Register Service
Yes
Bookadmin.jsp
(send request)
Bookadmin Servlet
(send request)
Name
Server
Bookadmin Server
(process request)
Figure 13 Logical View of Book Administration
37
4.4.2 Description of data flow
BookAdminServlet dynamically builds an administration page showing all the
book information available.
User can edit, add, delete books through the BookAdminServlet page.
Update.jsp page will allow the user to enter new or edit book information.
BookAdminupdate servlet will send the edit information to Admin Server to
process the request.
4.4.3 User interface for book administration
Figure 14 Interface of book Administration
In the above screenshot of the book administration page, if the user clicks on “EDIT” or
“ADD”, the following page will display and allow users to enter information for adding
or editing.
38
Figure 15 User interface for entering edit information
In the above screenshot, user can fill out the edited information and click on Edit button,
the edit information will be sent to the server, If the edit action executed successfully, the
following page will be displayed:
39
Figure 16 User interface of book edited confirmation
Figure 16 show the confirmation that the user has successfully edited the book
information.
40
CHAPTER 5 SYSTEM CONFIGURATION
System configuration takes an important role at the beginning of this application’s
development. This chapter describes all the necessary software installation and
configuration in detail.
5.1 Install Java JDK Package
In this project, Java SDK Standard Edition 1.3.1_09 was installed as development
language from the java sun website. After download the Java SDK package, set the
CLASSPATH and PATH environment variable in the development machine.
To Test if java is installed correctly, make sure that both "java -version" and "javac help" will give a result.
5.2 Install and Configure Tomcat
Tomcat 4.0.6 was installed as the web server which implements Servlet 2.3 and
JSP 1.2 specifications. The main steps to install and configure Tomcat are as
follows:
5.2.1 Download Tomcat software package from http://jakarta.apache.org/builds/jakartatomcat-4.0/release/ and unpack the zip file of Tomcat version 4.0.6.
5.2.2 Enable the ROOT context. Edit \\install_dir\conf\server.xml and uncomment this
line: <Context path="" docBase="ROOT" debug="0"/>.
41
5.2.3 Enable the invoker servlet. Go to \\install_dir\conf\web.xml and uncomment the
servlet-mapping element that maps the invoker servlet to /servlet/*.
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
5.2.4 Turn on servlet reloading. Edit \\install_dir\conf\server.xml and add a
DefaultContext subelement to the main Service element and supply true for the
reloadable attribute.
<DefaultContext reloadable="true"/>
It will allow Tomcat server to detect any changes happened to the servlet classes.
5.2.5 Set the JAVA_HOME environment variable. C:\jdk1.3.1_09
5.2.6 Set the CATALINA_HOME environment variable to refer to the top-level
Tomcat installation directory. C:\tomcat_4.0.6
5.2.7 Start Tomcat: Run the tomcat server from \\install_dir\bin\startup.bat
The following messages will be displayed in the command line window which
shows that tomcat is running in the background:
Starting service Tomcat-Standalone
Apache Tomcat/4.0.6
Starting service Tomcat-Apache
Apache Tomcat/4.0.6
5.2.8 Create JavaScript pages and put the files under \\install_dir\webapps\ROOT
folder, access the page from the browser at http://localhost:8080/filename. If the
42
new page can be viewed from above website, it means tomcat are installed
correctly.
5.3 Install Servlet
With Tomcat as the web server, the servlet package servlet.jar should be installed at the
location of \\Tomcat_install_dir\common\lib\servlet.jar. Also add the current
development directory where servlet classes located into the CLASSPATH environment
variable. When properly installed and configured, Tomcat will handle servlet requests at
port 8080. For example: http://localhost:8080/BS/servlet/AdminServlet1
5.4 Create Application Directories
5.4.1 Introduction of the directory structure:
Figure 17 Tomcat web application directory structure
43
Figure 17 shows the directory structure of Tomcat. Under the Tomcat install directory,
everything is relative to $CATALINA_HOME directory.
The folders under C:\Tomcat4.0.6\ are:
/bin – Startup.bat /shutdown.bat scripts
/conf - Server.xml, Web.xml – main tomcat configuration file
/common – common class and jar files used by Tomcat and web applications (include
JDBC drivers)
/server – class and jar files used by Tomcat internally
/shared – class and jar files for all web applications
/webapps – where web applications are located.
the new web application directory is created under the webapps folder. All the JSP,
servlet, java class will be under the new application folder.
5.4.2. Create BS (Book Store) directory structure under C:\Tomcat4.0.6\webapps\:
/BS
/BS/WEB-INF
/BS/WEB-INF/classes
/BS/WEB-INF/lib
5.4.3. Add BS application to Tomcat:
This is the root directory of the web application.
All JSP and HTML files are stored here.
This directory contains all resources related to
the application that are not in the document root
of the application. This is where the web
application deployment descriptor (web.xml) is
located.
This directory is where servlets and all other
utility classes are located.
This directory contains Java Archive files that
the web application depends upon. For example,
this is where a JAR file should be placed
containing a JDBC driver.
44
In order to let Tomcat know where the new application is, edit server.xml file and add the
following entries:
<Context path="/BS" docBase="BS" debug="9" reloadable="true" >
<Loader checkInterval="3"/>
<Logger className="org.apache.catalina.logger.SystemOutLogger" timestamp="true"/>
</Context>
The above specification means that an application called “BS” is added, it’s rooted in
C:\tomcat4.0.6\webapps\BS. It will give log messages at debug level '9' and the servlets
are re-loadable. It also specifies the reload interval is 3 seconds and also any logging
should go to the console. Remember to restart Tomcat to make the changes valid.
5.4.4. Add the servlet to server.
To make Java servlets work requires the knowledge of servers and servlet containers.
First add C:\Tomcat4.0.6\common\lib\servlet.jar to the CLASSPATH, then put the
servlet classes created for this application under: C:\Tomcat4.0.6\webapps\BS\WEBINF\classes\ and browse to http://<<hostname>>/BS/servlet/myservlet to find the servlet.
To make this servlet available to calls we need to give the servlet a name and then map
URL paths and/or extensions to the servlet. This is accomplished by editing 'deployment
descriptor'. The deployment descriptor is an XML file that lives in the WEB-INF
directory in this application called web.xml. We can specify a name for the servlet and
then browse to the servlet by name:
<web-app>...
<servlet>
<servlet-name>Simple</servlet-name>
45
<servlet-class>new_servlet</servlet-class>
</servlet>….
</web-app>
46
CHAPTER 6: RESULTS AND CONCLUSION
6.1 Summary and results
The scope of this project was to simulate a real on-line store by building a reliable and
secure web application using Java RMI and Servlet via Tomcat. The Online Book Store
application has been built with all designed features including services ranging from book
searches, book purchases, to updating the inventory on line through different servers.
This application can be installed on any Unix or Windows machines and the servers can
be located on different machines or on the same machine but different ports. All
functional servers will register themselves to the Name server and the connection
between client and server will be established dynamically as long as the registration is
successful and the server keeps running.
All the functionalities have been fully tested and have met the project goals, including the
implementation of client and server communication, replication of name servers, and
password encryption. If any server fails, the system will display an appropriate error
message identifying the failed servers.
6.2 Problems encountered and solutions
6.2.1 Send parameters by URL
47
JavaScript pass string as parameter with it’s URL??. If the string has special characters
or spaces, the complier will only take the first word and cut the rest of the string. So the
next page can not get the complete parameter. The solution for this problem was to use a
Java function “java.net.URLEncoder.encode (myString)” in JavaScript program to
convert special characters and pass it to the next page where the parameter will be
converted back with another Java function: “java.net.URLEncoder.decode (myString)”.
This will ensure the parameter will remain exactly the same as the first page.
6.2.2 Java version with tomcat
The application was developed with Java 1.3.9. When the application was
deployed to a machine with java 1.4.1 installed, some JSP pages could not be
displayed and the following error messages were displayed: "The major.minor
version '48.0' is too recent for this tool to understand." The reason for this
problem was because Tomcat has tools.jar in its common/lib directory and java
JDK 1.4.0 version has tools.jar in its own lib directory. This created a conflict for
the JSP compiler. The solution was to copy the tools.jar from Java jdk 1.4.0 to
Tomcat common/lib directory and restart Tomcat to make this change effective.
6.3 Other challenges
6.3.1. Configuring tomcat.
Configuring Tomcat is the first step to make this application work. There are several
configuration files that need to be changed to accommodate the new application. Tomcat
requires a strict directory structure to be created. If anything is in the wrong directory,
48
the complier will display some error message and the page cannot be viewed from the
web browser. The server.xml and web.xml file under conf directory also need to be
changed according to the new application and new servlet classes.
6.3.2. Client and Server communication. (RMI)
Java RMI only works with computers that have trusted connections to each other.
Certain firewalls within networks may result in RMI connection failures. If this occurs
RMI will throw a java.rmi.ConnectException error message when the client tries to
connect.
6.3.3 String parsing
This project involved a lot of string processing because data was stored as flat files on
different servers. This means every time the server accesses the data, the server would
read from the flat file, parsing the file with Java StringTokenizer. This made the
read/write operation more complicated. To correctly read/write from the flat file, two
helper classes were created: ioprocess.java and RWTextFile.java. They can handle the
entire Read/Write request and provide a simple interface for other classes to use.
6.3.4 Look and feel for web page
In order to keep this application consistent, all the pages (include static pages and
dynamic pages) had to be created with the same background, color and the size.
49
6.4 Future Enhancements:
6.4.1 Add more services to the application.
This on-line application can be extended and more services can be added to it.
For example:
Add price comparison feature that will enable a client to compare prices at
different on-line bookstores servers and find the best price.
Add email feature that will automatically notify the customer by email when the
order is confirmed and the payment has been processed.
Add automatic notification feature to inform customer of new book arrivals based
on their interest.
6.4.2 Replicate more servers
The Name server has been replicated once in this application, but it can be replicated
three or more times to enhance the reliability and availability of the application.
The other servers can also be replicated to increase the availability and sharing the
workload of that server.
6.4.3 Add database connection and use relational database to store and distribute data.
In this project, the data was stored as flat files because flat files are more portable and
easy to install on any machine to demonstrate the network communication. But in the
real world, the best solution for storing data is to use relational database, which will make
data processing easier and more organized.
50
BIBLIOGRAPHY
1. George Coulouris, Jean Dollimore and Tim Kindberg, “Distributed Systems,
Concepts and Design”, Second Edition, ADDISON-WESLEY, 1995
2. Thau “JAVASCRIPT --- A practical guide to interactive web pages”, 2000
3. DEITEL&DEITEL, “Java How to Program”, third edition, PRENTICE
HALL,1999
4. Peter Harrison, Ian McFarland, “Mastering Tomcat Development”, WILEY, 2003
5. The Java Tutorial --- A practical guide for programmers at
http://java.sun.com/docs/books/tutorial/
6. Servlets and JavaServer Pages (JSP) 1.0: A Tutorial at
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
7. Configuring & Using Apache Tomcat 4 at
http://www.moreservlets.com/Using-Tomcat-4.html
51
APPENDIX A: USER MANUAL
1. Lists of java programs
Java program name
nameServer.java
nameServerImpl.java
ReplicateNsImpl.java
Class name
nameServer.class
nameServerImpl.class
nameServerImpl_Skel.class
nameServerImpl_Stub.class
ReplicateNsImpl.class
ReplicateNsImpl_Skel.class
ReplicateNsImpl_Stub.class
Server name
Name Server
(Primary name server)
(Secondary name server)
AuthenServer.java
AuthenServerImpl.java
AuthClientadd.java
AuthClientServlet.java
AuthenServer.class
Authentication Server
AuthenServerImpl.class
AuthenServerImpl_Skel.class
AuthenServerImpl_Stub.class
AuthClientadd.class
AuthClientServlet.class
BookShop.class
BookShopImpl.class
BookShopImpl_Skel.class
BookShopImpl_Stub.class
BookshopServlet.class
Book Server
BookShop.java
BookShopImpl.java
BookshopServlet.java
Creditcard.java
CreditcardImpl.java
CreditServlet.java
Creditcard.class
CreditcardImpl.class
CreditcardImpl_Skel.class
CreditcardImpl_Stub.class
CreditServlet.class
Credit Card Server
BookAdmin.java
BookAdminImpl.java
AdminServlet1.java
AdminServletupdate.java
Book Admin Server
ioprocess.java
RWTextFile.java
BookAdmin.class
BookAdminImpl.class
BookAdminImpl_Skel.class
BookAdminImpl_Stub.class
AdminServlet1.class
AdminServletupdate.class
ioprocess.class
RWTextFile.class
CEncrypt.java
ConnectNS.java
CEncrypt.class
ConnectNS.class
Helper class for i/o process
Helper class for read/write
text file
For Encryption
Helper class connecting to
name server
52
2.Lists of JavaScript files
Javascript program name
Login_user.jsp
Login_admin.jsp
login_admin_add.jsp
BookStore.jsp
order.jsp
admin_add.jsp
update.jsp
Purpose
For user login
For Administrator login
For adding login names
After login, user can search for books
For user order books
Add new book item to book stock.
Edit or Delete book information
3.Lists of text data files.
File name
servernames.txt
logins.txt
bookfile.txt
ccard.txt
Purpose
Store server names
Store logins
Owner
Access by name servers.
Access or modified by authentication
server.
Store book information Access by bookshop server, credit card
server and book admin server.
Store credit card
Access by credit card server.
information
3.1 servernames.txt
N/A
//sfo1-fm264kf9gd:4998/BookShop
//sfo1-fm264kf9gd:4995/Creditcard
//sfo1-fm264kf9gd:5005/AdminServer
3.2 logins.txt
amy,t\PFL,1
amman,rYTEN,2
helen,}V[JA,1
smari,t\PF,2
amman,s_UC,2
amy, 12345, 1
Amman, amman, 1
Helen 6677 2,2
Testuser, test, 1
Kathy, Kathy,2
3.3 bookfile.txt
format: book name | author name|book Id | price | number of books
C++ in programing|Jackson|222222|25.00|182
Sun programming RPC|OREILLY|333333|11.00|26
Advanced pro Perl|Willam Amman|444444|60.00|22
53
Database Management|Gorge|555555|72.00|1
Visual C++ Basic|Scott|666666|89.00|34
Talk java to me|thau|889988|20.5|55
Amy's book|Amy|106|15.55|997
amy's first book|Wenping|111111|23|12
3.4 ccard.txt
11111111,05/01/2004,561.4
22222222,04/01/2006,238.0
33333333,09/01/2005,30.00
4. Steps to start the servers:
4.1 Start Tomcat at C:\Tomcat4.0.6\bin\, run startup.bat,
The following window will shows that Tomcat as web server runs at the background.
4.2 Start Java RMI Registry
From C:\jdk1.3.1_09\bin, run rmiregistry,
Rmiregistry will run at the background. The default port for rmiregistry is: 4999
54
4.3 Start name Server
Start from class directory, run the Primary name server:
Start from class directory, run the Secondary name server:
55
4.4. Start Authentication Server from port 4992
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java AuthenServerImpl 4992
4.5. Start BookShop Server from port 4995
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java BookShopImpl 4995
4.6. Start Credit Card Server
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java CreditcardImpl 4998
56
4.7 Start Book Admin Server
5. Testing Cases:
After all the servers are up and running, Check the name server screen, You should
find out that every time the web page make request, servlet will connect to the name
server to get server name. Then send the request to the server, all the action will show on
the screen and can be monitored.
Assume all the required server are available, plus tomcat is running, rmiregistry is
running, and name server is running , we can test the following functionalities:
57
Test Case 1:
Description:
Pre-requisites:
Test Steps:
Test Variations:
Expected Results:
Verify user, administrator login
The Authentication server should be running. Login page can be
accessed by address at: http://localhost:8080/BS/login.jsp
Input valid user login name and password from login_user.jsp and
click “Submit”
Input valid user login name and password from login_admin.jsp and
click “Submit”
If you don’t input anything, just click “Submit”, you will be prompt
to enter a value.
If Login information is correct, the user will be redirect to the book
search page. The administrator will be redirect to the book admin
page.
If login information is not correct, the user will be notified and page
return to login page again.
Test Case 2:
Description:
Pre-requisites:
Test Steps:
Test Variations:
Expected Results:
Verify the book search page
The Bookshop server should be running. Book search page can be
accessed by address at: http://localhost:8080/BS/jsp/BookStore.jsp
Select “Search By Book ID” item and input a valid book id, then
click on “Submit”
Select “Search By Book Name” item and input a valid Book Name,
then click on “Submit”
Select “Search By Book Author” item and input a valid Book
Author, then click on “Submit”
If you don’t input anything, or don’t select one item, just click
“Submit”, you will be prompt to enter a value.
If Bookshop server find the item you are searching, it will direct you
to the http://localhost:8080/BS/servlet/BookshopServlet page and
show you the search result.
If there is no match found in the server, it will give you a message
that “No result found. Click Back to return!”, if you click on back,
You should be back to the book search page.
58
Test Case 3:
Description:
Verify the Book ordering page
Pre-requisites:
The Credit card server should be running. Order page can be
accessed by address at: http://localhost:8080/BS/jsp/order.jsp
Test Steps:
Input the number of books you want to order, if it exceed the total
number of books, this page will request you to change the number.
Input six digit for credit card number.
Input a valid expiration date, then click order.
The credit card server should process your order.
If the purchase successful, the book will reduce it’s number.
If you don’t input anything, just click “Add”, you will be prompt to
enter a value.
Test Variations:
Expected Results:
If Bookshop server find the item you are searching, it will direct you
to the http://localhost:8080/BS/servlet/BookshopServlet page and
show you the search result.
If the credit card number or expiration date is incorrect, the page
http://localhost:8080/BS/servlet/CreditServlet will show the
message that your purchase failed.
Test Case 4:
Description:
The book Administration page
Pre-requisites:
The Book Administration server should be running.
Test Steps:
1.Access page http://localhost:8080/BS/servlet/AdminServlet1
You should see the page with the list of all the books.
2. Click on Add button, you should be directed to the page:
http://localhost:8080/BS/jsp/admin_add.jsp
You should fill out each field and click add to submit
If the new book’s id already existed in the book storage, the add
action failed, The page tells you that the book id is duplicate.
3. Click on Edit Button, You will be directed to the page
http://localhost:8080/BS/jsp/update.jsp
You can edit the book price or book number from this page.
Make changes to book price or book number, when you return to
http://localhost:8080/BS/servlet/AdminServlet1 Page, you will see
the change happened.
If you don’t input anything, just click “Order”, you will be prompt to
enter a value.
If http://localhost:8080/BS/servlet/AdminServlet1 page should
display all the books in the store storage. The administrator can
complete add, delete, edit operations through this page.
Test Variations:
Expected Results:
59
APPENDIX B: LIST OF JAVA PROGRAMS
1.nameServer.java
/**********************************************************************
* Master Project
* nameServer.java
* This is the interface of prmairy nameserver and replicate name server
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.rmi.*;
public interface nameServer extends Remote
{
public int RegisterServer (String serverName, int serverType)
throws RemoteException;
public void unregister(String serverName, int serverType)
throws RemoteException;
public String GetServername (int ServerType)
throws RemoteException;
}
2. nameServerImpl.java
/**********************************************************************
* Master Project
* nameServerImpl.java
* This is the implementation for nameServer interface
* command: java nameServerImpl will register itself at localhost with port#4999
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class nameServerImpl extends UnicastRemoteObject
implements nameServer
{
public String AuthenSer="", BookSer ="", CreditSer ="", ProviderSer ="";
public String ServerList[] = {"AuthenServer","BookServer","Creditserver","Providerserver"};
public int size = 4;
public nameServerImpl() throws RemoteException
60
{
super(); // intialize name list
// lookup nameServerImpl remote object in rmiregistry
try
{
String nameObject ="//localhost:5000/RepliNameServer";
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
String receive_name = myname.GetServername (0) ;
System.out.print("the receive name from Replicate nameserver: " + receive_name);
System.out.print("\nThe replicate name server already up and running...");
System.out.println();
}
catch( java.rmi.ConnectException e2)
{
System.out.println("Connection to Replicate nameserver failed. Server unavailable.");
System.out.println("So the primary name server is the first one to start service.");
File f = new File("servernames.txt" );
f.delete();
String GetServers[] = {"N/A", "N/A", "N/A", "N/A"," " };
ioprocess newprocess = new ioprocess( );
newprocess.writelines ( GetServers, 4, "servernames.txt" );
}
catch( Exception w_e2)
{
w_e2.printStackTrace();
System.out.println("General exception in starting primary name server...");
// System.exit(1);
}
}
// impletement methods of nameServer
// store the server names.
public int RegisterServer (String serverName, int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
int returnvalue =0;
GetServers = newprocess.readlines ("servernames.txt");
if ( ! GetServers[serverType].equalsIgnoreCase( serverName) )
{
GetServers[serverType]= serverName;
// get the new server
returnvalue =1;
61
} else
{ returnvalue =2;
}
File f = new File("servernames.txt" );
f.delete();
System.out.println
("the server type " + ServerList[serverType] + " is register as: " + GetServers[serverType]);
newprocess.writelines ( GetServers, 4, "servernames.txt" );
return returnvalue ;
// return value=1, success, value=0 unsucess. value=2, server already exists
}
public void unregister(String serverName, int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
GetServers = newprocess.readlines ("servernames.txt");
GetServers[serverType]="N/A";
newprocess.writelines ( GetServers, 4, "servernames.txt" );
}
public String GetServername (int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
GetServers = newprocess.readlines ("servernames.txt");
String
return_name = "";
return_name = GetServers[serverType];
// return_name = new String (" my name is bookserver");
System.out.println("The name server returnning string is "+ return_name );
return return_name;
}
public static void main(String args[]) throws Exception
{
// the wellknown name server register itself to rmi
System.out.println("Initializing nameServer: please wait...");
// create a server object
nameServerImpl theName = new nameServerImpl();
// bind nameServerImpl object to the rmiregistry to port
String serverObjectName = "//localhost/theNameServer";
Registry regi = LocateRegistry.createRegistry(4999);
Naming.rebind(serverObjectName, theName);
System.out.println("The name server serverObjectName is " + serverObjectName );
System.out.println("The primary name server is up and running...");
} // end main
} // end of class
62
3. ReplicateNsImpl.java
/**********************************************************************
* Master Project
* ReplicateNsImpl.java
* This is the implementation for nameServer interface
* Replicate name server will register at localhost with port#5000
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
**********************************************************************/
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class ReplicateNsImpl extends UnicastRemoteObject
implements nameServer
{
public String AuthenSer="", BookSer ="", CreditSer ="", ProviderSer ="";
public String ServerList[] = {"AuthenServer", "BookServer", "Creditserver", "Providerserver" };
public int size = 4;
public ReplicateNsImpl() throws RemoteException
{
super(); // intialize name list
try
{
String nameObject ="//localhost/theNameServer";
// lookup nameServerImpl remote object in rmiregistry
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
String receive_name = myname.GetServername (0) ;
//System.out.print("the receive name from primary nameserver: " + receive_name);
System.out.print("The primary name server is already up and running...");
System.out.println();
}
catch( java.rmi.ConnectException e2)
{
System.out.println("Connection to primary nameserver failed. Server unavailable.");
System.out.println("So the replicate name server is the first one to start service.");
File f = new File("servernames.txt" );
f.delete();
String GetServers[] = {"N/A", "N/A", "N/A", "N/A"," " };
ioprocess newprocess = new ioprocess( );
newprocess.writelines ( GetServers, 4, "servernames.txt" );
}
catch( Exception w_e2)
63
{
w_e2.printStackTrace();
System.out.println("General exception in starting replicate name server...");
// System.exit(1);
}
}
// impletement methods of nameServer
// store the server names.
public int RegisterServer (String serverName, int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
int returnvalue =0;
GetServers = newprocess.readlines ("servernames.txt");
if ( ! GetServers[serverType].equalsIgnoreCase( serverName) )
{
GetServers[serverType]= serverName;
// get the new server
returnvalue =1;
} else
{ returnvalue =2;
}
File f = new File("servernames.txt" );
f.delete();
System.out.println
("the server type " + ServerList[serverType] + " is register as: " + GetServers[serverType]);
newprocess.writelines ( GetServers, 4, "servernames.txt" );
return returnvalue ;
// return value=1, success, value=0 unsucess. value=2, server already exists
}
public void unregister(String serverName, int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
GetServers = newprocess.readlines ("servernames.txt");
GetServers[serverType]="N/A";
newprocess.writelines ( GetServers, 4, "servernames.txt" );
}
public String GetServername (int serverType) throws RemoteException
{
String GetServers[] = new String [4];
ioprocess newprocess = new ioprocess( );
GetServers = newprocess.readlines ("servernames.txt");
String
return_name = "";
64
return_name = GetServers[serverType];
System.out.println("The name server return values is "+return_name );
return return_name;
}
public static void main(String args[]) throws Exception
{
// the well known Replicate name server register itself to rmi
System.out.println("Initializing the Replicate nameServer: please wait...");
// create a server object
ReplicateNsImpl theName = new ReplicateNsImpl();
// bind nameServerImpl object to the rmiregistry to port
String serverObjectName = "//localhost:5000/RepliNameServer";
Registry regi = LocateRegistry.createRegistry(5000);
Naming.rebind(serverObjectName, theName);
System.out.println("The name server serverObjectName is " + serverObjectName );
System.out.println("The replicate name server is up and running...");
} // end main
} // end of class
4. AuthenServer.java
/**********************************************************************
* Master Project
* AuthenServer.java
* This is Authentication server interface definition
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
**********************************************************************/
import java.rmi.*;
public interface AuthenServer extends Remote {
public String check_login ( String name, String passwd, String logintype)
throws RemoteException;
public int register_user (String name, String passwd, String logintype)
throws RemoteException;
public void unregister_user(String name, String passwd, String logintype)
throws RemoteException;
}
5. AuthenServerImpl.java
/***********************************************************************
* Master Project
* AuthenServerImpl.java
* This is the implementation of authentication server
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
**********************************************************************/
import java.rmi.*;
import java.rmi.server.*;
65
import java.util.*;
import java.rmi.registry.*;
import java.io.*;
import java.net.*;
public class AuthenServerImpl extends UnicastRemoteObject
implements AuthenServer {
public AuthenServerImpl() throws RemoteException
{
super();
}
// implementation for AuthenServer interface method
public String check_login ( String name, String passwd, String thistype)
{
String loginresult = "NO";
int login_num=0;
ioprocess newprocess = new ioprocess( );
login_num = newprocess.row_num ( "logins.txt");
String Getloigns[] = new String [login_num];
Getloigns= newprocess.readlines ("logins.txt");
String loginstr = name + "," + passwd+","+ thistype;
System.out.println( "the login string is: " + loginstr );
for ( int i = 0; i < login_num; i++ )
{
if ( Getloigns[i].equalsIgnoreCase(loginstr) )
loginresult = "YES";
}
return loginresult ;
}
public int register_user (String name, String passwd, String thistype)
{
RandomAccessFile thisbookfile = null;
String thislogininfo = name +","+passwd +","+thistype;
int ret_code =0;
// open the file and append this record at the end.
try
{
thisbookfile = new RandomAccessFile ( "logins.txt" , "rw"); // open the file
}
catch (IOException ex)
{
System.out.println("Error openning file");
}
try
{
long end = thisbookfile.length();
thisbookfile.seek(end);
thisbookfile.writeBytes( thislogininfo +"\n");
thisbookfile.close();
ret_code =1;
} // end try
66
catch(IOException e1) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e2)
// general exception
{
System.out.println("General error ");
}
return ret_code ;
}
public void unregister_user(String name, String passwd, String thistype)
{
return 1;
}
public static void main( String args[] ) throws Exception
{
InetAddress address;
String
portNumber;
int portnum;
String myaddr ="";
String hostName, receive_name;
int i=3;
if(args.length != 1)
System.out.println("enter prot#");
portNumber = args[0];
portnum = Integer.parseInt(portNumber);
System.err.println("Initializing Authentication server, Please wait.");
// get to know its own name.
try{
address=InetAddress.getLocalHost();
myaddr=address.toString();
System.out.println("the inet address is "+address);
}
catch(Exception e)
{
System.out.println("can not get host address");
}
StringTokenizer token=new StringTokenizer(myaddr, "/");
hostName=token.nextToken();
System.out.println( "The hostname is: " + hostName );
// Being a client, register itself to well known nameserver by ConnectNS class.
ConnectNS newconnect =new ConnectNS() ;
String serverObjectstr = "//"+hostName+":"+portNumber+"/TempServer";
67
int r_status = newconnect.ProxyRegister ( serverObjectstr , 0 ) ;
if (r_status==1)
System.out.print("num is:" + r_status + " and the register Authentication server successful!");
else if ( r_status==2)
System.out.print("Register failed. Authentication server already registered to nameserver.");
else
{
System.out.print("num is: "+ r_status + " and Authentication register failed.");
System.exit(1);
}
try{
// create server object, Being a server
AuthenServerImpl tempAuthen = new AuthenServerImpl();
// bind AuthenServerImpl object to the rmiregistry
String serverObjectName = "//"+hostName+":"+portNumber+"/TempServer";
Registry regi = LocateRegistry.createRegistry(portnum);
Naming.rebind( serverObjectName, tempAuthen );
System.err.println("\nThe Authentication server is up and running." );
}
catch( java.rmi.ConnectException e)
{
System.out.println("creating server bind failed. Server may be temporarily unavailable.");
System.exit(1);
}
catch( Exception e)
{
System.out.println("Authentication server error:"+ e.getMessage());
System.exit(1);
}
}// end of main
}
6.AuthClientadd.java
/***********************************************************************
* Master Project
* AuthClientadd.java
* This is called by login_admin_add.jsp page,
* Ther servlet will capture the login and pass it to Authentication server.
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
68
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
public class AuthClientadd extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String thischeck = "NoTChecked";
String receive_name="";
String dataName = request.getParameter("name_field");
String dataValue = request.getParameter("password_field");
String datatype = request.getParameter("logintypefield");
CEncrypt myencrypt = new CEncrypt();
String newpwd= myencrypt.encryptString(dataValue);
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (0) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else System.err.println("the return is: "+ receive_name);
try {
// lookup remote object in rmiregistry
AuthenServer mytemp = ( AuthenServer ) Naming.lookup( receive_name );
// get information from server
System.err.println( "finding the server... ");
int i = mytemp.register_user ( dataName ,newpwd,datatype );
System.err.println( "finding the server result is... "+i );
if (i==1)
{
thischeck = "YES";
}
} // end inner try
catch ( java.rmi.ConnectException ce ) {
System.err.println( "Connection to server failed. " +
"Server may be temporarily unavailable." );
}
catch ( Exception e ) {
e.printStackTrace();
// System.exit( 1 );
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
69
out.println("<html>");
out.println("<body bgcolor=\"white\">");
out.println("<head>");
out.println("<title>Authentication Add page</title>");
out.println("</head>");
out.println("<body>");
if ( thischeck.equalsIgnoreCase("YES") )
{
out.println("Your login information has been successfully added" );
} else if (thischeck.equalsIgnoreCase("NoTChecked") )
{
out.println("The Authentication Server is not running, please try to login later. Thank you.");
}
out.println("<META http-equiv=refresh content=2;Url=../jsp/login_user.jsp >");
out.println("<P>");
out.println("</body>");
out.println("</html>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
throws IOException, ServletException
{
doGet(request, response);
}
HttpServletResponse response)
}
7. AuthClientServlet.java
/**********************************************************************
* Master Project
* AuthClientServlet.java
* This is called by login.jsp page,
* servlet will caputre the login information and pass it to Authentication server.
* The authentication server will response by yes or no.
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
**********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
public class AuthClientServlet extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
70
{
String thischeck = "NoTChecked";
String receive_name="";
String dataName = request.getParameter("name_field");
String dataValue = request.getParameter("password_field");
String datatype = request.getParameter("thislogintype");
CEncrypt myencrypt = new CEncrypt();
String newpwd= myencrypt.encryptString(dataValue);
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (0) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else System.err.println("the return is: "+ receive_name);
try {
// lookup remote object in rmiregistry
AuthenServer mytemp = ( AuthenServer ) Naming.lookup( receive_name );
// get information from server
System.err.println( "finding the server... ");
thischeck = mytemp.check_login ( dataName , newpwd,datatype );
System.err.println( "finding the server result is... "+thischeck );
} // end inner try
catch ( java.rmi.ConnectException ce ) {
System.err.println( "Connection to server failed. " +
"Server may be temporarily unavailable." );
}
catch ( Exception e ) {
e.printStackTrace();
// System.exit( 1 );
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body bgcolor=\"white\">");
out.println("<head>");
String title = "Session Information";
out.println("<title>" + title + "</title>");
if ( thischeck.equalsIgnoreCase("YES") )
{
if ( datatype.equalsIgnoreCase("1") )
{
out.println("<META http-equiv=refresh content=2;Url=../jsp/BookStore.jsp >");
} else
{
out.println("<META http-equiv=refresh content=2;Url=../servlet/AdminServlet1 >");
}
71
}
else
{
out.println("<META http-equiv=refresh content=2;Url=../jsp/login_user.jsp >");
}
out.println("</head>");
out.println("<body>");
out.println("<h3>" + title + "</h3>");
System.err.println( "finding the server result is... "+thischeck );
HttpSession session = request.getSession();
out.println(rb.getString("sessions.id") + " " + session.getId());
out.println("<br>");
out.println(rb.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "<br>");
out.println(rb.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()) + "<br>");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println(" Both Primary and Replicate name Server are unavailable. Please try again later.");
}
else if ( thischeck.equalsIgnoreCase("YES") )
{
out.println("Hello " + dataName + " You are now login to the book store" );
out.println("Please wait for 20 seconds to enter bookstore." );
}else if (thischeck.equalsIgnoreCase("NoTChecked") )
{
out.println("The Authentication Server is not running, please try to login later. Thank you.");
}
else
{
out.println(" You don't have permission to login to the book store, redirect back..." );
}
if (dataName != null && dataValue != null) {
session.setAttribute(dataName, dataValue);
}
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
// out.println(name + " = " + value + "<br>");
}
out.println("<P>");
out.println("</body>");
out.println("</html>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
72
throws IOException, ServletException
{
doGet(request, response);
}
}
8.BookShop.java
/***********************************************************************
* Master Project
* BookShop.java
* This is the interface of BookShop
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.rmi.*;
public interface BookShop extends Remote
{
public String SearchAuthor(String TheAuthor) throws RemoteException;
public String SearchId (String TheId) throws RemoteException;
public String SearchBookname (String thebookname ) throws RemoteException;
}
9.BookShopImpl.java
/***********************************************************************
* Master Project
* BookShopImpl.java
* This is the implementation the Bookshop.java interface
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
import java.rmi.registry.*;
public class BookShopImpl extends UnicastRemoteObject implements BookShop{
private RandomAccessFile BookList;
private JTextArea output;
String[] Line = new String[8];
int index=1;
public BookShopImpl() throws RemoteException
{
super();
73
}
public String SearchAuthor(String TheAuthor) throws RemoteException
{
String text="", F_Name="", F_Author="", F_Id="";
String F_price="", Num="", returnString="NO";
System.out.println("Server start, Searching by id...");
try
{
BookList= new RandomAccessFile("bookfile.txt", "r");
}
catch (IOException e1)
{
System.err.println("Read bookfile failed...");
}
try{
while((text=BookList.readLine())!=null)
{
StringTokenizer token2 = new StringTokenizer(text,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
System.out.println("parsing bookfile F_Author is: " + F_Author);
if(TheAuthor.equalsIgnoreCase(F_Author))
{
returnString=text;
System.out.println("\nFound F_Author is: " + F_Author);
break;
}
}
}
catch (IOException e1)
{
System.err.println("parsing bookfile failed...");
}
System.err.println("the return is: "+returnString);
return returnString;
}
public String SearchId (String TheId) throws RemoteException
{
String text="", F_Name="", F_Author="", F_Id="";
String F_price="", Num="", returnString="NO";
System.out.println("Server start, Searching by id...");
try
{
BookList= new RandomAccessFile("bookfile.txt", "r");
}
catch (IOException e1)
{
74
System.err.println("Read bookfile failed...");
}
try{
while((text=BookList.readLine())!=null)
{
StringTokenizer token2 = new StringTokenizer(text,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
System.out.println("parsing bookfile F_Id is: " + F_Id);
if(TheId.equalsIgnoreCase(F_Id))
{
returnString=text;
System.out.println("\nFound F_Id is: " + F_Id);
break;
}
}
}
catch (IOException e1)
{
System.err.println("parsing bookfile failed...");
}
System.err.println("the return is: "+returnString);
return returnString;
}
public String SearchBookname (String thebookname ) throws RemoteException
{
String text="", F_Name="", F_Author="", F_Id="";
String F_price="", Num="", returnString="NO";
System.out.println("Server start, Searching by id...");
try
{
BookList= new RandomAccessFile("bookfile.txt", "r");
}
catch (IOException e1)
{
System.err.println("Read bookfile failed...");
}
try{
while((text=BookList.readLine())!=null)
{
StringTokenizer token2 = new StringTokenizer(text,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
System.out.println("parsing bookfile f_name is: " +F_Name);
75
if(thebookname .equalsIgnoreCase(F_Name))
{
returnString=text;
System.out.println("\nFound f_name is: " +F_Name);
break;
}
}
}
catch (IOException e1)
{
System.err.println("parsing bookfile failed...");
}
System.err.println("the return is: "+returnString);
return returnString;
}
public static void main( String args[] ) throws Exception
{
InetAddress address;
String
portNumber;
String temp="", hostName;
int i=0;
String receive_name="";
if(args.length != 1)
System.out.println("Please enter prot#");
portNumber = args[0];
System.err.println("Initializing Book server: Please wait.");
// get to know its own name.
try{
address=InetAddress.getLocalHost();
temp=address.toString();
System.out.println("the inet address is "+address);
}
catch(Exception e)
{
System.out.println("Can not get host address");
}
StringTokenizer token=new StringTokenizer(temp, "/");
hostName=token.nextToken();
// register itself to wellknown nameserver.
// Being a client, register itself to well known nameserver by ConnectNS class.
ConnectNS newconnect =new ConnectNS() ;
String serverObjectstr = "//"+hostName+":"+portNumber+"/BookShop";
int r_status = newconnect.ProxyRegister ( serverObjectstr , 1 ) ;
if (r_status==1)
System.out.print("num is:" + r_status + " and BookServer register successful!");
else if ( r_status==2)
System.out.print("Register failed. This server already registered to nameserver.");
else
76
{
System.out.print("num is: "+ r_status + " and register failed.");
System.exit(1);
}
try{
//nameServerImpl myName= new nameServerImpl();
BookShopImpl MyBook=new BookShopImpl();
// bind nameServerImpl object to the rmiregistry
String serverObject="//"+hostName+":"+portNumber+"/BookShop";
Registry newRegi=LocateRegistry.createRegistry( Integer.parseInt(portNumber));
Naming.rebind(serverObject, MyBook);
System.out.println("\nBookServer is up and running at"+serverObject);
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connection to nameserver failed for get_host_name" +
" Server may be temporarily unavailable.");
}
catch( Exception e)
{
System.out.println("Book server error:"+ e.getMessage());
}
}// end of main
}
10.BookshopServlet.java
/**********************************************************************
* Master Project
* BookshopServlet.java
* This is called by Bookstore.jsp page, will take user action information and pass it to
* Bookshop server. The Bookshop server will response by the result of search action.
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Object.*;
import java.rmi.*;
import java.net.*;
public class BookshopServlet extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
String text, F_Name, F_Author, F_Id, F_price, Num, returnString="";
public void doGet(HttpServletRequest request,
HttpServletResponse response)
77
throws IOException, ServletException
{
String thischeck = "NOTCHECKED";
String thiscondition="";
String receive_name="";
String dataName = request.getParameter("SearchAction");
String dataValue = request.getParameter("SearchType");
String booklists="NO";
String booklistcp="NO";
System.out.print("\nNow Will send request to server: " +dataName +" " +dataValue );
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (1) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else System.err.println("the return is: "+ receive_name);
try
{
// name of remote server object bound to rmi registry
String bookObject = "//"+receive_name +"/BookShop";
System.out.print("the bookObject name is: " + bookObject );
// lookup nameServerImpl remote object in rmiregistry
BookShop MybookServer =(BookShop)Naming.lookup(receive_name);
// call the name server to get the servcie server
if ( dataValue.equalsIgnoreCase("0") )
{
booklists =MybookServer.SearchId ( dataName ) ;
thischeck ="Checked0!";
thiscondition = "searching book by Id = " + dataName ;
}
else if ( dataValue.equalsIgnoreCase("1") )
{
booklists = MybookServer.SearchBookname( dataName) ;
thischeck ="Checked1!";
thiscondition = "searching book by book name = " + dataName ;
}
else if ( dataValue.equalsIgnoreCase("2") )
{
booklists = MybookServer.SearchAuthor( dataName) ;
thischeck ="Checked2!";
thiscondition = "searching book by Author= " + dataName ;
}
System.out.println( "\n The booklists is: "+ booklists );
if ( booklists.equalsIgnoreCase("NO") )
{
System.out.println( "\n There is no result return." );
78
}
else
{
StringTokenizer token2 = new StringTokenizer(booklists,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
System.out.println( "\n Getting the result from bookserver is.. "+F_Name+ F_Author+ F_Id );
System.out.println();
}
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connection to bookserver failed,Server may be temporarily unavailable.");
}
catch( Exception w_e)
{
w_e.printStackTrace();
System.out.println("general exception in getting the book service...");
//System.exit(1);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> ");
out.println("<TITLE>On Line Book Store Search Result</TITLE> </HEAD><BODY > ");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR> <td> </td> ");
out.println("<td align=right valign=bottom> ");
out.println(" </td> </tr></table>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>");
out.println(" <br><U><B><font color=#6633cc SIZE=5> ");
out.println("On-line Book Store Search Result Page</font></B></U></td></tr> </TABLE>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa><TR><TD valign=bottom align=center> ");
out.println("<br><U><B><font color=#6633cc> </font></B></U>");
out.println("<FORM NAME=searching method = post ");
if ( booklists.equalsIgnoreCase("NO") )
{
out.println("action=../jsp/BookStore.jsp > ");
out.println("<TABLE width=80% BORDER=0 CELLPADDING=3 CELLSPACING=3> ");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println(" Both Primary and Replicate name Server are unavailable. Please try again later.");
} else if (thischeck.equalsIgnoreCase("NoTChecked") )
{
out.println("The Book Server is not running, please try to login later.");
} else{
out.println("<TR> <TD valign=top align=left> No result found. Click Back to retrun! </td> <TD> ");
}
out.println("<input type=submit tabindex=3 Value=Back > </FONT></TD> </tr>");
out.println(" </TABLE> </FORM> </TABLE> ");
out.println("</body>");
79
out.println("</html>");
}
if ( !booklists.equalsIgnoreCase("NO") )
{
String newstr1= java.net.URLEncoder.encode( F_Name );
String newstr2= java.net.URLEncoder.encode( F_Author);
out.println("action=../jsp/order.jsp > ");
out.println("<INPUT TYPE=hidden NAME=UserAction ><INPUT TYPE=hidden
NAME=SearchType > ");
out.println("<input type=hidden name=fname value= " + newstr1 + ">");
out.println("<input type=hidden name=fauthor value= " + newstr2 + ">");
out.println("<input type=hidden name=fid value= " + F_Id + ">");
out.println("<input type=hidden name=fprice value= " + F_price + ">");
out.println("<input type=hidden name=fnum value= " + Num + ">");
out.println("<TABLE width=80% BORDER=0 CELLPADDING=3 CELLSPACING=3> ");
out.println("<TR> <TD valign=top align=left><b> Found the book </b></td> <TD> ");
out.println( thiscondition + "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=top align=left> Book Name: </td> <TD> ");
out.println( F_Name+ "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=top align=left> Book Author: </td> <TD> ");
out.println( F_Author + "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=top align=left> Book ID: </td> <TD> ");
out.println( F_Id + "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=top align=left> Book Price: </td> <TD> ");
out.println( F_price + "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=top align=left> Book number availble </td> <TD> ");
out.println( Num + "</FONT></TD> </tr>" );
out.println("<TR> <TD valign=bottom align=left><FONT SIZE=1>" );
out.println("<input type=submit tabindex=3 Value=Order> </td> </FORM>" );
out.println("<Td valign=bottom align=left> " );
out.println(" <form NAME=back method = post action=../jsp/BookStore.jsp>");
out.println(" <input type=submit Value=Back > </td></tr></TABLE>");
out.println(" </form></TABLE> ");
out.println("</body>");
out.println("</html>");
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
11. Creditcard.java
/**********************************************************************
* Master Project
* Creditcard.java
* This is the interface of credit card service
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
**********************************************************************/
80
import java.rmi.*;
public interface Creditcard extends Remote
{
public int MakePurchase (String totalAmount, String creditnum, String creditpwd , String bookid,
String ordernum) throws RemoteException;
}
12. CreditcardImpl.java
/**********************************************************************
* Master Project
* CreditcardImpl.java is the implementaton the Creditcard interface
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
import java.rmi.registry.*;
public class CreditcardImpl extends UnicastRemoteObject implements Creditcard{
private RandomAccessFile Record;
public CreditcardImpl() throws RemoteException
{
super();
}
public int ReduceStock (String Id2, String quantity )
{
ioprocess newprocess = new ioprocess( );
int linecount=0, ret=0;
String text="", F_Name="", F_Author="", F_Id="";
String F_price="", Num="" ;
int orig_amount, left_amount;
String left_amount_s="";
String Booklines[];
int i_quantity;
i_quantity= Integer.parseInt (quantity);
linecount= newprocess.row_num ( "bookfile.txt");
Booklines = new String[linecount];
Booklines = newprocess.readlines ("bookfile.txt");
String writestr="";
for ( int i = 0; i < linecount; i++ )
{
String temp=Booklines[i];
System.out.println("found the temp is " + temp );
StringTokenizer token2 = new StringTokenizer(Booklines[i],"|");
81
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
if ( F_Id.equalsIgnoreCase( Id2) )
{
System.out.println("found the bookid " + F_Id + "and num is " +Num );
try {
// need to change
orig_amount = Integer.parseInt (Num) ;
System.out.println("found the orig_amount " + orig_amount);
left_amount = Integer.parseInt (Num) - i_quantity;
left_amount_s =String.valueOf(left_amount);
Booklines[i] =F_Name+"|"+F_Author+"|"+F_Id+"|"+F_price+"|"+ left_amount_s;
System.out.println("the book record change to " + Booklines[i] );
ret = 1;
}
catch(Exception e)
{
System.out.println("Can not get the diff value");
}
}
writestr = writestr.concat(Booklines[i]);
writestr = writestr.concat("\n");
System.out.println("the book writestr is " + writestr );
} // end of for
try{
RWTextFile myRWTextFile = new RWTextFile();
File testFile = new File("bookfile.txt");
myRWTextFile.writeContents( testFile, writestr );
}
catch(IOException e3) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e3)
// general exception
{
e3.printStackTrace();
System.out.println("General error ");
}
return ret ;
}
public int MakePurchase ( String totalAmount, String creditnum, String creditpwd , String bookid, String
ordernum)
{
int ret = 0;
// 1: purchase sucess, 0: purchase unsucess. no match credit card
double d_balance, d_totalamount, d_diff;
String text="", C_num="", C_pwd="", C_amount="", s_diff="";
int linecount=0;
String creditlines[], creditnewlines[];
82
ioprocess newprocess = new ioprocess( );
d_totalamount = (Double.parseDouble ( totalAmount));
linecount= newprocess.row_num ( "ccard.txt");
System.out.println("the linecout is "+ linecount );
creditlines = new String[linecount];
creditnewlines = new String[linecount];
creditlines = newprocess.readlines ("ccard.txt");
String writestr="";
System.out.println("the pass value are: "+totalAmount + "," + creditnum + "," +creditpwd + ","
+ordernum);
System.out.println("the d_totalamount is "+d_totalamount + "line is: " + creditlines[0] );
for ( int i = 0; i < linecount; i++ )
{
StringTokenizer token2 = new StringTokenizer(creditlines[i],",");
C_num=token2.nextToken();
C_pwd=token2.nextToken();
C_amount=token2.nextToken();
System.out.println("the creditlines[i] is "+ C_num + " and " + C_pwd + " and " + C_amount);
if(C_num.equalsIgnoreCase(creditnum) && C_pwd.equalsIgnoreCase(creditpwd))
{
d_balance = Double.parseDouble ( C_amount );
d_diff = d_balance - d_totalamount;
s_diff = String.valueOf(d_diff);
int p= ReduceStock (bookid, ordernum );
System.out.println("return p for reducestock is "+ p);
// write back to ccard for new balance
creditnewlines[i]= C_num +","+ C_pwd +"," + s_diff ;
ret=1;
} // end if
else{
creditnewlines[i]= C_num +","+ C_pwd +"," + C_amount ;
}
writestr= writestr.concat(creditnewlines[i]);
writestr= writestr.concat("\n");
System.out.println("write back line is "+ writestr );
} //end for
try{
RWTextFile myRWTextFile = new RWTextFile();
File testFile = new File( "ccard.txt");
myRWTextFile.writeContents( testFile, writestr );
}
catch(IOException e3) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e3)
// general exception
{
e3.printStackTrace();
System.out.println("General error ");
}
83
System.out.println("Return code here is "+ ret );
return ret;
}
public static void main( String args[] ) throws Exception
{
InetAddress address;
String
portNumber;
String temp="", hostName;
int i=0;
String receive_name="";
if(args.length != 1)
System.out.println("Please enter prot#");
portNumber = args[0];
System.err.println("Initializing Credit Card server: Please wait.");
// get to know its own name.
try{
address=InetAddress.getLocalHost();
temp=address.toString();
System.out.println("the inet address is "+address);
}
catch(Exception e)
{
System.out.println("Can not get host address");
}
StringTokenizer token=new StringTokenizer(temp, "/");
hostName=token.nextToken();
// Being a client, register itself to well known nameserver by ConnectNS class.
ConnectNS newconnect =new ConnectNS() ;
String serverObjectstr = "//"+hostName+":"+portNumber+"/Creditcard";
int r_status = newconnect.ProxyRegister ( serverObjectstr , 2 ) ;
if (r_status==1)
System.out.print("num is:" + r_status + " and the register server successful!");
else if ( r_status==2)
System.out.print("Register failed. This server already registered to nameserver.");
else
{
System.out.print("num is: "+ r_status + " and register failed.");
System.exit(1);
}
try{
//nameServerImpl myName= new nameServerImpl();
CreditcardImpl MyCredit=new CreditcardImpl();
// bind CreditcardImpl object to the rmiregistry
String serverObject="//"+hostName+":"+portNumber+"/Creditcard";
Registry newRegi=LocateRegistry.createRegistry( Integer.parseInt(portNumber));
Naming.rebind(serverObject, MyCredit);
System.out.println("CreditServer is up and running at"+serverObject);
}
84
catch( java.rmi.ConnectException e)
{
System.out.println("Creating credit card server failed" +
" Server may be temporarily unavailable.");
}
catch( Exception e)
{
System.out.println("Credit card server error:"+ e.getMessage());
e.printStackTrace();
}
}// end of main
}
13. CreditServlet.java
/**********************************************************************
** Master Project
* CreditServlet.java
* This is the servlet call the Credit Card server
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
import java.io.*;
public class CreditServlet extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String thischeck = "NOTCHECKED";
String check = "NO";
int rec_ret=0;
int order ;
double ordertotal ;
int mytotal;
String s_name = request.getParameter("h_name");
String s_author = request.getParameter("h_author");
String s_id = request.getParameter("h_id");
String s_price = request.getParameter("h_price");
String s_num = request.getParameter("h_num");
String s_ordernum = request.getParameter("orderamount");
String s_creditnum = request.getParameter("creditnum");
String s_creditpwd = request.getParameter("creditpwd");
ordertotal = Double.parseDouble (s_price) * Integer.parseInt ( s_ordernum);
85
mytotal = (int) ( ordertotal*100) ;
ordertotal = ((double ) mytotal )/100 ;
String s_ordertotal = String.valueOf( ordertotal );
System.out.println("the int ordertotal is: "+ mytotal );
System.out.println("the ordertotal in string is: "+ s_ordertotal);
String receive_name="";
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (2) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else System.err.println("the return is: "+ receive_name);
try {
// lookup remote object in rmiregistry
Creditcard mytemp = ( Creditcard ) Naming.lookup( receive_name);
// get information from server
System.out.println( "finding the credit card server... ");
rec_ret = mytemp.MakePurchase ( s_ordertotal, s_creditnum , s_creditpwd , s_id , s_ordernum);
System.err.println( "finding the server result is... "+rec_ret );
thischeck ="CHECKED";
} // end inner try
catch ( java.rmi.ConnectException ce ) {
System.err.println( "Connection to server failed. " + "Server may be temporarily unavailable." );
receive_name="N/A";
}
catch ( Exception e ) {
e.printStackTrace();
// System.exit( 1 );
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> ");
out.println("<TITLE>On Line Book Store Search Result</TITLE> </HEAD><BODY > ");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR> <td> </td> ");
out.println("<td align=right valign=bottom> ");
out.println(" </td> </tr></table>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>");
out.println(" <br><U><B><font color=#6633cc SIZE=5> ");
out.println("On-line Book Store Order Result Page</font></B></U></td></tr> </TABLE>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa><TR><TD valign=bottom align=center> ");
out.println("<br><U><B><font color=#6633cc> </font></B></U>");
String title = "Session Information";
out.println("<title>" + title + "</title>");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println(" Both Primary and Replicate name Server are unavailable. Please try again later.");
}
86
else if ( receive_name.equalsIgnoreCase("N/A") )
{
out.println("The Credit card Server is not running, please try to login later.");
}
else if ( rec_ret==1 )
{
out.println("You purchase is successful! You have purchased " + s_ordernum+" books <p>" );
out.println("<p>Your purchase amount is $"+ s_ordertotal );
}
else
{
out.println("You purchase failed! Please enter the correct credit card information." );
}
out.println("<P>");
out.println("</body>");
out.println("</html>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
14.BookAdmin.java
/***********************************************************************
* Master Project
* BookAdmin.java
* This is the interface of book administration service
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.rmi.*;
public interface BookAdmin extends Remote
{
public int Edit_Bookinfo (String thisbookinfo, String thisaction)
throws RemoteException;
public String View_Bookinfo () throws RemoteException;
}
15.BookAdminImpl.java
/**********************************************************************
* Master Project
* BookAdminImpl.java
* This is the Book Admin server functionality definition
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
87
*********************************************************************/
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.rmi.registry.*;
import java.io.*;
import java.net.*;
import java.lang.Object.*;
public class BookAdminImpl extends UnicastRemoteObject
implements BookAdmin {
public BookAdminImpl() throws RemoteException
{
super();
}
public int Edit_Bookinfo (String thisbookinfo, String thisaction)
{
int returncode =0;
RandomAccessFile thisbookfile = null, thatbookfile = null;
System.out.println("Passed infor is: "+ thisbookinfo + "and "+thisaction );
if ( thisaction.equals( "ADD") )
{
// open the file and append this record at the end.
try
{
thisbookfile = new RandomAccessFile ( "bookfile.txt" , "rw"); // open the file
}
catch (IOException ex)
{
System.out.println("Error openning file");
}
try
{
String text, F_Name, F_Author, F_Id, F_price, Num;
String text1, F_Name1, F_Author1, F_Id1, F_price1, Num1;
int index=0;
int dup=0;
StringTokenizer token2 = new StringTokenizer(thisbookinfo,"|");
F_Name1=token2.nextToken();
F_Author1=token2.nextToken();
F_Id1=token2.nextToken();
F_price1=token2.nextToken();
Num1=token2.nextToken();
while((text= thisbookfile.readLine())!=null)
{
String writeline="";
StringTokenizer token1 = new StringTokenizer(text,"|");
F_Name=token1.nextToken();
F_Author=token1.nextToken();
F_Id=token1.nextToken();
F_price=token1.nextToken();
88
Num=token1.nextToken();
if ( F_Id.equals(F_Id1) )
{
dup=1;
returncode =4; // duplicate
System.out.println("Found duplicate in the record, can not insert. ");
}
} // end while
if (dup==0 )
{
long end = thisbookfile.length();
thisbookfile.seek(end);
thisbookfile.writeBytes( thisbookinfo +"\n");
thisbookfile.close();
returncode=2; // success
System.out.println("Add succesulfully!");
}
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e2)
// general exception
{
System.out.println("General error ");
}
}
// this is the editing part
if ( thisaction.equals( "EDIT") )
{
String editstr ="";
try
{
thisbookfile = new RandomAccessFile ( "bookfile.txt" , "rw"); // open the file
}
catch (IOException ex)
{
System.out.println("Error openning file");
}
try
{
String text, F_Name, F_Author, F_Id, F_price, Num;
String text1, F_Name1, F_Author1, F_Id1, F_price1, Num1;
int index=0;
StringTokenizer token1 = new StringTokenizer(thisbookinfo,"|");
F_Name1=token1.nextToken();
F_Author1=token1.nextToken();
F_Id1=token1.nextToken();
F_price1=token1.nextToken();
Num1=token1.nextToken();
89
while((text= thisbookfile.readLine())!=null)
{
String writeline="";
StringTokenizer token2 = new StringTokenizer(text,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
if ( F_Id.equals(F_Id1) )
{
editstr= editstr.concat(thisbookinfo );
System.out.println("Changed!");
}
else
{
editstr = editstr.concat(text);
System.out.println("No change");
}
editstr = editstr.concat("\n");
index +=1;
}
thisbookfile.close();
System.out.println("the index is: "+ index );
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e2)
// general exception
{
System.out.println("General error ");
}
try{
RWTextFile myRWTextFile = new RWTextFile();
File testFile = new File("bookfile.txt");
myRWTextFile.writeContents( testFile, editstr );
}
catch(IOException e3) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e3)
// general exception
{
e3.printStackTrace();
System.out.println("General error ");
}
returncode=1;
}
90
if ( thisaction.equals( "DELETE") )
{
// open the file and append this record at the end.
System.out.println("start deleting... " );
String writestr ="";
try
{
thisbookfile = new RandomAccessFile ( "bookfile.txt" , "rw"); // open the file
}
catch (IOException ex)
{
System.out.println("Error openning file");
}
try
{
String text, F_Name, F_Author, F_Id, F_price, Num;
String text1, F_Name1, F_Author1, F_Id1, F_price1, Num1;
int index=0;
StringTokenizer token1 = new StringTokenizer(thisbookinfo,"|");
F_Name1=token1.nextToken();
F_Author1=token1.nextToken();
F_Id1=token1.nextToken();
F_price1=token1.nextToken();
Num1=token1.nextToken();
while((text= thisbookfile.readLine())!=null)
{
String writeline="";
StringTokenizer token2 = new StringTokenizer(text,"|");
F_Name=token2.nextToken();
F_Author=token2.nextToken();
F_Id=token2.nextToken();
F_price=token2.nextToken();
Num=token2.nextToken();
if ( !F_Id.equals(F_Id1) )
{
writestr=writestr.concat(text);
writestr=writestr.concat("\n");
// System.out.println("writestr is: " + writestr);
index +=1;
}
} // end while
thisbookfile.close();
System.out.println("the index is: "+ index );
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e2)
// general exception
{
91
e2.printStackTrace();
System.out.println("General error ");
}
try{
RWTextFile myRWTextFile = new RWTextFile();
File testFile = new File("bookfile.txt");
myRWTextFile.writeContents( testFile, writestr );
}
catch(IOException e3) //IO Exception
{
System.out.println("Write file error...io error.");
}
catch(Exception e3)
// general exception
{
e3.printStackTrace();
System.out.println("General error ");
}
returncode=3;
}
return returncode;
}
public String View_Bookinfo ()
{
String returnstr="";
ioprocess newprocess = new ioprocess( );
int linecount= newprocess.row_num ( "bookfile.txt");
String Booklines[];
Booklines = new String[linecount];
Booklines = newprocess.readlines ("bookfile.txt");
for ( int i = 0; i < linecount; i++ )
{
returnstr= returnstr+ Booklines[i]+"!";
}
return returnstr;
}
public static void main( String args[] ) throws Exception
{
InetAddress address;
String
portNumber;
int portnum;
String myaddr ="";
String hostName, receive_name;
int i=3;
if(args.length != 1)
System.out.println("enter prot#");
portNumber = args[0];
portnum = Integer.parseInt(portNumber);
System.err.println("Initializing BookAdmin server, Please wait.");
// get to know its own name.
92
try{
address=InetAddress.getLocalHost();
myaddr=address.toString();
System.out.println("the inet address is "+address);
}
catch(Exception e)
{
System.out.println("Can not get host address");
}
StringTokenizer token=new StringTokenizer(myaddr, "/");
hostName=token.nextToken();
System.out.println( "The hostname is: " + hostName );
// Being a client, register itself to well known nameserver by ConnectNS class.
ConnectNS newconnect =new ConnectNS() ;
String serverObjectstr ="//"+hostName+":"+portNumber+"/AdminServer";
int r_status = newconnect.ProxyRegister ( serverObjectstr , 3 ) ;
if (r_status==1)
System.out.print("num is:" + r_status + " and the Book Admin register successful!");
else if ( r_status==2)
System.out.print("Register failed. This server already registered to nameserver.");
else
{
System.out.print("num is: "+ r_status + " and register failed.");
//System.exit(1);
}
try{
// create server object, Being a server
BookAdminImpl tempAdmin = new BookAdminImpl();
// bind BookAdminImpl object to the rmiregistry
String serverObjectName = "//"+hostName+":"+portNumber+"/AdminServer
Registry regi = LocateRegistry.createRegistry(portnum);
Naming.rebind( serverObjectName, tempAdmin );
System.err.println( "\nThe BookAdmin server is up and running." );
}
catch( java.rmi.ConnectException e)
{
System.out.println("creating server bind failed. Server may be temporarily unavailable.");
}
catch( Exception e)
{
System.out.println("BookAdmin server error:"+ e.getMessage());
}
}// end of main
}
16.AdminServlet1.java
/***********************************************************************
* Master Project
* AdminServlet1.java
* This is the servlet to send request and get response from bookadmin server.
* This class is called by login_amdin.jsp page then display all the book information.
93
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Object.*;
import java.rmi.*;
import java.net.*;
public class AdminServlet1 extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
String text, F_Name, F_Author, F_Id, F_price, Num, returnString="";
int linecnt;
String booklines[];
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String thischeck = "NOTCHECKED";
String thiscondition="";
String receive_name="";
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (3) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else System.err.println("the return is: "+ receive_name);
try
{
// name of remote server object bound to rmi registry
String AdminObject = "//"+receive_name +"/AdminServer";
System.out.print("the AdminObject name is: " + AdminObject );
// lookup nameServerImpl remote object in rmiregistry
BookAdmin MybookAdmin =(BookAdmin)Naming.lookup(receive_name );
String testBooklines = MybookAdmin.View_Bookinfo () ;
thischeck = "CHECKED";
int j=0;
StringTokenizer st = new StringTokenizer(testBooklines, "!");
linecnt = st.countTokens() ;
booklines = new String[linecnt];
while (st.hasMoreTokens()) {
94
String w = st.nextToken();
System.out.println("Get book item from server is: "+ w );
booklines[j]=w;
j=j+1;
}// end while
System.out.println();
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connection to bookserver failed,Server may be temporarily unavailable.");
}
catch( Exception w_e)
{
w_e.printStackTrace();
System.out.println("general exception in getting the book service...");
//System.exit(1);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> ");
out.println("<TITLE>On Line Book Store Search Result</TITLE> </HEAD><BODY > ");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa font color=#6633cc SIZE=2> <TR> <td>");
if (linecnt==0 )
{
if ( receive_name.equalsIgnoreCase("None") )
{
out.println("Both Primary and Replicate name Server are unavailable. Please try again later. ");
} else if (thischeck.equalsIgnoreCase("NoTChecked") )
{
out.println(" The Book Admin Server is not running, please try to login later. ");
} else{
out.println(" No result found. Book store is empty now.");
}
}
out.println(" </td> </tr></table>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>");
out.println(" <br><U><B><font color=#6633cc SIZE=5> ");
out.println("On-line Book Store Administration Page</font></B></U></td></tr> </TABLE>");
out.println("<TABLE width=80% BORDER=1 CELLPADDING=3 CELLSPACING=3
bgcolor=#e6e6fa> " );
out.println("<FORM NAME=searching method = post ");
out.println("action=../jsp/admin_add.jsp?p1=&p2=&p3=&p4=&p5=&Act=ADD > ");
out.println("<TR> <TD valign=top align=left><b> Book Name </td> ");
out.println("<TD valign=top align=left><b> Book Author </td> " );
out.println("<TD valign=top align=left> <b> Book ID </td> ");
out.println("<TD valign=top align=left> <b> Book Price </td> " );
out.println("<TD valign=top align=left> <b> Number</b></td> ");
out.println( "<TD valign=top align=left> <input type=submit Value=ADD> </td></tr>");
String text1="", F_Name1="", F_Author1="", F_Id1="", F_price1="", Num1="";
for ( int i = 0; i < linecnt; i++ )
95
{
String inputname="";
inputname = "input" + String.valueOf(i);
StringTokenizer st2 = new StringTokenizer(booklines[i], "|");
while (st2.hasMoreTokens()) {
F_Name1=st2.nextToken();
F_Author1=st2.nextToken();
F_Id1=st2.nextToken();
F_price1=st2.nextToken();
Num1=st2.nextToken();
// System.out.println("the book is: "+ F_Name1 + " " +Num1 );
} // end of while
out.println("<TR> <TD valign=top align=left>" + F_Name1 + " </td> ");
out.println("<TD valign=top align=left> "+ F_Author1+ " </td> " );
out.println("<TD valign=top align=left> "+F_Id1 + " </td> ");
out.println("<TD valign=top align=left> "+ F_price1 + " </td> " );
out.println("<TD valign=top align=left> "+ Num1 + "</td> ");
out.println(" <TD valign=top align=left><STRONG> ");
String newstr= java.net.URLEncoder.encode( F_Name1 );
String newstr2= java.net.URLEncoder.encode( F_Author1);
out.println("<A HREF=../jsp/update.jsp?p1="+newstr+"&p2="+ newstr2 +"&p3="+ F_Id1+"&p4="+
F_price1+"&p5="+ Num1+"&Act=CHANGE> EDIT</a> </STRONG> </TD></tr> " );
} // end for
out.println("</TABLE> </FORM> </TABLE> ");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
17.AdminServletupdate.java
/***********************************************************************
* Master Project
* AdminServletupdate.java
* This is the implementation of bookadmin interface
* This is called by Bookstore.jsp page and edit the book information
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
96
import java.awt.event.*;
import javax.swing.*;
import java.lang.Object.*;
import java.rmi.*;
public class AdminServletupdate extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
String text, F_Name, F_Author, F_Id, F_price, Num, returnString="";
int linecnt;
String booklines[];
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String thischeck = "NOTCHECKED";
String thiscondition="";
String receive_name="";
String s1= request.getParameter("h_name");
String s2 = request.getParameter("h_author");
String s3= request.getParameter("h_id");
String s4= request.getParameter("h_price");
String s5 = request.getParameter("h_num");
String UserAct = request.getParameter("UserAction");
String bookline = "";
bookline= s1+"|"+s2+"|"+s3+"|"+s4+"|"+s5;
int retint=0;
if ( UserAct.equalsIgnoreCase("CHANGE") )
{
UserAct = request.getParameter("submit");
System.out.println("the action change to "+ UserAct );
}
ConnectNS newconnect =new ConnectNS() ;
receive_name = newconnect.ProxyGetname (3) ;
if ( receive_name.equalsIgnoreCase("None") )
{
System.out.println("Both Primary and Replicate name Server are unavailable.");
}
else if ( receive_name.equalsIgnoreCase("N/A") )
{
System.out.println("The reuqested server type 1 is not running.");
}
else
System.err.println("the return is: "+ receive_name);
try
{
// lookup nameServerImpl remote object in rmiregistry
BookAdmin MybookAdmin =(BookAdmin)Naming.lookup( receive_name );
System.out.print("Before call server p are " + bookline +" " + UserAct );
retint = MybookAdmin.Edit_Bookinfo (bookline, UserAct ) ;
97
System.out.println("the retrun int is: " + retint);
System.out.println();
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connection to bookserver failed,Server may be temporarily unavailable.");
receive_name = "N/A";
}
catch( Exception w_e)
{
w_e.printStackTrace();
System.out.println("general exception in getting the book service...");
//System.exit(1);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> ");
out.println("<TITLE>On Line Book Store Administration Page</TITLE> </HEAD><BODY > ");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR> <td> </td> ");
out.println("<td align=right valign=bottom> ");
out.println(" </td> </tr></table>");
out.println("<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>");
out.println(" <br><U><B><font color=#6633cc SIZE=5> ");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println("Both Primary and Replicate name Server are unavailable. Please try later. </font> </B>
</U> </td></tr> <FORM NAME=searching method = post action=../servlet/AdminServlet1> <td
align=center><input type=submit Value=GoBack ></td> </TABLE> ");
} else if (receive_name.equalsIgnoreCase("N/A") )
{
out.println(" The Book Admin Server is not running, please try to login later. </font> </B> </U>
</td></tr><FORM NAME=searching method = post action=../servlet/AdminServlet1> <td
align=center><input type=submit Value=GoBack ></td> </TABLE>");
} else if ( retint ==4 )
{
out.println("Please change the new book id, it's duplcate with other books.</font> </B> </U>
</td></tr><FORM NAME=searching method = post action=../servlet/AdminServlet1> <td
align=center><input type=submit Value=GoBack ></td> </TABLE>");
}
else
{
out.println("The following books has been " + UserAct +"ED</font></B></U></td></tr>
</TABLE>");
out.println("<TABLE width=80% BORDER=1 CELLPADDING=3 CELLSPACING=3
bgcolor=#e6e6fa> " );
out.println("<FORM NAME=searching method = post ");
out.println("action=../servlet/AdminServlet1 > ");
out.println("<TR> <TD valign=top align=left><b> Book Name </td> ");
out.println("<TD valign=top align=left><b> Book Author </td> " );
out.println("<TD valign=top align=left> <b> Book ID </td> ");
out.println("<TD valign=top align=left> <b> Book Price </td> " );
out.println("<TD valign=top align=left> <b> Number</b></td> ");
98
String text1="", F_Name1="", F_Author1="", F_Id1="", F_price1="", Num1="";
out.println("<TR> <TD valign=top align=left>" + s1 + " </td> ");
out.println("<TD valign=top align=left> "+ s2 + " </td> " );
out.println("<TD valign=top align=left> "+ s3 + " </td> ");
out.println("<TD valign=top align=left> "+ s4 + " </td> " );
out.println("<TD valign=top align=left> "+ s5 + "</td></tr> ");
out.println("<TR> <TD valign=top align=left> </td> ");
out.println("<TD valign=top align=left> </td> " );
out.println("<TD valign=top align=center> <input type=submit Value=GoBack > </td> ");
out.println("<TD valign=top align=left> </td> " );
out.println("<TD valign=top align=left> </td></tr> ");
out.println("</TABLE> </FORM> </TABLE> ");
}
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
18. ioprocess.java
/**********************************************************************
* Master Project
* ioprocess.java
* This is a helper class to assist other class deal with read write file issue.
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.awt.*;
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.io.File;
public class ioprocess
{
public String linelist[] ;
public int size, position=0;
public String filename, one_record ;
private RandomAccessFile file = null;
public ioprocess ()
{
//
}
99
// Initialize string array
public ioprocess ( String mylines[], int mysize, String myfilename )
{
size= mysize;
linelist = new String[size];
for ( int i = 0; i < size; i++ )
linelist[ i ] =mylines[i];
filename = myfilename ;
}
public String[] readlines ( String myfilename)
{
int line_num =0;
filename = myfilename;
try
{
file = new RandomAccessFile ( filename, "r");
}
catch (IOException ex)
{
System.out.println("Error opening file " );
}
try
{
while ( ( one_record = file.readLine() ) != null )
{
line_num = line_num +1;
//System.out.println("the record is " + one_record);
} // end while
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Error reading file " );
}
catch(Exception e2) // general exception
{
System.out.println("General error in file " );
}
String retrunlines[] = new String [line_num];
line_num=0;
try
{
file.seek(0);
while ( ( one_record = file.readLine() ) != null )
{
retrunlines[ line_num ] = one_record ;
line_num = line_num +1;
} // end while
file.close();
100
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Error reading file " );
}
catch(Exception e2) // general exception
{
System.out.println("General error file " );
}
return retrunlines ;
}
public int writelines ( String mylines[], int mysize, String myfilename )
{
try
{
file = new RandomAccessFile ( myfilename , "rw"); // open the file
}
catch (IOException ex)
{
System.out.println("Error creating file " );
}
try
{
file.seek(0);
// at the begining of the file
for ( int i = 0; i < mysize; i++ )
{
System.out.println("writing record " + mylines[i] );
file.writeBytes(mylines[i]+"\n");
}
file.close();
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Write file error...io error. " );
}
catch(Exception e2)
// general exception
{
System.out.println("General error " );
}
return 1;
}
public int row_num ( String myfilename)
{
int line_num =0;
filename = myfilename;
try
{
file = new RandomAccessFile ( filename, "r");
101
}
catch (IOException ex)
{
System.out.println("Error opening file");
}
try
{
while ( ( one_record = file.readLine() ) != null )
{
line_num = line_num +1;
System.out.println("the record is " + one_record);
} // end while
} // end try
catch(IOException e1) //IO Exception
{
System.out.println("Error reading file ");
}
catch(Exception e2) // general exception
{
System.out.println("General error in file " );
}
return line_num;
}
}
19. RWTextFile.java
/***********************************************************************
* Master Project
* RWTextFile.java
* This is the helper class process read and write to text file
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
public class RWTextFile {
static public String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex){
ex.printStackTrace();
}
102
finally {
try {
if (input!= null) {
//flush and close both "input" and its underlying FileReader
input.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
return contents.toString();
}
static public void writeContents(File aFile, String aContents)
throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
output.write( aContents );
}
finally {
if (output != null) output.close();
}
}
}
20. CEncrypt.java
/**********************************************************************
* Master Project
* CEncrypt.java
* This is the encription class for encripting user password before send it out.
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CEncrypt
{
103
static final String key = "Encrypt"; // The key for 'encrypting' and 'decrypting'.
public CEncrypt()
{
super();
}
public static String encryptString(String str)
{
StringBuffer sb = new StringBuffer (str);
int lenStr = str.length();
int lenKey = key.length();
// For each character in our string, encrypt it...
for ( int i = 0, j = 0; i < lenStr; i++, j++ )
{
if ( j >= lenKey ) j = 0; // Wrap 'round to beginning of key string.
// XOR the chars together. Must cast back to char to avoid compile error.
//
sb.setCharAt(i, (char)(str.charAt(i) ^ key.charAt(j)));
}
return sb.toString();
}
public static String decryptString(String str)
{
//
// To 'decrypt' the string, simply apply the same technique.
return encryptString(str);
}
}
21. ConnectNS.java
/**********************************************************************
* Master Project
* ConnectNS.java
* This code will take the request and connect nameserver onbehalf of client
* Date: Oct 1, 2003
* Wrtten by: Amy (Wenping) Peng
***********************************************************************/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Object.*;
import java.rmi.*;
import java.net.*;
public class ConnectNS {
public ConnectNS()
{
104
super();
}
public String ProxyGetname ( int Servertype )
{
// name of remote server object bound to rmi registry
String receive_name="None";
System.out.println("Start connecting to primary name server...");
try
{
String nameObject="//romeo.ecs.csus.edu/theNameServer";
// lookup nameServerImpl remote object in rmiregistry
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
receive_name = myname.GetServername (Servertype ) ;
System.out.print("the receive name from primary nameserver: " + receive_name);
System.out.println();
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connection to primary nameserver failed. Server unavailable.");
System.out.println("Try to connect to Replicate name Server..");
try
{
String nameObject="//romeo.ecs.csus.edu:5000/RepliNameServer";
// lookup nameServerImpl remote object in rmiregistry
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
receive_name = myname.GetServername (Servertype ) ;
System.out.print("the receive name from Replicate nameserver: " + receive_name);
System.out.println();
}
catch( java.rmi.ConnectException e2)
{
System.out.println("Connection to Replicate nameserver failed. Server unavailable.");
System.out.println("Return message to notify the client...");
}
catch( Exception w_e2)
{
w_e2.printStackTrace();
System.out.println("General exception in get server name...");
// System.exit(1);
}
}
catch( Exception w_e)
{
w_e.printStackTrace();
System.out.println("General exception in connecint nameservers..");
// System.exit(1);
}
105
return receive_name;
}
public int ProxyRegister ( String Server_Name, int Servertype )
{
int reg_status=0;
try
{
// name of remote server object bound to rmi registry
String nameObject ="//romeo.ecs.csus.edu/theNameServer";
// lookup nameServerImpl remote object in rmiregistry
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
reg_status= myname.RegisterServer ( Server_Name,Servertype);
if (reg_status>0)
System.out.print("num is:" + reg_status + " and the register server successful!");
else
System.out.print("num is: "+reg_status + " and the register server failed!");
System.out.println();
reg_status=1;
}
catch( java.rmi.ConnectException e)
{
System.out.println("Connect to primary nameserver failed. Server unavailable.");
//System.exit(1);
}
catch( Exception w_e)
{
w_e.printStackTrace();
System.out.println("General exception in Register...");
//System.exit(1);
}
if ( reg_status==0 )
{
try
{
String nameObject="//romeo.ecs.csus.edu:5000/RepliNameServer";
// lookup nameServerImpl remote object in rmiregistry
nameServer myname =(nameServer)Naming.lookup(nameObject);
// call the name server to get the servcie server
reg_status= myname.RegisterServer ( Server_Name,Servertype);
if (reg_status>0)
System.out.print("num is:" + reg_status + " and the register server successful!");
else
System.out.print("num is: "+reg_status + " and the register server failed!");
System.out.println();
reg_status=1;
}
catch( java.rmi.ConnectException e2)
{
System.out.println("Connection to Replicate nameserver failed. Server unavailable.");
System.out.println("Return message to notify the client...");
}
catch( Exception w_e2)
106
{
w_e2.printStackTrace();
System.out.println("General exception in get server name...");
// System.exit(1);
}
}
return reg_status;
}
}
107
APPENDIX C: LIST OF JSP PROGRAMS
1.Login_user.jsp
<HTML> <HEAD>
<SCRIPT language="javascript">
function isReady(form)
{
var id = form.name_field.value + "";
var pwd = form.password_field.value + "";
var order_num = form.password_field.value + "";
if(id.length == 0 || id == "")
{
alert("Please enter your login name!");
form.name_field.focus();
return false;
}
if(pwd.length == 0 || pwd == "")
{
alert("Please enter your password!");
form.password_field.focus();
return false;
}
return true;
}
</script>
<TITLE>Login Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH="80%" bgcolor=#e6e6fa> <TR> </TR> <TR> <td>
</td>
<td> <a href="login_admin.jsp">Administrator Login </a> </td>
<td align=right valign=bottom>
<img src="bookicon.gif" width=70 height=60 border="0">
</td> </tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br><U><B><font color="#6633cc" SIZE=5>
Welcome to the Online Book Store </font></B></U> </td>
</tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br> <B><font color="#6633cc">
User Login Session, Please login</font></B>
<FORM NAME=register method = "post" onSubmit="return isReady(this)"
action="../servlet/AuthClientServlet">
<INPUT TYPE=hidden NAME=LoginAction Value=RESULT>
<INPUT TYPE=hidden NAME=thislogintype Value=1>
<TABLE width="80%" BORDER=0 CELLPADDING=3 CELLSPACING=3>
108
<TR><TD valign=bottom align=center> <FONT SIZE=-1>Login Name: </FONT>
<INPUT NAME=name_field SIZE=15 TABINDEX=1></TD></TR>
<TR><TD valign=top align=center> <FONT SIZE=-1>Password: </FONT>
<INPUT SIZE=15 TYPE="password" NAME=password_field TABINDEX=2></TD></TR>
<TR><TD ALIGN="center">
<input type="submit" tabindex=3 Value="Submit">
<INPUT TABINDEX=4 TYPE=RESET VALUE="Cancel"></TD></TR>
<TR><TD valign=top align=center>
</TD></TR> </FORM> </TABLE>
</BODY></HTML>
2. Login_admin.jsp
<HTML> <HEAD>
<SCRIPT language="javascript">
function isReady(form)
{
var id = form.name_field.value + "";
var pwd = form.password_field.value + "";
if(id.length == 0 || id == "")
{
alert("Please enter your login name!");
form.name_field.focus();
return false;
}
if(pwd.length == 0 || pwd == "")
{
alert("Please enter your password!");
form.password_field.focus();
return false;
}
return true;
}
</script>
<TITLE>Login Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH="80%" bgcolor=#e6e6fa> <TR> </TR>
<TR> <td> </td>
<td> <a href="login_user.jsp">User Login </a> </td>
<td align=right valign=bottom>
<img src="bookicon.gif" width=70 height=60 border="0">
</td>
</tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br><U><B><font color="#6633cc" SIZE=5>
Welcome to the Online book Store </font></B></U> </td>
</tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br> <B><font color="#6633cc">
Book Administrator Login Session, Please login</font></B>
109
<FORM NAME=register method = "post" onSubmit="return isReady(this)"
action="../servlet/AuthClientServlet">
<INPUT TYPE=hidden NAME=LoginAction Value=RESULT>
<INPUT TYPE=hidden NAME=thislogintype Value=2>
<TABLE width="80%" BORDER=0 CELLPADDING=3 CELLSPACING=3>
<TR><TD valign=bottom align=center><FONT SIZE=-1>Login Name: </FONT>
<INPUT NAME=name_field SIZE=15 TABINDEX=1></TD></TR>
<TR><TD valign=top align=center><FONT SIZE=-1>Password: </FONT>
<INPUT SIZE=15 TYPE="password" NAME=password_field TABINDEX=2></TD></TR>
<TR><TD ALIGN="center">
<input type="submit" tabindex=3 Value="Submit">
<INPUT TABINDEX=4 TYPE=RESET VALUE="Cancel"></TD></TR>
<TR><TD valign=top align=center>
</TD></TR> </FORM> </TABLE>
</BODY></HTML>
3. login_admin_add.jsp
<HTML> <HEAD>
<SCRIPT language="javascript">
function isReady(form)
{
var id = form.name_field.value + "";
var pwd = form.password_field.value + "";
var thetype = form.logintypefield.value + "";
if(id.length == 0 || id == "")
{
alert("Please enter your login name!");
form.name_field.focus();
return false;
}
if(pwd.length == 0 || pwd == "")
{
alert("Please enter your password!");
form.password_field.focus();
return false;
}
if(thetype.length == 0 || thetype == "")
{
alert("Please enter your type!");
form.logintypefield.focus();
return false;
}
return true;
}
</script>
<TITLE>Login Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR> </TR>
110
<TR> <td> </td>
<td> <a href="login_user.jsp">User Login </a> </td>
<td align=right valign=bottom>
<img src="bookicon.gif" width=70 height=60 border="0">
</td>
</tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br><U><B><font color="#6633cc" SIZE=5>
Welcome to the Online book Store </font></B></U> </td>
</tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
<br> <B><font color="#6633cc">
Book Administrator ADD Login Session </font></B>
<FORM NAME=register method = "post" onSubmit="return isReady(this)"
action="../servlet/AuthClientadd">
<INPUT TYPE=hidden NAME=LoginAction Value=RESULT>
<INPUT TYPE=hidden NAME=thislogintype Value=2>
<TABLE width="80%" BORDER=0 CELLPADDING=3 CELLSPACING=3>
<TR><TD valign=bottom align=center><FONT SIZE=-1>Login Name: </FONT>
<INPUT NAME=name_field SIZE=15 TABINDEX=1></TD></TR>
<TR><TD valign=top align=center><FONT SIZE=-1>Password: </FONT>
<INPUT SIZE=15 TYPE="password" NAME=password_field TABINDEX=2></TD></TR>
<TR><TD ALIGN="center">
<TR><TD valign=top align=center><FONT SIZE=1>Type: </FONT>
<INPUT SIZE=15 NAME= logintypefield TABINDEX=2></TD></TR>
<TR><TD ALIGN="center">
<input type="submit" tabindex=3 Value="ADD">
<INPUT TABINDEX=4 TYPE=RESET VALUE="Cancel"></TD></TR>
<TR><TD valign=top align=center>
</TD></TR> </FORM> </TABLE>
</BODY></HTML>
4. BookStore.jsp
<HTML> <HEAD>
<SCRIPT language="javascript">
function isReady(form)
{
// if selected, then it should have a value. otherwise return
var rad_checked ="NO";
var indexchecked = "";
var searchinput="";
for (var index=0; index<3; index++)
{
if (window.document.searching.Searchbook[index].checked == true)
{
rad_checked ="YES";
indexchecked = index;
}
}
if ( rad_checked =="NO")
{
111
alert ( "You must chose one option first");
return false;
}
if ( rad_checked =="YES")
{
if ( indexchecked==0 && window.document.searching.searchbyid.value =="")
{
alert("Please fill out the value of your selection");
return false;
}
if ( indexchecked==1 && window.document.searching.searchbyname.value =="")
{
alert("Please fill out the value of your selection");
return false;
}
if ( indexchecked==2 && window.document.searching.searchbyauthor.value =="")
{
alert("Please fill out the value of your selection");
return false;
}
if ( indexchecked==0 && window.document.searching.searchbyid.value !="")
{
searchinput = window.document.searching.searchbyid.value;
}
if ( indexchecked==1 && window.document.searching.searchbyname.value !="")
{
searchinput = window.document.searching.searchbyname.value;
}
if ( indexchecked==2 && window.document.searching.searchbyauthor.value !="")
{
searchinput = window.document.searching.searchbyauthor.value;
}
}
window.document.searching.SearchAction.value= searchinput ;
window.document.searching.SearchType.value= indexchecked;
return true;
}
</script>
<TITLE>On Line Book Store Main Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH="80%" bgcolor=#e6e6fa> <TR> </TR> <TR> <td>
</td>
<td> <a href="login_admin_add.jsp">Administrator ADD Login </a> </td>
<td align=right valign=bottom>
<img src="bookicon.gif" width=70 height=60 border="0">
</td> </tr></TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valitn=bottom align=center>
112
<br><U><B><font color="#6633cc" SIZE=5>
Welcome to the On-line Book Store</font></B></U>
</td></tr> </TABLE>
<TABLE WIDTH="80%" bgcolor=#e6e6fa>
<TR><TD valign=bottom align=center> <br><U><B><font color="#6633cc">
</font></B></U>
<FORM NAME=searching method = "post" onSubmit="return isReady(this)"
action="../servlet/BookshopServlet">
<INPUT TYPE=hidden NAME=SearchAction Value="">
<INPUT TYPE=hidden NAME=SearchType Value="" >
<TABLE width="80%" BORDER=0 CELLPADDING=3 CELLSPACING=3>
<TR><TD valign=top align=left>
<input type = "radio" name="Searchbook" value="1" > Search By BookID </td>
<TD valign=bottom align=left><FONT SIZE=-1> </FONT>
<INPUT NAME=searchbyid SIZE=30 TABINDEX=1></TD> </tr>
<TR><TD valign=top align=left>
<input type = "radio" name="Searchbook" value="1"> Search By Book Name </td>
<TD valign=bottom align=left><FONT SIZE=-1> </FONT>
<INPUT NAME=searchbyname SIZE=30 TABINDEX=1></TD> </tr>
<TR><TD valign=top align=left>
<input type = "radio" name="Searchbook" value="1"> Search By Book Author </td>
<TD valign=bottom align=left><FONT SIZE=-1> </FONT>
<INPUT NAME=searchbyauthor SIZE=30 TABINDEX=1></TD> </tr>
<TR>
<td align=center> </td> <td>
<input type="submit" tabindex=3 Value="Submit">
<INPUT TABINDEX=4 TYPE=RESET VALUE="Cancel"> </td> </TR>
</TABLE>
</FORM>
</TABLE>
</BODY></HTML>
5. order.jsp
<SCRIPT language="javascript">
function isNum(argvalue) {
for (var n = 0; n < argvalue.length; n++)
{
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;
}
return true;
}
function isReady(form)
{
var id = form.creditnum.value + "";
var pwd = form.creditpwd.value + "";
var order_num = form.orderamount.value;
var myprice = 100* <%=request.getParameter("fprice")%>;
var myprice2= parseInt ( myprice);
// alert("the myprice2 is: $"+3* myprice2);
if(order_num.length == 0 || order_num == "")
{
alert("Please enter the number of book you want to order!");
113
form.orderamount.focus();
return false;
}
if(order_num<= 0 || order_num ><%=request.getParameter("fnum")%> )
{
alert("Please enter the number of book >0 and also < than "+
<%=request.getParameter("fnum")%>);
form.orderamount.focus();
return false;
}
// var order_total= fprice * order_num;
if(id.length == 0 || id == "")
{
alert("Please enter the credit card number!");
form.creditnum.focus();
return false;
}
if(pwd.length == 0 || pwd == "")
{
alert("Please enter your credit card expiration date!");
form.creditpwd.focus();
return false;
}
if (!isNum(order_num))
{
alert("Please enter an int value for number of books!");
form.orderamount.focus();
return false;
}
if (!isNum(id))
{
alert("Please enter an int value forcredit card number!");
form.creditnum.focus();
return false;
}
// alert("the order price is: $"+<%=request.getParameter("fprice")%> );
alert("the order total is: $"+ parseInt ( 100*order_num *<%=request.getParameter("fprice")%>)/100 );
return true;
}
</script>
<HTML> <HEAD>
<TITLE>On Line Book Store Order page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH=80% bgcolor=#e6e6fa>
<TR> <td> </td>
<td align=right valign=bottom>
</td> </tr>
</TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>
<br><U><B><font color=#6633cc SIZE=5>
114
On-line Book Store Order Book Page</font></B></U></td></tr> </TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa><TR><TD valign=bottom align=center>
<br><U><B><font color=#6633cc> </font></B></U>
<FORM NAME=ordering method = post onSubmit="return isReady(this)"
action=../servlet/CreditServlet >
<INPUT TYPE=hidden NAME=UserAction ><INPUT TYPE=hidden NAME=SearchType >
<TABLE width=60% BORDER=0 CELLPADDING=3 CELLSPACING=3>
<INPUT TYPE=hidden NAME=h_name value = <%=request.getParameter("fname")%> >
<INPUT TYPE=hidden NAME=h_author value= <%=request.getParameter("fauthor")%> >
<INPUT TYPE=hidden NAME=h_id value = <%=request.getParameter("fid")%> >
<INPUT TYPE=hidden NAME=h_price value= <%=request.getParameter("fprice")%> >
<INPUT TYPE=hidden NAME=h_num value=<%=request.getParameter("fnum")%> >
<TR> <TD valign=top align=left> Book Name: </td> <TD>
<%=java.net.URLDecoder.decode(request.getParameter("fname"))%> </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book Author: </td> <TD>
<%=java.net.URLDecoder.decode(request.getParameter("fauthor"))%> </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book ID: </td> <TD>
<%=request.getParameter("fid")%> </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book Price: </td> <TD>
<%=request.getParameter("fprice")%> </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book number availble </td> <TD>
<%=request.getParameter("fnum")%>
</FONT></TD> </tr>
<TR> <TD valign=top align=left> How many books do you want to order</td> <TD>
<input type=text tabindex=3 name=orderamount > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Please enter your eight digit credit account number </td> <TD>
<input type=text tabindex=3 name=creditnum > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Credit card expiration date (format: 04/01/2003) </td> <TD>
<input TYPE=text tabindex=3 name=creditpwd > </FONT></TD> </tr>
<TR> <TD valign=bottom align=left><FONT SIZE=1>
<input type=submit tabindex=3 Value=Order> </td> <td> </FORM>
<FORM NAME=back method = post action=../jsp/BookStore.jsp >
<input type=submit tabindex=3 Value=Back > </td></tr>
</TABLE> </TABLE>
</BODY>
</HTML>
6. admin_add.jsp
<SCRIPT language="javascript">
function isNum(argvalue) {
for (var n = 0; n < argvalue.length; n++)
{
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;
}
return true;
}
function isDouble(argvalue) {
for (var n = 0; n < argvalue.length; n++)
{
if ((argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9" ) && !(argvalue.substring(n, n+1)
=="."))
return false;
}
return true;
115
}
function isReady(form)
{
var r1 = form.h_name.value + "";
var r2 = form.h_author.value + "";
var r3 = form.h_id.value + "";
var r4 = form.h_price.value + "";
var r5 = form.h_num.value + "";
if(r1.length == 0 || r1 == "")
{
alert("Please enter The Book number!");
form.h_name.focus();
return false;
}
if(r2.length == 0 || r2 == "")
{
alert("Please enter The Book Author First!");
form.h_author.focus();
return false;
}
if(r3.length == 0 || r3 == "")
{
alert("Please enter The Book ID!");
form.h_id.focus();
return false;
}
if(r4.length == 0 || r4 == "")
{
alert("Please enter The Book Price!");
form.h_price.focus();
return false;
}
if(r5.length == 0 || r5 == "")
{
alert("Please enter The Book number!");
form.h_num.focus();
return false;
}
if (!isDouble(r4))
{
alert("Please enter a nemeric value for book price!");
form.h_price.focus();
return false;
}
if (!isNum(r5))
{
alert("Please enter an int value for book number!");
form.h_num.focus();
return false;
}
116
return true;
}
</script>
<HTML> <HEAD>
<TITLE>On Line Book Store Administration Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH=80% bgcolor=#e6e6fa>
<TR> <td> </td>
<td align=right valign=bottom>
</td> </tr>
</TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>
<br><U><B><font color=#6633cc SIZE=5>
On-line Book Store Administrator Add Page</font></B></U></td></tr> </TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa><TR><TD valign=bottom align=center>
<br><U><B><font color=#6633cc> </font></B></U>
<FORM NAME=form method = post onSubmit="return isReady(this)"
action=../servlet/AdminServletupdate >
<TABLE width=60% BORDER=0 CELLPADDING=3 CELLSPACING=3>
<INPUT TYPE=hidden NAME=UserAction Value="ADD" >
<TR> <TD valign=top align=left> Book Name: </td> <TD>
<INPUT NAME=h_name value="" > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book Author: </td> <TD>
<INPUT NAME=h_author value= "" > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book ID: </td> <TD>
<INPUT NAME=h_id value= "" > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book Price: </td> <TD>
<INPUT NAME=h_price value="" > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book number availble </td> <TD>
<INPUT NAME=h_num value="" > </FONT></TD> </tr>
<TR> <TD valign=bottom align=left><FONT SIZE=1>
<input type=submit tabindex=3 Value= ADD> </td> <TD> </Form>
<FORM NAME=form2 method = post action=../servlet/AdminServlet1 >
<input type=submit tabindex=3 Value=Back > </td></tr>
</TABLE> </FORM> </TABLE>
</BODY>
</HTML>
7. update.jsp
<SCRIPT language="javascript">
function isNum(argvalue) {
for (var n = 0; n < argvalue.length; n++)
{
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;
}
return true;
}
function isDouble(argvalue) {
for (var n = 0; n < argvalue.length; n++)
{
117
if ((argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9" ) && !(argvalue.substring(n, n+1)
=="."))
return false;
}
return true;
}
function isReady(form)
{
var r1 = form.h_name.value + "";
var r2 = form.h_author.value + "";
var r3 = form.h_id.value + "";
var r4 = form.h_price.value + "";
var r5 = form.h_num.value + "";
if(r1.length == 0 || r1 == "")
{
alert("Please enter The Book Name First!");
form.h_name.focus();
return false;
}
if(r2.length == 0 || r2 == "")
{
alert("Please enter The Book Author First!");
form.h_author.focus();
return false;
}
if(r3.length == 0 || r3 == "")
{
alert("Please enter The Book ID!");
form.h_id.focus();
return false;
}
if(r4.length == 0 || r4 == "")
{
alert("Please enter The Book Price!");
form.h_price.focus();
return false;
}
if(r5.length == 0 || r5 == "")
{
alert("Please enter The Book number!");
form.h_num.focus();
return false;
}
if (!isDouble(r4))
{
alert("Please enter a nemeric value for book price!");
form.h_price.focus();
return false;
}
118
if (!isNum(r5))
{
alert("Please enter an int value for book number!");
form.h_num.focus();
return false;
}
return true;
}
</script>
<HTML> <HEAD>
<TITLE>On Line Book Store Administration Page</TITLE>
</HEAD>
<BODY >
<TABLE WIDTH=80% bgcolor=#e6e6fa>
<TR> <td> </td>
<td align=right valign=bottom>
</td> </tr>
</TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa> <TR><TD valitn=bottom align=center>
<br><U><B><font color=#6633cc SIZE=5>
On-line Book Store Administrator Edit Page</font></B></U></td></tr> </TABLE>
<TABLE WIDTH=80% bgcolor=#e6e6fa><TR><TD valign=bottom align=center>
<br><U><B><font color=#6633cc> </font></B></U>
<FORM NAME=form method = post onSubmit="return isReady(this)"
action=../servlet/AdminServletupdate>
<TABLE width=60% BORDER=0 CELLPADDING=3 CELLSPACING=3>
<INPUT TYPE=hidden NAME=UserAction Value="CHANGE" >
<TR> <TD valign=top align=left> Book Name: </td> <TD>
<INPUT NAME=h_name size= 35 value="<%=request.getParameter("p1")%>" READONLY>
</FONT></TD>
<TD valign=top align=left> (Read only) </td> </tr>
<TR> <TD valign=top align=left> Book Author: </td> <TD>
<INPUT NAME=h_author size= 35 value= <%=request.getParameter("p2")%> READONLY>
</FONT></TD>
<TD valign=top align=left> (Read only) </td> </tr>
<TR> <TD valign=top align=left> Book ID: </td> <TD>
<INPUT NAME=h_id size= 35 value= <%=request.getParameter("p3")%> READONLY>
</FONT></TD>
<TD valign=top align=left> (Read only) </td> </tr>
<TR> <TD valign=top align=left> Book Price: </td> <TD>
<INPUT NAME=h_price size= 35 value= <%=request.getParameter("p4")%> > </FONT></TD> </tr>
<TR> <TD valign=top align=left> Book number availble </td> <TD>
<INPUT NAME=h_num size= 35 value= <%=request.getParameter("p5")%> > </FONT></TD> </tr>
<TR> <TD valign=bottom align=left><FONT SIZE=1>
<input type=submit name=submit tabindex=3 Value= "EDIT" > </td>
<TD valign=bottom align=left><FONT SIZE=1>
<input type=submit name=submit tabindex=3 Value= "DELETE" > </td> </tr>
</TABLE> </FORM> </TABLE>
</BODY>
</HTML>