CHAPTER 1: INTRODUCTION
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
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: __________________
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 Date
Department of Computer Science
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 built-in network capabilities that make it easy to develop Internet-based and web-based applications. Java RMI (Remote Method Invocation) technology was implemented in 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
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.
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
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
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
Chapter 1: introduction
2 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
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 . 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.
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.
➢ APPENDIX A – User Manual, Program lists and Test cases.
➢ APPENDIX B – List of Java Programs.
➢ APPENDIX C – List of JSP Programs
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.
Figure 1: Connections made when client uses RMI
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.
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
On UNIX, a port number can be ranging from 5000 and 32767; On Windows, the default port is 1099.
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, reusability, and crash protection. In recent web development, servlets are a popular choice for building interactive web applications.
[pic]
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 .
Servlet Methods
Servlet interacts between client and server. It has some basic methods such as:
➢ doGet, if the servlet supports HTTP GET requests
➢ 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.
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.
login
Get Service Register
Get server name
User
Register
Get Service
Get Server Name
Payment
Register
Get Service
Get Server Name
Register
Get Service
Get Server Name
Figure 3 Application Structure Chart
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.
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 client-server 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. 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:
[pic]
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 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
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).
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
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
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.
• 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.
[pic]
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.
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
Register Service
NO Yes
Figure 6 Logical View of User login
4.1.2 Description of data flow
➢ 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:
[pic]
Figure 7 User login interface
4.2 Logical flow of book searching services:
4.2.1 Diagram for book searching:
Find Book Server
Register Services
If want to purchase
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.
➢ 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:
[pic]
Figure 9 Book searching interface
4.3 Logical flow for book purchase
4.3.1 Diagram for purchasing books with credit card:
Response Credit Server Name
Register Credit Services
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.
4.3.3 User interface for book purchase page:
[pic]
Figure 11 Interface of book purchasing services
If the purchase is executed successfully, the user will get a confirmation as below:
[pic]
Figure 12 Interface of book purchasing confirmation
4.4 Logical flow for book Administrator
4.4.1 Logical flow for book administration:
Find AuthenServer
Register itself
Register Service
NO Yes
Figure 13 Logical View of Book Administration
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
[pic]
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.
[pic]
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:
[pic]
Figure 16 User interface of book edited confirmation
Figure 16 show the confirmation that the user has successfully edited the book information.
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:
1. Download Tomcat software package from and unpack the zip file of Tomcat version 4.0.6.
2. Enable the ROOT context. Edit \\install_dir\conf\server.xml and uncomment this line: .
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/*.
invoker
/servlet/*
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.
It will allow Tomcat server to detect any changes happened to the servlet classes.
5. Set the JAVA_HOME environment variable. C:\jdk1.3.1_09
6. Set the CATALINA_HOME environment variable to refer to the top-level Tomcat installation directory. C:\tomcat_4.0.6
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
8. Create JavaScript pages and put the files under \\install_dir\webapps\ROOT folder, access the page from the browser at . If the 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:
5.4 Create Application Directories
5.4.1 Introduction of the directory structure:
[pic]
Figure 17 Tomcat web application directory structure
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 |This is the root directory of the web application. All JSP and HTML files|
| |are stored here. |
|/BS/WEB-INF |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. |
|/BS/WEB-INF/classes |This directory is where servlets and all other utility classes are |
| |located. |
|/BS/WEB-INF/lib |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. |
5.4.3. Add BS application to Tomcat:
In order to let Tomcat know where the new application is, edit server.xml file and add the following entries:
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\WEB-INF\classes\ and browse to 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:
...
Simple
new_servlet
….
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
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 “.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: “.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, 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.
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.
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
6. Servlets and JavaServer Pages (JSP) 1.0: A Tutorial at
7. Configuring & Using Apache Tomcat 4 at
APPENDIX A: user manual
1. Lists of java programs
|Java program name |Class name |Server name |
|nameServer.java |nameServer.class |Name Server |
|nameServerImpl.java |nameServerImpl.class | |
|ReplicateNsImpl.java |nameServerImpl_Skel.class |(Primary name server) |
| |nameServerImpl_Stub.class | |
| |ReplicateNsImpl.class |(Secondary name server) |
| |ReplicateNsImpl_Skel.class | |
| |ReplicateNsImpl_Stub.class | |
| |AuthenServer.class |Authentication Server |
|AuthenServer.java |AuthenServerImpl.class | |
|AuthenServerImpl.java AuthClientadd.java |AuthenServerImpl_Skel.class | |
|AuthClientServlet.java |AuthenServerImpl_Stub.class | |
| |AuthClientadd.class AuthClientServlet.class | |
| |BookShop.class |Book Server |
|BookShop.java |BookShopImpl.class | |
|BookShopImpl.java |BookShopImpl_Skel.class | |
|BookshopServlet.java |BookShopImpl_Stub.class | |
| |BookshopServlet.class | |
|Creditcard.java |Creditcard.class |Credit Card Server |
|CreditcardImpl.java |CreditcardImpl.class | |
|CreditServlet.java |CreditcardImpl_Skel.class | |
| |CreditcardImpl_Stub.class | |
| |CreditServlet.class | |
|BookAdmin.java |BookAdmin.class |Book Admin Server |
|BookAdminImpl.java |BookAdminImpl.class | |
|AdminServlet1.java |BookAdminImpl_Skel.class | |
|AdminServletupdate.java |BookAdminImpl_Stub.class | |
| |AdminServlet1.class | |
| |AdminServletupdate.class | |
|ioprocess.java |ioprocess.class |Helper class for i/o process |
|RWTextFile.java |RWTextFile.class |Helper class for read/write text file |
|CEncrypt.java |CEncrypt.class |For Encryption |
|ConnectNS.java |ConnectNS.class |Helper class connecting to name server |
2.Lists of JavaScript files
|Javascript program name |Purpose |
|Login_user.jsp |For user login |
|Login_admin.jsp |For Administrator login |
|login_admin_add.jsp |For adding login names |
|BookStore.jsp |After login, user can search for books |
|order.jsp |For user order books |
|admin_add.jsp |Add new book item to book stock. |
|update.jsp |Edit or Delete book information |
| | |
3.Lists of text data files.
|File name |Purpose |Owner |
|servernames.txt |Store server names |Access by name servers. |
|logins.txt |Store logins |Access or modified by authentication server. |
|bookfile.txt |Store book information |Access by bookshop server, credit card server and book admin |
| | |server. |
|ccard.txt |Store credit card information |Access by credit card server. |
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 |amy, 12345, 1 |
|amman,rYTEN,2 |Amman, amman, 1 |
|helen,}V[JA,1 |Helen 6677 2,2 |
|smari,t\PF,2 |Testuser, test, 1 |
|amman,s_UC,2 |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
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.
[pic]
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
[pic]
3. Start name Server
Start from class directory, run the Primary name server:
[pic]
Start from class directory, run the Secondary name server:
[pic]
4.4. Start Authentication Server from port 4992
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java AuthenServerImpl 4992
[pic]
4.5. Start BookShop Server from port 4995
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java BookShopImpl 4995
[pic]
4.6. Start Credit Card Server
C:\Tomcat4.0.6\webapps\BS\WEB-INF\classes>java CreditcardImpl 4998
[pic]
4.7 Start Book Admin Server
[pic]
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:
|Test Case 1: |
|Description: |Verify user, administrator login |
|Pre-requisites: |The Authentication server should be running. Login page can be accessed by address at: |
| | |
|Test Steps: |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” |
|Test Variations: |If you don’t input anything, just click “Submit”, you will be prompt to enter a value. |
|Expected Results: |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: |Verify the book search page |
|Pre-requisites: |The Bookshop server should be running. Book search page can be accessed by address at: |
| | |
|Test Steps: |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” |
|Test Variations: |If you don’t input anything, or don’t select one item, just click “Submit”, you will be prompt to enter |
| |a value. |
|Expected Results: |If Bookshop server find the item you are searching, it will direct you to the |
| | 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. |
|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: |
| | |
|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. |
|Test Variations: |If you don’t input anything, just click “Add”, you will be prompt to enter a value. |
|Expected Results: |If Bookshop server find the item you are searching, it will direct you to the |
| | page and show you the search result. |
| |If the credit card number or expiration date is incorrect, the page |
| | 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 |
| |You should see the page with the list of all the books. |
| |2. Click on Add button, you should be directed to the page: |
| | |
| |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 |
| |You can edit the book price or book number from this page. |
| |Make changes to book price or book number, when you return to |
| | Page, you will see the change happened. |
|Test Variations: |If you don’t input anything, just click “Order”, you will be prompt to enter a value. |
|Expected Results: |If page should display all the books in the store |
| |storage. The administrator can complete add, delete, edit operations through this page. |
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 .*;
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
{
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;
} 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
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 .*;
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)
{
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 = "";
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.*;
import java.util.*;
import java.rmi.registry.*;
import java.io.*;
import .*;
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
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";
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.*;
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();
out.println("");
out.println("");
out.println("");
out.println("Authentication Add page");
out.println("");
out.println("");
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("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, 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
{
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("");
out.println("");
out.println("");
String title = "Session Information";
out.println("" + title + "");
if ( thischeck.equalsIgnoreCase("YES") )
{
if ( datatype.equalsIgnoreCase("1") )
{
out.println("");
} else
{
out.println("");
}
}
else
{
out.println("");
}
out.println("");
out.println("");
out.println("" + title + "");
System.err.println( "finding the server result is... "+thischeck );
HttpSession session = request.getSession();
out.println(rb.getString("sessions.id") + " " + session.getId());
out.println("");
out.println(rb.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "");
out.println(rb.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()) + "");
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 + "");
}
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
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 .*;
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();
}
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)
{
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);
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
{
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 .*;
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)
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." );
}
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(" ");
out.println("On Line Book Store Search Result ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println("On-line Book Store Search Result Page ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
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(" No result found. Click Back to retrun! ");
}
out.println(" ");
out.println(" ");
out.println("");
out.println("");
}
if ( !booklists.equalsIgnoreCase("NO") )
{
String newstr1= .URLEncoder.encode( F_Name );
String newstr2= .URLEncoder.encode( F_Author);
out.println("action=../jsp/order.jsp > ");
out.println(" ");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" ");
out.println(" Found the book ");
out.println( thiscondition + " " );
out.println(" Book Name: ");
out.println( F_Name+ " " );
out.println(" Book Author: ");
out.println( F_Author + " " );
out.println(" Book ID: ");
out.println( F_Id + " " );
out.println(" Book Price: ");
out.println( F_price + " " );
out.println(" Book number availble ");
out.println( Num + " " );
out.println(" " );
out.println(" " );
out.println(" " );
out.println(" ");
out.println(" ");
out.println(" ");
out.println("");
out.println("");
}
}
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
**********************************************************************/
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 .*;
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],"|");
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[];
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 ");
}
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);
}
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);
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(" ");
out.println("On Line Book Store Search Result ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println("On-line Book Store Order Result Page ");
out.println(" ");
out.println(" ");
String title = "Session Information";
out.println("" + title + "");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println(" Both Primary and Replicate name Server are unavailable. Please try again later.");
}
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 " );
out.println("Your purchase amount is $"+ s_ordertotal );
}
else
{
out.println("You purchase failed! Please enter the correct credit card information." );
}
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
}
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
*********************************************************************/
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.rmi.registry.*;
import java.io.*;
import .*;
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();
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();
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;
}
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
{
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.
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.
* 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 .*;
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()) {
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(" ");
out.println("On Line Book Store Search Result ");
out.println(" ");
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(" ");
out.println(" ");
out.println(" ");
out.println("On-line Book Store Administration Page ");
out.println(" " );
out.println(" ");
out.println(" Book Name ");
out.println(" Book Author " );
out.println(" Book ID ");
out.println(" Book Price " );
out.println(" Number ");
out.println( " ");
String text1="", F_Name1="", F_Author1="", F_Id1="", F_price1="", Num1="";
for ( int i = 0; i < linecnt; i++ )
{
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(" " + F_Name1 + " ");
out.println(" "+ F_Author1+ " " );
out.println(" "+F_Id1 + " ");
out.println(" "+ F_price1 + " " );
out.println(" "+ Num1 + " ");
out.println(" ");
String newstr= .URLEncoder.encode( F_Name1 );
String newstr2= .URLEncoder.encode( F_Author1);
out.println(" EDIT " );
} // end for
out.println(" ");
out.println("");
out.println("");
}
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.*;
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 ) ;
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(" ");
out.println("On Line Book Store Administration Page ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" ");
if ( receive_name.equalsIgnoreCase("None") )
{
out.println("Both Primary and Replicate name Server are unavailable. Please try later. ");
} else if (receive_name.equalsIgnoreCase("N/A") )
{
out.println(" The Book Admin Server is not running, please try to login later. ");
} else if ( retint ==4 )
{
out.println("Please change the new book id, it's duplcate with other books. ");
}
else
{
out.println("The following books has been " + UserAct +"ED ");
out.println(" " );
out.println(" ");
out.println(" Book Name ");
out.println(" Book Author " );
out.println(" Book ID ");
out.println(" Book Price " );
out.println(" Number ");
String text1="", F_Name1="", F_Author1="", F_Id1="", F_price1="", Num1="";
out.println(" " + s1 + " ");
out.println(" "+ s2 + " " );
out.println(" "+ s3 + " ");
out.println(" "+ s4 + " " );
out.println(" "+ s5 + " ");
out.println(" ");
out.println(" " );
out.println(" ");
out.println(" " );
out.println(" ");
out.println(" ");
}
out.println("");
out.println("");
}
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 .*;
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 ()
{
//
}
// 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();
} // 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");
}
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();
}
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
{
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 .*;
public class ConnectNS {
public ConnectNS()
{
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);
}
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)
{
w_e2.printStackTrace();
System.out.println("General exception in get server name...");
// System.exit(1);
}
}
return reg_status;
}
}
APPENDIX C: list of jsp programs
1.Login_user.jsp
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;
}
Login Page
Administrator Login
Welcome to the Online Book Store
User Login Session, Please login
Login Name:
Password:
2. Login_admin.jsp
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;
}
Login Page
User Login
Welcome to the Online book Store
Book Administrator Login Session, Please login
Login Name:
Password:
3. login_admin_add.jsp
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;
}
Login Page
User Login
Welcome to the Online book Store
Book Administrator ADD Login Session
Login Name:
Password:
Type:
4. BookStore.jsp
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 "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* ;
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!");
form.orderamount.focus();
return false;
}
if(order_num )
{
alert("Please enter the number of book >0 and also < than "+ );
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: $"+ );
alert("the order total is: $"+ parseInt ( 100*order_num *)/100 );
return true;
}
On Line Book Store Order page
On-line Book Store Order Book Page
Book Name:
Book Author:
Book ID:
Book Price:
Book number availble
How many books do you want to order
Please enter your eight digit credit account number
Credit card expiration date (format: 04/01/2003)
6. admin_add.jsp
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;
}
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;
}
return true;
}
On Line Book Store Administration Page
On-line Book Store Administrator Add Page
Book Name:
Book Author:
Book ID:
Book Price:
Book number availble
7. update.jsp
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;
}
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;
}
if (!isNum(r5))
{
alert("Please enter an int value for book number!");
form.h_num.focus();
return false;
}
return true;
}
On Line Book Store Administration Page
On-line Book Store Administrator Edit Page
Book Name:
(Read only)
Book Author:
(Read only)
Book ID:
(Read only)
Book Price:
Book number availble
-----------------------
Book Admin Servlet
Administration
Server
Credit Card Servlet
Replicate
Name
Server
Credit card server
Bookshop Servlet
Book Server
(Search books)
Administrator
Login
Authentication Servlet
Secret Key Encrypt
Primary
Name
Server
Authentication Server
( Decrypt)
Book Store Client (login.jsp)
Name Servers
Authentication Servlet
(check login)
Authentication
Server
Bookpage.jsp
(send request)
Login failure
Page
(return to login)
Bookpage.jsp
(send request)
Name Server
BookShop Servlet (pass the request)
BookShop
Server
(process the request)
Response from Servlet
(BookResult)
Credit Card.jsp
Credit Card.jsp
(send request)
Credit Card Servlet (pass the request)
Name Server
Credit Card
Server
(process the request)
Response from Servlet
(Purchase detail)
Thank you page or
Purchase more
Login.jsp
(Admin login )
Name Server
Authentication Servlet
(check login)
Authentication
Server
Login failure
Page
(return)
Bookadmin.jsp
(send request)
Name Server
Bookadmin Servlet
(send request)
Bookadmin Server
(process request)
RMI Service
RMI Registry
2
1
Web Server
Client
3
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
Related searches
- genesis chapter 1 questions and answers
- chap 1 introduction to management
- introduction to psychology chapter 1 quiz
- 1 john chapter 1 explained
- chapter 1 introduction to life span
- quiz 1 introduction to psychology
- chapter 1 quiz 1 geometry
- algebra 1 chapter 1 pdf
- algebra 1 chapter 1 test
- chapter 9 introduction to waves
- 1 chapter 1 test form 2
- 1 chapter 1 test form 2c