Академический Документы
Профессиональный Документы
Культура Документы
Master Thesis
Location and Time Based Information Exchange System
Master of Science (M.Sc) Study Program at ITU
By
H.M. Bilal Sarwar
: sarwar@it-c.dk
Nadeem Ahmad
: nadeem@it-c.dk
Shouket Iqbal
: shouket@it-c.dk
Supervisors
John Aasted Srensen
Kre Jelling Kristoffersen
December 2003
________________________________________________________________________
Preface.............................................................................................................................- 1 Abstract...........................................................................................................................- 2 1 Introduction..................................................................................................................- 3 1.1 Motivation.............................................................................................................- 3 1.2 Problem Statement................................................................................................- 4 1.3 Focus.....................................................................................................................- 5 1.4 Literature...............................................................................................................- 6 1.5 Methodology.........................................................................................................- 7 1.6 Project Guide.........................................................................................................- 7 2 Problem Analyses.........................................................................................................- 9 2.1 Background...........................................................................................................- 9 2.2 Related Work.......................................................................................................- 10 2.2.1 PDCS Architecture.......................................................................................- 11 2.2.2 PDCS Implementation.................................................................................- 11 2.2.3 FPCS Architecture........................................................................................- 11 2.2.4 FPCS Implementation..................................................................................- 12 2.3 Example Scenarios..............................................................................................- 13 2.3.1 Location Scenario........................................................................................- 13 2.3.2 Time Scenario..............................................................................................- 14 2.3.3 Time and Location Scenario........................................................................- 14 2.3.4 Alert Zone Scenarios....................................................................................- 14 2.4 Cooperative Perspective of LTBIES...................................................................- 15 2.4.1 Mobile Location Based Services Offered by LTBIES.................................- 15 2.4.2 Usability in Different Cooperative Environments.......................................- 16 2.4.3 Market Segments for LTBIES......................................................................- 17 3 Positioning Technologies for Mobile Systems...........................................................- 20 3.1 Outdoor Positioning Technology........................................................................- 21 3.1.1 Global Positioning System (GPS)................................................................- 21 3.1.2 Global System for Mobile Communication (GSM).....................................- 24 3.2 Indoor Positioning Technology...........................................................................- 28 3.2.1 Wireless Local Area Network (WLAN).......................................................- 29 3.2.2 Ekahau Positioning Engine..........................................................................- 33 4 System Design............................................................................................................- 43 4.1 Database Design..................................................................................................- 43 4.1.1 User Relation................................................................................................- 46 4.1.2 Group Relation.............................................................................................- 46 4.1.3 Message Relation.........................................................................................- 46 4.1.4 Location Relation.........................................................................................- 46 4.1.5 Group Member Relation..............................................................................- 47 4.2 Client Server Architecture...................................................................................- 47 4.3 Positioning Server...............................................................................................- 49 4.4 Simulated Position Server...................................................................................- 50 4.5 Suggested Services..............................................................................................- 51 4.5.1 My Location.................................................................................................- 52 4.5.2 Online Users.................................................................................................- 52 4.5.3 Track Person.................................................................................................- 53 4.5.4 Message Services.........................................................................................- 53 4.5.5 Alert Messages.............................................................................................- 53 -
________________________________________________________________________
4.6 Graphical User Interface Design.........................................................................- 54 4.7 System Requirements..........................................................................................- 55 4.7.1 Hardware Requirements...............................................................................- 55 4.7.2 Software Requirements................................................................................- 56 4.8 Tools and Techniques..........................................................................................- 56 5 Implementation..........................................................................................................- 58 5.1 Software Design..................................................................................................- 58 5.2 LTBIES Programming Model.............................................................................- 60 5.2.1 LTBIES Client to LTBIES Server Communication.....................................- 61 5.2.2 LTBIES Client to Positioning Server Communication................................- 61 5.2.3 LTBIES Client and LTBIES Server to LTBIES Database Communication.- 62 5.2.4 Client Side Classes.......................................................................................- 63 5.2.5 Server Side Classes......................................................................................- 64 5.3 Server Side Implementation................................................................................- 66 5.3.1 Database Connectivity.................................................................................- 70 5.4 Client Side Implementation................................................................................- 73 5.4.1 Exception Handling......................................................................................- 78 5.4.2 Implementation of Map Component............................................................- 79 5.5 Thread Handling..................................................................................................- 81 5.5.1 Issue in Multithreaded Programs.................................................................- 81 5.5.2 Threads for Server........................................................................................- 81 5.5.3 Threads for Client........................................................................................- 82 5.5.4 Problem of Shared Resources......................................................................- 83 5.6 Database Implementation....................................................................................- 83 5.7 Protocol Design...................................................................................................- 87 5.7.1 Protocols.......................................................................................................- 87 5.7.2 LTBIES Protocol Structure..........................................................................- 87 5.7.3 Client to Server Protocol..............................................................................- 87 5.7.4 Server to Client Protocol..............................................................................- 89 6 Software Testing and Simulation...............................................................................- 90 6.1 Software Testing..................................................................................................- 90 6.1.1 White Box Testing........................................................................................- 90 6.1.2 Black Box Testing........................................................................................- 92 6.2 Simulation...........................................................................................................- 94 6.2.1 Simulation for LTBIES Application.............................................................- 95 6.2.2 Simulation for All Other LBS Application Developers...............................- 97 7 Conclusions................................................................................................................- 99 Further Enhancements in LTBIES..............................................................................- 100 Acknowledgements.....................................................................................................- 102 References...................................................................................................................- 103 Appendices..................................................................................................................- 106 A1 User Manual......................................................................................................- 106 A2 Abbreviation List..............................................................................................- 108 A3 UML Diagrams.................................................................................................- 109 A4 Screen Shots......................................................................................................- 116 A5 Database Tables.................................................................................................- 123 A6 Program Listing.................................................................................................- 125 -
________________________________________________________________________
Preface
This thesis has been written by a group of students at the IT University of
Copenhagen during the period of 1st of July 2003 to 8th of December 2003.
The idea of this system is conceived from the Global and Mobile applications,
mobile systems and distributed system courses.
To fulfil the requirements of the Master of Science (M.Sc) degree at the IT
University, we have to write a master thesis at end of our study program. So
this thesis is also a part of our final academic activity.
The evaluation of this thesis is based on 30 credit points.
H. M. Bilal Sarwar
Nadeem Ahmed
Shouket Iqbal
Copenhagen, December 2003
________________________________________________________________________
Abstract
With the recent and continuing advances in areas such as wireless
communications
and
positioning
technologies,
mobile,
location-based
________________________________________________________________________
2
________________________________________________________________________
1 Introduction
Location-awareness is a key to the success of future mobile applications.
Information about a users current location enables a wide range of new
services and can be used to increase the usability of existing applications
deployed on resource-restricted small handheld devices like laptops, PDAs
and mobile phones. In past the research in this area has mainly focused on
outdoor geolocation systems. Examples for such systems include the Global
Positioning System and positioning schemes deployed in cellular
communication networks. These approaches however cannot provide
accurate indoor geolocation and do not address the technical challenges of
indoor environments. Hence, in the past few years there has been an
increasing interest not only in research on indoor geolocation science and
technology but also in developing many location based applications [Schmidt,
2003].
Generally locating users and terminals accurately within the buildings is new
and important technology for different fields like commercial areas, customer
service, military and public safety applications. Examples may include mcommerce1 applications to guide customers through huge departmental
stores to aid policemen for surveillance, medical personals in hospitals and
fire fighters within the buildings. Apart from such applications, which would
not be possible without location information, many other applications can
benefit from user context information [Schmidt, 2003], of which the
geolocation is one of the important aspects. Knowledge about the users
context in general and the users precise location in particular can greatly
improve the usability of applications designed for mobile devices.
1.1 Motivation
Mobile devices have really revolutionized the communication and drastically
affected the life style of the modern nomadic users. The inherent features of
mobile devices are their high portability and personal nature. The voice
capabilities of the mobile phones are currently augmented with data
capabilities of increasing speed. The decreasing size of such mobile devices
1
________________________________________________________________________
3
________________________________________________________________________
laptops, mobile phones and PDAs are converging and evolving into smart
phones and communicators, which have allowed users to access Mobile
Internet services and run different kind of applications at any time and at any
place. Therefore, they are being used for storing and accessing information
at any time wherever the users go.
Thus the continuous availability of these devices and the emerging capability
of the mobile terminals and/or the mobile network infrastructure to locate
the mobile terminals in the indoor environment have motivated us with many
others to develop new types of spatial and real-time services that are exactly
called Location-Based Services. According to some estimates in near future
major part of the future Mobile Internet services are expected to be LBSs
[Virrantaus, 2001].
________________________________________________________________________
4
________________________________________________________________________
1.3 Focus
Applications for a mobile environment certainly take advantage of contextual
information, such as position, which itself is a very complex phenomena and
needs special attention. Position can be discussed geographically, socially and
relative to workflow model to offer greater services to the user. In this
project, consideration was only a small part of the users context, specifically
location and time. Knowledge of the users current location is used to provide
more of the kind of services that we come to expect from a real or normal
type of application. The architecture and features of the application will be
described and then developed, only for indoor use on a given platform. The
discussion will include the general research and technological issues that are
important in developing context-aware (Location Based) applications in a
mobile environment.
Obviously the general application domain which has driven the development
of this project is indoor Location Based Services, which is quiet complicated
and involves a lot of elements but we have found it necessary to be even
more focused in one specific problem domain. That is the development of an
application on a given platform (LaCoMoCo) [Schmidt, 2003].
Moreover Location Based Services can be classified by their functionality and
utilization of location information. The basic class of the Location Based
Services is location-based information services, utilizing the mobile users
present location. In a simplest form it is a positioning service, informing the
user about her/his present location (Where am I?). However, knowing only
the coordinates is not very useful. Therefore this service is usually combined
with a digital map associated to the users location. This service is a map
service. A digital map can be only a basic map available on network without
any more information. When the map is augmented with an access to some
point-of-interest location information, the service type becomes a guiding
service showing users on map. When the service includes capabilities to
search information about real-world physical services, and perhaps a
possibility to contact them, it becomes a mobile communication and
information exchange service. The service may have features that support
finding of the way to the specified destinations. This type of service is called
navigation service. Location-based functional services can be distinguished
from the information services [Schmidt, 2003].
________________________________________________________________________
5
________________________________________________________________________
Therefore, this application is mainly concerned with some functional services,
which are using the mobile users present location. The example of asking a
friend to pickup your books, which you have forgotten in the canteen by
locating him in the canteen, can be a functional service. In this example
present location of your friend belongs to this category. Alert messaging
services are also an important group of functional services in the application.
The next class of services in the application are location-aware services.
Location-aware services are services where the users position or proximity to
another object triggers some event or defines some condition. One example
of such services is location-based marketing; where for example
advertisement is send to the terminals approaching the ITU canteen.
The long-term research area is an application that knows where the user is,
what he is looking at, can predict and answer questions he might pose, and
provide the ability to interact with other people, organizational environment.
Short-term goal is to implements a complete version of a kind of application
on commercially available laptops.
1.4 Literature
We have taken courses like Global and Mobile Applications, Distributed
Systems and Mobile Systems at the ITU. In these courses, we have
studied positioning technologies GPS, GSM and WLAN, where WLAN is
specifically being used for indoor positioning .At the ITU there is a positioning
server called Ekahau installed, which is based on WLAN indoor positioning
technology.
The purpose of introducing students to these technologies was to give them a
brief insight of problems and features of advanced and usable mobile LBS.
When developing LBS, the constraints of a mobile computing environment
have to be studied carefully. A general location-based service demands
flexibility and scalability from the system architecture, so it is essential for
application developers to read and understand existing system and platform.
For this application development, abundance of detailed literature about
positioning technologies motivated our choice of this area. While doing this
we are following course compendium and the cases, which it has presented.
More over, we are taking help from course web page and other online
available recourses.
________________________________________________________________________
6
________________________________________________________________________
1.5 Methodology
In this study, we embedded use of available literatures as much as possible
into observational work. Some small meetings had also been arranged with
other groups to practically see their activities while working on their projects
in which we were participants and observers. We spent several days
observing the existing positioning system at the ITU. A focus of this work was
the transfer of every piece of important information, such as how many
access points are installed at the ITU or for example how LaCoMoCo is
running on top of Ekahau. Mainly, some small meetings were held with the
pioneers of LBS at the ITU. They were the members of LaCoMoCo team at
the ITU.
On the basis of this observational work it was concluded that the system
(LTBIES) will run on both a client machine (laptop/PDA) and a local serve in a
Wireless Local Area Network (WLAN). The IT University of Copenhagen will
be taken as a test environment, where the Ekahau positioning engine is
running [Ekahau, 2002].We were intended to design a generic system that
can be adjusted and deployed easily on different environments such as
schools, Hospitals, Multi-storey shopping centres and huge complexes.
________________________________________________________________________
7
________________________________________________________________________
applications for indoor environment. A brief cooperative perspective is
presented at the end of this chapter to analyse the viability of the application
in different organizations.
Chapter Three covers basic technologies of positioning system. It is divided
into two parts, outdoor positioning technologies which give the brief
description of Global Positioning System and Global System for Mobile
Communication and the second part give the description of indoor positioning
technology which covers basic principles of wireless local area network (IEEE
802.11b standard) and Ekahau positioning engine technique and technology.
Chapter Four covers components of system design which we developed to
achieve the goals of this project.
Chapter Five tends to describe all aspects of implementation. This includes
the actual steps for implementing the complete architecture. To give more
meaning we have divided implementation of LTBIES application in to three
main parts server side implementation, client side implementation and
database implementation. Prior to these modules and core implementation
software design along with definition of classes is given for better
understanding.
Chapter Six covers the testing of software. For testing purposes, a
simulation is developed. By using this simulation, the results are checked
against particular location and specified time. This chapter also describe a
general test bed (Simulated positioning server) for other location based
services application developers.
Chapter seven gives the conclusions of thesis work and some ideas of
possible future extension. It is followed by the list of references and
appendices which include the programming code, abbreviations, database
tables and diagrams
________________________________________________________________________
8
________________________________________________________________________
2 Problem Analyses
2.1 Background
LBS satisfy users information needs at any given time relevant to their
geographic position. This is a very practical technology solution to everyday
problems that holds a truly exciting future. It is estimated that LBS revenue
will grow in billions in near future according to an Allied Business Intelligence
study [Bacastow, 2002]. This research effort strives to examine the viability
and benefits of location-based services, to determine if its usefulness,
convenience, and ability to satisfy users information needs at any given
location and time will make it the next significant trend in mobile
communication/computing on university campuses. Visitor information
guides, event statistics, traffic patterns, weather forecasts, surveillance and
local news are examples of useful information that could be delivered via
LBS. Moreover, new smart devices are becoming available to better support
LBS. In future research will be focused on applying this technology more and
more almost every possible area including, personal security, public services,
and commercial ventures.
The IT University of Copenhagen and Nokia are part of a group of European
Universities and private enterprises that plan to create a European
Laboratory for Context dependent Mobile Communication. To this end, an
Expression of Interest has recently been submitted to the Commission of the
European Union. The core group of partners in LaCoMoCo consists of the
partners of Crossroads Copenhagen, a consortium of private and public
companies including ITU and Nokia. The members of Crossroads Copenhagen
started discussing possible project ideas in 1999 . After many rounds of
discussions, the members settled on the topic of Context-dependent Mobile
Communication in early 2002, and then Crossroads Copenhagen was officially
launched on May 2, 2002, by the Danish Minister for Science, Technology and
Innovation. Crossroads Copenhagen has a board consisting of the CEOs of
the partners and it has a professional secretariat, whose role is to help with
the integration and administration of subprojects [Birkedal, 2002].
See www.crossroadscopenhagen.com/project_b.htm
________________________________________________________________________
9
________________________________________________________________________
The purpose of these subprojects is to establish a standardised platform for
distribution of individually relevant services and information on wireless
terminals to persons who move around within a given geographic area
[Birkedal, 2002].
________________________________________________________________________
10
________________________________________________________________________
________________________________________________________________________
11
________________________________________________________________________
user authentication by voice is used to filter the services for users. Moreover
these provided services will depend on the users location.
________________________________________________________________________
12
________________________________________________________________________
We propose a Location and Time Based Information Exchange System
(LTBIES), which allows the user to define complex conditions under which a
reminder will be generated (e.g. time is "9:00" and location is "office1.49").
Conditions are stored in a database and linked to users. Whenever a
condition is fulfilled, the system generates a message box. In our intended
scenarios, however, we have to address issues such as connectivity across a
network and mobility of clients, thus we have to use data distribution
concepts. We will also rely on existing platform LaCoMoCo, especially, for the
relation between physical to semantic locations and the mapping of local
sensor-data to global location information.
________________________________________________________________________
13
________________________________________________________________________
The Second scenario is also based on location service. A student who is
working on a project remembers that one of his classmates has a book that
might be helpful for his work. A system is needed which could locate and give
the message to his friend about the book. System should be able to deliver
the message immediately after he enters in the ITU or any predefined
location for example library canteen or even a particular floor.
________________________________________________________________________
14
________________________________________________________________________
advance, moreover it should be able to inform everybody who reaches in
front of the room and tries to enter in the room.
________________________________________________________________________
15
________________________________________________________________________
________________________________________________________________________
16
________________________________________________________________________
relevant to a user at a specific location at a specific point of time. LTBIES is
designed for end users. User can enjoy information exchange that is relevant
in a particular location and at right moment. Personalized information is also
available this information is about the users own location. User is allowed to
make information more focused and of higher quality, when information is
tailored according to the users defined location and time.
________________________________________________________________________
17
________________________________________________________________________
Time bound information exchange
Location bound information exchange
________________________________________________________________________
18
________________________________________________________________________
policies is going to take place in conference hall. Hotel management could
not inform about it earlier to their staff and customers. It was critical issue
for the management because they have to do two major tasks. First one is to
arrange the hall for the conference to make it perfectly ready and pass this
information to their employees. The second is to locate all their customers
who belong to business community and inform them about this conference.
Hotel management first want to locate their staff then they want to see
where they are and what they are doing. They know their routine but some
times some of them do not have anything to do, therefore they go into staff
room to get some rest. They want to pass this information to customers
without disturbing them, especially those who are in bar or out of any activity
or logged on to the system or those who reaches in front of the conference
hall. Using the proposed system Hotel management can inform its free staff
while sensing their location in the staff room without bothering them in the
position of their routine work.
By analysing and understanding the nature of managerial activities involved
in different organizational works, it can be viewed that all these activities are
highly collaborative, and involves a wide range of practices that can be better
supported by deploying LBS. Factories can use it to inform their new
employees or visitors on reaching at some danger zones by alert messaging.
Hospitals could be a good market, where doctors, nurses and patients can
use this; Nurses can use this system to make sure that the patient should
take medicine at the right time if they are busy with other patients, by
sending or making messages time bound.
Customer Scenario
This customer is a middle age man. He is a businessman from USA. He is in a
business of import and export and as a result of the nature of his business he
has to travel around the world to visit his business counterparts. He goes for
meetings and spends time in different hotels. Major part of his business is in
Europe. He visits constantly Copenhagen and stays in five star Hotel,
Now suppose if he has been given a location based services enabled device
from hotel management. He had a business meeting with some business
counterparts in the conference room but some how he is not feeling well so
he decided to go to mini-bar but he leaves a message in the conference room
for his friends which will be delivered to them when they enter in the
________________________________________________________________________
19
________________________________________________________________________
conference hall. After a while he realizes that he might not be able to wait
more that one hour in the bar therefore he can make his message time
bound. During this period if the system senses those persons in that location
system will deliver these messages, after that system will not deliver the
message.
For customers point of view big supermarkets could be benefited from this
application. Popping up messages and giving the customer information about
special offers in a specific department.
Although the existing traditional systems are working good and both the
customers and organizational managements are practicing it for a long time,
the new Location Based Service can influence them all and they can have
benefits out of these new technologies. In any important sense it seems that
the new system will have strong impact on the coordination of their work.
________________________________________________________________________
20
________________________________________________________________________
________________________________________________________________________
21
________________________________________________________________________
In Network based geolocation, fixed stations receive signal from the
mobile station and send information to a central station where the mobile
stations location is computed [Nerguizian, 2001]. It is referred to as
Network based because the mobile network, in conjunction with network
based position determination equipment is used to position the mobile
device [Turner, 2002].
In Handset based geolocation, a mobile station receives signals from the
fixed stations and computes its own location. It is referred to as Handset
based because the handset itself is the primary means of positioning the
user, although the network can be used to provide assistance in acquiring
the mobile device and/or making position estimate determinations based on
measurement data and handset based position determination algorithm
[Turner, 2002].
________________________________________________________________________
22
________________________________________________________________________
The main principle behind the GPS is the distance between the receiver and
the satellites. The distance can be calculated by estimating the amount of
time for GPS signals to reach the receiver. When the GPS receiver finds
distance to at least three GPS satellites then it can calculate its position in
two dimensions (latitude and longitude) and when four or more satellites are
in view, the receiver can determine the user's 3D position (latitude, longitude
and altitude) [Srensen, 2003].
GPS satellites circle the earth twice a day in a very precise orbit and transmit
signal information to earth. GPS receiver on earth receives this information
and use triangulation to calculate the users exact location. GPS receiver
compares the time, when a signal was transmitted by a satellite with the
time it was received. The time difference tells the GPS receiver how far away
the satellite is from the receiver [Srensen, 2003].
GPS gives good results for outdoor environment only. Now the question is,
Does GPS can also work in the indoor environment? The simple answer of
this question is No because the GPS signal will not pass through most solid
objects such as buildings and mountains [Srensen, 2003]. The GPS signal is
reflected by objects such as tall buildings or large rock surfaces before it
reaches the receiver. This increases the travel time of the signal, thereby
causing error. Because of this reason GPS doesnt give good results near tall
buildings.
Velocity is the velocity of light which is equal to 1, 86, 000 miles per second.
________________________________________________________________________
23
________________________________________________________________________
The three distances which has been calculated shows the mobile is on the
spheres that are ta x c, tb x c and td x c miles away from the first, second
and third satellite. It means that the position of mobile device on the surface
of the earth is the intersection between these three cones. Each satellite is
on the top point of the cone with a side length of ta x c, tb x c or td x c. It is
illustrated in Figure (3.1.1.1) and Figure (3.1.1.2) [Srensen, 2003].
td
tb
ta
Figure (3.1.1.1): Mobile device on the surface of earth. Its position is determined by the intersection of the
cones with side lengths ta x c, tb x c and td x c (where c is velocity of light) (source idea [Srensen,
2003])
ta x c
Figure (3.1.1.2): Satellite is on the top point of a cone with a side length of ta x c. (source idea [Srensen,
2003])
________________________________________________________________________
24
________________________________________________________________________
3.1.1.2 Advantages of GPS
The system works all over the world.
It is free for all civilians. One can request and receive positions.
It is a reliable system.
It gives good accuracy for outdoor positioning in open terrains.
________________________________________________________________________
25
________________________________________________________________________
system operating at 800-900 MHz or 1800 MHz [IEC, 2003]. It was first
deployed in 1992 and is now widely used around the world. The abbreviation
GSM derives from Group Special Mobile.
N S S
P S D N
A U C
I S D N
V L R
H L R
E I R
P S T N
M S C
P L M N
O S S
in te r fa c e
B S S
B S C
A b is
in t e r fa c e
B T S
M I S
S I M
Figure (3.1.2.1) General architecture of the GSM network (Source idea [IEC, 2003])
The first element mobile station is the equipment carried by the subscriber. It
consists of a mobile terminal and a smart card called the Subscriber Identity
Module (SIM). The second element is Base Station System (BSS). It consists
of Base Transceiver Station (BTS) and the Base Station Controller (BSC). BTS
handles the radio interface to the mobile station. The BTS is the radio
________________________________________________________________________
26
________________________________________________________________________
equipment needed to serve each cell in the network. A group of BTSs are
controlled by a BSC. BSC provides all the control functions and physical links
between the Mobile Switching Centre (MSC) and BTS [IEC, 2003].
The third element is Network Switching Subsystem (NSS), which manages
the communication between the mobile users with other users. NSS contains
MSC, which performs the connection and switching services to other
networks. NSS also contains Home Location Register (HLR), Visitor Location
Register (VLR), Equipment Identity Register (EIR) and the Authentication
Centre (AuC). The fourth element, Operation Support Subsystem (OSS)
connects the different components of NSS to the BSC. OSS controls and
monitors the GSM system [IEC, 2003].
This method involves measuring the time that a signal takes to travel
between a base station and a mobile telephone or vice versa. Measurement
constrains the position of the mobile telephone to a circular locus around the
base station. If other propagation time measurements are made with respect
to a second and third base station, two more circles loci are produced.
Position determination is the point of intersection of three loci. The system
which makes propagation time measurements is also referred as a circularcircular-circular system.
________________________________________________________________________
27
________________________________________________________________________
Angle of Arrival
This method involves measuring the angle of arrival of a signal from a base
station at a mobile telephone or vice versa. A single angle measurement
produces a straight line locus from the base station to the mobile telephone.
Another AOA measurement from second base station yields a second straight
line. The intersection of the two straight lines gives the position of the
mobile.
Time Difference of Arrival
A mobile telephone can listen to a number of base stations and measure the
time difference between each pair of arrivals. From three base stations two
independent TDOA measurements can be made. Each TDOA measurement
defines a hyperbolic locus on which the mobile telephone must lie. The
intersection of the two hyperbolic loci will define the position of the mobile
telephone.
________________________________________________________________________
28
________________________________________________________________________
There can be some problems with the indoor positioning since the
accuracy is not well (up to 87 meter) [Srensen, 2003].
This system can be used for indoor environment but because of the accuracy
problem this system is not generally preferred for indoor positioning. For the
development of indoor location based services, it is necessary to look any
other accurate system that can give more accurate location of mobile
devices.
________________________________________________________________________
29
________________________________________________________________________
IE E E 8 0 2 .2
L o g ic a l L in k C o n t r o l ( L L C )
IE E E 8 0 2 .1 1
M e d ia A c c e s s C o n t r o l ( M A C )
F re q u e n cy
H o p p in g
S p re a d
S p e c tru m P H Y
D ir e c t
S equence
S p re a d
S p e c tru m
PHY
In fra re d
O SI Layer 2
( D a t a L in k )
MAC
PHY
O SI Layer 1
( P h y s ic a l)
Figure (3.2.1.1) IEEE 802.11 standards mapped to the OSI reference model
________________________________________________________________________
30
________________________________________________________________________
IEEE 802.11 architecture comprises several components: the mobile station,
access point, wireless medium, the basic service set, the distributed system
and the extended service set [Petrick, 1999]. Depending on the size of the
covered area the following WLAN architectures can be used.
Independent Basic Service Set (IBSS)
Basic Service Set (BSS)
Extended Service Set (ESS)
BSS is a set of stations that communicate with one another. The BSS uses
one Access Point and all communication must go through this.
When all the stations in the basic service set are mobile and there is no
connection to the wired network or AP, the basic service set is called
Independent basic service set (IBSS). IBSS is also called ad-hoc network
(Figure (3.2.1.2)). An ad-hoc network is typically created in a spontaneous
manner and also for limited time.
D is t r ib u t e d N e t w o r k
Independen t B SS
I n fra s tru c tu re B S S
Figure (3.2.1.2) General architecture of adhoc and infrastructure basic service set
________________________________________________________________________
31
________________________________________________________________________
in wireless LAN configuration is Access Point and is discussed in section
below.
A P
B a ck b o n e N e tw o rk
M T
M T
M T
AP
M T
________________________________________________________________________
32
________________________________________________________________________
an antenna. Supporting wireless LAN cards and drivers for different operating
systems can be found in [Ekahau, 2002].
At the beginning six Access Points were installed as shown in Figure (3.2.1.4)
for wireless LAN and for positioning purposes but at present 13 Access Points
have been installed.
A P
3 .0 7
3 .0 8
3 .1 0
3 .0 9
3 .1 2
3 .1 1
3 .2 0 d
3 .2 0 c
A P
A P
3 .0 8 a
A P
3 .1 2 a
3 .3 0
3 .0 3
A P
A P
3 .1 5
3 .1 6
3 .1 7
3 .1 8
3 .1 9
3 .2 0 a
________________________________________________________________________
33
________________________________________________________________________
3.2.1.3 Disadvantages of WLAN
Main drawback of Wireless LANs is security concern. IEEE 802.11b
addresses this issue in wired equivalent privacy (WEP).
WLAN protocol 802.11b works in an unlicensed 2.4 GHz ISM band.
Some other appliances such as microwave oven, cordless phones etc
also share this bandwidth. This may also cause interference in the
propagation of the radio waves between the access point and mobile
user.
________________________________________________________________________
34
________________________________________________________________________
Via Ekahau Java SDK
Via LaCoMoCo WEB API
In order to retrieve the positioning data from connected clients in the
network, Ekahau provides their own Java API and SDK which is compatible
with Java2 SDK (version 1.4 and up). The Ekahau Java packages must be
imported in the application and the client must be able to access the
positioning server via the TCP/IP socket.
Ekahau Positioning Engine TM 2.0 has many good features that make it
attractive to use for indoor environment like its compatibility with IEEE
802.11b WLAN, Java2 SDK and accuracy etc.
________________________________________________________________________
35
________________________________________________________________________
3.2.2.3 How Does the Positioning System for Indoor Location
Work?
In this section it will be discussed how the indoor geolocation works. The
main objective is to find out the location of a mobile device in an indoor
environment. Figure (3.2.2.1) illustrates the functional block diagram of a
wireless geolocation system [Pahlavan, 2002].
L o c a tio n m e tr ic s :
T O A ,A O A ,R S S
R e c e iv e d
R F sig n a l
L o c a tio n
S e n sin g
L o c a tio n
c o o r d in a te s
( x ,y ,z )
P o s itio n in g
A lg o r ith m
D is p la y
S y ste m
L o c a tio n
S e n s in g
Figure (3.2.2.1) Functional block diagram of wireless geolocation system (Source [Pahlavan, 2002])
This block diagram shows that main elements of the system are, a number of
location sensing devices that measure metrics related to the relative position
of a mobile terminal with respect to a known reference point, a positioning
algorithm that process metrics reported by location sensing elements to
estimate the location coordinates of mobile terminal and a display system
that illustrates the location of the mobile terminal to users [Pahlavan, 2002].
The common location metrics are angle of arrival, time of arrival and
received signal strength.
Indoor systems using the existing wireless LANs may use RSS, AOA or TOA.
Pattern recognition positioning algorithm technique (Figure (3.2.2.2)) is used
to find out the location of a mobile device, based on the following two
phases.
________________________________________________________________________
36
________________________________________________________________________
Training phase - also called Learning phase, off-line phase or manual
calibration phase. It is the data collection phase.
Real-Time phase is the phase in which the position of mobile device
is determined.
Room 2
Room 1
Room 3
AP5
AP3
AP2
AP4
M o b ile d e v ic e
AP1
A c c e s s p o in t w it h f ix e d p o s it io n
a n d w ir e d c o n n e c t io n
D ir e c t p a t h a n d m u lt ip a t h s
Figure (3.2.2.2) Pattern recognition based indoor localization (Source [Srensen, 2002])
Grids are the known locations are sample points where signal strength is recorded during calibration.
________________________________________________________________________
37
________________________________________________________________________
the received signal pattern and compiles a unique signature for each zone. In
order to get good signatures, one has to collect many readings of signal
strength by rotating 360 degrees to capture access point signals from all
directions. This process is tedious and time consuming [Geier, 2002].
The received signal strength is a function of the amplitude of the signal,
transmitted from the access point to the mobile terminal. The IEEE 802.11b
standard contains a representation of the received signal strength, which is
available in the driver for the Wireless Local Area Network Card (hardware).
The received signal strength is the key information, needed for positioning
using WLAN [Srensen, 2003].
D a ta B a s e (S e t o f F in g e rp rin ts )
S e t o f R e c e iv e d
s ig n a ls
Set of know n
U s e r 's l o c a t i o n s
R e c e iv e r
Set of
F in g e rp rin t
In fo rm a tio n
Set of
F in g e rp rin ts
F in g e r p r in t K n o w n U s e r 's
I n fo r m a tio n L o c a tio n
In fo rm a tio n 1
L o c a tio n 1
In fo rm a tio n 2
L o c a tio n 2
L o c a tio n N
Figure (3.2.2.3) Data base of all fingerprints (Source idea [Nerguizian, 2001])
________________________________________________________________________
38
________________________________________________________________________
D a ta B a s e (S e t o f F in g e rp rin ts )
F in g e r p r in t K n o w n U s e r 's
I n fo r m a tio n L o c a tio n
In fo rm a tio n 1
L o c a tio n 1
In fo rm a tio n 2
L o c a tio n 2
I n f o r m a tio n ... L o c a t i o n .. .
In fo rm a tio n N
R e c e iv e d
s ig n a ls
R e c e iv e r
F in g e rp rin t
In fo rm a tio n
L o c a tio n N
P a tte r n M a tc h in g
A lg o r ith m
E s t i m a t e d u s e r 's l o c a t i o n
(c o rre s p o n d in g to th e re c e iv e d
F in g e rp rin t In fo rm a tio n )
Fig (3.2.2.4) Pattern matching with the data base (Source idea [Nerguizian, 2001])
________________________________________________________________________
39
________________________________________________________________________
Calibration needs revision periodically with changes in the building like
equipment, furniture and increase of population.
C L IE N T
H T T P
E k a h a u
S D K
P o s itio n in g
E n g in e
M o b ile
c lie n t s a p p
(G U I)
P C / L a p to p
S O C K E T
a p p
E k a h a u
S D K
Figure (3.2.2.5) Ekahau SDK and LaCoMoCo WEB API (source [Cervera, 2003])
________________________________________________________________________
40
________________________________________________________________________
3.2.2.7 Possible Design Considerations for LTBIES
Before starting location based services application development by using
Ekahau Positioning Engine, it is realized that one of the option from three
possible system options can be applied in the application development.
By using LaCoMoCo WEB API
By developing our own WEB API
By using Ekahau SDK
C LIE N T
H T T P
J S D K / M id le t
E k a h a u
S D K
P o s itio n in g
E n g in e
________________________________________________________________________
41
________________________________________________________________________
same facility like LaCoMoCo WEB API. In this case we will have to use Ekahau
SDK to get the position of mobile device and mapping the position retrieved
from Ekahau Positioning Engine with the floor maps of the ITU. This needs lot
of work on the server side which has already been done by Mr. Anders
Cervera and this platform is available for the students to develop their
applications on this API, which offers acceptable results and give the
information like (x, y, floor, room). Thus utilizing the facility of LaCoMoCo
WEB API seems more logical and time saving.
S E R V E R
S e lf D e fin e d
W E B A P I
C L IE N T
H T T P
J S D K / M id le t
E k a h a u
S D K
P o s it io n in g
E n g in e
By Using Ekahau DK
Another approach of getting position of a mobile device is directly using
Ekahau SDK. Drawback of adopting this type of approach is that then we will
have to focus on the server side programming. This architecture cannot track
J2ME enabled mobile devices, because J2ME does not support socket
connection.
S E R V E R
E k a h a u
P o s itio n in g
E n g in e
L A P T O P
C L IE N T
G U I
S O C K E T
E k a h a u
S D K
________________________________________________________________________
42
________________________________________________________________________
After going through the pro and cons of all these three options, it is
concluded that the most convenient design for this application is to use
LaCoMoCo WEB API. Since the concentration is only on the client side
development and from the application point of view the positioning system is
just a concept for retrieving position of mobile device and is demonstrated in
this application.
positioning
system
is
from
the
Finnish
firm
Ekahau
(www.ekahau.com).
The position precision in the middle part of the ITU building is approx 2
meter.
Ekahau updates the location after every 2 second [Srensen, 2003].
________________________________________________________________________
43
________________________________________________________________________
4 System Design
In this chapter the system architecture of this application will be discussed,
how it will be planned and designed to achieve the desired goals of this
project. The main goal is to enable the users of this application to avail some
indoor location based services which should also be time bound. So for
enough positioning technologies has been explored that was necessary for
location based services. Now we are going to design the system which brings
the idea of time and location bound services into reality.
The overall system architecture can be described into the four main
components. The components of system design are Server, Client, Database
and Positioning server. Keeping in view the importance of these components,
all components will be explained separately in brief along with an overview of
suggested services which we are going to provide the application users,
graphical user interface, system requirements and at the end of this chapter
summary of all tools and techniques which will be used to develop this
application. To keep the names of the system components unique, the
application server, client and database will be called as LTBIES server, LTBIES
client and LTBIES database respectively.
________________________________________________________________________
44
________________________________________________________________________
users information etc are stored and accessed in LTBIES database relation as
simple data types. Persistent data storage is necessary to make the
environment robust and to meet the long term storage requirements.
In this application, both client and server can access the LTBIES database.
Client can directly communicate with the LTBIES database when there is no
need of LTBIES server to be invoked and same situation is with position
server where client gets the location without the involvement of LTBIES
server. Application requirements were defined based on concept of services
to ensure that the storage is persistent and is available for client server
access.
Database is designed in a way that all the information needed for particular
tasks are normalized5, in the particular relation like all resources needed for
user authentication and registration is available in users relation and other
application services like leaving messages and getting messages are
available in message relation.
Entity6 Relationship Diagram is one of the most important elements of
database design. ERD enables a software engineer to identify data objects
and their relationships using graphical notations, ERD defines all data that
are input, stored, transformed and produced within an application [Watson,
2002].
Entities are shown by rectangles relationships are depicted by diamonds.
Attributes7 are shown as ellipse that connected to the entity or relationship to
which they belong. A detailed ERD8 of LTBIES database is given below.
Normalization is a way of splitting up data until each table represents propositions about a single type of
thing.
6
An entity is a thing about which data should be stored, something we need to describe.
7
An attribute describes an entity.
8
ERD is the abbreviation of entity relationship diagram.
________________________________________________________________________
45
________________________________________________________________________
b e lo n g s
U ser ID
Fnam e
E -m a il
G ro u p ID
D e s c rip tio n
U sers
G rou p s
P a ssw o rd
L nam e
send
M e ssa g e ID
re c e iv e
U se r ID
S ta rt T im e
E n d T im e
M essag es
F ro m
L o c a tio n N a m e
S u b je c t
To
M essages
has
L o c a tio n
L o c a tio n N a m e
D e s c rip tio n
U sage
A relational database stores all its data inside tables and table is a set of rows and columns. The rows are
analogous to a record and the columns are attributes of record.
________________________________________________________________________
46
________________________________________________________________________
addition of new materials, deletion of obsolete ones, and modifications to
existing ones. Brief detail of all the relations is given below.
________________________________________________________________________
47
________________________________________________________________________
Tier can be defined as "one of two or more rows, levels, or ranks arranged one above another" (see
http://www.m-w.com/cgi-bin/dictionary?Tier). N implies for any number, like 2-tier, or 4-tier, basically any
number of distinct tiers used in the architecture.
________________________________________________________________________
48
________________________________________________________________________
where the data is destined to be sent. For each socket connection, a thread is
spawned serving only one client. LTBIES server is a multi threaded server
and it can handle number of clients, where each client runs on a separate
thread. The server can serve many clients concurrently.
E k a h a u P o s itio n in g
E n g in e
L T B I E S C lie n t
LT B IE S S erver
L T B IE S D a ta b a se
Client may be any mobile terminal, but keeping in view the limitation of
mobile devices and also the memory problem the client is only laptop in this
project and is distinguished with the word LTBIES i.e. LTBIES client. Once the
server is running, the LTBIES client can start the log on procedure using the
log on interface.
On log on interface the client also has access to the relevant information
about the IP address of server in order to establish the connection to the
LTBIES server. Client is also allowed to enter the IP address of server if it is
running at some other machine. It means that it is the responsibility of the
client to know the IP address of server where it is running and replace it if
different than what is provided on the interface. In log on procedure the
client sends the request with user name and password. The LTBIES server
checks the name and password from the LTBIES database and if the client is
a valid registered user then server sends back ok reply i.e. the client user
name request has been accepted. If the log on procedure has been
________________________________________________________________________
49
________________________________________________________________________
successful, the LTBIES client now can avail all the services of our application.
Clients are also able to communicate directly with the Ekahau positioning
engine for location determination and to the database if there is no need of
application server.
11
________________________________________________________________________
50
________________________________________________________________________
S im u la te d P o s itio n in g
S erv er
L T B I E S /a n y o th e r C lie n t
L T B IE S S erv er
L T B IE S D a ta b a se
In order to avoid any ambiguity, it has been kept in mind that the request
and response format should remain the same as from the Ekahau Positioning
Engine. The http request will be sent to the Simulated Position Server and
one will get back the response in coordinates like (x, y, floor, room). This
________________________________________________________________________
51
________________________________________________________________________
Simulated Position Server can be used for testing the location element of
location based services. More detail of implementation and testing (see on
6.2.1).
________________________________________________________________________
52
________________________________________________________________________
S u g g e s te d S e r v ic e s
O n lin e U s e r s
O n L is t
M y lo c a tio n
In fo E x c h a n g e
T rack U ser
O n M ap
B y IP
L o c a tio n B a s e d
T a r g e t O r ie n te d
S in g le P e r s o n
G ro u p
M M T
IN T
B y N am e
T im e B o u n d
A ll
A D M
4.5.1 My Location
This service should provide the present location of user himself/herself. After
log on to application as registered or guest user, a user friendly interface of
application gives the opportunity to the user to find his/her location by just
clicking the button MY LOCATION and gets his location inside the building
shown in terms of (x, y, level, room). User can also request to view his
position on map by the option SHOW ON MAP.
________________________________________________________________________
53
________________________________________________________________________
________________________________________________________________________
54
________________________________________________________________________
User can interact with the application through two interfaces. Start
interface shown in Figure (4.6.1) is used for authentication of the
registered users and also provide the facility of registration for new
users. If the user clicks on login button an authentication dialog box
will open where the user will have to write the name and password.
After successful authentication, main application interface shown in
Figure (4.6.2) will be opened with welcome message like Mr.
Shouket, Welcome to location and time based information exchange
system. This interface should be user friendly and has menu buttons
on one side of application GUI. All the services should be displayed at
central area of the same window so that user can easily use different
services and can see results on the same window without botheration
and eye jumping at different places on different windows. Some screen
shots of interface are given in appendix A4.
________________________________________________________________________
55
________________________________________________________________________
12Systems contain integral parts and components. If there is a problem or malfunction within one of the components, it
system.
________________________________________________________________________
56
________________________________________________________________________
Mobile terminal. For this project the mobile terminals are
laptops.
Wireless LAN card13
Wireless network running in the indoor environment.
Database server (the hardware piece).
13
Wireless LAN cards are also called LAN adopter. A variety of wireless LAN cards are being used, the most common are Ayaya, ORiNOCO, HP,
Nokia etc.
________________________________________________________________________
57
________________________________________________________________________
Both client and server can run on the same mobile terminal or on
different machines.
Ekahau positioning engine is used for indoor location determination.
LaCoMoCo WEB API will be used for finding the location of mobile
terminal.
Java programming language is used to achieve all proposed services.
My SQL database server is used for data storage.
Windows oriented graphical user interface.
Updating the position of connected clients after every two seconds.
________________________________________________________________________
58
________________________________________________________________________
5 Implementation
We were given a good deal of options (software and hardware) for developing
application on a platform. This opportunity gave us a certain amount of
insight into the important issues in developing and implementing mobile,
context-aware applications. Our prototyping efforts were iterative, modifying
software to improve functionality. When choosing hardware platform, we
considered several mobile hand-held devices including mobile phone before
deciding on the laptops. One of the driving considerations in deciding
hardware was memory. The downside of this decision is the fact that for an
organization it is not easy to give every user a laptop and on the other hand
it is not practical on the users side to carry a weight like laptop all the time.
However, in the near future the issues like size and memory will no longer
remain because of the rapid development and technological advances in the
field of mobile devices.
Mobile location services applications do require the complex systems
integration of many different technology components. Therefore several
technical issues needed to be well understood before final implementation of
the application. The serious issues that have to be considered during the
design of such an application are consistency guarantees provided to the
clients, synchronization between the position server and the self-defined
server, servers should be aware of the status of other servers in the
environment and the way stored data is organized and accessed through
database server.
________________________________________________________________________
59
________________________________________________________________________
design were created: the Client and the Server. The description of the
program will be divided into two parts, the first referring to the Client side
and the other referring to the Server side.
C lie n t
Server
P o s itio n S e r v e r
S c o k e t C o n n e c tio n
C la s s S e r v e r
C la s s C lie n t
c la s s C lie n tW o r k e r
C la s s S e v e rW rite T h re a d
c la s s G u e s t
c la s s L o g in
c la s s R e g is t e r
c la s s M a in
D a ta b a se
c la s s L o c a tio n
c la s s M e s s a g e T h r e a d
From the above diagram one can easily understand the two sides of the
program. Moreover it is clear form the diagram that the client side of the
program is interacting with the User, whereas the server side is oriented
towards managerial work. Therefore these two sides will be discussed
completely in different parts.
________________________________________________________________________
60
________________________________________________________________________
________________________________________________________________________
61
________________________________________________________________________
LT B IE S S erver
S o c k e t C o n n e c tio n
The application must be able to store and retrieve data such as messages or
location. This data must be accessible by all users. Thus, the implementation
should consist of at least two main parts: a LTBIES client part that can
execute locally on an end-users mobile device and a LTBIES server part that
provides common functionality between all clients. The main reason for this
is that the location information and the data about usage of the messages
have to be available centrally to all users. One of the most important
responsibilities of LTBIES server is to maintain the list of all available
users/clients. It does so to provide clients with the status of other clients to
allow them to locate each other and get other services like get or leave
messages. Another reason relates to the fact that LTBIES is a mobile service
and as such it is subject to network connections and its quality. Therefore, it
is desirable to maintain network connectivity otherwise it will not work.
L a C o M o C o (W E B A P I)
H T T P R eq u est
H T T P R esp on ce
________________________________________________________________________
62
________________________________________________________________________
In the application client will also communicate with the positioning server by
sending an HTTP request to the positioning server. This positioning server
resides on the ITU server. LTBIES client does this communication with the
position server to get the position of other clients along with its own position.
On the basis of this positioning it provides other services. Practically client
sends an HTTP request to the positioning server with a predefined
formathttp://server_address/TrackServlet?
value=x,y,z&clientId=192.168.100.102&measure=pixels and in return the
positioning
server
will
response
with
a
format
3624.475983266959,1149.5646103746471,level3,3.19 like this.
LT B IE S S erver
L T B IE S D a ta b a se
Figure (5.2.3.1): LTBIES client and LTBIES server connection with LTBIES Database
LTBIES client and LTBIES server both can communicate with LTBIES
database. LTBIES serve use communication with LTBIES database to achieve
client authentication from the database. Server also deletes the expired
messages form the database. Server is responsible for deleting those
messages, which has reached their maturity (message end time) seven days
ago.
LTBIES client has communication with LTBIES database. LTBIES use it to get
and put messages in to the database. The main advantage of this
________________________________________________________________________
63
________________________________________________________________________
communication of client and database is to share load form the LTBIES
server.
class Client
On client side this class includes the main method.
class Login
This class is used to provide option to the registered users for getting
in the system.
class Guest
This class is responsible for taking care of Guest users on client side of
the application. Its responsibility is to provide user interface to every
guest client who logs on to the server.
class Register
This class is providing the option of becoming a member to the system
by filling a form, and allows the client to become a registered user on
the server soon after.
class Main
This class mainly includes GUI components. This class represent the
Main interface to the client.
class MessageThread
This class is always running and keeps checking messages, location
and time for the client. It is also responsible for keep informing the
client about messages by showing a popup window.
class MainListener
________________________________________________________________________
64
________________________________________________________________________
This class is responsible for listening actions events on buttons.
class getMessage and class leaveMessageForm
These classes are responsible for providing the client facility of
receiving or leaving a message from other clients.
class myLocation
This class is used to provide client his location in the form of
coordinates and area form Ekahau positioning engine via LaCoMoCo.
class Trackperson
It is used to find out the position of a particularer person. It returns
the position as a text message on the map and shows this message on
the map.
________________________________________________________________________
65
________________________________________________________________________
message database. This information it will deliver to client after
checking the flag. This class is responsible of taking care of those
messages which are written by the client.
Helping Classes
These classes have been developed to add more functionality to the existing
classes among them one class is created for a very important purpose of
simulation.
class SimulationFOrm
For performance evaluation of application, class simulation was
developed, which provides a simulation form.
class CustomScrollPan
To make interface more practical and functional this class was
developed, which is responsible for providing scroll bars on every
window of the application, where it is necessary to scroll down or scroll
up.
________________________________________________________________________
66
________________________________________________________________________
L o c a t io n
L o g in
C lie n t
R e g is t e r
M a in
M y L o c a t io n
G u est
g e tM e ssa g e
T rack P erson
c lie n tR e a d t h r e a d
m e s s a g e th r e a d
O n lin e U s e r s
S h o w O n M a p A ll
Show O nM ap
________________________________________________________________________
67
________________________________________________________________________
In LTBIES implementation we are initializing a Server socket object in order
to make a socket connection for every incoming client. Generally a network
connection between client and server is made through sockets. A socket
connection is defined as one end-point of a tow way communication system,
which links two programs running parallel on the network. This socket tends
to connect these programs, which are called client and server. Server runs on
a specific computer and has a socket for communication and listens on a
specific port. It basically waits and listens until a client requests a
connection. In order to differentiate one client form another client, socket is
bound to a specific port number so that the TCP layer can easily identify,
which client application has asked for the data.
The client should know the hostname/IP address of the computer on which
the server is running and also the port number to which the server is
connected. If the server accepts the connection request from the client, the
server makes a communication link with the client from this socket. Then the
port on the server that waits and listens is available again and ready to
receive new connection requests from other client(s) and at the same time
creates to the needs of the connected client. This socket connection can be
seen in the following figure.
C lie n t
C o n n e c tio n
R eq u est
C lie n t
N e x t C o n n e c tio n
R eq u est
C lie n t
A
R eq u est
A c c e p te d
Server
Server
________________________________________________________________________
68
________________________________________________________________________
public static void main(String[] args){
Server frame = new Server();
frame.listenSocket();
}
public void listenSocket(){
server = new ServerSocket(9786);
while(true){
ClientWorker w;
try{
new ClientWorker(server.accept(), textArea).start();
}
}
Here above mentioned main method starts the application server and the
second listenSocket () method opens a serverSocket and a new loop that
always listen for a client connection when a client does so it runs the
following client worker thread object.
protected void finalize(){
server.close();
System.exit(-1);
}
When ever the server goes down this method will execute and close the
socket connection.
After invocation, LTBIES server has to perform some tasks along with the
initialization of server socket in order to provide the clients better services.
These tasks are listed below.
LTBIES server opens the socket connection for the client on the
specified port number.
________________________________________________________________________
69
________________________________________________________________________
LTBIES spawns a new session thread every time a new LTBIES client
approaches. After establishing each connection it again starts waiting
for a new client.
LTBIES server tends to establish a database connection by running a
calss ClientWorker.
LTBIES server then performs user authentication.
This class ClientWorker further initializes one class, class server write
thread.
Class
writethread
after
initialization
will
take
the
complete
________________________________________________________________________
70
________________________________________________________________________
out.println(true/false);//send the response back to client and break the while loop
}
________________________________________________________________________
71
________________________________________________________________________
Establishment of LTBIES database connection with client and server is
essential because LTBIES database holds different data relations 14 [Ullman,
2002] each of which is responsible for its unique data. For example, in here
the user relation is used for storing information about user like their names,
email address user ID and password, where as location table is used for
storing information about locations along with some short description about
their physical environment and usage. Each of this information can be
accessed and processed through LTBIES server by sending quires to the
database.
JDBC drive makes it easy for Java programs to communicate with the
relational database. Here one can see that how this private database
connector takes a url string along with other parameters as arguments and
establishes a connection. Another important argument is a driver, which has
been
downloaded
in
the
package
to
make
this
connection.
com.mysql.jdbc.Driver is a suitable drive to establish connection between
java programs and MySQL relational database. To load this JDBC driver a
statement
class.forName
(com.mysql.jdbc.Driver)
is
used.
DriverManager.getConnection(url,username,password) gets an internet type
of network connection to the database. Statement object provides
functionality to build a query and eventually execute it. This also returns a
Resultset. If the network connection goes down an exception can be thrown.
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "******";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(Q);
stmt.executeUpdate(Q);
Relation is a database term which defines the data in the form of rows and columns. A relation is also
called a table.
________________________________________________________________________
72
________________________________________________________________________
SELECT userID FROM users where userID ='Jelling'
SELECT * FROM users where userID = 'Nadeem' and password= 'gujrat'
INSERT INTO users VALUES('jelling','Kristoffersen','kjk@itu.dk','Kristoffersen','jelling')
Above-illustrated quires show some quires with their structure. They also
show that how different types of informations are being accessed by LTBIES
server. Some other quires with their respective methods have already been
discussed on page 68.
________________________________________________________________________
73
________________________________________________________________________
L o g in
C lie n t
R e g is te r
M a in
M y L o c a tio n
G u est
g etM essa g e
T rack P erson
c lie n tR e a d th r e a d
m essa g eth re a d
O n lin e U s e r s
S h o w O n M a p A ll
Show O nM ap
________________________________________________________________________
74
________________________________________________________________________
String ip = "192.168.100.229";
ipS.setText(ip),
int port = 9786;
static Socket socket;
try {
if (socket == null) {
socket = new Socket(ipS.getText(), port);
socket.setSoTimeout( 5000 );
}
}
catch (UnknownHostException e) {
message.setText("Unknown host: " + e);
}
catch (IOException e) {
message.setText("No I/O " + e);
}
if (command == "Login") {
Login l = new Login();
}
else if (command == "Register") {
Reg r = new Reg();
}
else if (command == "Guest") {
Guest g = new Guest();
}
Above mentioned code is of the client class and its responsibility is to bring
first visual interface for the client and make the socket connection with the
server. PrintWriter and BufferReader objects are used to read and write
from this socket connection. It also shows that after the socket connection
stage program is holding the client for a period of time so that the LTBIES
server can respond after adequate processing of the client request which
certainly includes user authentication. At the same time we are giving a
certain amount of time to client for waiting after that it will be considered as
time out. In this application the time out is set to wait 500ms. Moreover if
this socket connection is not been able to establish within this amount of
time the request will be terminated and client has to send again a valid
request. Class client is also responsible for receiving and sending button
events to other three classes.
________________________________________________________________________
75
________________________________________________________________________
After providing the first interface with three options to the client, now this
class has initiated one class among three classes Class Guest, class Login
and Class register. Each of these classes is now able to communicate with the
class client worker which is ready to allocate the threads for further
communication. If the user is a registered user the class login will be
activated for user authentication by checking the password form database.
This class has following methods which are providing these services.
private JTextField Tname;
private JPasswordField Tpassword;
String text ="L'";
text+= Tname.getText()+"'";
text+= Tpassword.getText();
Client.out.println(text );
String line = Client.in.readLine();
if(line.equals("true")){
Main ma=new Main(Tname.getText(),"L",Client.socket);
If the user is not a registered user and he wants to become a member at the
application the class register will be activated for storing user information in
user table. This information will be collected from the user on a form and
sent to the LTBIES server which then stores this information in LTBIES
database. The same procedure is used to retrieve the information from the
database because server has to maintain the user list just to check that, tow
users should not have the same login or user name. This class has following
form format and the methods which are providing these services.
private JTextField TUname,TFname,TLname,Tlogin,Tpass,Temail;
String insert="R'"+TFname.getText()+"','"+TLname.getText()+"','"+Temail.getText();
insert+="','"+TUname.getText()+"','"+Tpass.getText()+"'";
Client.out.println(insert );
try{
String line = Client.in.readLine();
if(line.equals("true")){
fram.setVisible(false);
fram=null;
Main ma=new Main(TUname.getText(),"G",Client.socket);
}
else
message.setText("It is not a valid record please try again");
}catch (IOException ee){
message.setText ("READ failed");
________________________________________________________________________
76
________________________________________________________________________
}
Now if the LTBIES client has initialized, it spawns a thread by calling a start
method from class Main. Now this thread will remain intact until and unless
client request to close the connection.
static JFrame frame;
static HashMap userList = new HashMap();
static HashMap messageList = new HashMap();
frame = new JFrame(
"Location and Time Based Information Exchange System ");
if (command = = "Messages") {
if (command = = "exit") {
frame.setVisible(false);
frame = null;
System.exit(0);
}
If LTBIES client requests for closure or goes down form the LTBIES server,
then this connection will be brought down and an IO Exception is caught.
Soon after this disconnection server will update its list of clients status and
now the system will closedown by showing a message on the Client side.
________________________________________________________________________
77
________________________________________________________________________
messageThread is responsible for delivering a message when ever it
reaches to maturity. It will update the position after every two seconds just
like Ekahau positioning engine is doing. Every time the LTBIES client is
notified by the positioning server it will check the status of messages for the
LTBIES database, through the following methods.
Location loc=new Location(Cip);
String Q="SELECT * FROM `messages` where mTo='All' or mTo='"+Main.user+"' and areaID
='"+room+"' and sTime < '"+sT+"' and eTime >'"+sT+"'";
if(areaID!=null){
ResultSet rs = stmt.executeQuery(Q);
while (rs.next()) {
if (Main.messageList.get(messageID) == null){
Main.messageList.put(messageID, mFrom);
jf.setVisible(true);
}
}
}
stmt.close();
To set the location of client a class location is called. This can be seen in the
following part of the code.
private static String X,Y,Floor,Room;
public int getX(){
return (new Double(Double.parseDouble(X)).intValue());
}
public int getY(){
return (new Double(Double.parseDouble(Y)).intValue());
}
public String getFloor(){
return Floor;
}
public String getRoom(){
return Room;
}
public String toString(){
return ("X:"+X+"\tY:"+Y+"\tRoom:"+Room+"\tFloor:"+Floor);
}
public void getLocation( ) {
X=st.nextToken();
Y=st.nextToken();
Floor=st.nextToken();
Room=st.nextToken();
________________________________________________________________________
78
________________________________________________________________________
After the establishment of HTTP connection now it takes the location
information from the positioning server.
In the above given code getFloor () method is getting the floor from
LaCoMoCo WEB API. GetLocation (), This method is getting location in the
form of coordinates x and y in pixels. GetRoom () This method is getting the
room noumber from the LaCoMoCo for example room is 3.19.
For further simplification a comprehensive summery of above described steps
is given below.
LTBIES client at very first step initiates class Client
LTBIES client establishes a socket connection with LTBIES server.
LTBIES client initiates further classes, class login, class Guest and class
register.
After authentication process a class called Main will be initiated which
will further initiate a class MessageThread? Main will also create a HTTP
connection with positioning server via LaCoMoCo.
Class MessageThread starts taking care of matured messages to check
which one of them is ready for delivery
LTBIES client Initiates class clientReadThread, which is responsible for
further communication with positioning server.
________________________________________________________________________
79
________________________________________________________________________
message will appear in front of the user and will inform him about the
situation.
There are some other exceptions that are covering a number of exceptions
because so many exceptions can occur while running the application. There
are a number of unpredictable failures that can occur in any program either
by itself or by some external reasons. Let us take example of LTBIES system,
consider that we are using socket connection, input/output streaming,
database quires and positioning technology, now just assume that if the
socket connection is lost or positioning server is not responding. All such
failures lead us to a more flexible program where we can handle all such
situations more accurately for the potential users of the system.
________________________________________________________________________
80
________________________________________________________________________
pY=loc.getY();
String level=loc.getFloor();
Room=loc.getRoom();
if(Floor.equals(level)){
g.setColor(new Color(0,255,0));
g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,draw+12);
g.setColor(new Color(255,0,0));
g.drawString(user,pX/4, pY/4+draw);
draw+=12;
}
}
}
};
label.setIcon(image);
________________________________________________________________________
81
________________________________________________________________________
Dark Brown writing with a drop shadow effect is used to represent the
information of levels.
________________________________________________________________________
82
________________________________________________________________________
After establishing a socket connection with a client LTBIES server spawns a
session thread (ClientWorker), which further initializes another thread
(writeThread). The following method in the clientWorker class controls this
thread.
class ClientWorker extends Thread {
public void run(){
while(true){
String line=in.readLine();//read a authentication request from the client
StringTokenizer st=new StringTokenizer(line,"'");
if(st.hasMoreTokens())
String type=st.nextToken();
if(type.equals("G")){
//Perform the authentication steps
WriteThread wt=new WriteThread();
wt.start();
}
}
________________________________________________________________________
83
________________________________________________________________________
After establishing a socket connection with the server LTBIES client spawns a
session thread (messageThread).This is responsible for popping up the
mature messages and another thread (ClientReadThread) which is ready to
read data from the database at any time.
________________________________________________________________________
84
________________________________________________________________________
User Table
CREATE TABLE users (
userID CHAR(10) PRIMARY KEY,
Fname CHAR(20), Lname CHAR(30), e_mail
CHAR(30),
password CHAR(30) NOT NULL
);
Group Table
CREATE TABLE group(
groupID CHAR(10) PRIMARY KEY,
description CHAR(255),
FOREIGN KEY (userID)
REFERENCES users (userID),
);
Location Table
CREATE TABLE location (
areaID CHAR(6) PRIMARY KEY,
usage CHAR(30),
description CHAR(30)
);
________________________________________________________________________
85
________________________________________________________________________
Messages Table
CREATE TABLE messages123(
messageID TINYINT(6) PRIMARY KEY
AUTO_INCREMENT,
message TEXT NOT NULL,
subject VARCHAR(30) NOT NULL,
areaID VARCHAR(6) NOT NULL,
sTime DATETIME NOT NULL,
eTime DATETIME NOT NULL,
mFrom CHAR(10) NOT NULL,
mTo CHAR(10) NOT NULL,
status CHAR(4),
FOREIGN KEY (mTo)
REFERENCES users (userID),
FOREIGN KEY (areaID)
REFERENCES location (areaID),
FOREIGN KEY (mFrom)
REFERENCES users (userID)
);
________________________________________________________________________
86
________________________________________________________________________
U sers
u se rID
ch a r(1 0 )
Fnam e
ch a r(2 0 )
Lnam e
ch a r(3 0 )
e - m a il
ch a r(3 0 )
p a sse o rd
ch a r(8 )
g ro u p ID
u se rID
m essages
g ro u p M e m b e r
ch ar(10 )
m e ss a g e ID
ch a r(6 )
m e s sa g e te x t
ch a r(1 0 )
s u b je c t
ch a r(3 0 )
a re a ID
ch a r(6 )
s T im e d a t e t im e
g ro u p ID
lo c a t io n
e T im e d a t e t im e
a re a ID
ch a r(6 )
m To
usage
ch a r(3 0 )
v a rc h a r(1 0 )
m F ro m
s ta tu s
g ro u p
v a rch a r(1 0 )
d e s c r ip t io n
ch a r(2 5 5 )
v a rch a r(4 )
1
ch a r(1 0 )
d e s c r ip t io n
ch a r(2 2 5 )
= P r im a r y K e y
15
________________________________________________________________________
87
________________________________________________________________________
5.7.1 Protocols
In networking and communications, the formal specifications that define the
procedures to follow while transmitting and receiving data is called a
protocol. Infect protocols define the format timing, sequence, and error
checking used on the network [Kurose, 2002].
________________________________________________________________________
88
________________________________________________________________________
P ro to c o l
C le in t S id e
C lie n t R e q u e s t to S e rv e r
" L " R e q u e s t fo r U s e r L o g in
" R " R e q u e s t fo r R e g is tra tio n
"G " R e q u e st fo r G u est U se r
" U " R e q u e s t fo r G e ttin g th e U s e r L is t
In fo rm a tio n S trin g
L n a d e e m g u jra t
P ro to c o l C h a ra c te r
This is the protocol string. First character of the string is defined as the
protocol character, which is used to send, as a request for login from the
client. The second part of the string is classified as information string.
The rest of the string contains sub strings with an unknown number of
characters. In this case it is important to use one string separation
method that uses specific separators in order to divide the string into
suitable information sub strings. This method is the tokenizer, where a
separator () is defined, and the next token (or sub string) is returned
every time a separator is reached. We use the tokenizer when the string
we want to separate only has a () as a separator.
________________________________________________________________________
89
________________________________________________________________________
P ro to c o l
S e r v e r S id e
S e rv e r R e s p o n c e to C lie n t
" T " T ru e re s p o n c e fro m s e rv e r fo r a u th e n tic a tio n
" F " F a ls e re s p o n c e fro m s e rv e r fo r a u th e n tic a tio n
" U " U s e r lis t
" D " G o a n d re a d fro m th e d a ta b a s e
In fo rm a tio n S trin g
U g u e s t 1 2 3 .1 1 7 .1 9 1 .1 ,g u e s t,....
P ro to c o l C h a ra c te r
This is the server side protocol string. Here above presented protocol
string shows one example of a string, it has been sent to client from the
server. First character of the string is defined as the protocol character,
which is used by the server to send, a list of users to the client. The
second part of the string is classified as information string. This contains
the rest of the information.
________________________________________________________________________
90
________________________________________________________________________
________________________________________________________________________
91
________________________________________________________________________
input and right out put form each method was also tested and appearance of
GUI.
Class Location is going to be discussed for unit testing as a sample. Class
Location is responsible to make a http connection with the position server,
and to get the position of a provided IP. Then it sets the class variables
values, and provides these values on request.
public class Location{
private String X,Y,Floor,Room;
Location(String ip){
}
public void getLocation( ) {// get the position of a device and set the class variabls}
public int getX(){
// return the X coordinate }
public int getY(){// return the Y coordinate }
public String getFloor(){ // return the Floor }
public String getRoom(){ // return the Room
}
public String toString(){ // return All values as string}
}
For testing main method of the class was defined and all other class methods
were called. Results obtained from these methods were checked.
public static void main(String arg[]){
String ip = "192.168.100.229";
Location location=new Location(ip);
location.getLocation();
System.out.println(location.toString());
System.out.println(location.getX());
System.out.println(location.getY());
System.out.println(location.getRoom());
System.out.println(location.getFloor());
}
Y: 1325
Room: 3.19
Floor: level3
________________________________________________________________________
92
________________________________________________________________________
This output is the expected output from the methods of location class.
When unit testing is finished each and every unit is tested together for
integration of the system. It makes it confirmed that different units of the
system work together correctly.
Following tasks were defined for integration testing. Each task is using more
than one unit of the classes.
Few tasks tested on the server side are presented bellow
Task
Detail
Socket Connection
Authentication
Database Connection
Expected Result
should
Result
be OK
OK
be
Write to Client
no OK
perform OK
OK
________________________________________________________________________
93
________________________________________________________________________
Few tasks tested on the client side are presented bellow
Detail
Socket Connection
Authentication
Database Connection
Listen From Server
Popup Messages
Actions on Buttons
Expected Result
Result
be OK
Task
should
or
Should
window
show
Should
accordingly
popup OK
perform OK
________________________________________________________________________
94
________________________________________________________________________
Graphical User Interface
In GUI testing it was tested that it should be easy to use, self explanatory
and it should provide easy navigation to the user.
Message Delivery
Delivery of messages were tested by the users and they were satisfied with
the results
Message Receiving
Arrival of messages were also tested by the users and they were satisfied
with the results
Location finding devices
Location testing was also done. Users were invited to see their locations and
other users location.
6.2 Simulation
Simulation is defined as to do or make something which looks real but is not
real, it means that a system simulation is mimicking of the operation of a
real system. Paul A. Fishwick defines the computer simulation as computer
simulation is the discipline of designing a model of an actual or theoretical
physical system, executing the model on a digital computer [Fishwick,
1999], so simulation is the execution of a model, represented by a computer
program that gives information about the system being investigated.
Figure (6.2.1) shows the general architecture of the simulation process.
Simulation system takes the controllable16inputs, process these inputted
values and return the output in response.
16
Controllable inputs are the inputs which are given by the person who is testing the system
________________________________________________________________________
95
________________________________________________________________________
The reason of using simulation for LTBIES application testing is that Ekahau
Positioning Engine does not give right positioning result all the times.
Therefore it was very difficult to know that whether this application is able to
deliver the message at right location and at right time or not. Our supervisor
John Aasted Srensen advised to develop a simulation test which creates the
dummy environment for the location and time and the results would be
checked by using simulation.
This section is further divided into two parts. One is simulation developed for
LTBIES application and the second is simulation for other LBS application
developers.
________________________________________________________________________
96
________________________________________________________________________
simulation checks the messages of a particular person against predefined
particular location and also for specific time.
The detail of controllable input is given below
Area: The area information will come from the location table in MySQL
database. The area combo box takes the list of the predefined areas
from database and tester can select any area from this list where he
wants to check the messages.
Time: Hours are from 0 to 23 and minutes from 0 to 55 with 5 minute
interval i.e. 0, 5, 10 55
Date: By default the current date will be displayed, but previous 7
days and next 7 days from current date can be selected.
________________________________________________________________________
97
________________________________________________________________________
17
Person or developer who wants to check his application against some predefined location
________________________________________________________________________
98
________________________________________________________________________
From the above two responses, it can be visualized that both the responses
has same format. So LBS application developers can use Simulated Position
Server which certainly provides consistent position results instead of using
Ekahau Position Engine (LaCoMoCo).
________________________________________________________________________
99
________________________________________________________________________
7 Conclusions
In this thesis, first we have argued for providing different location based
services on the basis of location and time, then the potential applicability of
location and time bound services for a variety of indoor environments was
discussed. Based on a review of the issue from a technological, as well as an
implementation and cooperative perspective, we have developed the
hypothesis that Location and time bound services offered by LTBIES can
prove beneficial for many organizations in a number of application areas,
such as supermarkets, museums, hospitals, hotels and multi-storey
buildings. We have assessed the needs of a user in different organizational
environments. We have also created different scenarios for a set of justified
services for the deployment of LTBIES. To test the usability and usefulness of
LTBIES, cooperative perspectives of LTBIES for different organizations is also
discussed. As a result we have found answers to the important questions
about its viability much more efficiently. We have explored why organizations
would have such a system and probe how these services will be needed and
fit in different scenarios. This analysis has produced valuable information for
us about organizations and companies who are in need of systems like
LTBIES.
Proposed set of services of LTBIES on the basis of location and time was only
possible in the environment where the positioning technologies are installed
to get the location of a mobile device. In LTBIES Ekahau Positioning Engine is
used to get the location of mobile device. Quality of the location and time
bound services provided by LTBIES heavily depends on the positioning
engine. Ekahau Positioning Engine is not an accurate positioning engine and
sometimes it tends to give location results with error. Therefore if the system
gets wrong location from the positioning engine then the required quality of
services will not be achieved. The accuracy problem of Ekahau Positioning
Engine was overcome by the Simulated Position Server. This server has been
developed to test the accuracy of LTBIES. This Simulated Position Server
gives the reply for a position request in the same format as Ekahau
Positioning Engine does with more consistency and accuracy. This simulation
server can test the application for location.
LTBIES is using client systems time and it could be wrong as a result
message delivery can be affected; this inaccurate time can affect the quality
________________________________________________________________________
100
________________________________________________________________________
of services. Solution to this problem is to make time of all systems
synchronized, so that the message delivery time remains same and wrong
message delivery time can be controlled. To test time and location,
simulation was also made to give the controlled time and location to the
application.
Services that were proposed have been implemented successfully for indoor
environment. These services are location and time bound. LTBIES application
is developed by using Ekahau Positioning Engine, MySQL database server and
java API. The java programming language has made it more robust and
portable. The test results of LTBIES were satisfactory. Results directly form
the positioning server and simulation are also compared to get the proof of
applications abilities and accuracy. It is also concluded that if the positioning
engine gives the right location, then this application is capable to provide
complete set of services perfectly.
________________________________________________________________________
101
________________________________________________________________________
Make a record of users location history
Another service which can be achieved is Surveillance. Surveillance can be
done by keeping the records of users location as a history in the database.
This record database can be used to find the activity of users at different
locations in the past.
Shortest path guideline
The LTBIES can be expanded to become capable of finding the shortest path
between different users or any destination of their interests, who are logged
on to the system. This addition of shortest path will make LTBIES more
dynamic. In the real world this feature will have a very positive impact on the
users of the system they can find and reach each other at different
destinations.
Location information
Location can be defined in more details by defining more physical context,
like what is the use of room 3.19 what type of equipments it has.
Synchronized time
LTBIES is using client systems time and it could be wrong as a result
message delivery can be affected; this inaccurate time can affect the quality
of services. To undermine this problem system can be enhanced to use
servers time. By doing this, all time bound services will be delivered
according to the servers synchronized time.
________________________________________________________________________
102
________________________________________________________________________
Acknowledgements
We would like to say Thanks to our supervisors Kre Jelling Kristofferson and
John Aasted Srenson for their help, valuable comments and discussion for
the successful completion of this project.
This project was very much a group development effort. We would like to
acknowledge the support and help of all other groups during project period,
the inspiring discussions we had with them along with the development of
our work. Especial thanks goes to Anders Cervera who gave us a number of
positive suggestions to provide us with the knowledge and help.
We would also like to thank to all of our friends and families who have
supported and helped us during the thesis period.
________________________________________________________________________
103
________________________________________________________________________
References
[Bacastow, 2002] Todd M. Bacastow, Dr. Fred Loomis: Progress Report, fall
2001, IST 496-Fall 2001, Revised 2002
[Birkedal, 2002] Lars Birkedal, Kjeld Schmidt, and Peter Carstensen:
Description CIT Project #313, Prepared by Crossroads Copenhagen, Version
2.2, 31 October 2002
[Cervera, 2003] Anders Cervera: Ekahau Positioning Server, IT University of
Copenhagen, January 2003
URL: http://positionserver.it-c.dk:8000/doc/WEB_API_040403.pdf
[Colulouris, 2001] George Colulouris, Jean Dollimore and Tim Kindberg:
Distributed Systems - Concepts and Design, Addison-Wesley, 2001
[Ekahau, 2002] Ekahau: Configurations and system requirements, Ekahau
positioning engine, 2002
URL:http://www.ekahau.com/products/positioningengine/ClientReleaseNotes.
html
[Ekahau, 2002] Ekahau: Ekahau positioning Engine- user guide, 2002
URL: http://www.ekahau.com
[El-Akehal, 2003] Emad El-Dean El-Sayed El-Akehal: User Authentication and
Information Exchange by Speech and Location Information in Mobile
Systems, IT University of Copenhagen, August 2003
[Fishwick, 1999] Fishwick: The art and Science of Digital World Construction,
August 1999
URL: http://www.cise.ufl.edu/~fishwick/introsim/paper.html
[Geier, 2002] Jim Geier: Ekahau Positioning Engine,
URL: www.wi-fiplanet.com/reviews/SW/article.php/1560261
[IEC, 2003] International Engineering Consortium:
URL: http://www.iec.org/online/tutorials/gsm/
[Korth, 1991] Henry F.Korth, Abraham Silberschatz: Database system
concepts, Second edition, McGraw-hill Inc, 1991
[Kurose, 2002] James F. Kurose og Keith W. Ross: Computer Networking A
Top-Down Approach Featuring the Internet, Addison-Wesley, 2002
________________________________________________________________________
104
________________________________________________________________________
[Lee, 2002] Richard C. Lee, William M. Tepfenhart: Practical Object Oriented
Development with UML and Java, Prentice Hall, 2002
[Lynge, 2003] Thomas Lynge: Position Dependent Communication System, IT
University of Copenhagen, June 2003
[Nerguizian, 2001] Chahe Nerguizian: A framework for Indoor Geolocation
using an Intelligent System, 3rd WLAN workshop, 2001
URL: http://www.cwins.wpi.edu/wlans01/proceedings/wlan44d.pdf
[Pahlavan, 2002] Kaveh Pahlavan and Xinrong Li, Worcester Institute JuhaPekka, University of Oulu, Finland: Indoor Geolocation Science and
Technology, IEEE Communication Magazine, February 2002
[Petersen, 2003] Jonas E.Andersen and Bjrn E.Petersen: Geographic
information Systems in context of Location Based Services, IT University of
Copenhagen, May 2003
[Petrick, 1999] Bob OHara and Al Petrick: IEEE 802.11 Handbook A Designer
Companion, Standard Information Network IEEE Press, December 1999
[Pressman, 2000] Roger S. Pressman: Software Engineering A practioners
Approach, 5th edition, McGraw- Hill, April 2000
[Schmidt, 2003] Kjeld Schmidt: Global and Mobile
Compendium, IT University of Copenhagen, Spring 2003
Applications,
________________________________________________________________________
105
________________________________________________________________________
[Virrantaus, 2001] Kirsi Virrantaus, Jouni Markkula, Artem Garmash, Vagan
Terziyan, Jari Veijalanien, Artem Katanosov, Henri Tirri: Developing GISSpupported Location Based Services, University of Helsinki,Finland, Computer
Society, 2001
[Watson, 2002] Richeard T.Watson: Data Management Databases and
Orgnizations, Third edition,John Wiley & Sons,Inc,2002
[Yousaf, 2002] Moustafa A. Yousaf,Ashok Agrawala, A. Udaya Shankar, Sam
H. Noh: A Probabilistic Clustering-Based Indoor Location Determination
System, 2002
________________________________________________________________________
106
________________________________________________________________________
Appendices
A1 User Manual
Before running this application the user has to make sure that his system has
the following components:
Java virtual machine. Install Java2 SDK (from version 1.4 and up). It
can be downloaded from http://java.sun.com/downloads/.
Ekahau client must be installed on the mobile terminal. It can be
downloaded from http://www.Ekahau.com/downloads/.
Wireless local area network (IEEE 802.11b standard)
LTBIES application software.
In order to run the LTBIES application, the user has to follow the following
steps
First run the server program
Run the client program
Now the user will get first welcome GUI. Select one of the three
options to get authentication from the server. In welcome interface the
default IP address of server will be given, one can change the IP
address of server if server is running on some other machine.
After getting authentication user get the main GUI, where he will be
allowed to avail all the services provided by the application.
A very short description of all these services is given below
________________________________________________________________________
107
________________________________________________________________________
Popup messages: when the user log on to the system, he will receive
pop up messages. These messages are those whose time and location
coincides with the predefined limit of location and time.
My location: User can get his current position in the form (x, y, level,
room). User can also request to view his position on map by the option
SHOW ON MAP.
Messages: User can get text messages intended for him at current
location and also at specific time. The user can also send messages to
any other person or group at a specific location in the building at any
specific time.
Online persons: User can find the location of all connected users to
the system. The application also provides the location of other users
on any specific level (floor) by choosing floor number option.
Track person: This service is interested for those who want to track
the person by name (i.e. where is Mr. Bilal?). The application tracks
the requested person and shows the position of that person on map.
________________________________________________________________________
108
________________________________________________________________________
A2 Abbreviation List
802.11b
AP
API
BSC
BTS
EPE
GSM
GPS
HTTP
IEEE
ITU
J2ME
J2SE
JSDK
LaCoMoCo
LTBIES
MIDP
MIDlet
MSC
PDA
RF
RTP
SIM
TCP/IP
UML
URL
Wi-Fi
WLAN
________________________________________________________________________
109
________________________________________________________________________
A3 UML Diagrams
UML, the unified modelling language, is a standard notation for modelling
object oriented systems. It is a language that graphically described a set of
elements. It is used to specify visualize, construct and document not only
software systems but business models and non software systems. It is much
like a blue print for constructing a building [Lee, 2002]. Some of the
important UML diagrams of LTBIES are presented here.
________________________________________________________________________
110
________________________________________________________________________
________________________________________________________________________
111
________________________________________________________________________
________________________________________________________________________
112
________________________________________________________________________
________________________________________________________________________
113
________________________________________________________________________
________________________________________________________________________
114
________________________________________________________________________
________________________________________________________________________
115
________________________________________________________________________
________________________________________________________________________
116
________________________________________________________________________
A4 Screen Shots
________________________________________________________________________
117
________________________________________________________________________
________________________________________________________________________
118
________________________________________________________________________
________________________________________________________________________
119
________________________________________________________________________
________________________________________________________________________
120
________________________________________________________________________
Figure (A4.9): Get messages from specific person or from all persons
________________________________________________________________________
121
________________________________________________________________________
________________________________________________________________________
122
________________________________________________________________________
________________________________________________________________________
123
________________________________________________________________________
A5 Database Tables
All the database tables with sample data
MESSAGE TABLE
L o c a tio n
L o g in
C lie n t
R e g is te r
M a in
M y L o c a tio n
G u est
g e tM e ssa g e
T ra ck P erso n
c lie n tR e a d th r e a d
m e ssa g e th re a d
O n lin e U s e r s
S h o w O n M a p A ll
Show O nM ap
GROUP MEMBER
________________________________________________________________________
124
________________________________________________________________________
GROUP TABLE
LOCATION TABLE
USER TABLE
________________________________________________________________________
125
________________________________________________________________________
A6 Program Listing
ThisapplicationhasbeendevelopedforThesisproject,aspartofour
Masterdegreeprogram.
TheapplicationisforLBSWLANpositioningsystem. ItrunsonMobile
devices.
Participants:
H.M.BilalSarwar:sarwar@itu.dk
NadeemAhmad:nadeem@itu.dk
ShouketIqbal:shouket@itu.dk
Supervisor:
JohnAastedSrensen
KrejellingKristoffersen
ITUniversityofCopenhagen.
Novemebr2003
________________________________________________________________________
126
________________________________________________________________________
________________________________________________________________________
127
________________________________________________________________________
A6.1 ClientWorker
package LTBIES.Server;
/**
* <p> ClientWorker: </p>
* <p>Server side class that deal with each client: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>c
* @author Nadeem, Bilal, Shouket
* @version 1.0
*/
import javax.swing.JTextArea;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
class ClientWorker extends Thread {
private Socket client;
private JTextArea textArea;
private String type;
static String user;
static HashMap userList =new HashMap() ;// username and ip
static HashMap userMessage =new HashMap() ;// username and status to read database
private BufferedReader in;
static PrintWriter out;
ClientWorker(Socket client, JTextArea textArea){
this.client = client;
this.textArea = textArea;
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
}
________________________________________________________________________
128
________________________________________________________________________
firstStep();
}
public void run(){
while(true){
try{
String line=in.readLine();
StringTokenizer st=new StringTokenizer(line,"'");
if(st.hasMoreTokens()){
String t=st.nextToken();
if((t.equals("U"))||(t.equals("P"))){
String uList= userList.toString();
out.println("U"+uList);
}
}
userMessage.put(user,"true");
}catch(IOException ioex){
//System.out.print("ServerReadThread failed Removed element ");
textArea.append("Mr. \" "+user+" \" is disconnected from the system "+"\n");
userMessage.remove(user);
stop();
break;
}
}
}
public void firstStep(){
String line;
boolean s=false;
while(true){
try{
line = in.readLine();
//textArea.append("Connection request '"+line+"'\t"+" From Client "+ client.getInetAddress());
textArea.append("Connection request From User ");
} catch (IOException e) {
textArea.append("Read Write failed .... ");break;
}
StringTokenizer st=new StringTokenizer(line,"'");
if(st.hasMoreTokens()){
type=st.nextToken();
user=st.nextToken();
textArea.append(": "+user+"\n");
if(type.equals("G")){
//textArea.append(" as Guest"+"\n");
String Q="SELECT userID from users where userID ="+"'"+user+"'";
s=query(Q);
s=!s;
}
else if(type.equals("L")){
//textArea.append(" to Login "+"\n");
String pass=st.nextToken();
String Q="SELECT * from users where userID ="+" '"+user+"' and password= '"+pass+"'";
s=query(Q);
}
________________________________________________________________________
129
________________________________________________________________________
else if(type.equals("R")){
//textArea.append(" to make a registration "+"\n");
String insert=line.substring(1,line.length());
String Q="INSERT INTO users VALUES("+insert+")";
String pass=st.nextToken();
s=UpdateQuery(Q);
}
if(s){
if((userList.get(user))==null){
userList.put(user,client.getInetAddress());
userMessage.put(user,"false");
textArea.append(user+"'s Connection request is accepted"+"\n");
out.println("true");
WriteThread wt=new WriteThread();
wt.start();
break;
}
else {
out.println("Name is allready in use");
textArea.append(user+"'s Connection request is Rejected"+"\n");
}
}
else {
out.println("Name is allready in use");
textArea.append(user+"'s Connection request is Rejected"+"\n");
}
}
}
}
public boolean query(String Q){
boolean b=false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(Q);
if(rs.next())b=true;
stmt.close();
rs=null;
}catch( Exception e ) {
MySql record search query");
}
return b;
}
public boolean UpdateQuery(String Q){
boolean b=true;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
________________________________________________________________________
130
________________________________________________________________________
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
stmt.executeUpdate(Q);
stmt.close();
}catch( Exception e ) {
b=false;
return b;
}
return b;
}
}
class WriteThread extends Thread{
public void run(){
while(true){
if(ClientWorker.userMessage.get(ClientWorker.user)=="true")
print("D");
if(ClientWorker.userMessage.get(ClientWorker.user)=="true")
print(U+userList);
try{
sleep(2000);
}catch (InterruptedException e) {}
}
}
public synchronized void print(String p){
ClientWorker.out.println(p);
ClientWorker.userMessage.put(ClientWorker.user,"false");
}
}
class Server extends JFrame{
JTextArea textArea = new JTextArea();
ServerSocket server = null;
Server(){
JPanel panel = new JPanel();
ImageIcon LTBIES_Server=new ImageIcon("LTBIES_Server.png");
ImageIcon Downtext=new ImageIcon("Downtext.png");
JLabel label = new JLabel(LTBIES_Server);
Font font = new Font("Serif",Font.BOLD ,50);
label.setFont(font);
JLabel label2 = new JLabel(Downtext);
panel.setLayout(new BorderLayout());
panel.setBackground(new Color(211,106,1));//(Color.white);
getContentPane().add(panel);
panel.add("North", label);
panel.add("Center", textArea);
panel.add("South", label2);
________________________________________________________________________
131
________________________________________________________________________
}
//End Constructor
public void listenSocket(){
try{
server = new ServerSocket(9786);
} catch (IOException e) {
System.exit(-1);
}
while(true){
ClientWorker w;
try{
new ClientWorker(server.accept(), textArea).start();
} catch (IOException e) {
}
}
}
protected void finalize(){
try{
server.close();
} catch (IOException e) {
System.exit(-1);
}
}
public static void main(String[] args){
Server frame = new Server();
frame.setTitle("Location and Time Based Information Exchange System Server");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setSize(600,600);
frame.setLocation(10,50);
frame.setVisible(true);
frame.listenSocket();
}
}
________________________________________________________________________
132
________________________________________________________________________
A6.2 Location
package LTBIES.Client;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
import java.util.*;
import java.net.*;
import java.io.*;
public class Location{
private static String X,Y,Floor,Room;
private static String URL_TXTRESPONSE,SERVER_IP="http://192.168.100.10:8000";//lapTop;
String CLIENT_IP;
Location(String ip){
this.CLIENT_IP=ip;
URL_TXTRESPONSE= SERVER_IP+"/TrackServlet?
value=x,y,z&clientId="+CLIENT_IP+"&measure=pixels";
getLocation();
if(X==null){
SERVER_IP= "http://130.226.140.82:8000";//deskTop
URL_TXTRESPONSE= SERVER_IP+"/TrackServlet?
value=x,y,z&clientId="+CLIENT_IP+"&measure=pixels";
getLocation();
}
}
public void getLocation( ) {
String str;
StringBuffer lists = new StringBuffer();
try{
URL url = new URL(URL_TXTRESPONSE);
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
int i = 0;
while ((i = in.read()) != -1){
lists.append((char)i);
}
str=lists.toString();
in.close();
}
catch (MalformedURLException mal){
str = mal.toString();
}
catch (IOException ioe) {
str = ioe.toString();
}
________________________________________________________________________
133
________________________________________________________________________
int counter=0;
StringTokenizer st=new StringTokenizer(str,",");
while(st.hasMoreTokens()){
st.nextToken();
counter++;
}
st=new StringTokenizer(str,",");
if(counter==4){
X=st.nextToken();
Y=st.nextToken();
Floor=st.nextToken();
Room=st.nextToken();
}
}
public int getX(){
if(X!=null)
return (new Double(Double.parseDouble(X)).intValue());
else
return 0;
}
public int getY(){
if(Y!=null)
return (new Double(Double.parseDouble(Y)).intValue());
else
return 0;
}
public String getFloor(){
return Floor;
}
public String getRoom(){
return Room;//="3.19";
}
public String toString(){
return ("X:"+X+"\tY:"+Y+"\tRoom:"+Room+"\tFloor:"+Floor);
}
}
________________________________________________________________________
134
________________________________________________________________________
A6.3 Client
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class Client{
static JFrame frame;
static PrintWriter out = null;
static BufferedReader in = null;
JLabel message;
JTextField ipS;
int port = 9786;
static Socket socket;
//String ip = "192.168.100.229"; //laptop
String ip = "localhost"; //laptop
Client() {
Color bg = new Color(211, 106, 1);
frame = new JFrame(
"Location and Time Based Information Exchange System Ekahau");
frame.getContentPane().setLayout(new GridLayout(3, 3));
frame.setSize(600, 250);
frame.setLocation(60, 50);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}); //
ImageIcon labelImage = new ImageIcon("WELCOME_LTBIES.png");
ipS = new JTextField(ip);
JLabel ipL = new JLabel("Server IP : ");
JPanel BPanel, LPanel, panel;
panel = new JPanel();
BPanel = new JPanel();
LPanel = new JPanel();
JLabel label = new JLabel(labelImage);
Font font = new Font("Serif", Font.PLAIN, 30);
label.setFont(font);
message = new JLabel();
ImageIcon loginImage = new ImageIcon("Login_b.png");
ImageIcon regImage = new ImageIcon("Register_b.png");
ImageIcon guestImage = new ImageIcon("Guest_b.png");
JButton login, reg, guest;
login = new JButton(loginImage);
reg = new JButton(regImage);
guest = new JButton(guestImage);
login.setActionCommand("Login");
reg.setActionCommand("Register");
________________________________________________________________________
135
________________________________________________________________________
guest.setActionCommand("Guest");
login.setBackground(new Color(253, 176, 102)); //
reg.setBackground(new Color(253, 176, 102)); //
guest.setBackground(new Color(253, 176, 102)); //
welcomeListener listener = new welcomeListener();
login.addActionListener(listener);
reg.addActionListener(listener);
guest.addActionListener(listener);
LPanel.add(label);
BPanel.add(login);
BPanel.add(reg);
BPanel.add(guest);
panel.add(ipL, BorderLayout.NORTH);
panel.add(ipS, BorderLayout.CENTER);
panel.add(message, BorderLayout.SOUTH);
panel.setBackground(bg);
BPanel.setBackground(bg);
LPanel.setBackground(bg);
frame.getContentPane().add(LPanel, BorderLayout.NORTH);
frame.getContentPane().add(BPanel, BorderLayout.CENTER);
frame.getContentPane().add(panel, BorderLayout.SOUTH);
frame.getContentPane().setBackground(bg);
listenSocket();
frame.setVisible(true);
}
public static void main(String arg[]) {
Client w = new Client();
}
public void listenSocket() {
try {
if (socket == null) {
socket = new Socket(ipS.getText(), port);
// socket.setSoTimeout( 5000 );
}
}
catch (UnknownHostException e) {
System.out.println("Unknown host: ");
message.setText("Unknown host: " + e);
}
catch (IOException e) {
//System.out.println("No I/O "+e);
message.setText("No I/O " + e);
}
}
class welcomeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//ip=ipS.getText();
listenSocket();
if (socket != null) {
String command = e.getActionCommand();
if (command == "Login") {
________________________________________________________________________
136
________________________________________________________________________
//System.out.println("i m in login state");
frame.setVisible(false);
frame = null;
Login l = new Login(socket);
}
else if (command == "Register") {
//System.out.println("i m in Register state");
frame.setVisible(false);
frame = null;
Reg r = new Reg(socket);
}
else if (command == "Guest") {
frame.setVisible(false);
frame = null;
Guest g = new Guest();
}
}
}
}
}
///CLASS////GUEST///////////////////////////////////////////////////////////
class Guest{
JFrame frame;
JLabel message;
JTextField Tname;
JButton submit,back;
Guest( ){
gui();
frame.setVisible(true);
}
private void gui(){
Color bg=new Color(253,176,102);
frame=new JFrame("Location and Time Based Information Exchange System Ekahau");
frame.getContentPane().setLayout(new GridLayout(5, 1));
frame.setBackground(Color.blue);
frame.setSize(450,250);
frame.setLocation(60,50);
JLabel heading =new JLabel("Welcome as A Guest User");
Font font = new Font("Serif",Font.PLAIN,40);
heading.setFont(font);
JLabel heading2 =new JLabel("Please Enter a User Name");
Font font2 = new Font("Serif",Font.PLAIN,30);
heading.setFont(font2);
message =new JLabel(". . .");
Tname =new JTextField(15);
submit=new JButton("Submit");
back=new JButton("Back");
Tname.setActionCommand("Submit");
submit.setActionCommand("Submit");
back.setActionCommand("Back");
guestListener listener=new guestListener();
submit.addActionListener(listener);
back.addActionListener(listener);
________________________________________________________________________
137
________________________________________________________________________
Tname.addActionListener(listener);
JPanel panel1,panel2,panel3,panel4,panel5;
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
panel5=new JPanel();
panel1.add(heading);
panel2.add(heading2);
panel3.add(Tname);
panel4.add(submit);
panel4.add(back);
panel5.add(message);
panel1.setBackground(bg);
panel2.setBackground(bg);
panel3.setBackground(bg);
panel4.setBackground(bg);
panel4.setBackground(bg);
panel5.setBackground(bg);
frame.getContentPane().add(panel1);
frame.getContentPane().add(panel2);
frame.getContentPane().add(panel3);
frame.getContentPane().add(panel4);
frame.getContentPane().add(panel5);
try{
Client.out = new PrintWriter(Client.socket.getOutputStream(), true);
Client.in = new BufferedReader(new
InputStreamReader(Client.socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: ");
} catch (IOException e) {
System.out.println("No I/O "+e);
}
frame.getContentPane().setBackground(bg);
}
class guestListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Back"){
if(frame!=null){
frame.setVisible(false);
frame=null;
Client c=new Client();
}
}
if(command=="Submit"){
if(Tname.getText().length()>2){
connect();
if(frame!=null && message.getText().equals("true")){
frame.setVisible(false);
frame=null;
Main ma=new Main(Tname.getText(),"G",Client.socket);
}
________________________________________________________________________
138
________________________________________________________________________
else{
message.setText("This name is already registered Please try with another name");
Tname.setText(new String(""));
}
}
else
message.setText("Please Enter atleast three character");
}
}
}
private void connect(){
String text ="G'";
text+= Tname.getText();
Client.out.println(text );
try{
String line = Client.in.readLine();
message.setText(line);
//System.out.println("CLIENT...Text sended :" + line);
}catch (IOException e){
System.out.println("READ failed");
}
}
}
class Login{
JFrame frame;
JLabel heading,message;
private JTextField Tname;
private JPasswordField Tpassword;
private JButton submit,back;;
String ip="localhost";
Login(Socket socket){
gui();
frame.setVisible(true);
}
private void gui(){
JPanel Hpanel,panel1,panel2,panel3,panel4;
Color bg=new Color(253,176,102);
frame=new JFrame("Location and Time Based Information Exchange System Ekahau");
frame.getContentPane().setLayout(new GridLayout(5, 1));
frame.setSize(450,250);
frame.setLocation(60,50);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Hpanel=new JPanel();
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
submit=new JButton("Submit");
loginListener listener=new loginListener();
submit.addActionListener(listener);
________________________________________________________________________
139
________________________________________________________________________
heading=new JLabel("User Login");
Font font = new Font("Serif",Font.PLAIN,30);
heading.setFont(font);
JLabel Lname=new JLabel("User Name");
JLabel Lpassword=new JLabel("Password");
Tname=new JTextField(15);
Tpassword=new JPasswordField(15);
message=new JLabel();
back=new JButton(" Back ");
back.addActionListener(listener);
Tname.addActionListener(listener);
Tpassword.addActionListener(listener);
Tname.setActionCommand("Submit");
Tpassword.setActionCommand("Submit");
submit.setActionCommand("Submit");
back.setActionCommand("Back");
Hpanel.add(heading);
panel1.add(Lname);
panel1.add(Tname);
panel2.add(Lpassword);
panel2.add(Tpassword);
panel3.add(submit);
panel3.add(back);
panel4.add(message);
Hpanel.setBackground(bg);
panel1.setBackground(bg);
panel2.setBackground(bg);
panel3.setBackground(bg);
panel4.setBackground(bg);
frame.getContentPane().setBackground(bg);
frame.getContentPane().add(Hpanel);
frame.getContentPane().add(panel1);
frame.getContentPane().add(panel2);
frame.getContentPane().add(panel3);
frame.getContentPane().add(panel4);
try{
Client.out = new PrintWriter(Client.socket.getOutputStream(), true);
Client.in = new BufferedReader(new
InputStreamReader(Client.socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: ");
} catch (IOException e) {
System.out.println("No I/O "+e);
}
}
public void connect(){
String text ="L'";
text+= Tname.getText()+"'";
text+= Tpassword.getText();
Client.out.println(text );
try{
________________________________________________________________________
140
________________________________________________________________________
String line = Client.in.readLine();
if(line.equals("true")){
Main ma=new Main(Tname.getText(),"L",Client.socket);
if(frame!=null){
frame.setVisible(false);
frame=null;
}
}
else{
Tname.setText("");
Tpassword.setText("");
message.setText("Not a valied login..Please try again.");
}
}catch (IOException e){
System.out.println("READ failed");
}
}
class loginListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
System.out.println(command);
if(command=="Submit"){
connect();
}
if(command=="Back"){
if(frame!=null){
frame.setVisible(false);
frame=null;
Client c=new Client();
}
}
}
}
}
class Reg{
private JFrame fram;
private JLabel message;
private JTextField TUname,TFname,TLname,Tlogin,Tpass,Temail;
JButton submit,clear,back;
int port=9786;
Reg(Socket socket){
gui();
fram.setVisible(true);
}
private void gui(){
Color bg=new Color(253,176,102);
fram=new JFrame("Location and Time Based Information Exchange System Ekahau");
fram.getContentPane().setLayout(new GridLayout(8, 1));
fram.setSize(700,450);
fram.setLocation(60,50);
fram.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
________________________________________________________________________
141
________________________________________________________________________
}
});
JLabel heading,LUname,LFname,LLname,Llogin,Lpass,Lemail,message;
heading=new JLabel("User Registration");
Font font = new Font("Serif",Font.PLAIN,40);
heading.setFont(font);
message=new JLabel("");
LUname=new JLabel("User ID");
LFname=new JLabel("First Name");
LLname=new JLabel("Last Name");
Lpass=new JLabel("Password");
Lemail=new JLabel("E-mail");
TUname=new JTextField(15);
TFname=new JTextField(15);
TLname=new JTextField(15);
Tpass=new JTextField(10);
Temail=new JTextField(30);
submit=new JButton("Submit");
clear=new JButton("Clear");
back=new JButton("Back");
regListener listener=new regListener();
submit.addActionListener(listener);
clear.addActionListener(listener);
back.addActionListener(listener);
JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6,panel7,panel;
panel0=new JPanel();
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
panel5=new JPanel();
panel6=new JPanel();
panel7=new JPanel();
panel=new JPanel();
panel0.add(heading);
panel1.add(LUname);
panel1.add(TUname);
panel2.add(LFname);
panel2.add(TFname);
panel3.add(LLname);
panel3.add(TLname);
panel5.add(Lpass);
panel5.add(Tpass);
panel6.add(Lemail);
panel6.add(Temail);
panel7.add(submit);
panel7.add(clear);
panel7.add(back);
panel.add(message);
panel.setBackground(bg);
panel0.setBackground(bg);
panel1.setBackground(bg);
panel2.setBackground(bg);
________________________________________________________________________
142
________________________________________________________________________
panel3.setBackground(bg);
panel5.setBackground(bg);
panel6.setBackground(bg);
panel7.setBackground(bg);
fram.getContentPane().setBackground(bg);
fram.getContentPane().add(panel0);
fram.getContentPane().add(panel1);
fram.getContentPane().add(panel2);
fram.getContentPane().add(panel3);
fram.getContentPane().add(panel5);
fram.getContentPane().add(panel6);
fram.getContentPane().add(panel7);
fram.getContentPane().add(panel);
try{
Client.out = new PrintWriter(Client.socket.getOutputStream(), true);
Client.in = new BufferedReader(new
InputStreamReader(Client.socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: ");
} catch (IOException e) {
System.out.println("No I/O "+e);
}
}
class regListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Submit"){
String insert="R'"+TFname.getText()+"','"+TLname.getText()+"','"+Temail.getText();
insert+="','"+TUname.getText()+"','"+Tpass.getText()+"'";
System.out.println("Query is "+insert);
Client.out.println(insert );
try{
System.out.println("waiting to get responce from server");
String line = Client.in.readLine();
System.out.println("CLIENT...Text sended :" + line);
System.out.println("linbe is "+line);
if(line.equals("true")){
fram.setVisible(false);
fram=null;
Main ma=new Main(TUname.getText(),"G",Client.socket);
}
else
message.setText("It is not a valid record please try again");
}catch (IOException ee){
System.out.println("READ failed");
}
}
if(command=="Clear"){
System.out.println("i m in CLEAR button command of RegistRATION");
TUname.setText("");
TFname.setText("");
TLname.setText("");
Tlogin.setText("");
________________________________________________________________________
143
________________________________________________________________________
Tpass.setText("");
Temail.setText("");
}
if(command=="Back"){
System.out.println("i m in BACK button command of RegistRATION");
fram.setVisible(false);
fram=null;
Client c=new Client();
}
}
}
}
________________________________________________________________________
144
________________________________________________________________________
A6.4 Main
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.*;
import javax.swing.border.*;
public class Main{
static JFrame frame;
static HashMap userList = new HashMap();
static HashMap messageList = new HashMap();
JButton myLocationB, message, onlineUsers, traceUsers;
JPanel panel;
JButton exit;
static myLocation ml;
static JTextArea messages;
static JPanel field;
Socket socket;
static String user, type;
PrintWriter out = null;
BufferedReader in = null;
mainListener listener;
Main(String user, String type, Socket socket) {
this.socket = socket;
this.user = user;
this.type = type;
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (UnknownHostException e) {
System.out.println("Unknown host: " + socket);
}
catch (IOException e) {
System.out.println("No I/O " + e);
}
frame = new JFrame(
"Location and Time Based Information Exchange System Ekahau");
________________________________________________________________________
145
________________________________________________________________________
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().setBackground(new Color(211, 106, 1));
JLabel heading = new JLabel(
"Welcome to Location & Time Based Information Exchange System");
ImageIcon image = new ImageIcon("header.png");
heading = new JLabel(image);
Font font = new Font("Serif", Font.PLAIN, 35);
JLabel heading2 = new JLabel(" ");
heading2.setFont(font);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.setSize(960, 650);
frame.setLocation(55, 40);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ImageIcon myLocationImage = new ImageIcon("MyLocation.png");
ImageIcon messageImage = new ImageIcon("Messages.png");
ImageIcon onlineUsersImage = new ImageIcon("Avaiable.png");
ImageIcon traceUsersImage = new ImageIcon("Track.png");
ImageIcon exitImage = new ImageIcon("Exit.png");
myLocationB = new JButton(myLocationImage);
message = new JButton(messageImage);
onlineUsers = new JButton(onlineUsersImage);
traceUsers = new JButton(traceUsersImage);
exit = new JButton(exitImage);
myLocationB.setBackground(new Color(253, 176, 102)); //
message.setBackground(new Color(253, 176, 102)); //
onlineUsers.setBackground(new Color(253, 176, 102)); //
traceUsers.setBackground(new Color(253, 176, 102)); //
exit.setBackground(new Color(253, 176, 102)); //
myLocationB.setActionCommand("My Location");
message.setActionCommand("Messages");
onlineUsers.setActionCommand("Online Users");
traceUsers.setActionCommand("Track Person");
exit.setActionCommand("exit");
listener = new mainListener();
myLocationB.addActionListener(listener);
message.addActionListener(listener);
onlineUsers.addActionListener(listener);
________________________________________________________________________
146
________________________________________________________________________
traceUsers.addActionListener(listener);
exit.addActionListener(listener);
panel.setBackground(new Color(253, 176, 102));
panel.add(Box.createRigidArea(new Dimension(0, 50)));
panel.add(myLocationB);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
panel.add(message);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
panel.add(onlineUsers);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
panel.add(traceUsers);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
panel.add(exit);
ImageIcon imageB = new ImageIcon("button2.png");
JButton tryB = new JButton(imageB);
field = new JPanel();
messages = new JTextArea("\n Mr. " + user +
" Welcome to Location and Time \n
Based information Exchange System ");
//Font font = new Font("Serif",Font.PLAIN,35);
messages.setFont(font);
field.setBackground(new Color(250, 250, 250));
field.add(messages);
frame.getContentPane().add(heading, BorderLayout.NORTH);
frame.getContentPane().add(panel, BorderLayout.WEST);
frame.getContentPane().add(field, BorderLayout.CENTER);
frame.getContentPane().add(heading2, BorderLayout.SOUTH);
new ClientReadThread(in).start();
new messagesThread().start();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
JMenuItem mylocationFM = new JMenuItem("My Location", 'L');
JMenuItem messageFM = new JMenuItem("Messages", 'M');
JMenuItem onlineFM = new JMenuItem("Online Users", 'U');
JMenuItem trackFM = new JMenuItem("Track Person", 'T');
JMenuItem Exit = new JMenuItem("Exit", 'x');
JMenuItem aboutUs = new JMenuItem("About Us", 'U');
JMenuItem aboutApp = new JMenuItem("About Application", 'A');
mylocationFM.setActionCommand("My Location");
messageFM.setActionCommand("Messages");
onlineFM.setActionCommand("Online Users");
trackFM.setActionCommand("Track Person");
Exit.setActionCommand("exit");
________________________________________________________________________
147
________________________________________________________________________
aboutUs.setActionCommand("aboutUs");
aboutApp.setActionCommand("aboutApp");
mylocationFM.addActionListener(listener);
messageFM.addActionListener(listener);
onlineFM.addActionListener(listener);
trackFM.addActionListener(listener);
Exit.addActionListener(listener);
aboutUs.addActionListener(listener);
aboutApp.addActionListener(listener);
fileMenu.add(mylocationFM);
fileMenu.add(messageFM);
fileMenu.add(onlineFM);
fileMenu.add(trackFM);
fileMenu.add(Exit);
helpMenu.add(aboutUs);
helpMenu.add(aboutApp);
menuBar.setBackground(new Color(253, 176, 102));
menuBar.add(fileMenu);
menuBar.add(helpMenu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
class mainListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command == "My Location") {
field.removeAll();
messages.setText("
My Location ");
if (ml == null) {
ml = new myLocation(user);
}
field.setLayout(new GridLayout(1, 1));
field.add(ml);
Graphics gra = field.getGraphics();
field.paintAll(gra);
}
if (command == "Messages") {
field.removeAll();
JPanel messageMenu = new JPanel();
JPanel messageMenu1 = new JPanel();
JPanel messageMenu2 = new JPanel();
JPanel messageMenu3 = new JPanel();
JLabel messageLabel = new JLabel("Select One of Them to Proceed ");
messageLabel.setFont(new Font("Serif", Font.PLAIN, 40));
JButton getMessages = new JButton("Get Messages");
________________________________________________________________________
148
________________________________________________________________________
JButton leaveMessage = new JButton("Leave Message");
getMessages.addActionListener(listener);
leaveMessage.addActionListener(listener);
messageMenu.setLayout(new GridLayout(3, 1, 1, 1));
messages.setText(" Messages");
messageMenu1.add(messageLabel);
messageMenu2.add(getMessages);
messageMenu2.add(leaveMessage);
messageMenu.add(messageLabel);
messageMenu.add(getMessages);
messageMenu.add(leaveMessage);
field.removeAll();
field.add(messageMenu);
Graphics gra = field.getGraphics();
field.paintAll(gra);
frame.setVisible(true);
}
if (command == "Online Users") {
out.println("U'Online Users");
messages.setText("
Online Users ");
field.removeAll();
onlineUsers online = new onlineUsers(userList);
field.add(online);
Graphics gra = field.getGraphics();
field.paintAll(gra);
}
if (command == "Event Info") {
field.removeAll();
messages.setText(" Event Info ");
Graphics gra = field.getGraphics();
field.paintAll(gra);
frame.setVisible(true);
}
if (command == "Track Person") {
out.println("P'Track 'Users'");
field.removeAll();
messages.setText(" Trace Users ");
trackPerson tp = new trackPerson(user);
field.add(tp);
Graphics gra = field.getGraphics();
field.paintAll(gra);
}
if (command == "Get Messages") {
field.removeAll();
getMessage gm = new getMessage(user);
Graphics gra = field.getGraphics();
field.add(gm);
field.paintAll(gra);
________________________________________________________________________
149
________________________________________________________________________
}
if (command == "Leave Message") {
field.removeAll();
leavMessageForm lmf = new leavMessageForm(out, user);
field.add(lmf, BorderLayout.SOUTH);
Graphics gra = field.getGraphics();
field.paintAll(gra);
}
if (command == "icon Button") {
}
if (command == "exit") {
frame.setVisible(false);
frame = null;
System.exit(0);
}
if (command == "aboutUs") {
// System.out.println(" aboutUs Button is pressed : "+command);
}
if (command == "aboutApp") {
// System.out.println("aboutApp Button is pressed : "+command);
}
}
}
}
class ClientReadThread extends Thread {
BufferedReader in=null;
ServerSocket server;
ClientReadThread(BufferedReader in) {
this.in=in;
}
public void run(){
while(true){
try{
String line=in.readLine();
if(line.substring(0,1).equals("U")){
Main.userList.clear();
line=line.substring(2,line.length()-1);
StringTokenizer st=new StringTokenizer(line,",");
while(st.hasMoreTokens()){
StringTokenizer st2=new StringTokenizer(st.nextToken(),"=/");
String n=st2.nextToken().trim();
String i=st2.nextToken().trim();
Main.userList.put(n,i);
}
}
else
System.out.println("it is not user list "+line);
}catch(IOException ioex){System.out.println("out from read thread"+ioex);break;}
}
}
________________________________________________________________________
150
________________________________________________________________________
}
class messagesThread extends Thread{
SimulationForm SF;
String ip;
String Cip;
String areaID;
String room;
messagesThread(){
SF=new SimulationForm(Main.user);
}
public void run(){
try{
String ip=InetAddress.getLocalHost().toString();
String Cip=ip.toString();
Cip=Cip.substring(1,Cip.length());
}catch(IOException ioe){}
Location loc=new Location(Cip);
while(true){
room=loc.getRoom();
if(SF.getArea()!="null")
room=SF.getArea();
query(room);
try{
sleep(1000);
}catch (InterruptedException e) {}
}
}
public void query(String room){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd hh:mm:ss ");
Date date=new Date();
String sT=sdf.format(date);
sT=SF.getTime();
String Q="SELECT * FROM `messages` where mTo='All' or mTo='"+Main.user+"' and areaID
='"+room+"' and sTime < '"+sT+"' and eTime >'"+sT+"'";
if(areaID!=null){
ResultSet rs = stmt.executeQuery(Q);
while (rs.next()) {
String message = rs.getString("message");
String subject = rs.getString("subject");
String mFrom = rs.getString("mFrom");
String messageID = rs.getString("messageID");
String send = mFrom + ",,,,," + subject + ",,,,," + message;
String mes = "";
if (Main.messageList.get(messageID) == null) {
int i = 0;
if (message.length() > 50) {
________________________________________________________________________
151
________________________________________________________________________
for (; i + 50 < message.length(); i = i + 50)
mes += message.substring(i, i + 50) + "\n";
mes += message.substring(i, message.length());
}
else
mes = message;
JFrame jf = new JFrame("PopUp Message");
jf.getContentPane().setLayout(new GridLayout(4, 1));
jf.getContentPane().add(new JLabel(" Message From : " +
mFrom));
jf.getContentPane().add(new JLabel("
Subject : " +
subject));
jf.getContentPane().add(new JLabel("
Message : "));
jf.getContentPane().add(new JTextArea(mes));
jf.setSize(300, 200);
Main.messageList.put(messageID, mFrom);
jf.setVisible(true);
//System.out.println(" Sended Message "+send);
}
}
}
stmt.close();
}catch( Exception e ) {
System.out.println(" Exception Occured in MySql message search query");
}
}
}
class myLocation extends JPanel{
private JTextField X,Y,Floor,Room;
JButton onMap;
Location Loc;
String CLIENT_IP,user;
myLocation(String user){
this.user=user;
Color bg=new Color(191,223,255);
JPanel panel1,panel2,panel3,panel4,panel5;
try{
String cip =InetAddress.getLocalHost().toString();
System.out.println("cip is "+cip);
StringTokenizer st=new StringTokenizer(cip,"/");
while(st.hasMoreTokens()){
CLIENT_IP=st.nextToken();
}
System.out.println("cip is "+CLIENT_IP);
}catch(IOException ioe){}
setLayout(new GridLayout(5,3));
JLabel lX,lY,lFloor,lRoom;
lX=new JLabel(" X :");
lY=new JLabel(" Y :");
lFloor=new JLabel(" Floor");
lRoom=new JLabel(" Room");
X=new JTextField("D 311.11119",20);
Y=new JTextField("D 234.56789",20);
Floor=new JTextField("D 3rd",20);
________________________________________________________________________
152
________________________________________________________________________
Room=new JTextField("D 3.19",20);
onMap=new JButton(new ImageIcon("onMap.png"));
onMap.setActionCommand("Show on Map");//new ImageIcon("header.png");
onMap.setBackground(bg);
onMapListener listener=new onMapListener();
onMap.addActionListener(listener);
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
panel5=new JPanel();
panel1.add(lX);
panel1.add(X);
panel2.add(lY);
panel2.add(Y);
panel3.add(lFloor);
panel3.add(Floor);
panel4.add(lRoom);
panel4.add(Room);
panel5.add(onMap);
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
panel1.setBackground(bg);
panel2.setBackground(bg);
panel3.setBackground(bg);
panel4.setBackground(bg);
panel5.setBackground(bg);
locThread loc=new locThread();
loc.start();
}
class locThread extends Thread{
locThread(){
Loc=new Location(CLIENT_IP);
getLoc();
}
public void run(){
while(true){
try{
getLoc();
sleep(2000);
}catch (InterruptedException e) {}
}
}
public void getLoc(){
if(!(Room.getText().equals(Loc.getRoom()))){
X.setText(String.valueOf(Loc.getX()));
Y.setText(String.valueOf(Loc.getY()));
Floor.setText(Loc.getFloor());
Room.setText(Loc.getRoom());
}
________________________________________________________________________
153
________________________________________________________________________
}
}
class trackPerson extends JPanel{
JComboBox CList;
ImageIcon map;
String user;
trackPerson(String user){
this.user=user;
CList=new JComboBox();
JLabel label=new JLabel("
Track Person
");
JLabel label2=new JLabel("Select the name of a person to be Tracked");
JButton go=new JButton("Go");
JLabel message=new JLabel(" ");
Font font = new Font("Serif",Font.PLAIN,35);
label.setFont(font);
tarckPersonListener listener=new tarckPersonListener();
go.addActionListener(listener);
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
panel1.add(label);
panel2.setLayout(new GridLayout(1,2));
panel2.add(CList);
panel2.add(go);
panel2.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"Select the
name of a person to be Tracked",
TitledBorder.LEFT, TitledBorder.TOP,
new Font ("Serif", Font.ITALIC, 20),
Color.blue));
panel3.add(message);
panel4.setLayout(new GridLayout(3,1));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
setLayout(new BorderLayout());
add(panel4,BorderLayout.NORTH);
fillCList();
}
private void fillCList(){
CList.removeAllItems();
Set set=Main.userList.keySet();
Iterator iter=set.iterator();
while(iter.hasNext())
CList.addItem(iter.next());
}
class tarckPersonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Go"){
________________________________________________________________________
154
________________________________________________________________________
String ip=(String)Main.userList.get((String)CList.getSelectedItem());
showOnMap show=new
showOnMap((String)CList.getSelectedItem(),ip);
}
}
}
}
________________________________________________________________________
155
________________________________________________________________________
A6.5 getMessage
package LTBIES.Client;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.border.*;
public class getMessage extends JPanel{
JComboBox Cfrom,Cdate;
JButton submit;
String user;
CustomScrollPane sp;
JTextArea text;
getMessage(String user){
this.user=user;
Color bg=new Color(191,223,255);
//setLayout(new GridLayout(5,1));
Font font = new Font("Serif",Font.PLAIN,40);
JLabel label=new JLabel("Get Messages");
label.setFont(font);
JLabel from=new JLabel("From : ");
JLabel date=new JLabel("Date : ");
text=new JTextArea("Messages will come here ");
submit=new JButton("Click");
getMessageListener listener=new getMessageListener();
submit.addActionListener(listener);
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
this.setBackground(bg);
panel1.setBackground(bg);
panel2.setBackground(bg);
panel3.setBackground(bg);
panel4.setBackground(bg);
________________________________________________________________________
156
________________________________________________________________________
panel5.setBackground(bg);
Cfrom=new JComboBox();
Cdate=new JComboBox();
panel1.add(label);
panel2.add(from);
panel2.add(Cfrom);
panel2.add(date);
panel2.add(Cdate);
panel3.add(submit);
panel5.setLayout(new GridLayout(3,1));
panel5.add(panel1);
panel5.add(panel2);
panel5.add(panel3);
panel4.add(text);
panel5.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"",
TitledBorder.LEFT,
TitledBorder.TOP,
new Font ("Serif", Font.ITALIC, 10),
Color.blue));
panel4.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"Messages",
TitledBorder.LEFT,
TitledBorder.TOP,
new Font ("Serif", Font.ITALIC, 20),
Color.blue));
sp = new CustomScrollPane(panel4);
this.add(panel5);
this.add(sp);
fillCombo();
}
private void fillCombo(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd hh:mm:ss ");
Date date=new Date();
String sT=sdf.format(date);
Cfrom.addItem("All");
String Q="SELECT userID FROM `users`";
ResultSet rs = stmt.executeQuery(Q);
while( rs.next() ){
Cfrom.addItem(rs.getString("userID"));
}
stmt.close();
}catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Exception S O
O R Y ");
________________________________________________________________________
157
________________________________________________________________________
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
for(int i=0;i<7;i++){
String s=sdf.format(date);
Cdate.addItem(s);
date.setDate(date.getDate()-1);
}
}
public class getMessageListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Click"){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter= new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
String today=sdf.format(date);
String qDate=(String)Cdate.getSelectedItem();
String qDateS=new String(qDate+" 00:00:00");
if(today.equals(qDate)){
qDate=formatter.format(new Date());
}
else{
qDate=qDate+" 23:59:59";
}
String Q="SELECT * from messages where mTo='"+user+"' or mTo='All' and ";
if(!(Cfrom.getSelectedItem().equals("All"))){
Q+=" mFrom ='"+Cfrom.getSelectedItem()+"' and ";
}
Q+=" eTime >= ' "+qDateS+"'";
Q+="and sTime <= ' "+qDate+"'";
query(Q);
}
}
private void query(String Q){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(Q);
text.setText("");
if( rs.next()){
do{
String message = rs.getString("message");
String subject = rs.getString("subject");
String mFrom = rs.getString("mFrom");
String mes="Message From : "+mFrom+"\nSubject : "+subject;
mes+="\nMessage : \n";
int i=0;
for(;i+50<message.length();i=i+50)
________________________________________________________________________
158
________________________________________________________________________
mes+=message.substring(i,i+50)+"\n";
mes+=message.substring(i,message.length());
mes+="\n-------------------------------------------\n";
text.append(mes+"\n");
}while( rs.next() );
}
else
text.setText("\n There is no any Message \n");
stmt.close();
}catch( Exception e ) {
e.printStackTrace();
System.out.println("Exception S O O R Y ");
}
}
}
}
________________________________________________________________________
159
________________________________________________________________________
A6.6 leavMessageForm
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.border.*;
public class leavMessageForm extends JPanel{
static JFrame fram;
static JTextField Tsubject,TareaID,TsTime,TeTime,TmTo;
static JTextArea Tmessage;
private JButton submit,clear,back;
PrintWriter out = null;
String user;
private JComboBox comboMto,comboLocation;
private JComboBox sH,sM,sD,eH,eM,eD;
JLabel errorMessage;
leavMessageForm(PrintWriter out,String user){
this.out=out;
this.user=user;
JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6,panel7,panel8;
JLabel heading,LmTo,LareaID,Lsubject,LsTime,LeTime,Lmessage;
JLabel Lh,Lm,Ld;
comboMto=new JComboBox();
comboLocation=new JComboBox();
sH=new JComboBox();
sM=new JComboBox();
sD=new JComboBox();
eH=new JComboBox();
eM=new JComboBox();
eD=new JComboBox();
fillComboBox();
fillTime();
Lh=new JLabel("Hours:");
________________________________________________________________________
160
________________________________________________________________________
Lm=new JLabel("Minutes:");
Ld=new JLabel("Date:");
errorMessage=new JLabel("");
heading=new JLabel(" LEAVE MESSAGE ");
Font font = new Font("Serif",Font.PLAIN,40);
heading.setFont(font);
LmTo=new JLabel("Message To: ");
Lsubject=new JLabel("Subject:");
LareaID=new JLabel("Location: ");
LsTime=new JLabel("Start Time: ");
LeTime=new JLabel("End Time: ");
Lmessage=new JLabel("Message: ");
TmTo=new JTextField(15);
Tsubject=new JTextField(15);
TareaID=new JTextField(15);
TsTime=new JTextField(10);
TeTime=new JTextField(10);
Tmessage=new JTextArea(5,40);
back=new JButton("Back");
submit=new JButton(new ImageIcon("Submit.png"));
clear=new JButton(new ImageIcon("clear.png"));
submit.setActionCommand("Submit");
clear.setActionCommand("Clear");
regListener listener=new regListener();
submit.addActionListener(listener);
clear.addActionListener(listener);
back.addActionListener(listener);
panel0=new JPanel();
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
panel5=new JPanel();
panel6=new JPanel();
panel7=new JPanel();
panel8=new JPanel();
panel0.add(heading);
panel1.setLayout(new GridLayout(3,2));
panel1.add(LmTo);
panel1.add(comboMto);
panel1.add(Lsubject);
panel1.add(Tsubject);
panel1.add(LareaID);
panel1.add(comboLocation);
panel2.setLayout(new GridLayout(2,1));
panel2.add(panel0);
panel2.add(panel1);
panel3.add(LsTime);
panel3.add(new JLabel("Hours:"));
panel3.add(sH);
________________________________________________________________________
161
________________________________________________________________________
panel3.add(new JLabel("Minutes:"));
panel3.add(sM);
panel3.add(new JLabel("Date:"));
panel3.add(sD);
panel4.add(LeTime);
panel4.add(Lh);
panel4.add(eH);
panel4.add(Lm);
panel4.add(eM);
panel4.add(Ld);
panel4.add(eD);
JPanel timePanel=new JPanel();
timePanel.setLayout(new GridLayout(2,1));
timePanel.add(panel3);
timePanel.add(panel4);
timePanel.setBorder(new TitledBorder( LineBorder.createBlackLineBorder()," Time Period to deliver
the Message",
TitledBorder.LEFT,
TitledBorder.TOP,
new Font ("Serif", Font.ITALIC, 20),
Color.blue));
JPanel ePanel=new JPanel();
ePanel.add(errorMessage);
panel5.add(Lmessage);
panel5.add(Tmessage);
timePanel.setLayout(new GridLayout(2,1));
panel6.add(submit);
panel6.add(clear);
panel6.add(ePanel);
setLayout(new GridLayout(5,2,1,1));
setBackground(Color.white);
add(panel2);
add(timePanel);
add(panel5);
add(panel6);
}
public class regListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Submit"){
Date date=new Date();
boolean ok=false;
Date endDate=new Date();
Date startDate=new Date();
String startTime=(String)sD.getSelectedItem();
startTime+=" "+sH.getSelectedItem();
startTime+=":"+sM.getSelectedItem()+":00";
String endTime=(String)eD.getSelectedItem();
endTime+=" "+eH.getSelectedItem();
endTime+=":"+eM.getSelectedItem()+":00";
SimpleDateFormat formatter= new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
try{
________________________________________________________________________
162
________________________________________________________________________
startDate=formatter.parse(startTime);
endDate=formatter.parse(endTime);
}catch(ParseException exp){errorMessage.setText("Not a valied Time");}
if(endDate.after(startDate) && (startDate.after(date)||startDate.equals(date) )){
String Q="INSERT INTO `messages` ";
Q+="(`message`, `subject`, `areaID`, `sTime`, `eTime`, `mFrom`, `mTo`)VALUES ('";
Q+=Tmessage.getText()+"','";
Q+=Tsubject.getText()+"','";
Q+=comboLocation.getSelectedItem()+"','";
Q+=startTime+"','";
Q+=endTime+"','";
Q+=user+"','";
Q+=comboMto.getSelectedItem()+"')";
UpdateQuery(Q);
out.println("Q"+comboMto.getSelectedItem());
clear();
}
else {
errorMessage.setText("Message is not stored.. \n Sart time may be after the End time or before the Current
time: ");
}
}
if(command=="Clear"){
clear();
}
if(command=="Back"){
fram.setVisible(false);
fram=null;
}
}
}
private void UpdateQuery(String Q){
String b="true";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
stmt.executeUpdate(Q);
stmt.close();
}catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Exception S O O R Y ");
}
}
private void clear(){
Tsubject.setText("");
Tmessage.setText("");
errorMessage.setText("");
________________________________________________________________________
163
________________________________________________________________________
fillTime();
}
private void fillComboBox(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
tring Q="SELECT groupID FROM `group`";
ResultSet rs = stmt.executeQuery(Q);
comboMto.addItem("All");
while( rs.next() ){
comboMto.addItem(rs.getString("groupID"));
}
Q="SELECT userID FROM `users`";
rs = stmt.executeQuery(Q);
hile( rs.next() ){
comboMto.addItem(rs.getString("userID"));
}
Q="SELECT * FROM `location`";
rs = stmt.executeQuery(Q);
while( rs.next() ){
comboLocation.addItem(rs.getString("areaID")+" "+rs.getString("usage"));
}
stmt.close();
}catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Exception S O O R Y ");
}
}
private void fillTime(){
Date dateFill=new Date();
for(int i=0;i<24;i++){
sH.addItem(new Integer(i));
eH.addItem(new Integer(i));
}
for(int i=0;i<60;i=i+5){
sM.addItem(new Integer(i));
eM.addItem(new Integer(i));
}
sH.setSelectedItem(new Integer(dateFill.getHours()));
sM.setSelectedItem(new Integer(5*(dateFill.getMinutes()/5)+5));
dateFill.setMinutes(dateFill.getMinutes()+15);
eH.setSelectedItem(new Integer(dateFill.getHours()));
eM.setSelectedItem(new Integer(5*(dateFill.getMinutes()/5)+5));
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
________________________________________________________________________
164
________________________________________________________________________
for(int i=0;i<7;i++){
String s=sdf.format(date);
sD.addItem(s);
eD.addItem(s);
date.setDate(date.getDate()+1);
}
date=new Date();
sD.setSelectedItem(sdf.format(date));
eD.setSelectedItem(sdf.format(date));
}
}
________________________________________________________________________
165
________________________________________________________________________
A6.7 showOnMap
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.swing.border.*;
public class showOnMap extends Thread{
String user;
String ip;
Location loc;
int pX=0,pY=0;
JFrame frame ;
CustomScrollPane sp ;
Graphics g;int r=5;
String Floor,Room;
JLabel label;
ImageIcon image;
showOnMap(String name,String ip){
this.user=name;
this.ip=ip;
label=new JLabel();
sp = new CustomScrollPane(label);
frame =new JFrame("LTBIES "+user+"'s Location on map");
frame.getContentPane().add(sp);
frame.setSize(500,600);
frame.setVisible(true);
start();
}
public void run(){
while(frame.isShowing()){
loc=new Location(ip);
loc.getLocation();
if(pX+10>loc.getX()|| pX-10<loc.getX() || pY+6>loc.getY()|| pY+10>loc.getY()){
pX=loc.getX();
pY=loc.getY();
Floor=loc.getFloor();
Room=loc.getRoom();
image=new ImageIcon(Floor+".png"){
public void paintIcon(Component c,Graphics gg,int l,int m){
super.paintIcon(c, gg, 0,0 );
g=gg;
g.setColor(new Color(0,255,0));
g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,25);
g.setColor(new Color(255,0,0));
g.drawString(user,pX/4, pY/4);
}
________________________________________________________________________
166
________________________________________________________________________
};
label.setIcon(image);
}
try{
sleep(2000);
}catch (InterruptedException e) {}
}
}
}
class CustomScrollPane extends JPanel
{
protected JScrollBar m_vertSB;
protected JScrollBar m_horzSB;
protected CustomViewport m_viewport;
protected JComponent m_comp;
public CustomScrollPane(JComponent comp) {
setLayout(null);
m_viewport = new CustomViewport();
m_viewport.setLayout(null);
add(m_viewport);
m_comp = comp;
m_viewport.add(m_comp);
m_vertSB = new JScrollBar(
JScrollBar.VERTICAL, 0, 0, 0, 0);
m_vertSB.setUnitIncrement(5);
add(m_vertSB);
m_horzSB = new JScrollBar(
JScrollBar.HORIZONTAL, 0, 0, 0, 0);
m_horzSB.setUnitIncrement(5);
add(m_horzSB);
AdjustmentListener lst = new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
m_viewport.doLayout();
}
};
m_vertSB.addAdjustmentListener(lst);
m_horzSB.addAdjustmentListener(lst);
}
public void doLayout() {
Dimension d = getSize();
Dimension d0 = m_comp.getPreferredSize();
Dimension d1 = m_vertSB.getPreferredSize();
Dimension d2 = m_horzSB.getPreferredSize();
int w = Math.max(d.width - d1.width-1, 0);
int h = Math.max(d.height - d2.height-1, 0);
m_viewport.setBounds(0, 0, w, h);
m_vertSB.setBounds(w+1, 0, d1.width, h);
m_horzSB.setBounds(0, h+1, w, d2.height);
________________________________________________________________________
167
________________________________________________________________________
int xs = Math.max(d0.width - w, 0);
m_horzSB.setMaximum(xs);
m_horzSB.setBlockIncrement(xs/5);
m_horzSB.setEnabled(xs > 0);
int ys = Math.max(d0.height - h, 0);
m_vertSB.setMaximum(ys);
m_vertSB.setBlockIncrement(ys/5);
m_vertSB.setEnabled(ys > 0);
m_horzSB.setVisibleAmount(m_horzSB.getBlockIncrement());
m_vertSB.setVisibleAmount(m_vertSB.getBlockIncrement());
}
public Dimension getPreferredSize() {
Dimension d0 = m_comp.getPreferredSize();
Dimension d1 = m_vertSB.getPreferredSize();
Dimension d2 = m_horzSB.getPreferredSize();
Dimension d = new Dimension(d0.width+d1.width,
d0.height+d2.height);
return d;
}
class CustomViewport extends JPanel
{
public void doLayout() {
Dimension d0 = m_comp.getPreferredSize();
int x = m_horzSB.getValue();
int y = m_vertSB.getValue();
m_comp.setBounds(-x, -y, d0.width, d0.height);
}
}
}
________________________________________________________________________
168
________________________________________________________________________
A6.8 showOnMapAll
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.swing.border.*;
public class showOnMapAll extends Thread{
String user;
String ip;
Location loc;
int pX=0,pY=0;
JFrame frame ;
CustomScrollPane sp ;
Graphics g;int r=5;
String Floor="level4",Room;
JLabel label;
ImageIcon image;
JButton floor1,floor3,floor2,floor4;
HashMap userList=new HashMap();
showOnMapAll(HashMap userList){
this.userList=userList;
this.user="Shouket";
this.ip="192.168.100.229";
ImageIcon floor1Image=new ImageIcon("b_floor1.png");
ImageIcon floor2Image=new ImageIcon("b_floor2.png");
ImageIcon floor3Image=new ImageIcon("b_floor3.png");
ImageIcon floor4Image=new ImageIcon("b_floor4.png");
floor1=new JButton(floor1Image);
floor2=new JButton(floor2Image);
floor3=new JButton(floor3Image);
floor4=new JButton(floor4Image);
floor1.setActionCommand("First Floor");
floor2.setActionCommand("Second Floor");
floor3.setActionCommand("Thired Floor");
floor4.setActionCommand("Fourth Floor");
floor1.setBackground(new Color(253,176,102));//
floor2.setBackground(new Color(253,176,102));//
floor3.setBackground(new Color(253,176,102));//
floor4.setBackground(new Color(253,176,102));//
floor1.setActionCommand("one");
floor2.setActionCommand("two");
floor3.setActionCommand("three");
________________________________________________________________________
169
________________________________________________________________________
floor4.setActionCommand("four");
mapListener listener=new mapListener();
floor1.addActionListener(listener);
floor2.addActionListener(listener);
floor3.addActionListener(listener);
floor4.addActionListener(listener);
JPanel panel=new JPanel();
panel.add(floor1);
panel.add(floor2);
panel.add(floor3);
panel.add(floor4);
panel.setBackground(new Color(211,106,1));//
label=new JLabel();
sp = new CustomScrollPane(label);
frame =new JFrame("LTBIES "+user+"'s Location on map");
frame.getContentPane().add("North",panel);
frame.getContentPane().add("Center",sp);
frame.setSize(500,600);
frame.setBackground(new Color(253,176,102));//
frame.setVisible(true);
start();
}
public void run(){
while(frame.isShowing()){
loc=new Location(ip);
loc.getLocation();
image=new ImageIcon(Floor+".png"){
public void paintIcon(Component c,Graphics gg,int l,int m){
super.paintIcon(c, gg, 0,0 );
g=gg;
Set list=userList.keySet();
Iterator iter=list.iterator();
int draw=12;
while(iter.hasNext()){
user=(String)iter.next();
ip=(String)userList.get(user);
loc=new Location(ip);
loc.getLocation();
pX=loc.getX();
pY=loc.getY();
String level=loc.getFloor();
Room=loc.getRoom();
if(Floor.equals(level)){
g.setColor(new Color(0,255,0));
g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,draw+12);
g.setColor(new Color(255,0,0));
g.drawString(user,pX/4, pY/4+draw);
draw+=12;
}
}
}
};
label.setIcon(image);
________________________________________________________________________
170
________________________________________________________________________
try{
sleep(2000);
}catch (InterruptedException e) {}
}
}
public static void main(String[] str){
HashMap userList=new HashMap();
userList.put("Nadeem","192.168.100.229");
userList.put("Shouket","192.168.100.147");
userList.put("Bilal","192.168.100.186");
userList.put("Bilal Sarwar","192.168.100.235");
String name="Nadeem";
String ip="192.168.100.229";
showOnMapAll show=new showOnMapAll(userList);
}
class mapListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
System.out.println(command+user);
if(command=="one"){
Floor="level1";
}
if(command=="two"){
Floor="level2";
}
if(command=="three"){
Floor="level3";
}
if(command=="four"){
Floor="level4";
}
}
}}
A6.9 onlineUsers
package LTBIES.Client;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.swing.border.*;
public class onlineUsers extends JPanel{
HashMap userList;
JTextArea Tmessage;
onlineUsers(HashMap userList){
this.userList=userList;
System.out.println(userList);
JLabel label=new JLabel("Online Persons");
Font font = new Font("Serif",Font.PLAIN,35);
label.setFont(font);
________________________________________________________________________
171
________________________________________________________________________
Tmessage=new JTextArea("",10,50);
Tmessage.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"List of
Online persons",
TitledBorder.LEFT, TitledBorder.TOP,
new Font ("Serif", Font.ITALIC, 20),
Color.blue));
//JButton show=new JButton("Show on Map");
JButton show=new JButton(new ImageIcon("onMap.png"));
show.setActionCommand("Show");
onLineUsersListener listener=new onLineUsersListener();
show.addActionListener(listener);
setLayout(new BorderLayout());
add(label,BorderLayout.NORTH);
add(Tmessage,BorderLayout.CENTER);
add(show,BorderLayout.SOUTH);
fillCList();
}
private void fillCList(){
Set set=userList.keySet();
Iterator iter=set.iterator();
while(iter.hasNext()){
String s=(String)iter.next();
String ip=(String)userList.get(s);
System.out.println("ip to get location is "+ip);
Location loc=new Location(ip);
String room=loc.getRoom();
String floor=loc.getFloor();
Tmessage.append("Mr. "+s+" is in Room "+room+" on floor "+floor+"\n");
System.out.println(s);
}
}
class onLineUsersListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command=="Show"){
System.out.println("Show on Map is pressed");
showOnMapAll show=new showOnMapAll(userList);
}
}
}
}
________________________________________________________________________
172
________________________________________________________________________
A6.10 SimulationForm
package LTBIES.Client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.border.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class SimulationForm extends JPanel{
JLabel TName;
JButton onMap;
static JFrame jf;
JComboBox hours,minutes,date,comboLocation;
boolean on=false;
SimulationForm(String user){
JLabel LTime,Lhour,Lminutes,Ldate;
JLabel label,LName,LRoom,TName;
JPanel panel1,panel2,panel3,panel5;
setLayout(new GridLayout(5,3));
comboLocation=new JComboBox();
Font font = new Font("Serif",Font.PLAIN,15);
label=new JLabel("Please enter the Area & Time for Simulation ");
LName=new JLabel(" Name of Client: ");
LRoom=new JLabel(" Area:
");
TName=new JLabel(user);
onMap=new JButton("Start Simulation");
onMapListener listener=new onMapListener();
onMap.addActionListener(listener);
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel5=new JPanel();
hours=new JComboBox();
minutes=new JComboBox();
date=new JComboBox();
LTime=new JLabel("Time: ");
Lhour=new JLabel(" Hours ");
Lminutes=new JLabel("Minutes ");
Ldate=new JLabel("Date ");
font = new Font("Serif",Font.PLAIN,20);
LTime.setFont(font);
LRoom.setFont(font);
panel5.add(LTime);
panel5.add(Lhour);
________________________________________________________________________
173
________________________________________________________________________
panel5.add(hours);
panel5.add(Lminutes);
panel5.add(minutes);
panel5.add(Ldate);
panel5.add(date);
panel1.add(LName);
panel1.add(TName);
panel1.add(label);
panel2.add(LRoom);
panel2.add(comboLocation);
panel3.add(onMap);
add(panel1);
add(panel2);
add(panel5);
add(panel3);
fillTime();
fillComboBox();
jf=new JFrame("Simulation Test");
jf.getContentPane().add(this);
jf.setSize(440,240);
jf.setLocation(600,400);
jf.setVisible(true);
}
public static void main(String arg[]){
SimulationForm mL=new SimulationForm("nadeemAhmad");
}
public String getName(){
if(on)
return TName.getText();
else
return null;
}
public String getArea(){
if(on){
String s=(String) comboLocation.getSelectedItem();
s=s.substring(0,5);
return s.trim();
}
else
return null;
}
public String getTime(){
if(on){
String Ctime=(String)date.getSelectedItem();
Ctime+=" "+hours.getSelectedItem();
Ctime+=":"+minutes.getSelectedItem()+":00";
return Ctime;
}
else
return null;
________________________________________________________________________
174
________________________________________________________________________
}
public class onMapListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(on){
on=false;
onMap.setLabel("Start Simulation");
}
else{
on=true;
onMap.setLabel("Stop Simulation");
}
}
}
public void fillTime(){
for(int i=0;i<24;i++){
hours.addItem(new Integer(i));
}
for(int i=0;i<60;i=i+5){
minutes.addItem(new Integer(i));
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date1=new Date();
for(int i=0;i<7;i++){
date1.setMonth(5+i);
String s=sdf.format(date1);
date.addItem(s);
}
}
public void fillComboBox(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username = "na_e2002";
String password = "Eclipse";
String url = "jdbc:mysql://mysql.it-c.dk/" + username;
Connection con = DriverManager.getConnection(url, username , password);
Statement stmt = con.createStatement();
String Q="SELECT * FROM `location`";
ResultSet rs = stmt.executeQuery(Q);
while( rs.next() ){
comboLocation.addItem(rs.getString("areaID")+" "+rs.getString("usage") );
}
stmt.close();
}catch( Exception e ) {
System.out.println(e.getMessage());
}
}
}
________________________________________________________________________
175