INTRODUCTION

advertisement
DEVELOPING CHAT AND CALENDAR PLUG-IN USING AJAX PROGRAMMING
Jyothi Manjunath Leelavathi
B.E., Visveswaraiah Technological University, Karnataka, India, 2005
PROJECT
Submitted in partial satisfaction of
the requirements for the degree of
MASTER OF SCIENCE
in
COMPUTER SCIENCE
at
CALIFORNIA STATE UNIVERSITY, SACRAMENTO
FALL
2010
DEVELOPING CHAT AND CALENDAR PLUG-IN USING AJAX PROGRAMMING
A Project
by
Jyothi Manjunath Leelavathi
Approved by:
__________________________________, Committee Chair
Jinsong Ouyang, Ph.D.
__________________________________, Second Reader
Ying Jin, Ph.D.
____________________________
Date
ii
Student: Jyothi Manjunath Leelavathi
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.
__________________________, Graduate Coordinator
Nikrouz Faroughi, Ph.D.
Department of Computer Science
iii
________________
Date
Abstract
of
DEVELOPING CHAT AND CALENDAR PLUG-IN USING AJAX PROGRAMMING
by
Jyothi Manjunath Leelavathi
In this project, I am planning to develop a plug in module that can be integrated into the
web based application. The aim of this application is to provide email-services, calendar
services and chat services dynamically within the browser. I am responsible for
developing Chat Service and Calendar service. For example, in Google apps, the user can
open the Gmail and while working on this, the user can see the friends who are online
without changing a window or logging into another chat messenger and also will be able
to open the calendar and see the contents. In a single browser window, the user is able to
view and modify the different applications dynamically.
The client-side/web browser technologies used in Web 2.0 development are JavaScript
and Ajax (XML). Ajax programming uses JavaScript to upload and download new data
from the web server without undergoing a full page reload.
iv
Chat service is developed using Java and Ajax technology and the Mysql database. It has
all the basic features that we see in general popular chat applications like Yahoo chat or
Skype.
Java technologies and Ajax framework makes the application more scalable and
compatible to integrate with other application. The GUI part is greatly enhanced for
better end user experiences.
Calendar service application is provided with some of the basic features, such as ability
to schedule one or more events on a particular day, a standard view that can show any
month, with event times and titles listed in order and users will be able to open the
application like any other application.
_______________________, Committee Chair
Jinsong Ouyang, Ph.D.
_______________________
Date
v
ACKNOWLEDGMENTS
I am thankful to all the people who have helped and guided me through this journey of
completing my Masters Project.
My sincere thanks to Dr. Jinsong Ouyang, for giving me the opportunity to work on my
masters project under him and for guiding me throughout the project. My heartfelt thanks
to Dr.Ying Jin for agreeing to be my second reader and providing me with her invaluable
inputs on revising my report.
My special thanks to my roommates and friends Nandish B ,Veeresh Kortagere and Anh
Thai for helping me with their ideas and by reviewing my project report and lending me
their Computers when ever I had problem.
Last but not the least I would like to thank my husband Naren Veeranna, parents
Manjunath and Leelavathi, my brother Vasu Dev and my in-laws Girija and Dr.Veeranna
for their unconditional love. They have always motivated me and are the sole reasons for
me to have come this far in life.
vi
TABLE OF CONTENTS
Page
Acknowledgments.............................................................................................................. vi
List of Figures .................................................................................................................... ix
Chapter
1. INTRODUCTION .......................................................................................................... 1
2. BACKGROUND ............................................................................................................ 3
Purpose and Scope .......................................................................................................... 5
3. TECHNOLOGY SURVEY ............................................................................................ 7
AJAX (Asynchronous Java Script and XML) ................................................................ 8
Java Servlets.................................................................................................................... 8
Java Server Pages (JSP) .................................................................................................. 9
JQuery ........................................................................................................................... 10
JavaScript ...................................................................................................................... 10
4. ARCHITECTURE ........................................................................................................ 12
Introduction ................................................................................................................... 12
The Existing Architecture of Calendar Application ..................................................... 13
Architecture Subsystem ................................................................................................ 15
Server Side Architecture for Chat Application ......................................................... 15
vii
Chat Application Client ............................................................................................ 16
Database Architecture for Chat Application ............................................................. 19
5. SYSTEM DESIGN ................................................................................................... 20
Server Components for Calendar .................................................................................. 22
Insert Event Module .................................................................................................. 22
Delete Event Module ................................................................................................ 23
Update Event Method ............................................................................................... 24
Client Design for Calendar ........................................................................................... 26
Server Component Modules for Chat ........................................................................... 29
Get Message Module ................................................................................................ 30
Get User Details and Set Message ............................................................................ 31
Client Design Module for Chat Application ................................................................. 32
Data Tier Design ........................................................................................................... 36
6. IMPLEMENTATION ............................................................................................... 37
7. CONCLUSION ......................................................................................................... 44
Bibliography ................................................................................................................. 46
viii
LIST OF FIGURES
Page
Figure 1 Basic Architecture .............................................................................................. 13
Figure 2 Calendar Technical Structures ............................................................................ 14
Figure 3 Server Systems for Chat ..................................................................................... 15
Figure 4 Chat Application Client ...................................................................................... 17
Figure 5 Refractored Calendar Design ............................................................................. 21
Figure 6 Calendar Insert Events ....................................................................................... 23
Figure 7 Delete Event Method .......................................................................................... 24
Figure 8 Update Calendar Events ..................................................................................... 25
Figure 9 Update Calendar Event ....................................................................................... 25
Figure 10 Client Design for Calendar ............................................................................... 26
Figure 11 Technical Design of Chat Application ............................................................. 28
Figure 12 Properties .......................................................................................................... 29
Figure 13 XAMPP for Assigning DB Credentials ............................................................ 30
Figure 14 Update Message Holder Table ......................................................................... 31
Figure 15 Get and Set Message ........................................................................................ 32
Figure 16 Client Design for Chat ...................................................................................... 33
Figure 17 Web Ponder Chat .............................................................................................. 33
Figure 18 Chat Window for User 1 Eyan ......................................................................... 34
ix
Figure 19 Chat Windows for User 2 Guest ....................................................................... 35
Figure 20 Data Tier ........................................................................................................... 36
x
1
Chapter 1
INTRODUCTION
A Chat Centre basically enables users to communicate effectively at the same time and
share the information. It is similar to any instant messaging applications like “Gmail
Chat” where the users can share the information at the same time or at different times.
Both the parties involved need to be authenticated before logging into their respective
accounts. A Chat Center integrated along with the Messaging and Event Scheduling
application, Calendar makes a complete system for effective communication, sharing and
scheduling of events.
Now a days, more and more real time applications like Chat are built as per the
requirements based on the size of the organization. When two employees wants to
communicate on work issues who are distantly located, cannot use generic applications
like Gmail, yahoo applications. They need an organization specific application developed
for the Intranet network the company. This kind of applications where the users are on
the same network helps to prevent any breach of security within the organization as
virtually, both the parties involved and their shared information will reside on same
server which belongs to the company. For example, all the financial organizations like
Bank, insurance companies store huge amount of customer’s social security
information’s. If any employees exchanges or talk about the social security information
with the colleagues or try to transport the information, it can be easily tracked with
applications like Chat and Message built for the Intranet user purposes. The AJAX driven
2
application ,Chat is more user friendly and efficient .Majority of the web applications
built these days are using the AJAX for fast and user friendly navigation of web
resources.
3
Chapter 2
BACKGROUND
Chat is defined as a web based asynchronous/synchronous form of communication
through exchange of information. It is nothing but digitally exchanging messages and
share information in terms of different types of documents like MS world and PDF. The
server serves as the back end storage where it stores the credentials for particular
registered users. Each user has to login into their account through internet to chat and
share information simultaneously or to retrieve the information that has been sent to their
account. ARPANET (Advanced Research Projects Agency Network) created by small
research team led to the development of sending and receiving information through
packet switching [1].In earlier days, information was exchanged through File Transfer
Protocol known as FTP, but the same process is made simple with Simple Mail Transfer
Protocol, SMTP which is widely followed with various standards like SMTP-AUTH
defined by RFC 2554.
This internet based Chat system has advanced leaps and bounds since it has started. The
first chat sites featured simple interfaces made from dynamically generated HTML pages.
The use of HTML allowed sites to incorporate fonts, colors, links, and images into their
interfaces, giving them a more modern hypermedia feel, which was an advantage over
older, but more established text-based chat services like IRC. The biggest downside to
HTML chat was in its interactivity [2]. Every message sent to an HTML chat required a
form submission and subsequent page load, which meant that there was a waiting period
4
between the time a user could send one message and the time they could begin to type the
next one. Receiving messages also required frequent page reloads, and could lead to
delays, page flicker and distracting browser activity. For these reasons HTML chats have
largely fallen out of use today, although some of the older HTML chat sites still remain
active [2] .
In 1995, Java applet technology was introduced into web browsers. Java's well developed
network and graphical capabilities made it an ideal platform for creating chat interfaces,
some of which are in use on the most popular web chat sites today. While there are some
drawbacks associated with Java chats such as long initial page loading times, the
technology has worked well and scaled well [2] .
The traditional email system is has transformed itself into more real time communication
medium. The message sending and receiving time is very negligible. This kind of
technical advancements has taken the whole Chat and messaging system into entirely
new arena with launch of Face book, Gmail and Google chats. With new web based
technologies like AJAX and XML, the user experience has become more dynamic,
graphical and friendly. For example if an user is chatting with a friend while he is logged
into his account and at the same time he can also compose a new message and send it in
the same window i.e. the user can do both chatting as well as composing new message in
the same window which is a revolutionary change brought by advent of AJAX which will
be discussed in detail. Smaller, less busy chats can actually have more appeal to users
than crowded, popular ones. Really, the only unique feature web chat sites offer is instant
accessibility [3].
5
Event management achieved through web based Calendar and messaging system
integrated along with the chat makes a complete package which is ready for information
Sharing as well as well as scheduling the events like meetings and sending group
requests.
Purpose and Scope
The single bundles interface for communication has lot of advantage over desperate
sources for the similar tasks to be done. It becomes a single system where users come to
communicate with one another. This integrated project has been developed for the
professor which facilitates him to communicate with students and students can find each
other and discuss. This chat application along with integrated Calendar and messaging
makes a perfect tool for Professor to communicate with students, track events, classes
and facilitate students to identify and share information with each other. The Purpose of
this project is to build the application which can accomplish the above mentioned
features.
The scope of this Project is to build a Chat application which is more a real time
application and integrating with the existing Messaging and web based Calendar by
refactoring the back end code for the bundled applications. The application shall:
1. Allow Professor/User to communicate with the registered students
in the course.
2. Allow the registered Users/Students to communicate with each
Other.
3. Two users who logged in simultaneously can share the documents
6
in some of the standard format like MS World, PDF and receiver
Can download the document into their local machine.
4. Allow more than two users to chat simultaneously.
5. Provide users with more efficient and more intuitive light weight
Graphical interface.
7
Chapter 3
TECHNOLOGY SURVEY
In this section, I will discuss the various technologies that are used in developing the Chat
application and refactoring/Integrating the code of Messaging and Calendar application
and also give brief description on each one of them to familiarize and understand them
better.
The underlying architecture for this project along with overview of important
technologies used will be discussed below:
1. Presentation Layer - The presentation layer is responsible for rendering the view,
meaning the graphical representation of the user interface. In the J2EE point of view,
client-side access to an application in most cases occurs through a browser. This layer is
built using technologies like JSP, HTML, CSS and DOM objects. Basically, it’s the
designing of Graphical User Interface, GUI as how the application communicates directly
with end user and as well as communicates with the Business layer to process and
respond to user requests.
2. Business Layer - This is the middle tier and holds the actual business logic. The
requests sent through the presentation layer are processed by applying appropriate
business logic and in turn communicates with database layer to get the quick responses.
JSP , Servlets and EJB form the main components of Business layer.
3. Database Layer – It is the most important layer which acts as a holder or storage of the
data. Any good database should be able to integrate with the web application and more
8
efficient in handling the queries in least amount of response time possible. In this project,
I have used MYSQL as the back end database. The data base layer has generic interface
with basic Create, Retrieve, Update and Delete operations.
AJAX (Asynchronous Java Script and XML)
With traditional web pages and applications, every time a user clicks on something, the
browser sends a request to the server, and the server responds with a whole new page.
Even if user’s web browser is smart about caching things like images and cascading style
sheets, that’s a lot of traffic going back and forth between their browser and your server
and a lot of time that the user sits around waiting for full page refreshes [4].
Using Ajax, applications only ask the server for what they really need—just the parts of a
page that need to change, and just the parts that the server has to provide [4]. That means
less traffic, smaller updates, and quicker response to the user. Ajax page is built using
standard Internet technologies like XML and The DOM. Some of the popular
applications built using AJAX are Google.com , Yahoo Mail and Face book
Java Servlets
A servlet is a Java programming language class used to extend the capabilities of servers
that host applications accessed by means of a request-response programming model.
Servlets can respond to any type of request, they are commonly used to extend the
applications hosted by web servers. For such applications, Java Servlet technology defnes
HTTP-specific servlet classes. The javax servlet and javax.servlet.http packages provide
interfaces and classes for writing servlets. All servlets must implement the Servlet
interface, which defnes lifecycle methods. A servlet is a Java programming language
9
class used to extend the capabilities of servers that host applications accessed by means
of a request-response programming model. Although servlets can respond to any type of
request, they are commonly used to extend the applications hosted by web servers. For
such applications, Java Servlet technology defnes HTTP-specifc servlet classes. The
javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defnes lifecycle
methods. The lifecycle of a servlet is controlled by the container in which the servlet has
been deployed. When a request is mapped to a servlet, the container performs the
following steps [5].
a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method
d. Invokes the service method, passing request and response objects.
e. If it needs to remove the servlet, the container fnalizes the servlet by calling the
servlet’s destroy method [5].
Java Server Pages (JSP)
JavaServer Pages (JSP) technology provides a simplified and a quick way to create
dynamic web content. A JSP page is essentially a servlet. JSP pages run on a JSP
container. A servlet container is normally also a JSP container. The first time a JSP page
is requested, the JSP container does two things:
1. Translate the JSP page into a JSP page implementation class. This class must
implement the javax.servlet.Servlet interface. The result of the translation is dependent on
10
the JSP container. The class name is also JSP container-specific. If there is a translation
error, an error message will be sent to the client.
2. If the translation was successful, the JSP container compiles the implementation class,
and then loads and instantiate it and perform the normal lifecycle operations it does for a
servlet.
JQuery
jQuery [6] is a fast and concise JavaScript Library that simplifies the HTML document
traversing, event handling, and AJAX interactions for rapid web development. jQuery
changes the way you write JavaScript. jQuery greatly simplifies the client side scripting
of HTML. jQuery‟s syntax makes it easier to traverse documents and DOM [7] elements.
It also provides capabilities to the developers to create plugins on top of Javascript
library.
Key Features
1. DOM element selection using cross browser open source selector engine Sizzle.
2. DOM traversal and modification.
3. Events.
4. CSS manipulation.
5. Effects and animations.
6. Extensibility through plugins.
JavaScript
JavaScript, which is one of the programming language is primarily known as the
technology that allows web pages to become “dynamic” or “interactive”. JavaScript is
11
primarily used in the form of client-side JavaScript, implemented as part of a web
browser in order to provide enhanced user interfaces and dynamic websites [8].
The primary use of JavaScript [8] is to write functions that are embedded in or included
from HTML pages and that interact with the Document Object Model (DOM) of the
page. Some simple examples of this usage are:
1. Opening or popping up a new window with programmatic control over the size,
position, and attributes of the new window (e.g. whether the menus, toolbars, etc. are
visible).
2. Validating input values of a web form to make sure that they are acceptable before
being submitted to the server.
3. Changing images as the mouse cursor moves over them: This effect is often used to
draw the user's attention to important links displayed as graphical elements.
Because JavaScript code can run locally in a user's browser (rather than on a remote
server), the browser can respond to user actions quickly, making an application more
responsive. Furthermore, JavaScript code can detect user actions which HTML alone
cannot, such as individual keystrokes. Applications such as Gmail take advantage of this:
much of the user-interface logic is written in JavaScript, and JavaScript dispatches
requests for information (such as the content of an e-mail message) to the server. The
wider trend of Ajax programming similarly exploits this strength [8]. A web browser is
by far the most common host environment for JavaScript. Web browsers typically use the
public API to create "host objects" responsible for reflecting the DOM into JavaScript
[8].
12
Chapter 4
ARCHITECTURE
In this chapter, I am going to discuss about the over all system design implemented in
this project. It discusses the various components of the system, their interaction with each
other and how they integrate to form a system. This chapter further outlines the various
difficulties faced during designing the system and the eventual solutions to getting over
them.
Introduction
The Chat application has been divided into three tiers, the Client, Server and the
Database. I am also going to explain about architecture of the existing Chat application
and how the code was refractor from many different servlet into one java class to make it
as a Java programming interface which can be called anywhere from the Web ponder
application. The code is written in a more modular way with the future possibility of
extension. In the first section, I will describe about the existing architecture and in later
chapters, I will explain in detail as how this existing code with loads of servlets is
modularized into efficient single java class for each application.
In the below Figure 1, the basic pictorial overview of Chat and calendar are mentioned.
As the client gets loaded, an AJAX HttpRequest is made to the servlet to call specific
events and in turn talks with database to get the necessary information without reloading
the current web page.
13
Client
JavaScript/
HTML
Servlet
Java
Class
Appli
cation
data/
Chat
AJAXHttp
Request
Figure 1 Basic Architecture
The Existing Architecture of Calendar Application
HealthclubDemo.html is the file where the front end code for calendar GUI is written and
in the above html file, insertEventsIntoDB() function is written which in turn links to
SampleData.js JavaScript file. In .js file, small functions for each event like
InsertEventsIntoDB(), DeleteeventsFromDB() etc are written where the information is
stored in array. From each of the above function, AJAX HttpRequest is made to the
respective servlet which in turn talks with the respective Java class to bind the data into
separate tables in database. The technical representation of the same is done in the Figure
2.
14
HtmlClubDemo.html Page
Function: insertEventsIntoDB()
SampleData.js
Is a JavaScript file
InsertEvent()
AJAJava
InserEventsServlet
AJAX HttpReq Call
InserEvents.Java
DeleteEvent()
DeleteEventsServlet
UpdateEvent()
UpdateEventServlet
AJAX HttpReq Call
DeleteEvents.Java
AJAX HttpReq Call
Updateevents.Java
MySQL Calendar Tables (Group,Message,UserInfoTable)
Table
Figure 2 Calendar Technical Structures
15
The above code is refractor and made more modular with just one Servlet and one java
class, which will be discussed in detail in next chapter.
Architecture Subsystem
As mentioned above, the system consists of three main components; the server, the client
and the database.
In the following section, each of components is discussed in detail.
Server Side Architecture for Chat Application
In this project, I am using freeware software called XAMPP which acts as a cross module
Server package to the database. The server handles all the communication with the
database to send and receive the messages from database. The get message and get user
details are the modules that are called when the user first opens a chat window to chat
with another user.
SERVER
DATABASE
Chat Worker
Module
Get User details
Module
Get Message
Module
Set Message
Figure 3 Server Systems for Chat
D
B
C
O
N
N
E
C
T
I
O
N
Message
Holder
Table
16
In the chat worker module, a database connection to MYSQL is established for a user
named root with the admin/blank password. This user is the default administrator having
full privileges to do any task. In the get message module, the Message holder table in the
database is accessed to choose the user to chat with and his id and message are updated
every time. In get user details module, new properties or configuration file is loaded
which has built in configurations. Then a user is chosen from the user profile. In the set
message modules, the message holder table is inserted with the new values of
communication between from user and to user.
In the above mentioned way, the whole life cycle from server side starting from fetching
the user profiles, exchanging files and messages and updating the database table, message
holder is completed.
Chat Application Client
The chat client includes the following modules. The chat client subsystem is shown in
Figure 4.
17
Build Table
Function
Send Ajax
Request
Function
Active table
Function
Send Update
Chat Window
Send Message
Function
Poll Message
Function
Populate
Message
Build Chat
Window
Chat
Application
Server
Figure 4 Chat Application Client
All the modules in the above client diagram are described in detail below.
1. Build Table: When the user logs in into his account, he can see the list
of users that are online and start to chat with them. In this function, the
response from the Ajax request is used to get the list of all the users who
are currently online.
2. Send Ajax Request: The XMLHttpRequest object is used to send the
request from the user and get the response and parse it as a URL
18
response. The code is written which is compatible with many popular
browsers Internet Explorer, Firefox and Google Chrome.
3. Active Table: Here, when the user starts to chat with another user, the
chat window and the colors will be visible and he can able to see the
active window.
4. Send Update Chat Window: Once the users exchange many messages,
then the scroll bar on the side of the small chat window appears where
they can check all the messages starting from the first chat in the present
session.
5. Send Message: This function actually sends the XMLHttpRequest to the
Chat servlet to get from and to user id’s.
6. Poll Message: Here, an Ajax request is sent to poll the updated list of
online vendors with a time out set to 20000. On a ready status change,
the new messages are populated.
7. Populate Message: When the XMLHttpMsg status and response text is
received, then all the messages are split within the chat window as per
the events like visibility style, Scroll etc. This particular feature is made
simple with the use of DOM technology where in it systematically
organizes the HTML file and events by getElementById() function as
well as innerHTML to access the text content.
19
Database Architecture for Chat Application
For Chat application I have used a table named Message holder along with one more
shared table with Message application called user profile table that contains all the users
and related information like username. The message holder is storing all the messages sent
and received by the web ponder application. A freeware called Xampp acts as a interface to
the server and database which has inbuilt Apache server, MySql database and PHP
scripting language embedded.
20
Chapter 5
SYSTEM DESIGN
The existing design of the calendar project is remodeled to make it more modular. Looking
at the Figure 2 and the technical details, for each event, a separate servlet is created and a
separate java class is created. For example, for a Update event, there is separate update
servlet and an update event java class. This way, in future if more functionality has to be
added, more servlets has to be created and the application becomes heavy. So I refractored
the code from all the servlets belonging to calendar application and made it into one
servlet. In a similar fashion, all the Java classes created separately for each event are
refractored into a single java class. This way, the application becomes more lightweight
and easy for future enhancements with the efficient use of DOM objects, AJAX, JSON and
Java Script. Following is the diagram that depicts the new architecture for Calendar.
21
SampleData.js
InsertEvent
DeleteEvent
UpdateEvent
CalendaerServlet
AJAX HttpRequest
CalendarWorker Class
DB Tables,MySql
Figure 5 Refractored Calendar Design
The server side architecture for each plug in module is independent from Chat
application. The server side architecture has three main components , Servlet for taking
the requests from client and responding back with the data mainly in the form of XML
object that is HttpRequest and HttpResponse. The second component is java class where
the business logic is written and establishes connection with the database. The last
component is the database which stores and retrieves the data from respective database
tables.
22
Server Components for Calendar
Server components for both Calendar and Chat are independent modules. Each module
has separate Servlet to process the request from the client side and a java class to process
the business logic.
Insert Event Module
In this function, all the entries or specification entered by the user are stored in array
objects. The entries are name of the event, group, location and description. Below
diagram 6 shows the main page where user creates the event. Once the user enters all the
details, then they are carried through AJAX HttpRequest to the local java class. In the
java class, as soon as a insert request arrives, an insert event method is called which
inserts all the entries into calendar_events table in the MySql databse. The array is broken
into individual objects. If the user does not enter any information and tries to save an
empty form, an exception is raised telling that it cannot connect to database server and
the cause is printed on to the web page.
23
Figure 6 Calendar Insert Events
Delete Event Module
In this module, already created event is selected from the particular calendar month and
when the user right clicks, he can see a delete box and on clicking it, that corresponding
event will be deleted from the calendar and the box becomes empty. The moment the user
click on delete button, the event array in delete events function will be set to null. Then
through AJAX HttpRequest will be called from the servlet to the local delete event
method. In this method, the contents are deleted from the calendar_events table based on
id .This table was previously updated when insert event method is called.
Below is the diagram that shows the flow of data when a delete method is called or when
a user clicks on a delete button.
24
Servlet
Delete
Event
Method
Serv
Build XML
Local Class
Event Id
Data
Delete
Event
Business
Logic
XMLXM
L
XML
Object
D
B
C
O
O
N
N
E
C
T
DB
Calendar
Event
Table
Figure 7 Delete Event Method
Update Event Method
In this module, an already created event can be edited or updated if there are changes in
the event. For example, the user has created an event for November 21st to collect the last
assignments. If he wants to extend the deadline for another three days , then all he has to
do is to navigate to a that particular event and right click and choose edit event. Then he
can make the appropriate changes and save it. Below is the screen shot in Figure 8 which
explains the same. In another diagram Figure 9, the more technical details and flow of the
data is shown. When the user requests to update the event, an XML HttpRequest is made
from the servlet in Update Event Method and it communicates to a local java class,
Update event method and calls the Calendar_event table to update year, month, hours
25
,day etc with the identification of the event id. If the database connection exception is
raised then it is written in a catch block and the same is printed.
Figure 8 Update Calendar Events
In the below diagram, Update Event method is given parameters to update an event.
Request to Edit
Edit Event Info
Edit
Event
Method in
Calendar
Servlet
Update Event
local class
in calendar
worker java
API
Figure 9 Update Calendar Event
Calendar
Events
Table
26
Client Design for Calendar
When the user clicks on the calendar from the web ponder application, then a user
interface is loaded. Once the calendar user interface is loaded, the load event function is
called to get all the events from the server and load in on to calendar. This is done by
AJAX technology where the user does not feel the time lapses that happen behind the
scene.
Create
Events
AJAX call to
Server Side
Dynamic send and
Reply of events
Updated
User interface
S
E
R
V
E
R
AJAX call back
Function and
update or delete
event success or
failure Message
Figure 10 Client Design for Calendar
In the create event module when a user creates an event by entering the data and
submitting it, CreateEvent function is called which formats the entered data and sends it
to the servlet to write it into database. In this createEvent function XMLHttprequest
object is created to call the servlet asynchronously. Once the server completes the request
, call back function is called to display the create event success message status.
27
In the delete component when the user submits a request to delete an event, event_id
which is unique is passed to the server side to delete the appropriate event in
calendar_events table.
The system design of the Chat application will be briefly explained in the following
section. I designed this application to be more modular similar to calendar plug in
module. I have used a single servlet in which functions for all the events are written, a
single java class to bind the data into the message holder table created in MySql database.
In chat.js javascript file, all the front end code is written. Here the user requests are sent
from the front end GUI to the Servlet using AJAX request method and the chat windows
are built using DOM objects. The messages are exchanged between users using user id
that is from and to and when the user is active, the frame color of the chat window
changes as per the status. Once the request is made, all the information is communicated
through servlet which acts as a middle container between client and the database. This
carriage of information is taken care by AJAX Http Request and AJAX Http Response
objects.
In the database, the respective functions of a referred event carry out parsing of the actual
business logic. For example, if the two users exchange messages, then those messages are
inserted into the message holder table by calling setMessage methos in chatworker.java
class. These messages are stored in the MySql database table. Its a future enhancement
option where the user can see the history of his chat similar to one we see in Gmail chat
in their mail.
28
Chat.js JavaScript
Send AjaxRequest
Chat Servlet that has
Functions for each
Event
HttpServlet Request
Http Servlet Response
Calls
Chat worker Local
class that Binds data to
the table by applying
Business Logic
Message Holder Table
Figure 11 Technical Design of Chat Application
29
Server Component Modules for Chat
All the components for chat and calendar are designed separately and hence there is
scope for further enhancement for each module separately without much effort. They are
integrated only through a common web page given by professor to adhere to the
standards of web ponder application which is a MessageCenter.jsp file.
Below is the brief description of each component or event which forms the basic
functioning of chat application.
In Chat Worker Get Connection method, the main purpose is to establish the connection
between database server and the main application which is nothing but client. Here, the
URL of databse server is defined for database named MySql on the local host with the
default port number 3306. A new property file is created namely ChatApp. Properties
where any application admin/user can change the credentials as per the environment it is
running in.
From this property file, the name of database named “mysql” , db address “127.0.0.1”
,port name “3306” , db username “root” and database name “Project” are extracted and
using these credentials and the Jdbc driver, a connection to the database is established.
Db – mysql
Dbaddress- 127.0.0.1
Dbpost -3306
Dbusernme-root
Dbpassword-admin
Dbname-project
jdbc
Figure 12 Properties
Mysql databse
Message
holder table
30
The jdbc establishes the connection to the database for a user named root with admin or
blank “ “ password. This user is the default administrator having full privileges to do
anything with the application. If the connection is failed, an exception message is raised.
In the below figure 13, a screen shot for a server interface called Xampp is provided for
the better understanding.
Figure 13 XAMPP for Assigning DB Credentials
Get Message Module
In this java class method, after establishing the connection and user’s successful log in
into the application, the from user and to users are selected through the query “Select *
from messageholder where touser=’” + fromuser +”’ and readstatus=0 order by
messageid”. Once the last message read status is set to -1 ,then next message is got
31
through “messagetime” ,”message” ,”frmuserid” and “messageid”. If the user enters into
next line by hitting new line which is # , then a control character “|” appears in the chat
window.
Select the
“Fromuser” and
“ToUser” and type
the “Message”
Update the db table
with message time,
message, and message
id
Figure 14 Update Message Holder Table
If the last message Id is not equal to -1 , then the message holder table is updated with
read status is equal to one and with to user id, from user id and last message id. If it fails
to find the user, an exception message is raised.
Get User Details and Set Message
After establishing the connection, user profiles are retrieved through the sequential query
“Select username from userprofiles where username <> ‘ “ + fromuser + “ ‘” and user
names , “|” , “\” are used to navigate in the chat user with help of JSON technique. Once
the messages are collected, they are inserted into message holder table in set message
method. In the below Figure 15, a piece of code for set message is captured from Net
Beans IDE and the query “insert into messageholder (fromuser, touser,message) values (‘
“ + fromuser + “ ’, ’” + touser + “ ‘,’ “ + message + “ ‘)”; is executed to bind the chat
messages into the database table.
In both the modules, a file path “docroot \\ ChatApp \\src \\ conf\\ ChatApp.properties”
path sets the path for the properties file where all the credentials for database connection
32
as admin are established. So any changes to the settings can be made only in here without
repeating in multiple places.
Figure 15 Get and Set Message
Client Design Module for Chat Application
The client flows start with the user interacting with GUI to click on the chat application.
The client design has the following components: get user details, do get, do post, persist
message and persist servlet as shown in the Figure 16. They interact with the server
through AJAX interface.
33
Get Message
Method
Chat
Applicat
ion
GUI
Get user
Details
method
AJAX
Call
To
Servlet
Persist
Message
method
S
E
R
V
E
R
DB
Do Post
Method
Figure 16 Client Design for Chat
Chat
Application
Message
Inbox
AJAX Call to server
Side to fetch Messages
AJAX call back
function
Figure 17 Web Ponder Chat
S
E
R
V
E
R
34
Get message is the first module that will be called inside the servlet through
HttpServletRequest and HttpServletResponse and the parameter “fromuser” is passed to
the java class to get the respective user. After this, get User Details will be called to get
the user details and in Persist Message module, msg, from user id, to user id are passed as
a parameters to the local class.
Do Post method handles the HTTP <code>POST</code> method and parameters like
servlet request, servlet response and servlet exception are raised if a servlet specific errors
occur and it throws an IO exception if an input/output error occurs.
Below are the two screen shots to show hoe the chat GUI looks like when two users are
chatting with each other, eyan and Guest. The moment eyan starts to search for Guest and
he types G, Guest name appears similar to Google web page.
Figure 18 Chat Window for User 1 Eyan
35
Figure 19 Chat Windows for User 2 Guest
One of the main GUI interface that hints the user as from which user he is getting
message, as soon as the message is entered, the sending user name appears in the chatting
tab. For example, in the above Figure 18 and Figure 19, when the user eyan sends a
message to user Guest, in Guest’s window, it appears that “Message from eyan” which
can be seen on the top window to Figure 19. So if Guest user is chatting with multiple
users, then it will be easy for him to figure out from whom he received the message.
This way, one user can chat with multiple users and get intimation when he gets reply
back from each user. This facility makes user to avoid mangling of multiple messages.
36
Data Tier Design
The following is the design of the Chat and Calendar database. The Chat application
consists of one table called message holder and shares a table called user profiles with
both message center application as well as Calendar application. The user profiles stores
the information such as username, password, name etc. The message holder table has
information like Chat user name, from user list, to user list, admin credentials and so on.
Below is the schema for both calendar and chat.
Message holder
User Profiles
Messge id
User id
From user name
Username
To user name
Password
Message
name
Figure 20 Data Tier
37
Chapter 6
IMPLEMENTATION
Creating HttpRequest Object
XMLHttPRequest object has to be created to request the server for information through
AJAX call. In the below code, a function is created called sendAjaxRequest() for
Internet explorer ,firefox and so on.
function sendAjaxRequest()
{
var params="fromuser="+fromuserid;
params=params+"&operation=3";
url="ChatServlet";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp.onreadystatechange=parseResponse;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send(params);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=parseResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
38
Insert Message Module
In the below function, insert message into message holder table is implemented. The
function getMessage() is called from the front end GUI where the chat messages are
inserted. The below code processes requests for both HTTP GET and POST methods and
throes an IO Exception if an error occurs.
protected void getMessage(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Properties prop = new Properties();
String fromuser = "";
HttpSession session = request.getSession(true);
if ((String) session.getAttribute("USER") != null)
{
fromuser =
session.getAttribute("USER").toString();
}
if (fromuser.equals("")) {
fromuser = request.getParameter("fromuser");
}
ChatWorker chatWorker = new ChatWorker();
try {
String json = chatWorker.getMessage(fromuser);
out.print(json);
out.close();
} catch (Exception e) {
out.print(e.getMessage());
out.close();
}
}
Below is the local class that has been called after this servlet function which fetches the
appropriate queried data.
public String getMessage(String fromuser) {
String json = "";
try {
39
Connection con = getConnection();
Statement stmt = (Statement)
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
String sql = "select * from messageholder where touser='"+
fromuser + "' and readstatus=0 order by messageid";
ResultSet rs = stmt.executeQuery(sql);
int lastMessageId = -1;
while (rs.next()) {
String msgdate =
rs.getString("messagetime");
String message = rs.getString("message");
String from = rs.getString("fromuser");
lastMessageId = rs.getInt("messageid");
if(rs.getString("messagetype").equals("file"))
{
json = json + "#" + from + "|" +
msgdate + "|" + " You have got a file,<br> Please download
it <br> " +"<a href=downloads/"+message+">" + message +
"</a>";
}
else
{
json = json + "#" + from + "|" + msgdate + "|" + message;
}
}
rs.close();
if (lastMessageId != -1) {
sql = "update messageholder set readstatus=1 where
touser='" + fromuser + "' and messageid <= " +
lastMessageId;
stmt = (Statement) con.createStatement();
stmt.executeUpdate(sql);
}
con.close();
} catch (Exception e) {
}
return json;
}
jsonUsers = jsonUsers + user + "|";
40
}
rs.close();
con.close();
jsonUsers = jsonUsers + "\"}";
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonUsers;
}
The below code shows the interaction of FTP that is sending the file between two chat
users and the Ajax request is sent through the main Chat.js.
function ftpFile(userid)
{
params="fromuser="+fromuserid+"&operation=4";
url="ChatServlet"
xmlHttpFile.open("POST",url,true);
xmlHttpFile.setRequestHeader("Content-Type",
"multipart/form-data");
xmlHttpFile.send(params);
}
In the below code, getcalendarData() function is invoked from sampledata.js javascript
file that belongs to calendar application.
function getCalendarData()
{
var d = new Array();
var events = new Array();
xmlreq = newXMLHttpRequest();
//alert(xmlreq);
if(xmlreq==null)
{
alert("Your browser does not support AJAX!!");
}
var url = "CalendarServlet";
41
// var url = "EventsFetcherServ";
// alert(url);
xmlreq.onreadystatechange = function(){
};
xmlreq.open("POST", url, false);
xmlreq.setRequestHeader('Content-Type', 'application/xwww-form-urlencoded');
xmlreq.send("operation=4");
if(xmlreq.readyState==4){
var xmlDoc = xmlreq.responseXML;
var xmlDataSet =
xmlDoc.getElementsByTagName("row");
var events = new Array();
for(i=0;i<xmlDataSet.length;i++){
var id
=
xmlDataSet[i].getElementsByTagName("event_id")[0].childNode
s[0].nodeValue;
var name
=
xmlDataSet[i].getElementsByTagName("eventName")[0].childNod
es[0].nodeValue;
var groupName =
xmlDataSet[i].getElementsByTagName("group_name")[0].childNo
des[0].nodeValue;
var location =
xmlDataSet[i].getElementsByTagName("location")[0].childNode
s[0].nodeValue;
var desc
=
xmlDataSet[i].getElementsByTagName("desc")[0].childNodes[0]
.nodeValue;
var year
=
xmlDataSet[i].getElementsByTagName("year")[0].childNodes[0]
.nodeValue;
var month
=
xmlDataSet[i].getElementsByTagName("month")[0].childNodes[0
].nodeValue;
var s_hours =
xmlDataSet[i].getElementsByTagName("s_hours")[0].childNodes
[0].nodeValue;
var s_mins
=
xmlDataSet[i].getElementsByTagName("s_mins")[0].childNodes[
0].nodeValue;
var s_day
=
xmlDataSet[i].getElementsByTagName("s_days")[0].childNodes[
0].nodeValue;
42
var e_hours =
xmlDataSet[i].getElementsByTagName("e_hours")[0].childNodes
[0].nodeValue;
var e_mins
=
xmlDataSet[i].getElementsByTagName("e_mins")[0].childNodes[
0].nodeValue;
var e_day
=
xmlDataSet[i].getElementsByTagName("e_days")[0].childNodes[
0].nodeValue;
var allday
=
xmlDataSet[i].getElementsByTagName("allday")[0].childNodes[
0].nodeValue;
month = month - 1;
events.push(createEvent(name, id,
location,createDateTime(year,month,s_day,s_hours, s_mins,
0), createDateTime(year, month,e_day, e_hours, e_mins, 0),
desc));
} //end of second for loop
Once this function is invoked, a ‘calendarServlet’ is called from this function through
Ajax Request. In the calendar servlet, function for each event is written separately and
these events are called in ‘calendarworker’ java class.
private void deleteEvents(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
SQLException {
try {
String EventsArray = "";
if (request.getParameter("EventsArray") !=
null) {
EventsArray =
request.getParameter("EventsArray");
}
System.out.println("In Delete EventsServ:
Events Array= " + EventsArray);
ArrayList EveArray = new ArrayList();
StringTokenizer tokens = new
StringTokenizer(EventsArray, ",");
while (tokens.hasMoreTokens()) {
EveArray.add(tokens.nextElement());
43
}
Iterator it = EveArray.iterator();
Object id = it.next();
Object eventName = it.next();
CalendarWorker ie = new CalendarWorker();
ie.setEventsDeleter(id.toString(),
eventName.toString());
ie.deleteEveMethod();
} catch (Exception e)
Below is the code for java class for the above servlet that’s been called to implement
the business logic for delete event.
public void deleteEveMethod() {
java.sql.Connection conn = null;
try {
conn = getConnection();
Statement s = (Statement)
conn.createStatement();
s.executeUpdate("delete from calendar_events
where event_id='" + this.id + "'");
System.out.println("Database connection
established........");
} catch (Exception e) {
System.err.println("Cannot connect to database
server");
System.err.println("Caught Exception" +
e.getMessage());
System.err.println("Caught Exception" +
e.getCause());
System.err.println("Caught Exception" +
e.getStackTrace());
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Database connection
terminated");
} catch (Exception e) { /* ignore close
errors */ }
}
44
Chapter 7
CONCLUSION
In this project, we have seen that two plug-ins developed Chat and Calendar application
help when integrated with the web Ponder application will enable the registered users to
communicate via exchanging messages and sharing files. Calendar helps in scheduling
and organizing the events. The chat application accomplishes the goal of having a
dynamic messaging center that works across different browsers like Fire fox and Internet
Explorer.
The Ajax Technology is used extensively in the project which makes the User Interface
more dynamic.
In this project , I have learnt a great deal of work by learning new technologies like Ajax,
Java script , DOM objects etc. and how they can be integrated together to make a user
friendly application. In the Calendar project, initially we had each separate servlet created
to handle each event and a separate java class corresponding to that servlet event.
when I tried to make this application more modular , by combining all the events in
separate servlet into a single servlet and all the separate java classes into a single java
class , I learnt how important it is to design the application in a more modularize way
which gives the room for future enhancements without much hassle.
As a conclusion, we could say that this project has accomplished implementing the
necessary requirements to enable web ponder users to communicate among themselves
45
and organize events through calendar. There is great scope for future enhancements like
implementing voice chat in Chat application and so on.
46
BIBLIOGRAPHY
[1]ARPANET Wikipedia, [Online]
Available:http://en.wikipedia.org/wiki/ARPANET
[2] Web Chat, [Online]
Available:http://en.wikipedia.org/wiki/Web_chat
[3]Wayback Machine Archive: Yahoo Web Chat Listings, [Online]
Available:http://www.archive.org/about/faqs.php
[4] Rebecca Riordan , Head First AJAX - O'Reilly (2008)
[5] By Erci
Jendrock, Ian Evans,C Srivathsa,Devika G, Kim Hasse,
The Java EE 6 Tutorial: Basic Concepts (4th Edition)
[6] Ralph Whitebeck, JQuery, [Online]
Available: http://blog.jquery.com/
[7] Jesse Skinner, Simplify AJAX development with jQuery, [Online]
Available: http://www.ibm.com/developerworks/library/x-ajaxjquery.html
[8] JavaScript Wikipedia, [Online]
Available: http://en.wikipedia.org/wiki/JavaScript
Download