Jelastic Guest Post and How-to

advertisement
Using Jelastic for the Internet of Things
Guest Post and How-to by Charalampos Doukas, author of Arduino, Sensors and
the Cloud.
In the last few decades, especially in the last 10 years, the ability to not only tag
and monitor but also control uniquely identifiable objects has grown at a
tremendous pace. Everything generates data, from natural networks to human
networks to computer networks. Up until recently, it really wasn’t possible to
keep track of all this data and then on top of that, actually do something with it.
This new, all encompassing network—The Internet of Things (IoT)—is now
possible due to the emergence of Cloud computing. Within the IoT, objects in the
real world also have virtual representations, allowing us to interact with them
through the Internet.
The IoT relies on Cloud computing for provisioning the appropriate resources.
Connecting devices with each other and with the Internet, allowing users to
manage their data online and programming them remotely, requires web
applications that a) expose lightweight, open and easy to use interfaces for data
exchange with the devices, b) can handle the frequent requests by numerous
devices that participate in the IoT network, c) can be easily extended to provide
new functionality and also be able to accept new device members of the IoT
network.
I consider Jelastic (PaaS) one of the most appropriate platforms for hosting Web
applications that serve IoT networks. It provides web developers all they need to
quickly and easily deploy scalable applications that can manage sensor data
online. For me, as a developer working with Java, Jelastic is the best solution
since it provides complete access to the application server environment, the
option to create and use your own database and even access to the local file
system (as opposed to the Google App Engine), which was quite essential,
especially in one of the projects presented in my book (reprogramming your
Arduino remotely).
To demonstrate how easy it is to use Jelastic for managing a sensor data, let's
consider a very simple example of creating and deploying a web application that
receives and visualizes sensor data.
Step 1: Create the Jelastic Environment
The very first step is to create and configure the Jelastic environment for our
application. For the purpose of receiving and visualizing sensor data, we will
need an application server (Tomcat 6) and a Database server (MySQL 5.0).
In the main Jelastic console, click on the ‘Create Environment’ button and then
configure your new environment by selecting the Tomcat 6.0 application server,
MySQL 5.0 Database and add two servers, as in the following image.
Give your new environment whatever name you like, I chose sensorcloud for this
project. Once done, click on ‘Create’ and wait until Jelastic runs its magic in the
background and sets up your environment.
In a couple of minutes the environment will be up and running and you will also
receive an email notification about it, followed by an email that contains your
login credentials for the MySQL environment and the URL to the phpmyadmin
page for managing databases.
Next comes the setup of the database. Use the link in the email—it will look like
http://mysql-sensorcloud.jelastic.servint.net if you are using Servint as the
hosting provider—and the credentials to log into phpmyadmin.
Go to the ‘Databases’ tab and create a new database for handling the sensor data.
Add sensordata as a name for your new database and click ‘Create’ (don’t worry
about the collation, we will use the database to handle simple data).
For this simple project we will need 2 database tables, one to handle the sensor
information (like name and id) and another for the sensor data. To create the
tables, simply click on the name of your new database. Add sensor as the name
for the first table and enter 2 for the number of columns and click ‘Go’.
A popup window will come up that will allow you to edit the properties of the 2
columns for the sensor table. Add the information in each column like in the
following figure and click ‘Save.’ Make sure you have ticked the
‘AUTO_INCREMENT’ option for the column named id:
Our first table in the database is ready to accept data, let’s create the second one.
On the same page use the same text fields and enter data and 3 for name and
number of columns and the click ‘Go’.
Just like you did with the first table, set the attributes of the table in the pop-up
window like in the following figure and click ‘Save’:
You might also want to create a new user with data privileges on the new
database, but for demo purposes it is okay to use the default root user.
When done, you will be directed to the database structure view where you can
view the two tables you have just created. Click the ‘Insert’ icon on the ‘sensor’
table and add some custom value for sensor name (e.g., temp). Don’t worry about
the ID, it will automatically get an incremental value.
Now your Jelastic environment is complete and configured to host your
application and your data!
Step 2: Create the Java Servlet
The second step involves the development of the Java Application that will
receive the sensor data and allow you to visualize it. For this purpose we will
need two servlets, one for receiving the data from the sensors and another for
visualizing them to the user (the latter will be actually a Java Server page).
For this step, I am assuming that you are familiar with Java and servlet
programming, as well as the Eclipse environment.
Open your Eclipse IDE and create a new Dynamic Web Project. Add any name
you like (I have used JelasticSensorArduino) for your project, select a target
runtime (like Tomcat) and click ‘Finish’. A new web project will be created and
listed under the Project Explorer of your Eclipse IDE.
Expand the project and right click on the ‘Java Resources: src’ to create the
appropriate servlet class (I suggest you also create a package hierarchy first).
Create a new class named JelasticArduinoServlet and add the following code:
[code]
import
import
import
import
import
import
import
java.io.IOException;
java.util.Date;
javax.servlet.http.*;
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.Statement;
@SuppressWarnings("serial")
public class JelasticArduinoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
//Retrieve the sensor name and value from the GET requests
String SensorName = req.getParameter("sensor");
String value = req.getParameter("value");
//Create a new date object for retrieving date values from the server
Date date = new Date();
//Create the connection string to the MySQL DB hosted on Jelastic
String url="jdbc:mysql://mysql.arduinocloud.jelastic.servint.net:3306/sensor";
//User your credential for connecting to the DB
String user = "DBUSERNAME";
String password = "DBPASSWORD";
Connection con = null;
Statement st = null;
ResultSet rs = null;
boolean exists = false;
int id = 0;
//Make the connection to the server
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
//Execute the query for retrieving the sensor id
rs = st.executeQuery("SELECT id from sensor where name='"+SensorName+"';");
if (rs.next()) {
exists = true;
id = rs.getInt(1);
}
//If there is an ID for the given sensor name update the value
if(exists) {
st.executeUpdate("Insert
into
('"+id+"','"+date+"','"+value+"');");
}
data(sensorid,
date,
value)
VALUES
resp.getWriter().println("Sensor data updated!");
con.close();
}catch (Exception ex) {
resp.getWriter().println(ex.toString());
}
}
}
[/code]
The latter code is the servlet that handles the sensor value update. It can be
invoked by the Arduino or your browser simply as:
http://server.ip/servletname?sensor=sensorname&value=sensorvalue
First it looks into the database of the given sensor and retrieves its ID. Then ID
updates the data table accordingly.
Let’s move on to the jsp file that will visualize the sensor data. The jsp file needs
to be created under the WebContent folder of your project’s structure. Create a
new file and name it after sensorgraph.jsp and add the following code.
[code]
<%@
<%@
<%@
<%@
<%@
<%@
page
page
page
page
page
page
contentType="text/html;charset=UTF-8" language="java" %>
import="java.util.List" %>
import="java.sql.Connection" %>
import="java.sql.DriverManager" %>
import="java.sql.ResultSet" %>
import="java.sql.Statement" %>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', '<%=request.getParameter("sensor")%>');
<%
int counter=1;
String SensorName = request.getParameter("sensor");
if (SensorName == null) {
SensorName = "temp";
}
String url = "jdbc:mysql://mysql.arduinocloud.jelastic.servint.net:3306/sensor";
String user = "DBUSERNAME";
String password = "DBPASSWORD";
Connection con = null;
Statement st = null;
ResultSet rs = null;
boolean exists = false;
int id = 0;
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT id from sensor where name='"+SensorName+"';");
if (rs.next()) {
exists = true;
id = rs.getInt(1);
}
if(exists) {
rs = st.executeQuery("SELECT value from data where sensorid="+id);
while (rs.next()) {
counter++;
}
%>
data.addRows(<%=counter%>);
<%
rs = st.executeQuery("SELECT date, value from data where sensorid="+id);
counter = 0;
while (rs.next()) {
%>
data.setValue(<%=counter%>, 0, '<%= rs.getString(1) %>');
data.setValue(<%=counter%>, 1, <%= rs.getString(2) %>);
<%
counter++;
}
}
con.close();
}catch (Exception ex) {ex.printStackTrace();}
%>
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 240, title: 'My Arduino <%=SensorName%> Sensor
Readings'});
}
</script>
</head>
<body>
<p></p>
<div id="chart_div"></div>
</body>
</html>
[/code]
The jsp uses the Google Chart API in order to visualize data on a div element
called chart_div. To do so, it needs to fill the chart data for the chart by retrieving
the values for the given sensor from the database.
You may have noticed in the begging of the html code that it uses a specific CSS
style included in a file called main.css. To include such a file in your project,
simply create a new folder named stylesheets under the ‘WebContent’ folder of
your project. Create a main.css inside the ‘stylesheets’ folder and add the
following content:
body {
font-family: Verdana, Helvetica, sans-serif;
background-color: #FFFFFF;
}
Feel free to change fonts and background color to whatever you like. 
Last, but not least, you need to edit the web.xml file (under ‘WEB-INF’) and create
the appropriate servlet name-mapping so that you can link url paths with the
servlet and the jsp file. Replace the content of web.xml with the following:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JelasticSensorArduino</display-name>
<servlet>
<servlet-name>JelasticArduino</servlet-name>
<servlet-class>doukas.jelastic.arduino.JelasticArduinoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JelasticArduino</servlet-name>
<url-pattern>/jelasticarduino</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>sensorgraph.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>doukas.jelastic.arduino.JelasticArduinoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
Make sure you enter the correct servlet class name according to the package
hierarchy you have used in your project setup.
Step 3: Deploy and test your application
You are just a small step away from seeing your application receive and visualize
sensor data. First you need to export the servlet as a .war archive so that you can
deploy it on your Jelastic Environment. To do so, ‘right-click’ on your project
name and select ‘Export’. Then select Web->WAR file from the popup window
and click ‘Next’. Make sure the correct project is selected in the next window and
then browse to a destination folder for the .war file to be saved. Finally click
‘Finish’.
Next go to your Jelastic environment and click ‘Upload’ under the Deployment
Manager.
Browse to the location of the .war file and add a comment for your new
application in the popup window and click ‘Upload’:
As soon as the uploading process finishes, you will se your application archive
listed under the Jelastic Deployment Manager. In order to deploy your
application on the running instances of the Tomcat servers you have configured
for your environment, simply hover the mouse over the .war filename so that the
deploy icon appears and select your environment’s name from the list:
Click ‘Deploy’ on the popup dialog (assuming that we want our application to be
accessible from the default root path of our environment). You will notice the
‘Deploying…’ message next to your environment’s name. After a short time it will
change to ‘Deployed.’
That’s it! Your application is up and running, ready to accept your sensor data
through the web service interface you have previously created!
Well, almost ready…we need to take care a small detail first: your Java
Application, in order to connect to the MySQL database, needs a proper jdbc
driver. This is simply the mysql-connector jar library file you are using when
developing mysql-based java applications locally. You need to upload such a
library to the Tomcat environment so that the library is accessible from your
application environment. To do so, select the Tomcat configuration icon under
your environment, to the right of the Tomcat icon:
The configuration option reveals a new window with access to the Tomcat
directory. There you need to upload the jar file under the lib folder. Once you are
done with the uploading, restart Tomcat so that the library can be loaded by the
server’s running instance.
Let's do a test then! In your browser select the following url:
http://sensorcloud.jelastic.servint.net/add?sensor=temp&value=20
Changing sensorcloud to whatever you chose for your environment name. You
should see the ‘Sensor data updated!’ message. If not (highly unlikely if you
followed the steps exactly as presented) you will see the Java exception message
that will tell you what is wrong.
Keep adding some values to the temp sensor using the previous URL.
Then visit the URL for visualizing the sensor data, remembering to define the
sensor name as a URL parameter:
http://sensorcloud.jelastic.servint.net/?sensor=temp
You should get a graph something like the following:
The importance of Jelastic in making applications like this is that it provides all
the scalability and extensibility the application needs with just a few clicks: you
don’t need to worry about the frequency number of simultaneous requests for
updating the sensor values. You only have to focus on the functionality of the
application itself. You don’t even have to worry about setting up the server
environment for backing up your data.
The importance of having such a web application for managing sensor data
online is that it provides you with a direct and accessible way for uploading
sensor readings. All you need is a network-enabled microcontroller like the
Arduino
that
can
easily
access
the
URL
(http://sensorcloud.jelastic.servint.net/add?sensor=temp&value=20).
Jelastic eliminates all the extra hassle and work on the backend and allows you
to focus on your application. As we have shown in this example, Jelastic makes it
easy to host and scale your application.
Download