Sistem Software de Monitorizare a Costurilor de Calatoriedoc
=== Sistem software de monitorizare a costurilor de calatorie ===
Universitatea “Politehnica” din București
Facultatea de Electronică, Telecomunicații și Tehnologia Informației
Sistem software de monitorizare a costurilor de calatorie
Lucrare de dizertație
prezentată ca cerință parțială pentru obținerea titlului de
Master în domeniul Electronică și Telecomunicații
programul de studii de masterat Tehnologii software avansate pentru
comunicații
Conducător științific Absolvent
Șl.Dr.Ing. Laurențiu BOICESCU Ing. Artur KARAPETYAN
2016
TABLE OF CONTENTS
List of images…………….………………………………………………………………………………5
Introduction ………………………………………………………………………………………………6
I.1. Objectives of the thesis ………………………………………………………………………………6
I.2. Contents of the thesis ………………………………………………………………………………..7
I.3. Proposed solution ……………………………………………………………………………………7
CHAPTER 1 Used programming languages, platforms and programs.…………………………………9
1.1 DataBase.…………………………………………………………………………………………….9
1.2 MySQL..……………………………………………………………………………………………..10
1.3 Java .………………………………………………………………………………………………….15
1.3.1 Java description…………………………………………………………………………………….15
1.3.2 JavaServer Pages ( JSP )..…………………………………….………….……………………….17
1.3.3 Java Servlets…………………………………………………………………………….…………19
CHAPTER 2 Steps of PriceMeter creation .…………………………………………………….……..21
2.1 DataBase .…………………………………………………………………….…………………….21
2.2 Desktop application .………………………………………………………….……………..…….27
2.3 Web site .………………………………………………………………….…………………….….32
CHAPTER 3 PriceMeter at work .……………………………………………….……………….……36
3.1 Desktop version of PriceMeter .……………………………………………………………….……36
3.2 Web version of PriceMeter .…………………………………………………………………….….38
Conclusion .………………………………………………………………………………..…………….42
Futures .…………………………………………………………………………………………………..43
Bibliography .………………………………………………………………………………….…..……44
Annexes…………………………………………………………………………………………………..46
List of images
Picture 1 – economical layers of PriceMeter, page 7
Picture 2 – database example, page 10
Picture 3 – database example with multiple values in a cell, page 10
Picture 4 – database with duplicated records, page 11
Picture 5 – database with avoiding data redundancy, page 12
Picture 6 – Client-Server-Database architecture, page 16
Picture 7 – Position of Servlets in a Web Application, page 18
Picture 8 – The database construction, page 19
Picture 9 – Product table, page 19
Picture 10 – Priority table, page 20
Picture 11 – Country table, page 20
Picture 12 – Category table, page 21
Picture 13 – PriceMeter main window with selected labels, page 25
Picture 14 – PriceMeter main window with selected lists, page 26
Picture 15 – PriceMeter main window, page 34
Picture 16 – PriceMeter main window with some selections from the lists, page 34
Picture 17 – PriceMeter main and secondary windows with some selections from the lists and query, result based on them, page 35
Picture 18 – PriceMeter main and secondary windows with error information on it, page 35
Picture 19 – PriceMeter main and secondary windows with price average graphics, page 36
Picture 20 – registration page, page 36
Picture 21 – login page, page 37
Picture 22 – user’s account, page 37
Picture 23 – admin’s account, page 38
Picture 24 – admins account, survey page, page 38
Picture 25 – admins account, survey adding page, page 39
Introduction
Current situation
So let's imagine a situation that You have dreamed for a long time to go abroad and here is Your dream come true, You just buy a ticket and after few hours Your plane is landing. You immediately take taxi and go to the center of the city. And there the first time You ask Yourself “how much does it cost ?”. And You realize that You are in a foreign country and do not have a clue about the prices. You do not know how much will cost to rent a car, how much will be to take a room at hotel or how much do You have to have a dinner at a restaurant.
And now let's look another situation, You are a student and just came to study in another country. You have a certain amount of money and of course You want to spend it as efficiently as it possible. And You are starting asking Yourself how much costs water and food in the store or how much will be subway or bus.
Ways of solving it
To avoid such a situation it is the way better to look for prices before visiting certain country. But how ? Where from ? The answer is simple “ Just Google it !“ and You will get thousands of web sites about prices, living costs, quality of different services and a lot of interesting information about that country. But if You will look more attentively You will see that prices of the same things can vary from 10% until 1000%. That is because some sites are using old dates then the others are updating them frequently, or it is possible that one web page has information about expensive kind of that
product and the other page vice versa ( for example cognac’s prices depending on its age, stars, country of origin. So just simply one web page can take cheapest price and the other one highest. ).
I.1 Objectives of the thesis
The main goal of this project is to develop a complete product which will help people to save their time and money by giving them maximally actual and complete information about prices in desired country.
Our product will be separated into two parts. The first part will be a desktop application and the second part will be a web page. Of course they will be connected between each other.
To avoid that all I am presenting You << PriceMeter >> or just simply << PM >>. What is the difference between PriceMeter and the other web services ? At first PM is not only a web page, it is application which You can download to Your notebook and use it everywhere, even without internet ! The second advantage in face of other services is that here I am using different pricelists for every layer of people. So PriceMeter can use tourist, students, businessmen and anyone who what to know prices.
We are monitoring the cost of living in different countries based on the prices in several online stores. Also we are planning in future to collect the prices from users of our program across the country, allowing them to see how value prices of products in World and what the real prices of products.
I.2 Contents of the thesis
The main part of my work consists from three chapters. So lets discuss them. The first chapter is all about used programming languages, platforms and programs. Here I mainly speak about databases and Java. Since I used as a database MySql so I described its structure, usage and normalization. I also wrote about Java, JSP and Servlets. So summing all this I can assure that a reader after reading the first chapter gets basic knowledge about used programming languages, platforms and programs.
The name of the second chapter is PriceMeter design and implementation. Here I decided to write about database, desktop application and Web site. In subchapter database I in details spoke about creating process of the database which I used for saving information about prices in different countries. In “desktop application” there is description of the process how I created PriceMeter desktop version. Finally, in the subchapter “Web site” I decided to show to a reader how I made modifications on Twitter’s Bootstrap template and made it all necessary changes to reach our goal, create a web version of PriceMeter.
And the last but not less important chapter is “PriceMeter at work”. As you can understand from the name of the chapter here I spoke about utilization process of PriceMeter. I deeply discussed working process of the program, I explained which button what functionality has, what results we see then sending survey answers and so on.
I.3 Proposed solution
Now let’s understand how is constructed PM and how it works. First thing what I have done during working on PriceMeter was that I have created a huge database and collected prices of everything from different web sources and online shops. After that I have separated prices of everything into three layers: Student, Tourist, Businessman.
Picture 1 – economical layers of PriceMeter
For every category of people price of the same product is different because of quality and brand. Of course the lowest prices are in category << Student >> and the highest ones in << Businessman >>.
1. Used programming languages, platforms and programs
This chapter is all about used programming languages, platforms and programs. Here I mainly speak about databases and Java. Since I used as a database MySql so I described its structure, usage and normalization. I also wrote about Java, JSP and Servlets. So summing all this I can assure that a reader after reading the first chapter gets basic knowledge about used programming languages, platforms and programs.
1.1 DataBase
Database – is an information model that allows orderly store data about a group of objects with the same set of properties[1, 2, 3].
Software designed to work with databases, called a database management system (DBMS). Database used for the orderly storage and processing of large volumes of information.
Database organizes information storage so that it was convenient:
browse
replenish
change
look for the information
make any samples
sort in any order.
Classification of databases:
By the nature of the stored information: Factographic (card file) Documentary (archives)
According to the method of data storage: Centralized (stored on the same computer)
Distributed (used in local and global computer networks)
By structure of data organization: Tabular (relational) Hierarchical
The information in the databases is structured into separate records, which is a group of related data elements. The nature of the relationship between the records defines two basic types of organization of databases: hierarchical and relational.
In the relational databases there are four basic types of fields:
Numerical
Character (words, texts, codes, etc.)
Date (calendar date in the form "day / month / year")
Logical (accepts two values: "yes" – "no" or "true" – "false")
Table rows are records about the object. Database record is a table line which contains a set of values of certain property located in the fields of the database.
Database management systems allow to combine a lot of information and process them, sort, make selections according to specific criteria and so on.
Modern DBMS provide the opportunity to include them not only text and graphics, but sound bites and even video clips.
Simplicity of use DBMS allows to create new databases without any knowledge of programming, just with using built-in functions. DBMS provides the accuracy, completeness and consistency of the data and also easy access to them.
1.2 MySQL
One of the most popular DBMS in the modern Internet technologies undoubtedly is MySQL[4]. The main advantages that has MySQL is high performance, fast data processing and optimum
reliability. It is also important that MySQL is free open source software. Due to this all you can make changes and modify the code, which is very useful for webmasters.
DataBase normalization
Normalization of database tables – the first step in designing the structure of a relational database[5, 6, 7]. Strictly speaking, of course, not the first – you first need to decide what we do will be stored in the database, that is, to determine the structure of the fields, their types and dimensions, meaning stored in them. But that, as they say, is the default :).
The theory of normalization of relational database was developed in the late 70s of the 20th century. According to her, There are six normal forms, five of which are called first, second, third, fourth, fifth normal form and normal form Boyce-Codd, lying between the third and fourth.
The database is considered normalized, if the table (at least the majority of the tables) are presented at least in the third normal form. Often many of the table are normalized to the fourth normal form, sometimes, on the contrary, made denormalization. Use the tables in the fifth normal form (or rather, conscious of bringing them to the fifth normal form) in real databases, I have not personally
met.
The main objective of database normalization – elimination of redundancy and duplication of information. Ideally, when normalization is necessary to ensure that any value stored in the database in a single copy, and the value of it should not be obtained by calculation from other data stored in the database.
Probably, there is no sense in detail the examples of normalization tables. Such information and the Internet, in books and more than enough. Let me remind you just how essential requirements must be satisfied by each of the normal forms.
First Normal Form
First Normal Form:
prohibits duplicate columns (containing the same information within the meaning of)
prohibits multiple columns (containing a value of type list, etc.)
is required to determine the primary key for the table, that is the column or combination of columns that uniquely identify each row.
Let’s take, for example, site for car collectors, in which each collector can register his cars. The
following table stores information about registered vehicles.
Picture 2 – database example
Horizontal duplication of data is a bad practice
With this design option, you can save only five cars, and if you do them less than 5, then you are wasting space in a database for storage of empty cells.
Another example of bad practices in the design is to store multiple values in a cell.
Picture 3 – database example with multiple values in a cell
Multiple values in one cell
The right decision in this case will be the selection of vehicles in a separate table and use a foreign key that references the table.
The order of entries must not have value.
Rule: the procedure table entries should not matter.
You may be inclined to use the order of records in the customer table to determine which of the first customers to register. For these purposes, you better create a field of the date and time of registration of clients. The order of entries will inevitably change when customers will be deleted, changed or added. That's why you should never rely on the order of records in the table.
Second Normal Form
In order that the database has been implemented according to the second normal form, it must be normalized according to the first normal form. Second Normal Form is associated with data redundancy.
Data redundancy
Rule: field is not a primary key should not be dependent on the primary key.
It may sound a bit technical and confusing. And it means that you have to store in the table, only the data that are directly related to it, and have no relation to the other entity. Following the second normal form – is a matter of finding the data, which is often duplicated in the records of the table, which may belong to another entity.
Picture 4 – database with duplicated records
Duplication of data among the records in the store
The above table may belong to a company that sells cars and has a few shops in the
Netherlands.
If you look at this chart, you will see multiple instances of duplicate data among the records. Field brand could be isolated in a separate table. Also, as a field type (model), which also could be allocated in a separate table, which would have a many-to-one relationship with the table brand because the brand can be different models.
Column store contains the name of the store, which is currently in the machine. Store – this is an obvious example of data redundancy and a good candidate for a single entity to be associated with the table car foreign key relationship.
Below is an example of how you could model a database for vehicles, avoiding data redundancy.
Picture 5 – database with avoiding data redundancy
In the above example, the table has a foreign key car – a reference to the table type, and store. Column brand disappeared because there is implicit in the brand through a link to a table type. When there is a reference to the type, there is a link on the brand, because type belongs to brand.
Data redundancy has been substantially removed from our database model. If you are quite picky, you may still not satisfied with this decision. And what about the field in the table country_of_origin brand? So far, no duplicates, because there are only four brands from different countries. Attentive database designer must select the name of a table in a separate country.
And even now you should not be satisfied with the result because you could also highlight the color in a separate table.
How strongly do you approach creating your table – you decide, depending on the specific situation. If you plan to store a huge amount of units of cars in the system and you want to be able to search by color (color), it would be wise to highlight the colors in a separate table so that they are not duplicated.
There is another case where you might want to highlight the colors in a separate table. If you want to allow company employees to enter data about new cars you'll want to enable them to choose the color of the car from a predetermined list. In this case, you may want to store all possible colors in
your database. Even if you do not have machines with the color you want these colors are present in the database, so that workers can choose them. This is definitely a case where you need to select the colors in a separate table.
Third Normal Form
To the table is in third normal form, it is necessary that the non-key columns in it were independent of other non-key columns, and depend only on the primary key. The most common situation in this context – is calculated columns, the values of which may be obtained by any manipulation of the other columns of the table. To bring the table in third normal form such columns of the tables should be removed.
The normal form Boyce-Codd
The normal form Boyce-Codd requires that the table was only one potential primary key. Most of the time tables that are in third normal form, and sometimes, but not always. If you showed up the second column (a combination of columns) that uniquely identify a row, for the reduction to normal form Boyce-Codd such data is necessary to bring in a separate table.
Fourth Normal Form
To bring the table in the normal form Boyce-Codd to fourth normal form is necessary to eliminate existing therein multivalued dependencies. That is to ensure that the insertion / removal of any rows in the table would not require the insertion / removal / modification of the other rows of the same table.
Fifth normal form
The table, which is in fourth normal form, and seemed to have normalized to the limit, in some cases, there can still be divided into three or more (but not two!) Tables, combining that we get the original table. The resulting so, as a rule, very artificial, and the decomposition of the table referred to are in fifth normal form. The formal definition of the fifth normal form is that it is the form in which eliminated depending on the connection. In most cases, the practical benefits of the normalization table to fifth normal form is not observed.
Such is the theory … are special formal mathematical methods for normalization of relational database tables. In practice, the sensible design of databases, get acquainted with the subject area, is usually enough to quickly sketch a structure in which most of the tables are in fourth normal form :).
Brief results. Why the normalization.
The main thing we will, conduct database normalization – is to remove (or at least severely reduced) redundancy, duplication of data. As a consequence, significantly reduced the likelihood of conflicting data, easier administration database and update the information in it, reducing the amount of disk space.
But not all so white and fluffy. Often, to extract information from a normalized database necessary to design very complex queries, which moreover, is work quite slowly – due mainly a large number of compounds of tables. Therefore, to increase the speed of data retrieval and simplify the programming of queries often have to go to a custom database denormalization.
SQLyog
SQLyog is a graphical interface for managing the MySQL database.
Simple, compact and very convenient graphical interface for managing MySQL databases. In addition to such banal things as the ability to create new tables, edit their structure and content, Enterprise-version of the program has at its disposal a number of very useful features. One of them is HTTP Tunneling. Since hosting companies often block access to the database from outside, by closing firewall ports that belong to MySQL server, wherein connect to the database can only local scripts, with their help (for example, the script phpMyAdmin) has to manage the database, which is not very convenient. However, using SQLyog with a special PHP-script, you can easily pick up HTTP-tunnel and work with MySQL database remotely without any problems.
What utility has SQLyog:
Connect to the database via HTTP tunnel
Connect to the database via SSH tunnel
synchronize the structure of two databases
synchronization of the two databases
Scheduled backup of Database
Copy Database to another host
Export database schema in the HTML
CSV import / export
Graphical Query Builder
View the contents of the tables
View the table object
Management of user privileges
SQL syntax highlighting
code completion
BLOB viewer
hotkeys support
SQLyog runs on Wine / LINUX
1.3 Java
1.3.1 Java description
I just introduced you DataBase, MySQL and SQLyog, now it’s time to speak about programming language and the platform using which I have written PriceMeter.
PM is written in programing language named “Java”. Now let’s get a general information about that
programing language.
Java is a programming language that has been developed by a company called Sun Microsystems. Applications that are written in Java are usually encoded in a byte-code, so these applications can run on any Java-machine (JVM), independent of the type of computer work (phone, computer, etc.). As I told previously programs used to write in Java are displayed with a byte code which runs in an emulated machine, a program that handles the byte code and sends instructions to the
hardware, but the code in bytes, unlike the familiar to the text, is better in the sense that it is processed much faster than text. The advantage of the implementation of programs in such a way – the complete independence of the byte code from the operating system and hardware that just allows you to perform Java-based applications on any emulating device for which has its own emulation machine. Another important feature of Java language is a flexible security system, because the performance of the work is in full control of the virtual machine. Any of the operations that are being implemented or exceed the established authorization for the program (for example, an attempt to break the data connection or to connection to another computer) cause an immediate disconnection.
Eclipse
If you ever have closely followed the developments in the world of open-source and Java- related technologies, you just could not ever hear all the noise that is deployed around Eclipse[8]. Eclipse – an extensible, open-source Integrated Development Environment (IDE, Integrated Development Environment). This project was launched in November 2001, when IBM contributed source code from Websphere Studio Workbench, cost $ 40 million, and formed the Eclipse Consortium to manage the development of this tool.
The initial goal was to "develop a stable, full-featured, industrial platform, as a commercial product, for integrable development tools." Currently Eclipse Consortium focuses on the following projects:
The Eclipse Project (http://www.eclipse.org/eclipse/index.html) – responsible for the development of direct Eclipse IDE (Eclipse platform to build other tools), Java Development Tools (JDT) and Plug-In Development Environment (PDE ) that is used to enable the expansion of the platform itself.
The Eclipse Tools Project (http://www.eclipse.org/tools/index.html) – is engaged in creation of optimal tools for the Eclipse platform. In the current sub-projects include: Cobol IDE, C / C ++ IDE, as well as EMF modeling tool.
The Eclipse Technology Project (http://www.eclipse.org/technology/index.html) – is engaged in technology research, incubation, and education on the part of the Eclipse platform use.
Together with the JDT, Eclipse platform provides many different opportunities that you can watch in a commercial IDE: syntax highlighting editor, code compilation, the source code level debugger with support for "strands" (threads), Navigator by class, file manager and project manager, interfaces for standard source code control systems, such as, for example, CVS and ClearCase.
In addition, Eclipse provides a number of unique features, such as code refactoring (http://www.refactoring.com/), automatic updates and assembly code (via the Update Manager), task list, support the possibility of using unit testing JUnit (http: / /www.junit.org/), as well as integration with the Jakarta Ant build tool applications (http://jakarta.apache.org/ant/index.html).
Despite the large number of the standard set of features, Eclipse is different from the traditional IDE for several fundamental characteristics. Perhaps the most interesting features of Eclipse – is absolutely neutral with respect to the platform and programming language. In addition to an eclectic
mix of programming languages that are supported by Eclipse Consortium (Java, C / C ++, Cobol), there are plenty of third-party projects, through which you can provide support to the Eclipse programming language you are interested in. To date, there are implementation of the following popular
programming languages: Python, Eiffel, PHP, Ruby, and C #.
The Eclipse Platform is available through Eclipse Consortium,, in the form of pre-compiled binaries for Windows, Linux, Solaris, HP-UX, AIX, QNX, and Mac OS X. A lot of attention is concentrated around the architectural system of plug-ins of this platform, and and "rich" API (Application Programming Interface), provided with the Plug-in Development Environment to extend the Eclipse. Add support for a new type of editor, viewer (panel) or programming language outrageously simple, thanks to a well-designed API and the building blocks that provides Eclipse.
With about a hundred projects for the development of plug-ins, with the resources provided by such industry giants as IBM, HP and Rational (which was recently acquired by IBM), and design Erich Gamma, which helps to quickly understand the process of development – the future of Eclipse It will be very bright, interesting and promising.
1.3.2 JavaServer Pages ( JSP )
JSP (Java Server Pages) is a standard for developing interactive Web applications (pages containing dynamic content)[9, 10, 11]. A JSP web page (recognizable by the .jspextension) may display different content based on certain parameters (information stored in a database, the user preferences, ..), while a classic webpage (with the .htm or .html extension) will continuously display the same information.
JSP is actually a powerful scripting language (interpreted language) executed on the server side (like CGI, PHP, ASP, …) and not on the client side (unlike scripts written in JavaScript or Java applets which run in the browser of the user connected to a site).
JSPs are integrated in a web page in HTML using special tags which will notify the Web server that the code included within these tags are to be interpreted. The result (HTML codes) will be returned to the client browser.
Java Server Pages are part of a 3-tier architecture: where a server supporting the Java Server Pages (generally referred to as application server) will act as a mediatior between the client browser and a database (generally referred to as data server). JSP provides the necessary elements for the connection to the database management system and allow the manipulation of data through SQL.
Picture 6 – Client-Server-Database architecture
How Java Server Pages works?
A page using Java Server Pages is executed during the query, by a JSP engine (generally running with a Web server or an application server). The JSP model is derived from the one used for Java servlets (JSP are indeed a way to write servlets). It is a Java class derived from HttpServlet class, making use of using doGet() and doPost() to return an HTTP response.
When a user calls a JSP page, the Web server calls the JSP engine which creates a Java source code from the JSP script and compile the class to provide a compiled file (with the .class extension).
Note that: the JSP engine checks if the date of the .jsp file corresponds to the .class file. The JSP
engine will convert and compile the class, only if the JSP script has been updated. Thus, the fact that the compilation only takes place when the JSP script is updated, makes JSP, one of the fastest technologies to create dynamic pages.
Characteristics of Java Server Pages
JSPs can be used to create servlets, by including specific tags in the JSP code. In this way, they provide a fast technology to create dynamic pages.
In addition, JSP has all the characteristics of Java:
JSPs are multithreaded.
JSPs are portable.
JSPs are object-oriented.
JSPs are secure.
1.3.3 Java Servlets
As we have used in our web site’s code also a little bit Java Servlets, it would be right if we
speak about them too[12].
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
Servlets Architecture
Following diagram shows the position of Servelts in a Web Application.
Picture 7 – Position of Servlets in a Web Application
Servlets Tasks
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.
2. PriceMeter design and implementation
The name of the second chapter is PriceMeter design and implementation. Here I decided to write about database, desktop application and Web site. In subchapter database I in details spoke about creating process of the database which I used for saving information about prices in different countries. In “desktop application” there is description of the process how I created PriceMeter desktop version. Finally, in the subchapter “Web site” I decided to show to a reader how I made modifications on Twitter’s Bootstrap template and made it all necessary changes to reach our goal, create a web version of PriceMeter.
2.1 DataBase
Initially, it is important to notice that our database is created by using MySql. As a platform I preferred to use SQLyog, since it has a nice and easy interface, besides, during a table creating process you can see how they look. SQLyog is one of the most MySql based platforms, as it gives an opportunity to create database even without using any query.
Final version of our database looks like this:
Picture 8 – The database construction
So lets discuss our database and understand how and why are constructed its tables. The first and the main table is << Product >> table.
Picture 9 – Product table
As you can see from picture is has following columns:
id – which is an unique identifier for every single product
Name – in this column I decided to save names of product, like << Lunch >>, << Meal >> and so on. Price – it is easy to understand that here are prices of products
PriorityId – this is a Foreign Key which is connecting our << Product >> table with table named << Priority >>
CountryId – this is a Foreign Key which is connecting our << Product >> table with table named << Country >>
CategoryId – this is a Foreign Key which is connecting our << Product >> table with table named << Category >>
Now it is time to speak about table << Priority >>. In that table we save our list with priorities.
Picture 10 – Priority table
As you can see here we have just a two columns. The first one is unique identifier, which is insuring that we will not have any repeating priorities.
The second column is for saving names of priorities. As you can see we have only three priorities- Student, Tourist and Businessman.
The table << Country >> is almost the same with the previous table. The only difference is that here are saved names of countries.
Picture 11 – Country table
The column id is doing exactly the same function as in the previous situation. In the column << Name >>, currently, we have only two countries, they are Armenia and Romania.
And the last table is << Category >>. This one is also almost the same as previous two tables.
Picture 12 – Category table
Here the id field is a Primary Kay too. In the next column we save names of our categories, at this moment we have three categories Outside, Shop and Transport.
During creating database I have used such queries as CREATE, USE SELECT, INSERT. Lets speak a little bit about each one.
CREATE
Here is generic SQL syntax to create a MySQL table[13]:
CREATE TABLE table_name (column_name column_type);
Now, we will create following table in tutorilas database.
tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT, tutorial_title VARCHAR(100) NOT NULL, tutorial_author VARCHAR(40) NOT NULL, submission_date DATE,
PRIMARY KEY ( tutorial_id )
);
Here few items need explanation:
Field Attribute NOT NULL is being used because we do not want this field to be NULL. So if user will try to create a record with NULL value, then MySQL will raise an error.
Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field.
Keyword PRIMARY KEY is used to define a column as primary key. You can use multiple columns separated by comma to define a primary key.
USE
Once you get connection with MySQL server, it is required to select a particular database to
work with. This is because there may be more than one database available with MySQL Server.
Here is an example to select database called TUTORIALS:
[root@host]# mysql -u root -p Enter password:****** mysql> use TUTORIALS; Database changed
mysql>
Now, you have selected TUTORIALS database and all the subsequent operations will be performed on TUTORIALS database.
All the database names, table names, table fields name are case sensitive. So you would have to use proper names while giving any SQL command.
SELECT
The SQL SELECT command is used to fetch data from MySQL database[14]. You can use this command at mysql> prompt as well as in any script like PHP.
Here is generic SQL syntax of SELECT command to fetch data from MySQL table:
SELECT field1, field2,…fieldN table_name1, table_name2… [WHERE Clause]
[OFFSET M ][LIMIT N]
You can use one or more tables separated by comma to include various conditions using a
WHERE clause, but WHERE clause is an optional part of SELECT command.
You can fetch one or more fields in a single SELECT command.
You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
You can specify any condition using WHERE clause.
You can specify an offset using OFFSET from where SELECT will start returning records. By default offset is zero.
You can limit the number of returns using LIMIT attribute.
INSERT
To insert data into MySQL table, you would need to use SQL INSERT INTOcommand. You can insert data into MySQL table by using mysql> prompt or by using any script like PHP[15].
Here is generic SQL syntax of INSERT INTO command to insert data into MySQL table:
INSERT INTO table_name ( field1, field2,…fieldN ) VALUES
( value1, value2,…valueN );
To insert string data types, it is required to keep all the values into double or single quote, for example:- "value".
DELETE
If you want to delete a record from any MySQL table, then you can use SQL command DELETE FROM. You can use this command at mysql> prompt as well as in any script like PHP.
Here is generic SQL syntax of DELETE command to delete data from a MySQL table:
DELETE FROM table_name [WHERE Clause]
If WHERE clause is not specified, then all the records will be deleted from the given MySQL
table.
You can specify any condition using WHERE clause.
You can delete records in a single table at a time.
The WHERE clause is very useful when you want to delete selected rows in a table.
UPDATE
There may be a requirement where existing data in a MySQL table needs to be modified. You can do so by using SQL UPDATE command. This will modify any field value of any MySQL table.
Here is generic SQL syntax of UPDATE command to modify data into MySQL table:
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
You can update one or more field altogether.
You can specify any condition using WHERE clause.
You can update values in a single table at a time.
The WHERE clause is very useful when you want to update selected rows in a table.
PRIMERY KEY
A primary key is a column or a set of columns that uniquely identifies each row in the table. You must follow the rules below when you define a primary key for a table:
A primary key must contain unique values. If the primary key consists of multiple columns, the combination of values in these columns must be unique.
A primary key column cannot contain NULL values. It means that you have to declare the primary key column with the NOT NULL attribute. If you don’t, MySQL will force the primary key column as NOT NULL implicitly.
A table has only one primary key.
Because MySQL works faster with integers, the data type of the primary key column should be the integer e.g., INT, BIGINT.You can choose a smaller integer type: TINYINT, SMALLINT, etc. However, you should make sure that the range of values of the integer type for the primary key is sufficient for storing all possible rows that the table may have.
A primary key column often has the AUTO_INCREMENT attribute that generates a
uniquesequence for the key automatically. The primary key of the next row is greater than the previous one.
table.
MySQL creates an index named PRIMARY with PRIMARY type for the primary key in a
FOREIGN KEY
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
If a table has a primary key defined on any field(s), then you can not have two records having the same value of that field(s).
2.2 Desktop application
In our program we have six important classis on which I want to pay attention, that classes are: Patuhan, Diagram, DialogOutside, DialogShop, DialogTransport and DialogError[16]. Each one has its oven functionality and its significant roll in our program.
The class Patuhan is responsible for the main frame and content on it. As you can see from the window it has three buttons, three labels three list.
For the size, label text and background is responsible the following part of the code:
protected void createContents() {
shell = new Shell();
D));
shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUN
shell.setSize(450, 300);
shell.setText("PriceMeter");
So as you can see here we are setting the beckground color, the size of the main frame, which is
450 on 300, and the label which will be set on the left upper corner of the frame, in our case that label
is the text “PriceMeter”.
Labels are the simplest components of JFrame panel. With the JLabel we can show text with icon. If you need any component to display some message to the user or to enter the field to make a text label or an icon to show you have to use a JLabel. The text that shows the JLabel can not be copied or edited, only watched. In our case we have the following labels: lblCountry, lblPriority and lblType.
Picture 13 – PriceMeter main window with selected labels
The process of their creation and size initialization is looking like this: Label lblCountry = new Label(shell, SWT.NONE);
lblCountry.setBounds(23, 50, 55, 15);
lblCountry.setText("Country");
Label lblPriority = new Label(shell, SWT.NONE); lblPriority.setBounds(136, 50, 55, 15); lblPriority.setText("Priority");
Label lblType = new Label(shell, SWT.NONE); lblType.setBounds(261, 50, 34, 15); lblType.setText("Type");
A JList in Java Swing is used to display data in a list. JList can be configured in different ways as you like[17, 18]. On our frame we have list for chossing country, priority and type.
Picture 14 – PriceMeter main window with selected lists
Below is the code for the list for choosing countries.
List list = new List(shell, SWT.BORDER);
list.setItems(new String[] {"Armenia", "Romania"}); list.setBounds(10, 80, 86, 68); list.setToolTipText("Choose a country");
final List list1= list;
list.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
tiv_country= list1.getSelectionIndex();
switch (e.type) {
case SWT.MouseDown:
break;
}
}});
For switching between possible choices I preferred to do not use if/ else or case statements. There is an easier method for organizing that process. We can make Enum classes and work with them.
Enum is a type field which consist of a set of some constants. A simple example of it is the compass, this object will contain 4 constant: NORTH, SOUTH, EAST, and WEST. The variables declared in large letters, because they are constants.
Lets discuss Enums on our projet’s example:
package Enums;
public enum Country
{
ARMENIA, ROMANIA;
public static final int size = 2;
public static Country fromInteger(int countryIndex)
{
return values()[countryIndex];
}
public static int toInteger(Country country)
{
for ( int i = 0; i < size; ++i )
if ( country.equals( values()[i] ) )
return i;
return -1;
}
}
Here we have an Enum class which we named <<Country>>. As you can see there are two fields, choices, ARMENIA and ROMANIA ( of course in future we will have more ). By the variable size we are initializing the length of enum, in our case it is just two. The idea of enum is to do not use long if and else statements, here we need just to list the possible choices and depending on the choice the program will execute some code.
The other enum classes for the Type and Priority have almost the same configuration. The only difference is the list of choices.
Each application that provides a graphical user interface can not do without buttons. In Java Swing button is shown in the JButton class. Button have different methods for its configuration – setting the inscriptions on the JButton, installation icons, text alignment, sizing and so on. In addition, the developer needs to hang on the listener JButton that will be executed when the user clicks the button. And now lets see how it is working on the example of our btnExit ( << Exit >> )[19].
Button btnExit= new Button(shell, SWT.NONE);
btnExit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
}
});
btnExit.setBounds(220, 210, 75, 25); btnExit.setText("Exit"); btnExit.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.MouseDown: System.exit(0);
}
}
});
As you can see, when the user clicks on this button the class handleEvent gets run and as a result our window gets close.
However, the main functionality of the program mades button OK. Initially, when the user pushes OK button, the code generates several objects of the several classes.
btnOk.addListener(SWT.MouseDown, new Listener() { public void handleEvent(Event e) { switch (e.type) {
case SWT.MouseDown:
DialogOutside patuhan2= new DialogOutside(); DialogShops patuhan3= new DialogShops(); DialogTransport patuhan4= new DialogTransport();
DialogError patuhanError= new DialogError();
After it tries to make a connection between database and the Java program ( that process will be discussed a little bit letter ) and if everything goes ok it starts to generate queries. It looks like this:
if (tiv_country!=-1 || tiv_priority!=-1 || tiv_tesak!=-1)
{
String query = "SELECT * FROM Product WHERE PriorityId = " + (tiv_priority+1) + " AND CountryId = " + (tiv_country+1) + " AND CategoryId = " + (tiv_tesak+1);
ResultSet rs= stmt.executeQuery(query); patuhan2.results = rs; patuhan2.DialogOutside(); ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount(); System.out.println(columnsNumber);
}
As you can see firstly it checks are all choices made or not. If they all are made ( a vice versa situation will be discussed letter ) query gets generated and the result of it would be shown in the new window.
But if not all choices were selected. We will have a new informational window where the user will be announced about that problem. That part looks looks the following way:
if (tiv_country==-1 || tiv_priority==-1 || tiv_tesak==-1)
{
patuhanError.DialogError();
}
So here everything is very simple. The program checks and if not all choices were selected it calls DialogError class by using its patuhanError object.
Now it is time to look throw the DataBase and Java connection process[20]. As in most of Java programs, where is needed connection between Java and MySql, in PriceMeter also is used JDBC. For making a successful connection with our database I have used the following code:
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/ros", "root", "");
System.out.println("Connection success");
}
catch ( Exception ee ) { System.err.println(ee);
}
As you can see here we have a try and catch combination. The try part is doing all useful work such as making connection with a database, sending different queries and getting results. In our case it
is just making a connection with database named “ros”, with an username “root” and without password.
After that process it is simply printing “Connection success”.
The second part of the code is responsible for exceptions which can occur during the work process of the first part. If there would be any errors it will notify as about them in the console. That is making a work of a programmer the way easier.
So when the user makes choices and pushes the “OK” button the program makes connection with our database and considering with the user’s choice sends query. If all goes ok with sending of a query the program calls the necessary secondary window’s class and as a result the user sees the new secondary frame with searched database. But if something goes wrong, like when the user forgets to make one or several choices the program call the class called “DialogError”. That class opens a new secondary window and informs the user that something goes wrong, so after that notification the user probably will make new search with complete searching details.
Now lets speak a little bit about the last but not less important part of our program, about the
“Show diagram” button. As all other buttons this one also has an action listener and when the user
clicks on it PM calls class named “Diagram”. The idea of this class is to show some diagrams based on database. Currently, it shows the average prices diagrams for Armenia and Romania.
For creating diagrams I used well known JFreeChart library, which is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. Our “Diagram” class takes all necessary information from the database by itself. After it makes some calculations and opens a new secondary window. In that window it puts all mandatory components and of course the diagrams. So as a result of a click on the “Show diagram” button the user sees a new window with diagrams on it[21. 22].
Now lets pay attention on Diagram button’s code:
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/ros", "root", ""); System.out.println("Connection success");
String query1 = "SELECT AVG(Price) AS PriceAverageArmenia
FROM Product WHERE CountryID=1";
String query2 = "SELECT AVG(Price) AS PriceAverageRomania
FROM Product WHERE CountryID=2";
java.sql.Statement stmt1= conn.createStatement(); ResultSet rs1 = stmt1.executeQuery(query1); java.sql.Statement stmt2= conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
Immediately after clicking on the button the program generates the code which makes a connection between database and the Java program and prints “Connection success”, this is just for developers, to make him know that there were no problems connected with the connection process.
After making sure that there is stabile connection between our database and Java program it sends queries to figure out the average prices for countries. After getting that prices the programs forwards them to the Diagram class. And finally, the Diagram class creates a new window and shows that averages as graphics.
2.3 Web site
After discussing so much about PriceMeter desktop application it is time speak a little bit about PriceMeter web version too. Here mostly I have used Twitter’s Bootstrap technology, of course, I have modificated it a lot to get the necessary results.
Initially, I want to explain about user and admin filtering processes and bellow is the admin identification process:
User user = (User) session.getAttribute(Constant.SESSION_USER);
if(user == null) {
session.setAttribute(Constant.MSG_ERROR,"Please sign in,The session was expired"); ((HttpServletResponse) resp).sendRedirect("/go/login");
return;
} else if(user.getRole().getId() != UserRole.ADMIN.getId()) {
session.setAttribute(Constant.MSG_ERROR,"The page not allowed, Please sign in with your user account");
((HttpServletResponse) resp).sendRedirect("/go/login");
return;
}
So all is maximally simple, the user tries to login and if his username and password match with admin’s he enter as an admin into admin’s account. However, if they do not much the program shows an informational message and informs an user “The page not allowed, Please sign in with your user account”.
Now lets see what happens when an user tries to login as an user. User user = (User) session.getAttribute(Constant.SESSION_USER);
if(user == null) {
session.setAttribute(Constant.MSG_ERROR,"Please sign in,The session was expired"); ((HttpServletResponse) resp).sendRedirect("/go/login");
return;
} else if(user.getRole().getId() != UserRole.USER.getId()) {
session.setAttribute(Constant.MSG_ERROR,"The page not allowed, Please sign in with your user account");
((HttpServletResponse) resp).sendRedirect("/go/login");
return;
}
As you can see the code is almost the same with a previous one and the only difference is that
here program search for matching in the user list, not in the admin list.
Now, when the logic is clear we can start exploring of the sign up and the sign in processes. When a new user comes to our web site and wants to use functions of PriceMeter he has to register on site by filling a very simple application. Now lets see the code part which is responsible for that.
String name = request.getParameter("name");
String surname = request.getParameter("surname"); String email = request.getParameter("email");
String password = request.getParameter("password");
if (Utils.isEmpty(name)) {
forward(request, response, "Invalid name");
return;
}
if (Utils.isEmpty(surname)) {
forward(request, response, "Invalid surname");
return;
}
if (Utils.isEmpty(email)) {
forward(request, response, "Invalid email");
return;
}
if (Utils.isEmpty(password)) {
forward(request, response, "Invalid password");
return;
}
He will be asked to enter his name, surname, email address and password. Every time when he will fill the fields program automatic checks if everything is ok and if someone from that fields have a wrong content it announces the user by showing message like “Invalid name” or “Invalid password”.
The next and the one of the most important steps is hiding password. We need that process since someone can hack and steel users information from the site. To protect our users from hacking attacks we are encrypting password using SHAHash. That process is hard to explain but it looks very easy:
try {
password = SHAHashEnrypt.getMD5SecurePassword(password);
} catch (EncryptException e) {
e.printStackTrace();
}
Program tries to encrypt password and if something goes wrong with it, it throws an exception.
In the next step the site saves all user’s information into his base.
It is logical after discussing sign up process discuss sign in process. So here the program asks to enter email and password.
String email = request.getParameter("email");
String password = request.getParameter("password");
if (Utils.isEmpty(email)) {
forward(request, response, "Invalid email");
return;
}
if (Utils.isEmpty(password)) {
forward(request, response, "Invalid password");
return;
}
So an user enters them and site immediately starts to check them with its users details list. If field or fields are empty it gives the following error/ errors “invalid email”, “Invalid password”. But if they are not empty the program starts to decrypt the password from his database to check with an entered one.
try {
password = SHAHashEnrypt.getMD5SecurePassword(password);
} catch (EncryptException e) {
e.printStackTrace();
}
The following step depends on the previous one, so if the email and password were correct program checks the user’s role in the system, if he is admin enters to the admin panel, if he a regular user he enters to the user panel.
User user = userManager.getByEmailAndPassword(email, password); HttpSession session = request.getSession(); session.setAttribute(Constant.SESSION_USER, user);
String role = user.getRole().getRole();
String nextJSP = String.format("/%s/home", role);
response.sendRedirect(nextJSP);
However, there can be some situations when entered details are wrong or the site has an internal error. For that cases we have the following part of the code which provides a user with a necessary information:
catch (InternalErrorException e) {
forward(request, response, "An internal Error occurred please try later");
return;
} catch (EntityNotFoundException e) { forward(request, response, "Could not find user"); return;
}
The next very import think which I want to explain are DAOs. If you have look throw ProductCategoryManagerImpl, SurveyManagerImpl or ProductTypeManagerImpl there everywhere are used DAOs, it is right even to say that they are based on DAOs. DAOs are Data Access Objects.
They are responsible for working with database. Every time when we make a survey or a user fills it we use DAOs to send and get information from our database. They are pretty common with jdbc in Java.
public ProductCategoryManagerImpl(){
productCategoryDao = new ProductCategoryDaoImpl();
}
Usually in JSP when we use constants we use jaspers, however, using of JasperReports is very popular. JasperReports is an open source Java reporting tool that can write to a variety of targets, such as: screen, a printer, into PDF, HTML, Microsoft Excel, RTF, ODT, Comma-separated values or XML files. It can be used in Java-enabled applications, including Java EE or web applications, to generate dynamic content. It reads its instructions from an XML or .jasper file.
3. PriceMeter at work
The last but not less important chapter is “PriceMeter at work”. As you can understand from the name of the chapter here I spoke about utilization process of PriceMeter. I deeply discussed working process of the program, I explained which button what functionality has, what results we see then sending survey answers and so on.
3.1 Desktop version of PriceMeter
As almost all desktop applications, PriceMeter also has a Graphic User Interface ( GUI ). As
you can see from the imagine shown below it has very simply interface, that is done to make a working process maximally easy and fast.
Picture 15 – PriceMeter main window
There are just three columns and three buttons, nothing more. From that columns user can choose necessary criterias
Picture 16 – PriceMeter main window with some selections from the lists and by clicking on the OK button send a request to the program.
PM will analyze that request and send query to his DataBase. After a couple of milliseconds our program will open a new frame ( secondary frame ) there he will show the results of the request. That frame will look similar with the screenshot shown below.
Picture 17 – PriceMeter main and secondary windows with some selections from the lists and query result based on them
In the presented picture, as you can see, there were selected the choices fields:
1) from the field named << Country >> there was chosen as a choice << Armenia >>
2) from the field named << Priority >> there was chosen as a choice << Tourist >>
3) from the field named << Type >> there was chosen as a choice << Outside >>
PriceMeter has send query to his database and has got an answer from it. As you can see from the shown imagine as a result of user’s request it shows prices for Lunch and Meal which costs 1.5$ and 4.5$ for a tourist in Armenia.
Often there are situations when we forget to make a selection in programs. Of course, every complete program has to know what to do in that case, how to handle that exception. As all normal programs, PriceMeter also know how to response to such situations without lagging or giving fatal errors. In case when user forgot to select one or several choices our program opens the following informational secondary window.
Picture 18 – PriceMeter main and secondary windows with error information on it
And now lets speak about the last button, about << Show diagram >>. When a user clicks on it the program sends several queries to DataBase and calculates the price average for all countries which are listed in the << Country >> list. As a result of that calculations we can see the following screenshot:
Picture 19 – PriceMeter main and secondary windows with price average graphics
3.2 Web version of PriceMeter
After seeing the desktop version of PM it is time to see also the web one too. The site is constructed mainly by using JSP programing language.
The site has made as simple as it was possible. So everyone can use it without any problem.
The first step is starting from the registration form. As you can see from the attached screenshot, the registration procedure is very simple and does not request any extra information from a user. It is asking just for a basic information, such as a name, surname, username and the password.
Picture 20 – registration page
After completing the registration form user can login to his new created account by using his/
her username and password. The login form also easy one. The imagine of the login for is below:
Picture 21 – login page
If the user successfully passed that procedure he/ she sees the following page. There the user has a possibility to choose the interested function, such as downloading the desktop application of PriveMeter or searching for a necessary information using the web page. By the way, during the watching of the results of the search user can also correct the answers. That will give an extra chance to PM to always have actual database.
Picture 22 – user’s account
Of course our web does not have only the user pages, it has also admin page. Which is looking
almost similar with a user’s one.
Picture 23 – admin’s account
From here admin can control the existing database or to create the new one. For that he needs only to click on << Survey Layouts >>.
Picture 24 – admins account, survey page
As I told previously all is made maximum simple for use. The moderating process of the database is not an exception. If the database is not actual admin can anytime click on << Product Layouts >> and moderate it.
Picture 25 – admins account, survey adding page
Conclusion
In the first chapter we discussed about used programming languages, platforms and programs. Here I provided an information to reader about databases and especially about MySql since in my program I used MySql. Except databases I also wrote about the used programing languages such as Java for desktop application and Java Server Pages ( JSP ) for web version. Also there were provided
information about Java Servlets as in some parts of the web version’s code there were used servlets too.
So the main target of the first chapter was to provide a reader with a necessary information which will help him/ her to understand works from the second and the third chapters.
The second chapter is mainly about the stapes of PriceMeter creation. In this chapter I explained in details the whole process of the program’s creation process. I have discussed the database creation, the desktop application’s code writing process and of course the way how I connected them between each other. As my program has also a web version I wrote about its main parts too.
As a result of the reading the second chapter person gets deep knowledge in PriceMeter creation process.
The last, third chapter is about what results PriceMeter shows during the work process. I
showed reader how works the desktop version, what results it shows in different situations. Of course, I
also provided information about work process of the web version.
So the third chapter is a practical implementation of the second chapter.
Summing everything I can say for sure that I have reached the major mission of my dissertation work by creating and providing a complete programing product. I believe that PriceMeter will be very helpful program as for tourists as for native population of a countries.
Futures
In future I am planning to continue developing of PriceMeter to make it more and more complete. However it is ready for use even now and certainly it can make easier traveling process starting from this moment.
As future design I see the following points:
1) making the desktop application more nice and hospital by adding some new designing solutions
2) making the web version of PriceMeter more nice and hospital by adding some new designing solutions
3) adding possibility to choose more narrow destinations
4) adding new functionalities like finding prices for current location point by using internet
5) as we are living in the internet century and the most of us spends more and more time in social networks, I want to add also possibilities of share, like, dislike and comment of information provided by PriceMeter in a social network
6) more optimize the algorithms of the desktop application
7) since today almost everyone has smartphone, tablet and other gadgets, I want to create also a PriceMeter version for mobile equipments too. Soon I plan to make an Android version of PriceMeter. As desktop and web versions it will be totally free.
This futures will make PriceMeter more popular and comfortable. With adding newer and newer technologies I want to make PriceMeter a worldwide known product.
Bibliography
1. Bвeдeниe в базы данныx, http://www.codenet.ru/progr/vbasic/vb_db/1.php, Last accessed:
05.06.2016
2. Базы данныx, http://flash-library.narod.ru/Ch-Informatics/lektion/lektion7.html, Last accessed:
05.06.2016
3. ЧTO TAКOE БAЗЫ ДAHHЫX?, http://www.limm.mgimo.ru/LIMM/inform/db_intro.html, Last
accessed: 05.06.2016
4. Интepнeт и базы данныx. Чаcть 02. Hopмализация базы данныx, http://www.wwwmaster.ru/13- internet-i-bazy-dannyh-chast-02-normalizaciya-bazy-dannyh, Last accessed: 05.06.2016
5. Pyкoвoдcтвo пo пpoeктиpoванию peляциoнныx баз данныx, https://habrahabr.ru/post/193756/,
Last accessed: 05.06.2016
6. Пpoeктиpoваниe баз данныx. Hopмализация, http://club.shelek.ru/viewart.php?id=311, Last
accessed: 05.06.2016
7. Hopмализация oтнoшeний. Шecть нopмальныx фopм, https://habrahabr.ru/post/254773/, Last
accessed: 05.06.2016
8. Bвeдeниe в интeгpиpoваннyю cpeдy pазpабoтки Eclipse,
http://www.javaportal.ru/java/ide/intro_eclipse.html, Last accessed: 05.06.2016
9. JSP: Java Server Pages, http://www.javaportal.ru/java/articles/jsp.html, Last accessed: 05.06.2016
10. Чтo такoe JSP, http://www.javaprobooks.ru/java-
%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80% D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5/%D1%87%D1%82%D0%BE-
%D1%82%D0%B0%D0%BA%D0%BE%D0%B5-jsp.html, Last accessed: 05.06.2016
11. Java Server Pages – Introduction, http://ccm.net/faq/29751-java-server-pages-introduction, Last accessed: 05.06.2016
12. Servlets – Overview, http://www.tutorialspoint.com/servlets/servlets_overview.htm, Last accessed:
05.06.2016
13. Create MySQL Tables, http://www.tutorialspoint.com/mysql/mysql-create-tables.htm, Last accessed: 05.06.2016
14. MySQL Select Query, http://www.tutorialspoint.com/mysql/mysql-select-query.htm , Last accessed: 05.06.2016
15. MySQL Insert Query, http://www.tutorialspoint.com/mysql/mysql-insert-query.htm, Last accessed:
05.06.2016
16. Coзданиe нecкoлькиx oкoн в пpилoжeнии, http://javatalks.ru/topics/19925?page=1#!prettyPhoto, Last accessed: 05.06.2016
17. JList, https://thenewboston.com/videos.php?cat=31&video=18035, Last accessed: 05.06.2016
18. Java Eclipse GUI Tutorial 18 # How to link JList with Sqlite database in Java, https://www.youtube.com/watch?v=xZ2ijmDbU50&index=21&list=PLS1QulWo1RIbYMA5Ijb72QH aHvCrPKfS2, Last accessed: 05.06.2016
19. Как закpыть JFrame или JDialog, http://rsdn.ru/forum/java/1180691.all, Last accessed: 05.06.2016
20. How to connect Java and MySQL in Eclipse, https://www.youtube.com/watch?v=CrHZIW9pnnQ, Last accessed: 05.06.2016
21. JFreeChart – Pie Chart, http://www.tutorialspoint.com/jfreechart/jfreechart_pie_chart.htm, Last accessed: 05.06.2016
22. JFreeChart – Bar Chart, http://www.tutorialspoint.com/jfreechart/jfreechart_bar_chart.htm, Last accessed: 05.06.2016
Annexes
Anexa 1 MySQL database dump
/*
SQLyog Ultimate v9.20
MySQL – 5.5.18 : Database – ros
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ros` /*!40100 DEFAULT CHARACTER SET
latin1 */; USE `ros`;
/*Table structure for table `category` */ DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(31) NOT NULL AUTO_INCREMENT,
`Name` varchar(31) NOT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*Data for the table `category` */
insert into `category`(`id`,`Name`) values (1,'Outside'),(2,'Shop'),(3,'Transport');
/*Table structure for table `country` */ DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(31) NOT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*Data for the table `country` */
insert into `country`(`id`,`Name`) values (1,'Armenia'),(2,'Romania');
/*Table structure for table `priority` */ DROP TABLE IF EXISTS `priority`;
`PriorityName` varchar(31) NOT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*Data for the table `priority` */
insert into `priority`(`id`,`PriorityName`) values (1,'Student'),(2,'Tourist'),(3,'Businessman');
/*Table structure for table `product` */ DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Price` double(5,3) NOT NULL,
`PriorityId` int(11) NOT NULL,
`CountryId` int(11) NOT NULL,
`CategoryId` int(11) NOT NULL,
`UnitId` int(11) DEFAULT NULL, PRIMARY KEY (`id`),
KEY `FK1_Product` (`PriorityId`), KEY `FK2_Product` (`CountryId`), KEY `FK3_Product` (`CategoryId`),
CONSTRAINT `FK1_Product` FOREIGN KEY (`PriorityId`) REFERENCES `priority` (`id`), CONSTRAINT `FK2_Product` FOREIGN KEY (`CountryId`) REFERENCES `country` (`id`), CONSTRAINT `FK3_Product` FOREIGN KEY (`CategoryId`) REFERENCES `category` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=latin1;
/*Data for the table `product` */
insert into `product`(`id`,`Name`,`Price`,`PriorityId`,`CountryId`,`CategoryId`,`UnitId`) values (1,'Lunch',2.500,1,2,1,0),(2,'Meal',3.100,1,2,1,0),(3,'Lunch',2.900,2,2,1,NULL),(4,'Meal',3.600,2,2,1,N ULL),(5,'Lunch',3.500,3,2,1,NULL),(6,'Meal',7.000,3,2,1,NULL),(7,'Milk',0.600,1,2,2,NULL),(8,'Brea d',0.200,1,2,2,NULL),(9,'Milk',0.720,2,2,2,NULL),(10,'Bread',0.240,2,2,2,NULL),(11,'Milk',0.800,3,2,
2,NULL),(12,'Bread',0.240,3,2,2,NULL),(13,'Bus',0.320,1,2,3,NULL),(14,'Taxi',0.340,1,2,3,NULL),(1
5,'Bus',0.320,2,2,3,NULL),(16,'Taxi',0.440,2,2,3,NULL),(17,'Bus',0.320,3,2,3,NULL),(18,'Taxi',0.950,
3,2,3,NULL),(19,'Lunch',1.300,1,1,1,NULL),(20,'Meal',2.500,1,1,1,NULL),(21,'Lunch',1.500,2,1,1,NU LL),(22,'Meal',4.500,2,1,1,NULL),(23,'Lunch',1.500,3,1,1,NULL),(24,'Meal',5.000,3,1,1,NULL),(25,' Milk',0.750,1,1,2,NULL),(26,'Bread',0.400,1,1,2,NULL),(27,'Milk',0.750,2,1,2,NULL),(28,'Bread',0.40
0,2,1,2,NULL),(29,'Milk',0.750,3,1,2,NULL),(30,'Bread',0.400,3,1,2,NULL),(31,'Bus',0.200,1,1,3,NUL L),(32,'Taxi',0.200,1,1,3,NULL),(33,'Bus',0.200,2,1,3,NULL),(34,'Taxi',0.200,2,1,3,NULL),(35,'Bus',0.
200,3,1,3,NULL),(36,'Taxi',0.400,3,1,3,NULL);
/*Table structure for table `unit` */ DROP TABLE IF EXISTS `unit`;
CREATE TABLE `unit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(51) NOT NULL, PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `unit` */
/*Table structure for table `user` */ DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`UserName` varchar(31) NOT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `user` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Anexa 2 Java class Patuhan
import java.awt.BorderLayout; import java.awt.Desktop.Action; import java.awt.EventQueue; import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton;
import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Tree; import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import Enums.Country;
import com.mysql.jdbc.Statement;
import javax.naming.spi.DirStateFactory.Result;
import org.jfree.experimental.swt.SWTGraphics2D;
import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import javax.net.ssl.HttpsURLConnection; import Enums.*;
public class Patuhan {
private int tiv_country=-1; private int tiv_priority=-1; private int tiv_tesak=-1; boolean cb1=false;
boolean cb2=false;
boolean cb3=false;
protected Shell shell;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Patuhan window = new Patuhan();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
D));
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUN
shell.setSize(450, 300);
shell.setText("PriceMeter");
// List –––––––––––––––––––––––––––- Label lblCountry = new Label(shell, SWT.NONE); lblCountry.setBounds(23, 50, 55, 15); lblCountry.setText("Country");
Label lblPriority = new Label(shell, SWT.NONE); lblPriority.setBounds(136, 50, 55, 15); lblPriority.setText("Priority");
List list = new List(shell, SWT.BORDER); list.setItems(new String[] {"Armenia", "Romania"}); list.setBounds(10, 80, 86, 68); list.setToolTipText("Choose a country");
final List list1= list;
list.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
tiv_country= list1.getSelectionIndex(); System.out.println(tiv_country);
switch (e.type) {
case SWT.MouseDown: System.out.println("Erkrir@ @ntrvats e"); break;
}
}
});
List list_1 = new List(shell, SWT.BORDER);
list_1.setItems(new String[] {"Student", "Tourist", "Businessman"});
list_1.setBounds(115, 80, 86, 68); list_1.setToolTipText("Choose a priority"); final List list2= list_1;
list_1.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
tiv_priority= list2.getSelectionIndex(); System.out.println(tiv_priority);
switch (e.type) {
case SWT.MouseDown: System.out.println("Prioritet@ @ntrvats e"); break;
}
}
});
List list_3 = new List(shell, SWT.BORDER);
list_3.setItems(new String[] {"Outside", "Shop", "Transport"}); list_3.setBounds(220, 80, 86, 68); list_3.setToolTipText("Choose a type");
final List list3= list_3;
list_3.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
tiv_tesak= list3.getSelectionIndex(); System.out.println(tiv_tesak);
switch (e.type) {
case SWT.MouseDown: System.out.println("Tesak@ @ntrvats e"); break;
}
}
});
// List end ––––––––––––––––––––––––––
// Button ––––––––––––––––––––––––––– Button btnOk = new Button(shell, SWT.NONE); btnOk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
btnOk.setBounds(320, 210, 75, 25);
btnOk.setText("OK");
btnOk.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.MouseDown: System.out.println("Sax lava");
DialogOutside patuhan2= new DialogOutside(); DialogShops patuhan3= new DialogShops(); DialogTransport patuhan4= new DialogTransport(); DialogError patuhanError= new DialogError(); if(testInet("http://localhost:8181/downloadv_12")){
System.out.println(
"Online: "
);
}
else { System.out.println("Offline");
}
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/ros", "root", "");
System.out.println("Connection success");
java.sql.Statement stmt= conn.createStatement();
{
if (tiv_country!=-1 || tiv_priority!=-1 || tiv_tesak!=-1)
{
String query = "SELECT * FROM Product WHERE PriorityId = " + (tiv_priority+1) + " AND CountryId = " + (tiv_country+1) + " AND CategoryId = " + (tiv_tesak+1);
ResultSet rs= stmt.executeQuery(query); patuhan2.results = rs; patuhan2.DialogOutside(); ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount(); System.out.println(columnsNumber);
}
}
if (tiv_country==-1 || tiv_priority==-1 || tiv_tesak==-1)
{
patuhanError.DialogError();
}
}
catch ( Exception ee ) { System.err.println(ee);
}
}
}
});
Button btnExit = new Button(shell, SWT.NONE);
btnExit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
}
});
btnExit.setBounds(220, 210, 75, 25);
btnExit.setText("Exit");
Label lblType = new Label(shell, SWT.NONE); lblType.setBounds(261, 50, 34, 15); lblType.setText("Type"); btnExit.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.MouseDown: System.out.println("Elq"); System.exit(0);
}
}
});
Button btnDiagram = new Button(shell, SWT.NONE);
btnDiagram.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
}
});
btnDiagram.setBounds(320, 101, 88, 25);
btnDiagram.setText("Show diagram");
btnDiagram.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.MouseDown:
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/ros", "root", "");
System.out.println("Connection success");
String query1 = "SELECT AVG(Price) AS PriceAverageArmenia
FROM Product WHERE CountryID=1";
String query2 = "SELECT AVG(Price) AS PriceAverageRomania
FROM Product WHERE CountryID=2";
java.sql.Statement stmt1= conn.createStatement(); ResultSet rs1 = stmt1.executeQuery(query1); java.sql.Statement stmt2= conn.createStatement(); ResultSet rs2 = stmt2.executeQuery(query2); if(rs1.next() && rs2.next()){
double average1 = rs1.getDouble("PriceAverageArmenia");
double average2 = rs2.getDouble("PriceAverageRomania");
{
averages", "", rs1, rs2);
{
Diagram chart = new Diagram("The diagram of price
chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true );
}
}}
}catch ( Exception ee ) { System.err.println(ee);
}
}
}
});
// Button end –––––––––––––––––––––––––-
}
public static boolean testInet(String site) { Socket sock = new Socket();
InetSocketAddress addr = new InetSocketAddress(site,80);
try { sock.connect(addr,3000); return true;
} catch (IOException e) {
return false;
} finally {
try {sock.close();}
catch (IOException e) {}
}
}
}
Anexa 3 Java class Diagram
import java.sql.ResultSet; import Enums.Country; import Enums.Type;
import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class Diagram extends ApplicationFrame
{
public Diagram( String applicationTitle , String chartTitle, ResultSet rs1, ResultSet rs2 )
{
super( applicationTitle );
JFreeChart barChart = ChartFactory.createBarChart(
chartTitle, "Average prices", "Price", createDataset(rs1, rs2),
PlotOrientation.VERTICAL,
true, true, false);
ChartPanel chartPanel = new ChartPanel( barChart ); chartPanel.setPreferredSize(new java.awt.Dimension( 560 , 367 ) ); setContentPane( chartPanel );
}
public CategoryDataset createDataset(ResultSet rs1, ResultSet rs2)
{
final DefaultCategoryDataset dataset =
new DefaultCategoryDataset( );
double average1=0.0; double average2=0.0; try {
average1 = rs1.getDouble("PriceAverageArmenia");
average2 = rs2.getDouble("PriceAverageRomania");
} catch ( Exception ee ) { System.err.println(ee);
}
String arm = "Armenia"; String rom = "Romania";
final String av = "";
dataset.addValue( average1 , arm , av ); dataset.addValue( average2 , rom , av ); return dataset;
}
}
Anexa 4 Java class DialogError
import java.awt.EventQueue; import java.awt.EventQueue; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import javax.swing.JTextArea; import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JRadioButton; import javax.swing.SwingConstants; import java.awt.Font;
public class DialogError extends JDialog {
private JTable table;
public static ResultSet results;
/**
* Launch the application.
*/
public static void DialogError() { EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DialogError dialog = new DialogError();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
/**
}
}
});
* Create the dialog.
*/
public DialogError() {
setBounds(100, 100, 450, 300);
JButton btnClose = new JButton("Close");
btnClose.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { dispose ();
}
});
getContentPane().add(btnClose, BorderLayout.SOUTH);
JLabel lblNewLabel = new JLabel("Something goes wrong…"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 17)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); getContentPane().add(lblNewLabel, BorderLayout.CENTER);
}
}
Anexa 5 Java class DialogOutside
import java.awt.EventQueue; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import javax.swing.JTextArea; import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.table.DefaultTableModel;
public class DialogOutside extends JDialog {
private JTable table;
public static ResultSet results;
private JTable table_1;
static String Object[][]=new String [2][10];
/**
* Launch the application.
*/
public static void DialogOutside() { EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ResultSetMetaData rsmd = results.getMetaData();
int columnsNumber = rsmd.getColumnCount(); int rowNumber = 0; System.out.println(columnsNumber);
System.out.println("########################################");
int j=0;
while (results.next()) { System.out.println("**************************"); String[] a = new String[10];
for (int i = 1; i <= columnsNumber; i++)
{
if (i > 1) System.out.print(", ");
String columnValue = results.getString(i); System.out.print(columnValue + " " + rsmd.getColumnName(i));
a[i-1]=columnValue;
}
for(int i=0;i<5;i++)
{
}
j++;
System.out.println("");
}
Object[j][i]=a[i];
DialogOutside dialog = new DialogOutside();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
/**
}
}
});
* Create the dialog.
*/
public DialogOutside() { setBounds(100, 100, 450, 300); JButton btnOk = new JButton("OK");
btnOk.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { dispose ();
}
"Price", "Country"
});
getContentPane().add(btnOk, BorderLayout.SOUTH);
table_1 = new JTable();
table_1.setModel(new DefaultTableModel(
Object,
new String[] {
"Priority", "Cafe/ Restaurant/ FastFood", "Product name",
}
));
table_1.getColumnModel().getColumn(1).setPreferredWidth(151); table_1.getColumnModel().getColumn(2).setPreferredWidth(81); getContentPane().add(table_1, BorderLayout.CENTER);
}
}
Anexa 6 Java class DialogOutside
import java.awt.EventQueue; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import javax.swing.JTextArea; import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.table.DefaultTableModel;
public class DialogShops extends JDialog {
private JTable table;
public static ResultSet results;
private JTable table_1;
static String Object[][]=new String [2][4];
/**
* Launch the application.
*/
public static void DialogShops() { EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ResultSetMetaData rsmd = results.getMetaData();
int columnsNumber = rsmd.getColumnCount(); int rowNumber = 0; System.out.println(columnsNumber);
System.out.println("########################################");
int j=0;
while (results.next()) { System.out.println("**************************"); String[] a = new String[10];
for (int i = 1; i <= columnsNumber; i++)
{
if (i > 1) System.out.print(", ");
String columnValue = results.getString(i); System.out.print(columnValue + " " + rsmd.getColumnName(i));
a[i-1]=columnValue;
}
for(int i=0;i<4;i++)
{
}
j++;
System.out.println("");
}
Object[j][i]=a[i];
DialogShops dialog = new DialogShops();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
/**
}
}
});
* Create the dialog.
*/
public DialogShops() {
setBounds(100, 100, 450, 300); JButton btnOk = new JButton("OK"); btnOk.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
dispose ();
}
});
getContentPane().add(btnOk, BorderLayout.SOUTH);
table_1 = new JTable();
table_1.setModel(new DefaultTableModel(
Object,
new String[] {
"Priority", "Product name", "Price", "Country"
}
));
table_1.getColumnModel().getColumn(1).setPreferredWidth(151); table_1.getColumnModel().getColumn(2).setPreferredWidth(81); getContentPane().add(table_1, BorderLayout.CENTER);
}
}
Anexa 7 Java class DialogShops
import java.awt.EventQueue; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import javax.swing.JTextArea; import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.table.DefaultTableModel;
public class DialogShops extends JDialog {
private JTable table;
public static ResultSet results;
private JTable table_1;
static String Object[][]=new String [2][4];
/**
* Launch the application.
*/
public static void DialogShops() { EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ResultSetMetaData rsmd = results.getMetaData();
int columnsNumber = rsmd.getColumnCount(); int rowNumber = 0; System.out.println(columnsNumber);
System.out.println("########################################");
int j=0;
while (results.next()) { System.out.println("**************************");
String[] a = new String[10];
for (int i = 1; i <= columnsNumber; i++)
{
if (i > 1) System.out.print(", ");
String columnValue = results.getString(i); System.out.print(columnValue + " " + rsmd.getColumnName(i)); a[i-1]=columnValue;
}
for(int i=0;i<4;i++)
{
}
Object[j][i]=a[i];
j++; System.out.println("");
}
DialogShops dialog = new DialogShops();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
/**
}
}
});
* Create the dialog.
*/
public DialogShops() {
setBounds(100, 100, 450, 300); JButton btnOk = new JButton("OK"); btnOk.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
dispose ();
}
});
getContentPane().add(btnOk, BorderLayout.SOUTH);
table_1 = new JTable();
table_1.setModel(new DefaultTableModel(
Object,
new String[] {
"Priority", "Product name", "Price", "Country"
}
));
table_1.getColumnModel().getColumn(1).setPreferredWidth(151); table_1.getColumnModel().getColumn(2).setPreferredWidth(81); getContentPane().add(table_1, BorderLayout.CENTER);
}
}
Anexa 8 Java class DialogTransport
import java.awt.EventQueue; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import javax.swing.JTextArea; import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.table.DefaultTableModel;
public class DialogTransport extends JDialog {
private JTable table;
public static ResultSet results;
private JTable table_1;
static int n;
static String Object[][]=new String [n][5];
/**
* Launch the application.
*/
public static void DialogTransport() { EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ResultSetMetaData rsmd = results.getMetaData();
int columnsNumber = rsmd.getColumnCount(); int rowNumber = 0; System.out.println(columnsNumber);
System.out.println("########################################");
int j=0;
while (results.next()) { System.out.println("**************************"); String[] a = new String[10];
for (int i = 1; i <= columnsNumber; i++)
{
if (i > 1) System.out.print(", ");
String columnValue = results.getString(i); System.out.print(columnValue + " " + rsmd.getColumnName(i)); a[i-1]=columnValue;
}
for(int i=0;i<5;i++)
{
}
Object[j][i]=a[i];
j++; System.out.println("");
}
DialogTransport dialog = new DialogTransport();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
/**
}
}
});
* Create the dialog.
*/
public DialogTransport() { setBounds(100, 100, 450, 300); JButton btnOk = new JButton("OK");
btnOk.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { dispose ();
}
});
getContentPane().add(btnOk, BorderLayout.SOUTH);
table_1 = new JTable();
table_1.setModel(new DefaultTableModel(
Object,
new String[] {
"Priority", "Transport type", "Details", "Price", "Country"
}
));
table_1.getColumnModel().getColumn(1).setPreferredWidth(151); table_1.getColumnModel().getColumn(2).setPreferredWidth(81); getContentPane().add(table_1, BorderLayout.CENTER);
}
}
Anexa 9 JSP AdminFilter
package am.pm.controller.filter;
import am.pm.dataaccess.model.User;
import am.pm.dataaccess.model.lcp.UserRole;
import am.pm.util.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by Artur on 4/2/2016.
*/
public class AdminFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws
ServletException, IOException {
HttpSession session = ((HttpServletRequest)req).getSession();
User user = (User) session.getAttribute(Constant.SESSION_USER);
if(user == null) {
session.setAttribute(Constant.MSG_ERROR,"Please sign in,The session was expired"); ((HttpServletResponse) resp).sendRedirect("/go/login");
return;
} else if(user.getRole().getId() != UserRole.ADMIN.getId()) {
session.setAttribute(Constant.MSG_ERROR,"The page not allowed, Please sign in with your user account");
((HttpServletResponse) resp).sendRedirect("/go/login");
return;
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
Anexa 10 JSP UserFilter
package am.pm.controller.filter;
import am.pm.dataaccess.model.User;
import am.pm.dataaccess.model.lcp.UserRole;
import am.pm.util.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by Artur on 4/2/2016.
*/
public class UserFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws
ServletException, IOException {
HttpSession session = ((HttpServletRequest)req).getSession();
User user = (User) session.getAttribute(Constant.SESSION_USER);
if(user == null) {
session.setAttribute(Constant.MSG_ERROR,"Please sign in,The session was expired"); ((HttpServletResponse) resp).sendRedirect("/go/login");
return;
} else if(user.getRole().getId() != UserRole.USER.getId()) {
session.setAttribute(Constant.MSG_ERROR,"The page not allowed, Please sign in with your user account");
((HttpServletResponse) resp).sendRedirect("/go/login");
return;
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
Anexa 11 JSP SignUpController
package am.pm.controller;
import am.pm.dataaccess.exception.InternalErrorException;
import am.pm.dataaccess.model.User;
import am.pm.dataaccess.model.lcp.UserRole;
import am.pm.dataaccess.sevice.IUserManager;
import am.pm.dataaccess.sevice.impl.UserManagerImpl;
import am.pm.util.Constant;
import am.pm.util.EncryptException; import am.pm.util.SHAHashEnrypt; import am.pm.util.Utils;
import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by Artur on 4/2/2016.
*/
public class SigUpController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name");
String surname = request.getParameter("surname"); String email = request.getParameter("email");
String password = request.getParameter("password");
if (Utils.isEmpty(name)) {
forward(request, response, "Invalid name");
return;
}
if (Utils.isEmpty(surname)) {
forward(request, response, "Invalid surname");
return;
}
if (Utils.isEmpty(email)) {
forward(request, response, "Invalid email");
return;
}
if (Utils.isEmpty(password)) {
forward(request, response, "Invalid password");
return;
}
try {
password = SHAHashEnrypt.getMD5SecurePassword(password);
} catch (EncryptException e) {
e.printStackTrace();
}
IUserManager userManager = new UserManagerImpl();
try {
User user = new User(); user.setRole(UserRole.USER); user.setName(name); user.setSurname(surname); user.setEmail(email); user.setPassword(password); userManager.add(user);
String nextJSP = "/user/home"; HttpSession session = request.getSession(); session.setAttribute(Constant.SESSION_USER, user); response.sendRedirect(nextJSP);
} catch (InternalErrorException e) {
forward(request, response, "An internal Error occurred please try later");
return;
}
}
private synchronized void forward(HttpServletRequest request, HttpServletResponse response, String msg) throws ServletException, IOException {
request.getSession().setAttribute(Constant.MSG_ERROR, msg); String loginJSP = "/WEB-INF/pages/registration.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(loginJSP);
dispatcher.forward(request, response);
}
}
Anexa 12 JSP SignInController
package am.pm.controller;
import am.pm.dataaccess.exception.EntityNotFoundException; import am.pm.dataaccess.exception.InternalErrorException; import am.pm.dataaccess.model.User;
import am.pm.dataaccess.sevice.IUserManager;
import am.pm.dataaccess.sevice.impl.UserManagerImpl;
import am.pm.util.Constant;
import am.pm.util.EncryptException; import am.pm.util.SHAHashEnrypt; import am.pm.util.Utils;
import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by Artur on 4/2/2016.
*/
public class SigInController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
if (Utils.isEmpty(email)) {
forward(request, response, "Invalid email");
return;
}
if (Utils.isEmpty(password)) {
forward(request, response, "Invalid password");
return;
}
try {
password = SHAHashEnrypt.getMD5SecurePassword(password);
} catch (EncryptException e) {
e.printStackTrace();
}
IUserManager userManager = new UserManagerImpl();
try {
User user = userManager.getByEmailAndPassword(email, password); HttpSession session = request.getSession(); session.setAttribute(Constant.SESSION_USER, user);
String role = user.getRole().getRole();
String nextJSP = String.format("/%s/home", role);
response.sendRedirect(nextJSP);
} catch (InternalErrorException e) {
forward(request, response, "An internal Error occurred please try later");
return;
} catch (EntityNotFoundException e) {
forward(request, response, "Could not found user");
return;
}
}
private synchronized void forward(HttpServletRequest request, HttpServletResponse response, String msg) throws ServletException, IOException {
request.getSession().setAttribute(Constant.MSG_ERROR, msg); String loginJSP = "/WEB-INF/pages/login.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(loginJSP);
dispatcher.forward(request, response);
}
}
Copyright Notice
© Licențiada.org respectă drepturile de proprietate intelectuală și așteaptă ca toți utilizatorii să facă același lucru. Dacă consideri că un conținut de pe site încalcă drepturile tale de autor, te rugăm să trimiți o notificare DMCA.
Acest articol: Sistem Software de Monitorizare a Costurilor de Calatoriedoc (ID: 155226)
Dacă considerați că acest conținut vă încalcă drepturile de autor, vă rugăm să depuneți o cerere pe pagina noastră Copyright Takedown.
