Welcome!

Java Authors: Elizabeth White, Pat Romanski, Liz McMillan, Trevor Parsons, Jason Bloomberg

Related Topics: Java, Linux, Open Source, Eclipse

Java: Tutorial

Using Ext JS, Servlets, JSON, MySQL and Tomcat on Fedora

A simple how to

Java Developer Magazine on Ulitzer

These days the popularity of Ext JS (a JavaScript library) is gaining momentum. One of the most popular widgets within Ext JS is the DataGrid. The reason - displaying data from a database is one of the most common tasks of a web application. "Out of the box" the DataGrid has functionality (for instance, ascending or descending sorting and reordering of columns by dragging it) that otherwise would require some effort from developers. Another attractive feature of the DataGrid is that it can use JSON (JavaScript Object Notation), which allows you to reduce traffic in comparison with full Swing HTML or XML formatting on the server.

Examples from Ext JS site [1] and Ext JS books such as Learning Ext JS.Packt Publishing [2] are focused on PHP in conjunction with Ext JS.

However, what if your organization already uses servlets for web applications?

Googling the problem will lead to a number of "spotted" solutions in which key details are often missed. Besides, there is no "out of the box" JSON support in Java. Sure, you can do it manually but why reinvent the wheel?

This article will show you how to build a servlet-based web application with Ext JS from scratch, and will save you a lot of time on configuration issues that are usually hard to fix.

Example: Phone Book
The following describes how a phone book will be used within this article as it is usually easy to learn by example.

Suppose you need to create a web application to read a phone book for your organization.

As your clients and/or customers can be located all over the world, you need to have a "country" column within a database table in which the phone book is stored. Also suppose it's required to have a First Name, Last Name, Middle Name, Phone Number, Type of phone (home, office, etc.), Description (in here some useful information about a phone can be placed). Foreign names and phones (as dialed from the U.S.) can be long, so it's reasonable to store said information in lengthy enough fields.

For production, the possible length of fields should be researched carefully, but for our example let's assume it will be 250 characters. Of course, you will be able to easily change it if necessary. All names, companies and phones used in this example are entirely fictional. Any possible coincident with reality is by accident only. Data for the example will be stored in a table called phone1 of the MySQL phonebook database.

MySQL and Fedora
MySQL is a popular free open source database for Internet applications. At the time of writing the possible future of MySQL within Oracle was widely discussed (please see for example [3]). However, consider a big installation base and the fact that MySQL packages can be found for most Linux distributions, it will be safe to assume that MySQL will be used at least in the short term.

As an example of Linux, the popular Fedora distribution will be used within the article. With minimal effort, results can be reproduced in other distributions such as Ubuntu.

Configuration in which methods from this article were developed includes a virtual machine with Fedora on a Windows host. Please see my articles [4, 5] on how to use it effectively.

The installation procedure for MySQL on Fedora with yum is described in [6]. If you don't want to start MySQL each time you start Fedora, you may want to create a launcher with the following command:

service mysqld start

and place it, for instance, on your GNOME desktop.

Another useful script given below will allow you to easily start the mysql command within your terminal window

mysql -u <yourUserName> -p<yourPassword>

in the above script <yourUserName> and <yourPassword> should be substituted with your user name and password, respectively. Please note that there is a blank between -u and <yourUserName> but there is no blank between -p and <yourPassword>. You may want to place the script under some directory from your path. If you want a GUI tool for MySQL, it is recommended that you use Oracle SQL developer [7] rather than native MySQL GUI tools. The reason is the flexibility of Oracle SQL developer (for instance you can use it both with MySQL 5.x and Oracle 11g). Download the latest release of Oracle SQL developer  from [7]. At the time of writing Linux RPM of the release is sqldeveloper-1.5.4.59.40-1.noarch.rpm.

Installation can be performed by running the following command:

rpm -Uhv sqldeveloper-1.5.4.59.40-1.noarch.rpm

within the Fedora terminal window.

After that SQL Developer can be found under Applications | Programming of the GNOME menu. From here SQL Developer launchers can be added to the desktop or panel by right-clicking and making a corresponding choice.

The only additional thing that you will need to use is the JDBC driver for MySQL. At the time of writing it is recommended you select from the Oracle SQL developer menu Help | Check for updates, click Next. Than select Third-Party Extensions, click Next and select MySQL JDBC driver (assuming that your computer is connected to Internet). Please visit [7] for latest updates on Oracle SQL developer. Both mysql command, Oracle SQL developer and described below Ganymede Data Source Explorer can be used together as convenient.

Tomcat 6, MySQL and Dolphin
It is assumed within the article that Java SDK from Sun is used rather than the native Java that comes with Fedora. At the time of writing it was possible to use http://www.mjmwired.net/resources and select your Fedora release (say Fedora 10) for a "how to" on this subject. If this resource will not be available, you may want to Google for "Personal Fedora <your release number here> installation guide".

The easiest way to install Tomcat 6 on Fedora is to issue the following command within terminal window:

yum install tomcat6

The above command will install Tomcat 6 as a service. Assuming that you don't want to run Tomcat 6 each time you start Fedora, use the following commands within the terminal window. To start Tomcat 6 use:

service tomcat6 start

To stop Tomcat 6 use:

service tomcat6 stop

You may want to create launchers with these commands to conveniently start and stop Tomcat 6.

Web applications by default are located under /var/lib/tomcat6/webapps. Tomcat 6 libraries are located under /usr/share/tomcat6/lib. To work with MySQL you will need to download MySQL Connector/J tarball from the appropriate mirror mentioned here.

At the time of writing, a file with the latest connector is mysql-connector-java-5.1.7-bin.jar (tarball file name is mysql-connector-java-5.1.7.tar.gz). Check the site in question for updates.

It's convenient to use Dolphin (a file manager for KDE) to extract files from a tarball. Dolphin can be used under GNOME as well. You can start a Dolphin, navigate to the location of a tarball and double-click on the tarball. Dolphin will open the tarball just like a regular folder. Then you may locate the needed file, files or folders, select them (if the entire contents of a certain folder is needed, just select the folder or open the folder and press CTRL+A) and press CTRL + C. Then navigate to your destination and press CTRL + V to copy files selected from a tarball. That's it.

This way you can copy mysql-connector-java-5.1.7-bin.jar from the tarball to /usr/share/tomcat6/lib.

Ganymede
It's convenient to use an IDE to develop servlets. One of the most popular is Eclipse. The latest release of Eclipse at the time of writing is Ganymede, which can be downloaded from http://www.eclipse.org/downloads/. It's recommended to use at least the Eclipse IDE for Java EE Developers distribution of Ganymede. To install Ganymede just open Ganymede tarball (which is eclipse-jee-ganymede-SR2-linux-gtk.tar.gz at the time of writing) with Dolphin and copy the Eclipse folder under the desired location. A detailed description of Ganymede options is far beyond the scope of this article. However, one of them, namely the GUI, for work in particular with databases (in Ganymede terms it is Data Source Explorer) will be described.

  • To get to the Data Source Explorer select Window | Show View | Data Source Explorer from the Ganymede menu. Within Data Source Explorer navigate to Data Base Connections.
  • Once in here right-click and select New.
  • Select MySQL from a drop-down list and click Next.
  • Click the New Driver Definition button, which is a little circle with lines in it.
  • Select the MySQL JDBC driver MySQL 5.1.
  • Click the Jar List tab. Click Add Jar/Zip button.
  • Browse to /usr/share/tomcat6/lib/mysql-connector-java-5.1.7-bin.jar and select it.
  • Click Remove Jar/Zip button to remove mysql-connector-java-5.1.0-bin.jar, which is the Ganymede default.
  • Click the Properties tab to set up the correct connection URL, database name, password and user ID.

In Ganymede terms, the previously described operation is known as a connection profile creation.

  • Within the Data Source Explorer window click on the triangle that is located left of Data Base Connection folder. The name of your database will appear under your connection.
  • Click on a triangle left of the name. Authorization IDs and Schemas folders will appear.
  • Click on a triangle left of the Schemas folder. A representation of the schema of your database will appear.
  • Click on a triangle left of it. Folders named Dependencies, Stored Procedures and Tables will appear among others. Click on a triangle left of Tables. A list of tables from your database will appear. Select the needed table.
  • Right-click on it and select Data | Edit from the pop-up menu.

That's it. From this point you will be able to view and edit data directly from your table within the window named after the table in question. There is no Save button within said window so how do you save your work? Suppose you edited data, clicked on a row next to one in which data was changed, and after that attempted to close said window. In this case a Save Resource window will appear. You will be offered three options: Yes, No and Cancel. If you select Yes, said data will be saved. In this case Ganymede will generate and execute a corresponding SQL Update command for you. Ganymede will also report on results of the execution.

MySQL Stored Procedure for the Example
Usage of stored procedures rather than direct SQL statements in JDBC is highly recommended. The reasons are high execution speed, reduction of traffic (only needed parameters are transferred to a database, not a whole SQL statement) and improvements in security. The creation of stored procedures within MySQL is simple. Just set the delimiter to some symbol that you will not use in your procedure (say to "|"). In this simple example we will just select data from phone1 table. The reaction of our stored procedure within the MySQL command is shown below:

mysql> delimiter | ;
mysql> create procedure read_phonebook()
-> begin
-> select * from phone1;
-> end;
-> |

After that a delimiter can be set back to ";" and a procedure checked for accuracy by using

call read_phonebook();
statement.

Servlet with JSON-type Response
The source code of the servlet is given in Listing 1. Here are some comments for your convenience.

To bring JSON-type results to the HTML page with Ext JS one can use:

res.setContentType("text/html");

In the previous sentence res is an instance of HttpServletResponse. The result set using stored procedure described in the previous section can be obtained as follows:

CallableStatement stExtJS = connExtJS.prepareCall("{call read_phonebook()}");
stExtJS.execute();
ResultSet rsExtJS = stExtJS.getResultSet();

Please note that the datasource used in Listing 1 should be described within META-INF/context.xml

To interact with Ext JS we need to put "[" at the beginning  and "]" at the end of the information produced by the servlet.

Java (and specifically servlets) do not support JSON notation "out of the box." Rather than develop a "homemade" solution, it is recommended you use the free open source library, which is proven to be effective. For our example, json_simple-1.1.jar is chosen for its simplicity and effectiveness. The file can be obtained from this at the time of writing. Please contact me, if this resource is not available. You will need to include this file both in Build Path for your Ganymede project and in WEB-INF/lib for the servlet.

json_simple-1.1 automatically encloses the appropriate data with curly brackets; however, it is your job to put a comma (",") between said data (please see Listing 1 for more details on this).

Please note that of course json_simple-1.1 is not a "silver bullet." You need to research other libraries that implement JSON on Java to see what will fit your needs (for instance google-gson from http://code.google.com/p/google-gson/).

Putting It All Together: Ext JS, JSON, Tomcat
As a standalone, Tomcat is used both as a web server and a sevlet/JSP container, you may want to place your HTML page (or pages) for Ext JS under /var/lib/tomcat6/webapps/<YourApplicationName>. Replace <YourApplicationName> from previous sentence with the needed name of your application.

In the same directory, the corresponding war file or META-INF, WEB-INF for the servlet in question as well as extjs (a folder with Ext JS distribution that you downloaded from [1] and unzipped) and  JavaScript file(s) that will be used by the page(s) will be located.

In this case, the necessary HTML link elements for Ext JS components will be made like this one:

<link rel="stylesheet" href="extjs/resources/css/ext-all.css" />

Please note that path starts with extjs. Using the given link element as an example, you can easily write similar ones for ext-base.js and ext-all.js.

For our example, the name of the page is phone_book.html. This page uses phonebook.js JavaScript file, which in turn works with Ext JS and the servlet in question. Page and JavaScript file do not use any complicated constructions and are very much self-explanatory (please see Listing 2 and Listing 3 for details). It should be mentioned, however, that instead of the traditional PHP scripts, a reference to the URL for the servlet from the previous section (as it is described in web.xml) is used within the JavaScript file. Said reference has the following form:

url: '<nameOfTheServletAsItDescribedInWebXML>'.

Replace  < nameOfTheServletAsItDescribedInWebXML > from the previous sentence with the needed name.

What Do We Have?
Now when all the groundwork is done, what do we get in exchange?

With Ext JS a user can drag and drop columns, sort columns in the desired order and decide which columns to display as shown in Figure 1. Note that only checked columns from Figure 1 are displayed. If, for instance, we uncheck some of the columns, the result will be given in Figure 2.

Without writing any additional code that handles drag-and-drop, sorting, and partial displaying logic, we obtained the mentioned functionality by using simple methods described in this article together with Ext JS JSON, MySQL, Tomcat, and Fedora.

Resources

  1. Ext JS site
  2. Frederic S., Ramsay C. and Blades S.'C'. Learning Ext JS.Packt Publishing. 2008. ISBN-10: 1847195148.
  3. Schutzberg A. Oracle Buys Sun: What Happens to MySQL?
  4. Krivitsky A. Running Fedora Core 5 Under Windows XP - Tips and Tricks, LinuxWorld magazine, vol.4, issue 5, 2006, pp. 28 - 30
  5. Krivitsky A. The 'Best of Both Worlds': Running Fedora 8 on Legacy Windows XP.
  6. Negus C. Fedora 9 and Red Hat Enterprise Linux Bible. Wiley Publishing Inc. 2008. ISBN: 978-0-470-37362-0
  7. Oracle SQL Developer

More Stories By Anatoly Krivitsky

Anatoly Krivitsky has a PhD in computer science and has more than 24 years of working experience in the IT field. He's the author of 20 published papers and books and five patents. For more information, please visit http://www.myjavaserver.com/~akrivitsky/index.html.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, described an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people's real needs and desires.
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...