% !TEX encoding = IsoLatin

%%%%%%% La riga soprastante serve per configurare gli editor TeXShop, TeXWorks
%%%%%%% e TeXstudio per gestire questo file con la codifica IsoLatin o Latin 1
%%%%%%% o ISO 8859-1. Se si vuole usare un'altra codifica si veda sotto.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1.o Esempio con la classe toptesi
%\documentclass[b5paper,10pt,twoside,cucitura]{toptesi}
\documentclass[11pt,pdfa]{toptesi}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2.o Esempio con la classe toptesi
% \documentclass[11pt,twoside,oldstyle,autoretitolo,classica,greek]{toptesi}
% \usepackage[or]{teubner}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Commentare la riga seguente se si è specificata l'opzione "pdfa"
%\usepackage{hyperref}

\hypersetup{%
    pdfpagemode={UseOutlines},
    bookmarksopen,
    pdfstartview={FitH},
    colorlinks,
    linkcolor={blue},
    citecolor={red},
    urlcolor={blue}
  }
%
%%%%%%% Esempio di composizione di tesi di laurea con PDFLATEX <---------------- !
%
%%%%%%% Questo esempio e' stato preparato inizialmente il 13-marzo-1989
%%%%%%% e poi e' stato modificato via via che TOPtesi andava
%%%%%%% arricchendosi di altre possibilita'.
%
%%%%%%% Per comporre con XeLaTeX, invece che con pdfLaTeX, vedere il file
%%%%%%% toptesi-example-xetex.tex
%%%%%%% A parte i font, bisogna specificare alcune cose dopo la fine del preambolo.
%
%%%%%%% Nel seguito laurea "quinquennale" sta anche per "specialistica" o "magistrale".
%
%%%%%%% Cambiare encoding a piacere; oppure non caricare nessun encoding se si usano
%%%%%%% solo caratteri a 7 bit (ASCII) nei file d'entrata. La codifica utf8 sarebbe
%%%%%%% quella maggiormente desiderabile; richiede pero' un editor che sappia gestirla.
%
%\usepackage[latin1]{inputenc}% per macchine Linux/Mac/UNIX/Windows; sarebbe meglio utf8
\usepackage[utf8]{inputenc}% per macchine Linux/Mac/UNIX/Windows; sarebbe meglio utf8
\usepackage[T1]{fontenc}\usepackage{lmodern}

%
% Per scrivere testo fasullo in "latinorum"
%\usepackage{lipsum}
%
%%%%%%% Il nome generico dell'universita' viene sempre scritto se viene specificato;
%%%%%%% di default il file \jobname.cfg definisce una stringa nulla. Se non si
%%%%%%% specifica niente nel file di configurazione o qui nel preambolo, non viene
%%%%%%% scritto niente.
%%%%%%% Se il logo dell'universita' contiene anche il nome generico (o logotipo)
%%%%%%% E' opportuno che questa stringa resti vuota, ma se il logo non ne contiene
%%%%%%% il nome è meglio specificarlo qui o nel file di configurazione.
%%%%%%% Commentare la prossima riga per vedere che cosa succede.
\ateneo{Politecnico di Torino}
%
%%%%%%%%%%%%%%%%%%%%%
%
% Non tutte le università hanno un nome proprio
%\nomeateneo{Sede di Torre Elettra}
%
%%%%%%% Se \FacoltaDi è vuoto (qui e nel file di configurazione), non viene scritto
%%%%%%% niente, ma se \FacoltaDi ha un argomento non nullo (per esempio "Dipartimento
%%%%%%% di\space" allora viene scritto il nome della struttura didattica responsabile
%%%%%%% per il corso di laurea. Qui nonostante sia specificato il nome proprio della
%%%%%%% facoltà, non vine scritto niente perchè \FacoltaDi è vuoto.
%\FacoltaDi{}
%\facolta[III]{Matematica, Fisica\\e Scienze Naturali}
%\Materia{Remote sensing}
%\monografia{La pressione barometrica di Giove}% per la laurea triennale
\titolo{Design and Implementation of WebSocket API for the Dog Gateway}% per la laurea quinquennale e il dottorato
%\sottotitolo{Metodo dei satelliti medicei}% per la laurea quinquennale e il dottorato
%
%%%%%%% Corso degli studi
\corsodilaurea{Computer Engineering}% per la laurea
%\corsodidottorato{Meccanica}% per il dottorato

%%%%%%% Per inserire la matricola sotto il nome di ogni candidato.
%%%%%%% Usare solamente se prescritto dall'Università!
%%%%%%% Se non è prescritto, scrivere solo il nome nei comandi seguenti.
%%%%%%% Il comando \IDN è già definito nella classe ma lo si può ridefinire.
%\renewcommand*\IDN{\\\quad matricola: }
%
%\candidato{Teodoro \textsc{Montanaro}\IDN 188924}% per tutti i percorsi
\candidato{Teodoro \textsc{Montanaro}}% per tutti i percorsi
%\secondocandidato{Evangelista \textsc{Torricelli}\IDN 123457}% per la laurea magistrale solamente

%%%%%%% Relatori o supervisori
%
%\AdvisorName{Supervisors}% esempio per l'inglese
%\direttore{prof. Albert Einstein}% per il dottorato
%\coordinatore{prof. Albert Einstein}% per il dottorato
\relatore{Fulvio Corno}% per la laurea e/o il dottorato
\secondorelatore{Luigi De Russis}% per la laurea magistrale

%%%%%%%%%% Trucco per mettere il correlatore senza usare l'opzione classica
%\relatore{\tabular{@{}l@{}}
%prof.\ Albert Enstein\\[1.5ex]
%\textbf{Correlatore:}\\
%dipl.~ing.~Werner von Braun
%\endtabular}
%%%%%%%%%%
%
%%%%%%%%%% Trucco per far scrivere Laureando/a/i/e al posto di "Candidato/a/i/e"
%\def\Candidato{Laureando:}
%\def\Candidati{Laureandi:}
%\def\Candidata{Laureanda:}
%\def\Candidate{Laureande:}

%%%%%%%%%% Trucco per scrivere anche un quarto relatore
%\terzorelatore{{\tabular{@{}l}dott.\ Neil Armstrong\\prof. Maria Rossi\endtabular}}% per la laurea magistrale

%%%%%%% Tutore
%\tutore{ing.~Karl Von Braun}% per il dottorato
%\tutoreaziendale{dott.\ ing.\ Giovanni Giacosa}
%\NomeTutoreAziendale{Supervisore aziendale\\Centro Ricerche FIAT}

%%%%%%% Seduta dell'esame
%\sedutadilaurea{Agosto 1615}% per la laurea quinquennale; oppure:
\sedutadilaurea{\textsc{Academic~Year} 2013-2014}% per la laurea magistrale
%\esamedidottorato{Novembre 1610}% per il dottorato
%\annoaccademico{1615-1616}% solo con l'opzione classica
%\annoaccademico{2006-2007}% idem
%\ciclodidottorato{XV}% solo per il dottorato

%%%%%%% Logo della sede
\logosede{logopolito}% questo e' ovviamente facoltativo, ma e' richiesto per
% il dottorato al PoliTO; in questo caso si usa il "logopolito", il nome senza
% estensione del file che contiene in forma grafica il logo.
%
%\chapterbib %solo per vedere che cosa succede; e' preferibile comporre una sola
% bibliografia

%%%%%%% Per cambiare l'offset per la rilegatura
%\setbindingcorrection{3mm}

%%%%%%% Definizioni locali
\newtheorem{osservazione}{Osservazione}% Standard LaTeX

%
% Frequently used abbreviations.
% - example1: \ie this is an example
% - example2: the \ipsec protocol
%
\usepackage{xspace}
\def\myfigure#1{Figure ~#1\xspace}
\def\myfig#1{Fig.~#1\xspace}
\def\mytab#1{Tab.~#1\xspace}
\def\mylist#1{List.~#1\xspace}
\usepackage{subfigure}

\usepackage{minted}
\usepackage{indentfirst}
\renewcommand{\arraystretch}{1.5}
\usepackage{multirow}
\usepackage{longtable}

\makeatletter
\renewcommand\paragraph{%
   \@startsection{paragraph}{4}{0mm}%
      {-\baselineskip}%
      {.5\baselineskip}%
      {\normalfont\normalsize\bfseries}}
\makeatother

\newenvironment{fslongtable}
  {\linespread{1}\footnotesize
   \renewcommand{\arraystretch}{1.2}%
   \setlength{\LTpost}{0pt}%
   \begin{longtable}}
  {\end{longtable}}
  
\setcounter{LTchunksize}{10}

\setcounter{secnumdepth}{3} %enables numbering of subsubsections
\setcounter{tocdepth}{3} %includes subsubsections in the table of contents

%faccio in modo che caption sia distanziati da tabelle (spacing)
\usepackage{caption}
\setlength{\belowcaptionskip}{\baselineskip}

%appendix package
\usepackage{appendix}

\begin{document}\errorcontextlines=9% debugging

\english%  di default vale \italiano

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%% Change the strings if you want a title page and a copyright page in another language
%%%%%%% Comment just the \iflanguage statement and the closing line of the language test
%%%%%%% if you want to make a global change instead of a conditional one.
%%%%%%% Comment the following indented lines if you don't care about the title page
%%%%%%% in English
\iflanguage{english}{%
	\retrofrontespizio{This work is subject to the Creative Commons Licence}
	\DottoratoIn{PhD Course in\space}
	\CorsoDiLaureaIn{Master degree course in\space}
	\NomeMonografia{Bachelor Degree Thesis}
	\TesiDiLaurea{Master Degree Thesis}
	\NomeDissertazione{PhD Dissertation}
	\InName{in}
	\CandidateName{Candidate}% or Candidate
	\AdvisorName{Supervisors}% or Supervisor
	\TutorName{Tutor}
	\NomeTutoreAziendale{Internship Tutor}
	\CycleName{cycle}
	\NomePrimoTomo{First volume}
	\NomeSecondoTomo{Second Volume}
	\NomeTerzoTomo{Third Volume}
	\NomeQuartoTomo{Fourth Volume}
	\logosede{logopolito}% or comma separated list of logos
}{}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\frontespizio


%\tablespagetrue\figurespagetrue % normalmente questa riga non serve ed e' commentata
\indici

\addcontentsline{toc}{chapter}{\numberline{}\listfigurename}
\listoffigures
\addcontentsline{toc}{chapter}{\numberline{}\listtablename}
\listoftables


\mainmatter

%\part{Prima Parte}
\chapter{Introduction}
The rapid development of technology and the high standard of living have encouraged the spread of electronic devices in the life of almost all people all over the world.\\

The last century has seen the invention and the introduction of a lot of new devices and tools that, aiming at only improving the lives of people, has completely changed our habits and our way of thinking.\\

Let us think, for example, to the way by which news were heard till few decades ago: when our grandparents were children, there were not telephones or Internet connections that let news be spread all over the world in less than a minute. Similarly, there were not computer-based assistance technologies that checked all cars behaviour to avoid accidents.\\

Moreover, without considering computers or mobile phones by which almost none of us is able to live without, we can simply consider all the appliances invented to let home be a more interesting place: simple alarm clocks, complicated alarm systems, fridges or washing machines are electronic devices that let us live better than our ancestors and that has modified drastically our lives.\\

Whereas, considering home appliances and all these devices introduced to bring more benefits in our domestic life, we cannot consider that all these appliances functions have considerably changed and improved in recent years.

Specifically, manufacturers are progressively introducing automation and remote control to their products: it is not unusual, for example, to find a (smart) television that lets users turn itself on/off by a smartphone, or a washing machine that lets users schedule its start at a specific time in the day.

This kind of new features and additional tools is encouraging the spread of what is usually referred as ``home automation''.\\

Home automation (or domotics) is the use of automation, computer and telecommunication technology to bring better living condition, entertainment and security for users that live in the specific house in which it is installed.

\begin{figure}[htb]
\centerline{\includegraphics[width=0.7\paperwidth]{images/generic_domotic_environment.png}}
\caption{Generic domotic environment}
\label{fig:generic_domotic_environment}
\end{figure}

In a house equipped with domotic system, typically, there are the components depicted in \myfig{\ref{fig:generic_domotic_environment}}:
\begin{itemize}
\item
a central control system (usually called gateway) that is responsible of retrieving all the information about the environment and interacting with all the possible end-user devices connected to it;
\item
some intelligent and interactive devices and appliances (remote controlled power outlets, temperature sensors, humidity sensors) that monitor the environment and communicate with the gateway to provide the acquired information and receive commands;
\item
one or more end-user devices that interact with home inhabitants and communicate with the gateway in order to achieve information about the house devices and/or send commands that have to be executed on a specific appliance.
\end{itemize}


Even if in recent years home automation is becoming increasingly popular, some open problems obstacle its spread.

One of them is the lack of a standard protocol for communications between different devices and their gateways, so, once a technology has been chosen, the user cannot choose a new device depending only on its functionality and/or its appearance, but he has to select only devices supporting that specific technology.

In addition, most of existing gateways provide the so-called “polling” as method to exchange information with end-user devices connected to them.


\begin{figure}[htbp]
\centerline{\includegraphics[width=0.6\paperwidth]{images/how_does_polling_work.png}}
\caption{How does polling work}
\label{fig:how_does_polling_work}
\end{figure}

As shown in \myfig{\ref{fig:how_does_polling_work}}, this technique consists of actively and repeatedly sampling updated information from the central control system to know if something has changed after the last acquisition, instead of simply wait for new data.\\

Such a technique has some drawbacks, like a possible information loss: considering that we check for updates every a well defined number of seconds, we cannot realize if something happens between two samples (e.g., as shown in \myfig{\ref{fig:how_does_polling_work}}, a rapid state change from on to off and then, again to on).

Moreover, as can be easily understood, in this case it is impossible to have an asynchronous connection: every time an end-user device needs an information, it has to send a request to the gateway, that answers with a dedicated message. 

In this scenario, the gateway is not able to send information (e.g., a notification) to an hypothetical end-user device every time it is needed, and so the connection is synchronous: information are sent only when it is required and in order, i.e., if we send two requests, the gateway will start to answer from the first one.

Furthermore, by using polling, the possibility of an overhead exists and may affect response time of the whole system: every time we need an information, we have to establish a new connection, so the time for establishing it has to be added to the time actually needed for the request.
This problem is felt by both end users and developers, because it is related to the loss of information of which we have previously discussed.\\

Keeping in mind these problems, this thesis looks for existing solutions and protocols for asynchronous communications between the end-user devices and the domotic gateway.
Our aim is to find a way to provide a full duplex connection to existing domotics environment, and specifically, to the gateway developed at the Politecnico di Torino by the e-Lite research group \cite{elite_website}: Dog, a software gateway based on the OSGi framework, able to control domotic environments in a vendor-independent way.


\section{Goals}

Considering the features and problems described in the previous section, this thesis aims at designing and implementing a platform to provide an asynchronous full duplex communication to existing domotics environment.
The solution should improve the information exchange between end-user devices of a domotic system (e.g., touch-screen monitors, smartphones, ...) and a gateway, the central control system of each domotic environment.\\

Specifically, the purposes of this thesis are:

\begin{itemize}
\item
The first objective concerns the research of a cutting-edge and standard Web technology to provide an asynchronous ongoing and full duplex connection over the Internet.
It should be a standard protocol letting any domotic system implement a bidirectional communication between the gateway and all the possible end-user devices.

\item
Secondly, this thesis aims at designing all the features needed to implement an Application Programming Interface (API) that should support the chosen protocol.\\

An API is a set of commands, functions and instructions which developers could use to build their own software: a software company releases its API to the public so that other software developers can design products that are powered by its service.\\

Consequently, just because we want to provide such API for the Dog gateway, we aim at designing, and realizing, a proper messages structure based on a widely spread connection.

Moreover, our effort is to find the best way to maintain written code as clean as possible, so we will consider the possibility of reusing, for example by metaprogramming, the existing methods made available by the Dog REST API (that provides RESTful service to let end-user devices interact with Dog by HTTP methods).

After all, we will actually create the API, by implementing the designed features so that other developers can use the Dog gateway through the chosen protocol.

\item
Finally, a simple application will be developed to test and monitor the performances of the developed API, possibly making a comparison with the existing REST API in terms of delay time and efficiency.
\end{itemize}

\section{Structure of the thesis}

The content of this thesis is divided in six chapters, organized as follows. In the next chapter, we introduce three main topics:
\begin{itemize}
\item
``domotics'', focusing on the properties related to the Dog gateway,
\item
``OSGi framework'', explaining the role of all its component
\item
``Dog'', with its architecture, its ontology and its existing REST API implementation.\\
\end{itemize}

In the third chapter, we examine all the possible alternatives and the choices made in design phase, related to the available protocols able to provide a full duplex Web connection; then, we discuss the advantages and disadvantages of asynchronous and synchronous connections, explaining the reason of our choice; and, at last, we present the structure of messages that had to be sent on the just chosen WebSocket protocol.\\

Moreover, in the forth chapter, we explain all the actions performed to modify the REST API to fit our needs and implement the WebSocket API so that every developer can interact with it.\\

Hence, the fifth chapter exposes the results obtained within this thesis work: we show the simple client implemented to test the API and compare REST and WebSocket API in terms of delay time occurred by using both protocols and of efficiency of the two solutions.

Finally, the last chapter concludes the thesis and suggests possible future works.

\chapter{Background}

\section{Domotics}

Home automation (also called domotics) refers to the use of computers and information technologies to manage home appliances and features (such as windows or lighting) with the aim of improving the quality of people's life.

As the number of controllable devices in the home rises, interconnection and communication become useful and desirable features.
Nevertheless, the popularity of home automation has been increased only in recent years due to some critical issues, that nowadays continue to affect the home automation world, even if with less impact than before.

The most important problem, actually felt by end-users and manufacturers, is that there does not exists a standard protocol for communications between devices and their main control system.
As we can understand, it means that if a user has already bought one or more device of a specific standard, it is not easy to install devices belonging to another plant technology, and so a technician has to convince the customer to buy only devices made for the same specific standard, even if they are not exactly what the customer wants.

In addition, all domotic devices present on the market simply add irrelevant features to existing electronic devices and so users don't appreciate enough them to be convinced to buy an home automation system: they usually add only some controllable features like remote control, or functions for energy savings and, consequently, they cost more than what user expects and, moreover, don't provide enough additional features.

At last, there is what can be easily called ``skepticism'', an attitude of doubt or a disposition to incredulity toward new products. As explanation we can summarize it with a popular Italian sentence (here we will translate it literally): ``who leaves the old way for the new one, knows what he is leaving but not what the future holds for him''.
It means that when a person feels good using an object (e.g. an electronic device), even if we offer something new that could drastically improve her life or let her save a lot of energy, she will look at it disinterestedly and without the intention of adopting it. Usually, she will look first at the disadvantages in using the new device, then, if she doesn't find too problems and if the advantages of adopting it are a lot, she will start to think to its actual adoption.

In fact, until a few years ago, home automation was viewed only as a more expensive way to do the same things that can be already done with the existing and already owned technology, and people were not willing to introduce it in their house.
Luckily, nowadays people opinion about domotics is changing, and it is not unusual to find house with installed domotic systems.

However, just to solve the problem related to the not existing standard protocol for communications, the e-Lite research group \cite{elite_website} has implemented the Dog gateway, a software gateway, based on the OSGi framework, used to control domotic environments in a vendor-independent way. It is possible due to its high-level semantic device modeling strategy and its driver architecture that allows to support different domotic plant technologies (for more details about Dog see the section \emph{\ref{dog_section}}).

\section{OSGi}

The Dog gateway has been developed upon the OSGi Framework.
Considering the definition given by the OSGi Alliance (\cite{what_is_osgi}), the OSGi technology is a set of specifications that defines a dynamic component system for Java. These specifications enable a development model where applications are (dynamically) composed of many different (reusable) components (called bundles), that are able to hide their implementations from other bundles while communicating through services; the services are objects that are specifically shared between components and allow the cooperation between them.


\begin{figure}[htbp]
\centerline{\includegraphics[width=0.5\paperwidth]{images/layering-osgi.png}}
\caption{OSGi layers - reprinted from \cite{what_is_osgi}}
\label{fig:layering-osgi}
\end{figure}

The OSGi framework has a layered model (as shown in \myfig{\ref{fig:layering-osgi}}) in which 6 different areas can be identified.\\

\paragraph{Bundles} 

The main component of an OSGi system is the ``bundle''.

Essentially, a bundle is a group of Java classes and additional resources equipped with a detailed manifest MANIFEST.MF file that describes all its contents, as well as additional services needed to give the included group of Java classes more sophisticated behaviours.

Bundles executing within an OSGi service platform are independent of each other, yet they collaborate in well-defined ways. They are fully self-describing, declaring their public API, defining their runtime dependencies on other bundles, and hiding their internal implementation.\\


\begin{figure}[htbp]
\centerline{\includegraphics[width=0.5\paperwidth]{images/bundle_anatomy.png}}
\caption{Bundle Anatomy}
\label{fig:bundle_anatomy}
\end{figure}

\myfig{\ref{fig:bundle_anatomy}} shows the component of a typical bundle.\\

The only mandatory file is the ``MANIFEST.MF'' that specifies the contents and the requirements of the bundle.\\

Then we can find an ``src'' folder, containing all the bundle classes, and the ``OSGI-INF'' folder that can contains configuration files. Specifically, in the above example the ``OSGI-INF'' folder contains the ``component.xml'', that is an XML file that contains the list of provided services and their references (we will discuss about the content of this file in the next paragraph).\\

\paragraph{Services}

Bundles collaborate through services that facilitate dynamic collaboration; a service is simply an object that implements a contract, a type, and is registered with the OSGi service registry.

Bundles looking to use a service need only import the package defining the contract and discover the service implementation in the service registry.

Services are an inherent part of the overall OSGi architecture and have been there from the beginning, however, over time the facilities around services have evolved.

For this reason, nowadays there exists two main different mechanisms for dealing with the dynamic nature of services: OSGi’s Service Trackers, and OSGi’s Declarative Services (DS).
\\

In this thesis we decided to use the last one: OSGi’s Declarative Services (DS), which makes handling the dynamic acquisition and release of services easier for bundle developers by eliminating all service management code.

DS is a way for a bundle to declare, in an XML file (component.xml), the services it provides and references. DS binds and unbinds these services at the appropriate time.\\


The OSGi Alliance has specified many services. Two of the most significant for this thesis are:
\begin{itemize}
\item
the ``EventAdmin'', that uses an inter-bundle communication mechanism to simplify sending and receiving events between bundles; we use it to handle events generated by the bundle responsible for notifications generation.
\item
the ``HttpService'', that allows other bundles in the OSGi environment to dynamically register resources and servlets into the URI namespace of Http Service. We use it to expose the REST API.\\
\end{itemize}


\paragraph{Life-Cycle}

As reported in the OSGi Alliance description (\cite{what_is_osgi}), the Life Cycle Layer provides an API to control the security and life cycle operations of bundles. The layer is based on the module and security layer. This API allows to install, start, stop, update, and uninstall bundles.\\

\mytab{\ref{table:bundle_states_description}} shows the list of all bundle states with their description, while \myfig{\ref{fig:bundle_life_cycle}} shows the typical life cycle of a bundle.

\begin{center}
\begin{fslongtable}{| l | p{10cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Bundle State}} & \multicolumn{1}{|c|}{\textbf{Description}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
  \textbf{INSTALLED} & The bundle has been successfully installed. \\ [0.5ex]
\hline
  \textbf{RESOLVED} & All Java classes that the bundle needs are available. This state indicates that the bundle is either ready to be started or has stopped. \\ [0.5ex]
\hline
  \textbf{STARTING} & The bundle is being started, the start method will be called, and this method has not yet returned. When the bundle has an activation policy, the bundle will remain in the STARTING state until the bundle is activated according to its activation policy. \\ [0.5ex]
\hline
  \textbf{ACTIVE} & The bundle has been successfully activated and is running;\\ [0.5ex]
\hline
  \textbf{STOPPING} & The bundle is being stopped. The stop method has been called but the stop method has not yet returned. \\ [0.5ex]
\hline
  \textbf{UNINSTALLED} & The bundle has been uninstalled. It cannot move into another state.\\ [1ex] % [1ex] adds vertical space
\hline %inserts single line
\caption{Bundle States and Description - reprinted from \cite{what_is_osgi_wikipedia}} % title of Table
\label{table:bundle_states_description} % is used to refer this table in the text
\end{fslongtable}
\end{center}

\begin{figure}[htb]
\centerline{\includegraphics[width=0.6\paperwidth]{images/bundle_life_cycle.png}}
\caption{Life cycle of a bundle - reprinted from \cite{osgi_specification}}
\label{fig:bundle_life_cycle}
\end{figure}

All bundles start from the ``installed'' state, from which they can go to the ``resolved'' one if all their dependencies are resolved.
Then a bundle can be executed both by invoking itself by ``start'' method or by an automatic invocation from the framework (in case of an ``autostart'' setting); in this case, its state goes from ``resolved'' to ``starting''.

The next state is the ``active'' state, that can be reached only when the start method ends.

Similarly, when a bundle has to be stopped for any kind of reason (for example when it is necessary to shut down the whole system), the bundle will remain in ``active'' state till the ``stop'' method doesn't end, and only at this point the bundle state can change from ``active'' to ``stopping'' and finally to ``resolved''.

\paragraph{Modules}

The standard Java platform provides only limited support for packaging, deploying, and validating Java-based applications and components. Because of this, many Java-based projects, such as JBoss and NetBeans, have resorted to creating custom module-oriented layers with specialized class loaders for packaging, deploying, and validating applications and components.

As an alternative, the OSGi Framework provides a generic and standardized solution for Java modularization, in fact the modularization layer has an important role in sharing Java packages between bundles and hiding packages from other bundles.

\paragraph{Security}

The Security Layer is a cross-level framework and can be activated optionally.

This level is based on Java 2 security but adds a number of constraints and fills in some of the blanks that standard Java leaves open. It defines a secure packaging format as well as the runtime interaction with the Java 2 security layer.

Essentially, we can distinguish two kinds of security issues changes.
\begin{itemize}
\item
Code authentication

The OSGi framework can authenticate code by:
\begin{itemize}
\item
Location

At higher layers there are defined services that can manage permissions associated with the authenticated unit of code and based on full location strings or on a comprehensive conditional model.
\item
Signer

The specification says that the code can be digitally signed to verify the following properties:
\begin{itemize}
\item
Authenticates the signer.
\item
Ensures that the content has not been modified after it was signed by the principal.
\end{itemize}
\end{itemize}
\item
Permissions

Each bundle is associated with a set of permissions. During runtime, they are queried every time a permission is requested through the Security Manager.
\end{itemize}
 
\paragraph{Execution Environment}

Defines what methods and classes are available in a specific platform.


As reported in the specification (\cite{osgi_specification}), the Java environment provides all packages in the java.* namespace. However, this namespace is not well defined and can be different for different runtime environments (for example, Java SE 5 is not equal to Java SE 7 and an Android environment has substantial differences between a Java SE environment).\\

These differences and backward compatibilities can not be captured using versions because they are variations: bundles do not import the java.* packages and can therefore not specify their dependencies on these variations in the environment using the Import-Package header.
Thus, the OSGi Execution Environment defines how frameworks can inform bundles about the available execution environments.


\section{Dog}
\label{dog_section}

Dog is an OSGi gateway able to expose different home and building automation networks as a single and technology neutral system. The adoption of a standard framework such as OSGi, and of sophisticated modeling techniques (\emph{\nameref{dogont}}) stemming from the Semantic Web research community, allows Dog to go beyond simple automation and to support reasoning-based intelligence inside various environments. By exploiting automatic device generalization, syntactic and semantic command validation, and inter-network scenario definition, Dog provides the building blocks for supporting the evolution of current, isolated, automation plants into so-called Smart Environments, where heterogeneous devices and automation systems are coordinated to behave as a single, intelligent, proactive system.

Dog was born in 2008 and is actively maintained and developed by the e-Lite research group \cite{elite_website} at the Politecnico di Torino.
During 2013, it has been improved in its design and underwent a code refactoring, with the aim at improving overall performances and providing a better compliance with the OSGi specifications. This refactoring led Dog to the version 3.0, released with the Apache Licence 2.0.

\subsection{Architecture}

\begin{figure}[htb]
\centerline{\includegraphics[width=0.6\paperwidth]{images/dog_architecture.png}}
\caption{Dog Architecture}
\label{fig:dog_architecture}
\end{figure}

As we can see in \myfig{\ref{fig:dog_architecture}}, Dog is organized in a layered architecture with 4 layers, each dealing with different tasks and goals, ranging from low-level interconnection issues to high-level modeling and interfacing.
Each layer includes several OSGi bundles corresponding to the functional modules of the system.
Let us analize all of them.

\begin{itemize}
\item
\textbf{Drivers Layer}:
it contains all the Dog bundles that provide an interface to the various home and building automation networks to which Dog can be connected (e.g. KNX NetIP, Z-Wave, etc.).
Each Driver implements a ``self-configuration'' phase, in which it interacts with the OSGi framework to retrieve all the needed low-level information, according to the specific technology, e.g., the device address(es) or its ID in the network. For each technology, there must exist:
\begin{itemize}
\item
a \textit{Network Driver} for each technology, which handles network-level communication, in terms of protocols, connections and polling (when needed), and defines the network access APIs for all the driver bundles of the same technology;
\item
a \textit{Gateway Driver} for each technology, that supports multi-gateway operations for a given technology and handles the association between devices and their gateways. It allows to install Device Driver bundles when the corresponding network gateway is present at the configuration level. Furthermore, according to the specific technology, it can provide gateway-specific commands and functionalities.
\item
at least one \textit{Device Driver}, that implements the DogOnt (a modeling language for Smart Environments that will be introduced in the \emph{\nameref{dogont}} subsection) device features for a given class of devices, i.e., it translates ontology-defined commands, functionalities and states into network level messages.
\end{itemize}

Eight different technologies are supported by Dog, each with a different number of device categories covered: KNX NetIP, Modbus (RTU and TCP), Echelon iLon100, eLite (simulated drivers), BTicino OpenWebNet, Z-Wave, ZigBee Home Automation profile, and SimpliciTI.
\item
\textbf{Core Layer}:
it hosts the core intelligence of Dog, based on the \emph{\nameref{dogont}} ontology, and provides a set of common libraries and useful services.
As shown in \myfig{\ref{fig:dog_architecture}}, it is made up of the following four different categories.
\begin{itemize}
\item
The ``Device Management'' category is made up of three bundles for handling all the life-cycle of a Device and its status variables: the \textit{Device Factory} bundle, that is responsible of Device instances creation and deletion in the framework; the \textit{Device Manager} bundle, that manages the procedure responsible of matching and attaching a Device to the ``right'' Driver when it is added, modified or removed from/to the framework; and the \textit{Monitor Admin} bundle, which offers security checking and scheduling of periodic or event-based monitoring jobs and implements the OSGi Monitor Admin Service Specification that provides unified access to any declared status variables defined in the framework.
\item
The ``House Models'' category consists of two bundles: the \textit{Semantic House Model}, that manages the building (or home) description in form of DogOnt instances, and the \textit{Simple House Model}, that manages the building XML description (that can be generated by the \textit{Semantic House Model} bundle) and is usually used for Dog instances targeted to devices with low computational power.
\item
The ``Facilities'' category includes two bundles (\textit{Logger} and \textit{Clock}) that offer a console logger, and an internal clock service that triggers a time event each second.
\item
The ``Libraries'' category is made up of six bundles that act as repositories of classes, interfaces and different services needed by the other Dog bundles: \textit{JAXB Library}, \textit{Measure Library}, \textit{Semantic Library}, \textit{Stream Library}, \textit{org.rxtx} and the \textit{Core Library} that is the most important, because contains all the possible devices, functionalities, states and state values as defined in DogOnt; moreover it includes all the possible device implementations, and provides core-level notifications and utility classes to other bundles.
\end{itemize}

\item
\textbf{Addons Layer}:
it provides additional bundles for injecting further capabilities or more intelligence to the previous layer (\textbf{Core Layer}).
It is made up of four bundles:
\begin{itemize}
\item
\textit{Rule Engine}, that provides a rule engine runtime for defining automation scenarios, interoperation and complex device behaviours;
\item
\textit{Power Bundle}, that offers power consumption estimation based on actual measures, typical or nominal values defined in the DogOnt power extension and exploited by the \textit{Power Model} (this model provides power-specific query functionalities and plugs in the \textit{Semantic House Model})
\item
\textit{Stream Processor}, that provides stream processing capabilities by handling measure and boolean events for processing them.
\item
\textit{Event Storage}, that maintains a storage of relevant events (e.g measures).
\end{itemize}
\item
\textbf{Communication Layer}:
it provides access from external, non-OSGi, applications by offering a REST API endpoint.
It helps retrieving the building configuration, sending messages to devices managed by Dog, handling the building structural information (rooms, flat, etc), getting the devices status, etc.
For all details about REST API see the \emph{\nameref{rest_api}} subsection.
In this thesis we have implemented a second alternative endpoint: the WebSocket API, that uses the same basic message structures and expose the same functionalities and information as the REST one, but, in addition, let us manage asynchronous events (i.e. notifications) that may come from any device handled by Dog.

\end{itemize}

\subsection{DogOnt}
\label{dogont}

DogOnt is a formal model  based on Semantic Web technologies used to represent a home and building automation environment.
It is able to face interoperation issues allowing to describe:
\begin{itemize}
\item
where a domotic device is located;
\item
the set of capabilities of a domotic device;
\item
the technology-specific features needed to interface the device;
\item
the possible configurations that the device can assume;
\item
how the home environment is composed;
\item
what kind of architectural elements and furniture are placed inside the home.
\end{itemize}

This information can then be leveraged by inference-based intelligent systems to provide advanced functionalities required in Smart Environments.


\subsection{REST API}
\label{rest_api}

As previously told, Dog is already equipped by an API that allows developers to easily integrate home and building automation into their applications, whether they are web applications, smartphone (Android, iOS, etc.) apps or computer programs.\\

However, the reason why this thesis aims at developing and implementing a different version of API, is related to the problems described in the Introduction chapter: the Dog REST API, that is the API of which we are speaking, uses polling to get information from the gateway, and, moreover, does not allow to send notifications to end-user devices without an explicitly request.\\

By the way, let us analyze the features provided by this API, so that we can use their information in the future design phase in which we will choose between the possibility to reuse existing API and develop a completely new version of it.\\

As the name suggests, the Dog REST API is an implementation of the REpresentational State Transfer (REST) architectural style, that describes the design logic behind the Web architecture.

Even if RESTful architectures may be based on any kind of Application Layer protocol, it is usually based on HTTP and HTTPS, and this is exactly our case: Dog exposes the REST API on HTTP.

Due to the description reported in \cite{what_is_rest}, the REST architectural style consists of a set of constraints applied to elements within the architecture itself, so let us analyze these constraints:
\begin{itemize}
\item
\textit{Client–server}

The uniform interface separates clients from servers. This separation means that, for example, clients are not concerned with data storage, which remains internal to each server and servers are not concerned with the user interface or user state, which remains internal to each client.
\item
\textit{Stateless}

It means that the necessary state to handle the request is contained within the request itself, whether as part of the URI, query-string parameters, body, or headers.
\item
\textit{Cacheable}

As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests. 
\item
\textit{Layered system}

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies.
\item
\textit{Uniform Interface}

The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently.
\item
\textit{Code on demand} (optional)

Servers are able to temporarily extend or customize the functionality of a client by transferring logic that it can execute to it. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.
\end{itemize}

Thus, like each consumer of any RESTful architecture and API, the Dog API consumers are able to use GET, POST, PUT, and DELETE verbs. These verbs greatly enhance the clarity of what a given request should do, as described in \mytab{\ref{table:http_verbs}}:

\begin{table}[ht]
\centering % used for centering table
\begin{tabular}{| l | p{12cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Verb}} & \multicolumn{1}{|c|}{\textbf{Description}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
  GET & Used to retrieve resources and their status or description or more other information \\ \hline
  POST & Used to create resources, or performing custom actions \\ \hline
  PUT & Used to update or insert resources \\ \hline
  DELETE & Used to delete resources \\ [1ex] % [1ex] adds vertical space
\hline %inserts single line
\end{tabular}
\caption{HTTP Verbs available in Dog} % title of Table
\label{table:http_verbs} % is used to refer this table in the text
\end{table}

The Dog RESTful API allows to:
\begin{itemize}

\item
manage connected devices, i.e.,
\begin{itemize}
\item
query the gateway about installed devices, their location, functionalities and configurations;
\item
require execution of commands to existing devices;
\item
monitor device statuses and measures in real-time;
\item
add or update the set of devices controlled through the gateway;
\item
update the location and the description of a device controlled through the gateway;
\end{itemize}

\item
manage information about the environment, i.e.,
\begin{itemize}
\item
insert, update or delete rooms;
\item
insert, update, or delete flats.
\end{itemize}

\end{itemize}


To summarize, \mytab{\ref{table:function_summary}} reports a function summary, that shows the correspondence between URL and resources, where terms in ``\{...\}'' are parameters needed by the specific function. A parameter is usually a unique identifier for a device or an environment, but it should also be a command that has to be executed.

\begin{center}
\begin{fslongtable}{| p{4cm} | p{5cm} | p{5cm}|} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Resource path}} & \multicolumn{1}{|c|}{\textbf{Corresponding resource}} & \multicolumn{1}{|c|}{\textbf{Available methods}}\\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
 /devices &	Represents domotic devices handled by Dog and ``controllable'' by applications using this API & GET: List all devices (with their details) used by the Dog gateway \\ \hline
 /devices/\{device-id\} & Represents a single domotic device handled by Dog, identified by a unique device-id (currently encoded in the id attribute for the XML response to the GET /devices request), and ``controllable'' by applications using this API & GET: Returns the details of the device identified by the given device-id \\ \hline
 /devices/\{device-id\}/location & Update the location of a single domotic device handled by Dog, identified by a unique device-id & PUT: Update the location of the device identified by the given device-id \\ \hline
 /devices/\{device-id\}/description & Update the description (i.e., the long name) of a single domotic device handled by Dog, identified by a unique device-id & PUT: Update the description (i.e., the long name) of the device identified by the given device-id \\ \hline
 /devices/status & Represents the status of devices registered in the Dog gateway runtime, i.e., defined in the Dog configuration and successfully registered within the gateway runtime & GET: List the current status of all devices actually managed by the Dog gateway, i.e. defined in the Dog configuration and registered within the gateway runtime, be they active or not \\ \hline
 /devices/\{device-id\}/status & Represents the status of the device identified by the given device-id, registered in the Dog gateway runtime, i.e., defined in the Dog configuration and successfully registered within the gateway runtime & GET: List the current status of the device identified by the given device-id and actually managed by the Dog gateway, i.e. defined in the Dog configuration and registered within the gateway runtime, be they active or not \\ \hline
 /devices/\{device-id\}/commands/ \{command-name\} & Represents a command, identified by a command-name, to be sent to the device identified by the given device-id. Commands are idempotent: the same command always results in the same behavior of the selected device. If the command brings the device in same state in which the device is, no differences will be appreciable & PUT: sends the command identified by the given command-name \\ \hline
 /environment & Represents the environment (i.e., the building) configured in Dog & GET: List the building environments (i.e., the building) configured in the Dog gateway \\ \hline
 \multirow{2}{*}{\parbox{4cm}{/environment/flats}} & Represents all the flats present in the environment (i.e., the building) & GET: List all the flats present in the in the (only, right now) building configured in Dog \\
 & & POST: Add a new flat to the building configured in Dog \\ \hline
 \multirow{2}{*}{\parbox{4cm}{/environment/flats/ \{flat-id\}}} & Represents a specific flat present in the environment (i.e., the building) & GET:Returns the details of the flat identified by the given flat-id \\
 & & PUT: Update the flat identified by the given flat-id \\ \hline
 \multirow{2}{*}{\parbox{4cm}{/environment/flats/ \{flat-id\} /rooms}} & Represents all the rooms present in a given flat & GET: List all the rooms present in the flat identified by the given flat-id \\
 & & POST: Add a new room to the flat identified by the given flat-id \\ \hline
 \multirow{2}{*}{\parbox{4cm}{/environment/flats/\{flat-id\} /rooms/\{room-id\}}} & Represents a specific room present in a given flat in the environment (i.e., the building) & GET: Returns the details of the room identified by the given room-id and located in the given flat \\
 & & PUT: Update the room identified by the given room-id and located in the given flat \\ [1ex] % [1ex] adds vertical space
\hline %inserts single line
\caption{Function summary} % title of Table
\label{table:function_summary} % is used to refer this table in the text
\end{fslongtable}
\end{center}


Moreover, all the responses provided by the API should respect the HTTP specification (as shown in \mytab{\ref{table:http_status_code}}), so that the server could return relevant HTTP status codes;
this feature was not yet implemented at the beginning of this thesis, in fact we will discuss the way by which we had implemented it in the \emph{\nameref{implementation_chapter}} chapter.

This is necessary because, in addition to the improvements linked to the respect of specifications, if, for example, we will decide to re-use methods already provided by REST API, it would be desirable to receive significant information about the status of the request.\\

Let us analyze the responses that the REST API should send when it receives a request:


\begin{center}
\begin{fslongtable}{| l | p{12cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Verb}} & \multicolumn{1}{|c|}{\textbf{Possible answers}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
  \multirow{2}{*}{\textbf{GET}} & \textbf{200 OK} (with corresponding JSON or XML content): the operation seems to be executed correctly \\
   & \textbf{404 (Not Found)}: the resource was not found \\ \hline
  \multirow{5}{*}{\textbf{POST}} & \textbf{200 OK}: the operation seems to be executed correctly (the methods didn’t generate exceptions) \\
   & \textbf{201 Created}: The resources that had to be created was created successfully \\
   & \textbf{304 Not modified}: The resources was not modified \\
   & \textbf{412 Precondition failed}: Even if the request is valid the operation cannot be performed due to problems in accessing resources \\
   & \textbf{417 Expectation failed}: Even if the request is valid the operation cannot be performed \\ \hline
	\multirow{5}{*}{\textbf{PUT}} & \textbf{200 OK}: the operation seems to be executed correctly (the methods didn’t generate exceptions) \\
   & \textbf{201 Created}: The resources that had to be created was created successfully \\
   & \textbf{304 Not modified}: The resources was not modified \\
   & \textbf{412 Precondition failed}: Even if the request is valid the operation cannot be performed due to problems in accessing resources \\
   & \textbf{417 Expectation failed}: Even if the request is valid the operation cannot be performed \\
	\hline
	\multirow{3}{*}{\textbf{DELETE}} & \textbf{200 OK}: the command was accepted (but it is not guaranteed that the resource was deleted)\\
   & \textbf{412 Precondition failed}: Even if the request is valid the operation cannot be performed due to problems in accessing resources \\
   & \textbf{417 Expectation failed}: Even if the request is valid the operation cannot be performed \\ [1ex] % [1ex] adds vertical space
\hline %inserts single line
\caption{HTTP status code} % title of Table
\label{table:http_status_code} % is used to refer this table in the text
\end{fslongtable}
\end{center}


To better exemplify the usage and the possibilities offered by the Dog API, we report some case studies.\\

For example, if we want to get the status of the device named ``MainsPowerOutlet\_2'' we have to send the following request:

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	tabsize=4]{js}     

GET http://www.mydog.com/api/devices/MainsPowerOutlet_2/status
\end{minted}
\caption{Simple request to get the status of a device}
\end{listing}

And a possible response is shown in \mylist{\ref{sample_status_response}}.\\


\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	tabsize=4]{js}     

{
  "id" : "MainsPowerOutlet_2",
  "active" : true,
  "status" :
  {
    "OnOffState" :
    [
      {
        "value" : "off"
      }
    ]
  }
}
\end{minted}
\caption{Sample status response}
\label{sample_status_response}
\end{listing}


Finally, if we want to turn a Dimmer Lamp \footnote{a Dimmer Lamp is a lamp that has the possibility to vary the brightness of its light} on, setting its value to 63\%, we have to send the request shown in \mylist{\ref{request_to_set_dimmer}} (let us assume its name is ``DimmerLamp\_l4\_livingroom''):

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	tabsize=3]{html}

PUT http://www.mydog.com/api/devices/DimmerLamp_l4_livingroom/
commands/set

-- REQUEST-BODY: --
{
	"value" : "63"
}
\end{minted}
\caption{Simple request to set the value of a dimmer}
\label{request_to_set_dimmer}
\end{listing}


\chapter{Design}
\label{design_chapter}

In this chapter we discuss about all the evaluated possibilities and the decisions made in all the different steps into which the design phase can be divided:

\begin{itemize}
\item
formerly, we focus on the research of a cutting-edge and standard web technology (and related protocol) to provide an asynchronous ongoing and full duplex connection over the Internet supported by almost all major browsers;
\item
after, we analyze the differences between synchronous and asynchronous connections, in order to choose the best alternative for developers that would use our API;
\item
eventually, we design the structure and the format of all possible messages that would be exchanged with the gateway \footnote{i.e., to recap, the central control system that is responsible of retrieving all the information about the system and interacting with all the possible clients connected to it}.
\end{itemize}

\section{Protocol choice}

This section discusses about three topics:
\begin{itemize}
\item
the analysis of standard web technologies that let us provide an asynchronous ongoing and full duplex connection over the Internet supported by almost all major browsers;
\item
the discussion about the differences between available technologies (and protocol provided by/for them), focusing our attention on their strengths and weaknesses;
\item
the final choice of the best protocol for our purpose.
\end{itemize} 

\subsection{Available protocols}

We can begin from the analysis of some well-known existing protocol, techniques and generic solutions that provide a way to let a server send asynchronous information to a client whenever he wants.

\paragraph{Polling}


Polling, or polled operation, consists in actively sampling information needed by a client as a synchronous activity. Thus, it is not a protocol, but a widely used technique in which a server can send information to a client only after an explicitly request that asks for them.


\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/polling.png}}
\caption{Possible use of polling in our situation}
\label{fig:polling_for_our_needs}
\end{figure}

As shown in \myfig{\ref{fig:polling_for_our_needs}}, in our situation, in which we would allow server-to-client communication as well, the polling could be used to ask repeatedly (at regular intervals) for new messages.

The use of polling has its own advantages and disadvantages.\\

Advantages range from the possibility to determine the frequency at which information has to be taken, to the fact that it is used over HTTP, so it uses a standard, consolidated and widely available technology.\\

Instead, the disadvantages can be summarized only in an high HTTP overhead: every time we need an information, we have to establish a new connection, so the time for establishing it has to be added to the time actually needed for the request.


\paragraph{Comet techniques}


Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.

Comet is an umbrella term, encompassing multiple techniques for achieving this interaction: all these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins.\\

Let us analyze the techniques that compose Comet, looking at specific advantages and disadvantages.\\

\subparagraph{\textit{Ajax with long polling}}



\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/long_polling.png}}
\caption{Possible use of long polling in our situation}
\label{fig:long_polling_for_our_needs}
\end{figure}


As the name suggests and \myfig{\ref{fig:long_polling_for_our_needs}} shows, long polling requires the client to poll the server for an event (or set of events). The browser makes an Ajax-style request to the server, which is kept open until the server has new data to send to the browser. After new data is available, it is sent back to the browser in a complete response. After that the browser initiates a new long polling request in order to obtain subsequent events.\\

The advantages and disadvantages of such a technique are almost the same of polling: as advantages we can mention that it is possible to determine the frequency at which information has to be taken and that it is not necessary to add anything to existing technologies, because it is used over HTTP; the disadvantages are, again, summarized in the high HTTP overhead.\\


\subparagraph{\textit{Hidden iframe}}


A basic technique for dynamic web application is to use an hidden iframe HTML element, an inline frame, which allows a website to embed one HTML document inside another.

This invisible iframe is sent as a chunked block, which implicitly declares it as infinitely long (sometimes called ``forever frame'').

As events occur, the iframe is gradually filled with script tags, containing JavaScript to be executed in the browser.

Because browsers render HTML pages incrementally, each script tag is executed as soon as it is received. Some browsers require a specific minimum document size before parsing and execution are started: it can be obtained by initially sending 1-2 kB of padding spaces.\\

The main advantages of such a technique are that it works across all browsers and that the server can actually send information to the client without any explicitly request.\\

Instead, disadvantages are that, at first, there is not a reliable method to handle errors, so it is not possible to track the status of the process making the request; moreover, it is actually an hidden ``polling'', so has the same problem shown for it (HTTP overhead).\\

\subparagraph{\textit{Ajax with XMLHttpRequest}}


XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script.

It works in two alternative ways.

\begin{itemize}
\item
Use ``multipart'' answers on the server and a ``onreadystatechange'' function on the client: the server sends each message as a separated part of the whole ``multipart'' answer, and on the browser a function (``onreadystatechange'') will be executed every time something (a part of the ``multipart'' answer) will be received.
\item
Use only the ``onreadystatechange'' function on the client: a custom data format will be used for messages, so that the function can be executed each time it receives new data.\\
\end{itemize}

As expected, these two techniques have their own advantages and disadvantages.
Advantages include almost all major browser support, the fact that they are used over HTTP, and, the fact that they actually provide a  good workaround to interact with a server without reloading the page.

Instead, as disadvantages we have to mention that they are sometimes too slow and that some troubles exist with some mobile browsers.\\

\paragraph{Server-Sent Events (SSE)}


SSE is similar to the long-polling mechanism, except for the fact that it does not send only one message per connection.


\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/sse.png}}
\caption{Possible use of SSE in our situation}
\label{fig:sse_for_our_needs}
\end{figure}

As shown in \myfig{\ref{fig:sse_for_our_needs}}, at the beginning, the client sends a request to the server that holds the connection until a new message is ready.

Then the server sends the response back to the client, but without closing the connection: it still keeps the connection open so that it can be used for other messages once they become available.

Thus, even the client processes the messages sent back from the server individually without closing the connection after each message processing.

So, SSE typically reuses one connection for more messages (called events).\\

Moreover, SSE defines a dedicated media type that describes a simple format of individual events sent from the server to the client and offers standard JavaScript client API implemented in most modern browsers.\\


The advantages of such a technique can be summarized in the following list.
\begin{itemize}
\item
Transported over simple HTTP instead of a custom protocol;
\item
can be poly-filled with JavaScript to "backport" SSE to browsers that do not support it yet;
\item
built in support for re-connection and event-id;
\item
Simple protocol.\\
\end{itemize}


Instead, the main disadvantage is that SSE is not yet supported by all modern browsers (specifically it is not supported by Internet Explorer).\\

\paragraph{WebSocket}


WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. It is an independent TCP-based protocol: its only relationship to HTTP is that its handshake is interpreted by HTTP servers as a request to \emph{Upgrade} the service to WebSocket service.\\

The WebSocket protocol makes possible interaction between a browser and a web site, letting easy the supplying of live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing messages to be sent back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server.\\


The main advantages of this protocol are that it provides a real time, two directional communication and it is natively supported by most of existing browsers.\\

Otherwise, as disadvantage we have to consider that it is an independent TCP-based protocol: one of the things anti-virus and malware scanning solutions are very good at is detecting anomalies in specific types of content looking at the specific fields of HTTP headers. Thus, considering that WebSocket does not use HTTP, the ability to correctly identify a given object gets a bit iffy.\\


\subsection{WebSocket choice}

Looking at the reported solutions, it is too simple to understand why we decided to use the WebSocket protocol.\\

First of all, we have already seen that, using WebSocket, there is less HTTP overhead than with the other techniques.

Then, we can easily understand that, providing a real time, two directional communication, once the connection has been established, all future messages will be sent over a socket rather than new HTTP request/response calls.

Moreover, it has been demonstrated that WebSocket is faster than polling (even if sometimes the difference is negligible, as shown at \cite{websocket_polling_comparison} ) and than all the Comet technologies.\\

Furthermore, another advantage of using WebSocket instead of other protocols or techniques, is that it is natively supported by most of existing modern browsers (even mobile browsers).

It is of our interest because we want to implement the Dog API on a solution/protocol that should be as accessible as possible in order to let every kind of developers (i.e., developers that implement software in any programming language and on any device) access it.\\

But, now let us discuss about its main competitor: SSE.

SSE and WebSocket seemed to be very similar, in fact they are both part of HTML5, they are both faster than their competitors and they are both capable of providing a solution to let gateways push data to clients.

However, there are a lot of differences that have let us choose WebSocket instead of SSE.\\

First of all, we have to notice that SSE is not supported by Internet Explorer, the most widespread browser in the world.

Moreover, even if SSE uses HTTP instead of a custom protocol (as already discussed, it should be an advantage), WebSocket opens a real full duplex connection instead of an half duplex one.\\

In addition, there was another difference that brought us to the WebSocket choice: the possibility to implement it in OSGi easy.\\

Looking for the best way to develop our API in OSGi, we found that there were only 2 possibilities:
\begin{enumerate}
\item
Implement the SSE standard using Jersey (\cite{jersey_website}), that is a Web Services framework for developing RESTful Web Services in Java; it provides support for JAX-RS (Java API for RESTful Services) and, also serves as a JAX-RS Reference Implementation;
\item
Implement the WebSocket protocol using the Jetty project (\cite{jetty_website}), that is a Java-based HTTP (Web) server.
\end{enumerate}

As discussed in the \emph{\nameref{how_dog_exposes_rest_api}} subsection, it was not a problem for us to use an external tool as Jersey or Jetty, because both of them were already used by Dog.\\

However, a problem arises: since, to use Jersey in OSGi, Dog uses a connector (OSGi - JAX-RS Connector \cite{osgi_jax_rs_connector}) that connect Jersey and OSGi at the service level.

This connector does not implement all the features provided by Jersey (even if Jersey implements some more features respect to the ones contained in JAX-RS, the connector was created as JAX-RS connector, so it implements only the component present in its specifications) and one of the features that were not supported at the time of our research was just SSE API.\\

On the other hand, Jetty supports WebSocket by default, and considering the fact that we already use Jetty as internal WebServer, the best thing to do was to choose WebSocket instead of SSE.\\

\subsubsection{WebSocket}

WebSocket is a protocol providing a real full duplex connection over a single TCP connection.\\

It was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL (format for describing interfaces that are intended to be implemented in web browsers) is being standardized by the W3C.\\

The WebSocket Protocol is an independent TCP-based protocol and the communication is established over default TCP ports ( 80 for HTTP and 443 for HTTPS), which is of benefit for those environments which block non-web Internet connections using a firewall or other similar solutions.

Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as a request to \emph{Upgrade} the service to WebSocket service.\\


\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/WebSocket_sequence_diagram.png}}
\caption{WebSocket network diagram - reprinted from \cite{websocket_implementation_example}}
\label{fig:websocket_network_diagram}
\end{figure}


As we can see in \myfig{\ref{fig:websocket_network_diagram}}, the initiator of the connection is always the client, which sends a request to the server containing a special HTTP header to inform it that the HTTP connection should be ``upgraded'' to a full duplex TCP/IP WebSocket connection.

An example of client request is shown in \mylist{\ref{websocket_client_request_example}}.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
GET /dogws HTTP/1.1
Host: localhost:8080
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: yxZkWd+TYliFwWYDXXiHbw==
Sec-WebSocket-Version: 13
Origin: http://localhost
\end{minted}
\caption{Sample WebSocket request header sent by a client} 
\label{websocket_client_request_example}
\end{listing}


Then, if the server supports WebSocket, it chooses to upgrade the connection and sends a response that is similar to the one shown in \mylist{\ref{websocket_server_response_example}}.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: bqQFBh9vTN3QpBogRRRrKmSoRAY=
\end{minted}
\caption{Sample WebSocket response header sent by a server} 
\label{websocket_server_response_example}
\end{listing}


At this point, the HTTP connection breaks down and is replaced by WebSocket over the same underlying TCP/IP connection: the protocol switch (from HTTP to WebSocket) is referred to as ``the WebSocket handshake''.\\


Optionally, there is the possibility to enable a secure connection, by setting a ``secure'' field to true.

In this specific situation, the client must perform a TLS (Transport Layer Security) handshake over the connection after opening it and before sending the handshake data.

If it fails (e.g., the server certificate could not be verified), then the client must ``Fail'' the WebSocket connection and abort it. Otherwise, all further communications on this channel must run through the encrypted tunnel (for more details see \cite{websocket_specification}).\\


Once a WebSocket connection is established, both client and server can send data to the other party whenever it is needed.\\

In the WebSocket protocol, data is transmitted using a sequence of frames.
To avoid confusing network intermediaries (such as intercepting proxies) and for security reasons, a client must mask all frames that it sends to the server: masking is done whether or not the WebSocket protocol is running over TLS.

The server must close the connection upon receiving a frame that is not masked sending a Close frame with a status code of 1002 (protocol error). A server must not mask any frames that it sends to the client, otherwise the client must close the connection sending the status code 1002 (protocol error).\\

The masking key is a 32-bit value chosen at random by the client: when preparing a masked frame, the client must pick a fresh masking key from the set of allowed 32-bit values. Moreover, the key needs to be unpredictable: it is essential to prevent authors of malicious applications from selecting the bytes that appear on the wire.\\

An high-level overview of the framing is given in \myfig{\ref{fig:websocket_frame_map}}.

\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/websocket_frame_map.png}}
\caption{WebSocket frame map}
\label{fig:websocket_frame_map}
\end{figure}


As we can see, there are a lot of fields, so we will demand the explanation of their meanings to the RFC specification \cite{websocket_specification}; here we can only point out, as expected, that:
\begin{itemize}
\item
there is not a predefined length of the message (in fact there is a field dedicated to store it),
\item
there is a field dedicated to the ``Masking key'',
\item
fragmentation is available and controllable simply by the ``FIN'' field;\\
\end{itemize}


\subsubsection{WebSocket in OSGi}
\label{websocket_in_osgi}

Even if the WebSocket protocol is natively supported by the latest Java Enterprise Edition version (Java EE 7), it is not so easy to natively implement it on OSGi.\\

As reported before, the best way to implement a WebSocket OSGi server is through the Jetty Web Server (\cite{jetty_website}).

Jetty is a Web Server that provides an HTTP server and Servlet container capable of serving static and dynamic content and provides, as needed, the following services:
\begin{itemize}
\item
asynchronous HTTP Server
\item
standards based Servlet Container
\item
\textbf{WebSockets server}
\item
SPDY server
\item
asynchronous HTTP Client
\item
\textbf{OSGi}, JNDI, JMX, JASPI, AJP support\\
\end{itemize}

As all the other implementations of the WebSocket protocol, Jetty implements the following 4 methods:
\begin{itemize}
\item
``onOpen'', called every time a user asks for opening a WebSocket connection; this method is responsible for instantiating the connection;
\item
``onClose'', called every time a connection is closed, either for some problems or due to simple close requests; in contrast with other implementations, in Jetty we cannot find an ``onError'' method, that would be called every time an error occurs, so errors are managed by the ``onClose'' one.
\item
``onMessage'', called every time a message is received; it receives simple strings.
\item
``sendMessage'', used to send messages to a client; it is a method made available for a specific instance of the connection, so that it is easy to send a message to the right user.
\end{itemize}

Finally, even if in the RFC6455 \cite{websocket_specification} specification there is not any indication, the connection is closed after 5 minutes of inactivity.



\subsubsection{How Dog exposes REST API}
\label{how_dog_exposes_rest_api}

As already discusses, the work of exposing the REST API in Dog is done by Jetty (\cite{jetty_website}), a pure Java-based HTTP (Web) server providing an HTTP server, an HTTP client, and a javax servlet container.\\

OSGi allows other bundles in the OSGi environment to dynamically register resources and servlets into the URI namespace of Http Service, and Jetty is distributed with a bundle that deploys this servlet: it provides an implementation of HttpService that we use to expose API and host the Jersey RESTful Web Services framework (\cite{jersey_website}).\\

Jersey is an open source framework for developing RESTful Web Services in Java: it provides support for JAX-RS (Java API for RESTful Services (\cite{jax-rs_documentation})) API and it also serves as a JAX-RS Reference Implementation.

Furthermore, Jersey provides its own API that extends the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development.\\

Essentially, it let developers rapidly expose POJO (Plain Old Java Object) methods as RESTful Web resources simply using an high level easy-to-use declarative annotation-based API, so we use it to map directly methods with their own URI path.\\

Thus, it means that if a developer wants to create a class with a POJO method that should answer with an ``Hello'' message every time a user type in ``http://localhost\-:8080\-/api\-/greetings'' in his browser, he has only to do the following actions:
\begin{itemize}
\item
define a Class (without caring about its name) specifying the ``/api'' Path annotation;
\item
define a method (without caring about its name) that returns a String with the ``Hello'' message;
\item
define the ``@Path'' annotation specifying the path ``/greetings'' for the method;
\item
define the ``GET'' annotation for the method if he wants to answer to a GET call.\\
\end{itemize}

In \mylist{\ref{jersey_class_example}} there is the just described example code.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
@Path("/api")
public class WidgetResource {

    @GET
    @Path("/greetings")
    public String getGreetings() {
        return 'Hello';
    }
}
\end{minted}
\caption{Simple Class exposing a method with Jersey} 
\label{jersey_class_example}
\end{listing}

Therefore, by implementing a Class with a simple method and two annotations, we have a ready to use RESTful Web Service that answers to a GET invocation with an ``Hello'' message.\\


\section{Connection type}

\begin{figure}
\begin{minipage}[b]{7cm}
\centering
\includegraphics[width=0.33\paperwidth]{images/synchronous_connection.png}
\caption{Simplified sequence diagram of a Synchronous connection}
\label{fig:synchronous_connection}
\end{minipage}
\ \hspace{7mm} \
\begin{minipage}[b]{7cm}
\centering
\includegraphics[width=0.33\paperwidth]{images/asynchronous_connection.png}
\caption{Simplified sequence diagram of an Asynchronous connection}
\label{fig:asynchronous_connection}
\end{minipage}
\end{figure}

The next step is related to the type of connection we wanted to provide to developers.

There were 2 possibilities: synchronous connection and asynchronous connection.\\

As shown in \myfig{\ref{fig:synchronous_connection}}, in a synchronous connection all the requests received by the server are treated as if they were in a queue. This means that if a message is sent before another one, the server has to send the answers in the same order. As advantage, in a synchronous connection, it is easy to understand if a message was lost, because there is a well-known predefined interval in which the answer could be received, and, after this time, the client can suppose that the message was lost and so decide to send it again.\\

As shown in \myfig{\ref{fig:asynchronous_connection}}, in an asynchronous connection all the requests received by the server can be treated as independent of each other. Thus, the server can send a message even if it is the response to the last received request and the other requests are not yet satisfied.
Consequently, with asynchronous connections we have two main problems.
First of all, it is not possible to understand if a message was lost or if it is only late.
Moreover, in a situation in which 2 messages contain the same information, it could be not easy to understand which is the updated one (unless there is an indication about it).\\

Looking only at the above descriptions, it seems that the best one is the synchronous connection, but we had to consider the fact that we were looking for a full duplex connection on which the server and the client would have to send messages whenever they wanted and on which the server would have to send notifications.\\

Thus, considering these further information it's easy to understand the reason why we chose to implement an asynchronous connection: with an asynchronous connection we can send notifications every time an event occurs and without waiting for a request from the client.

Furthermore, in this way developers can easily manage an hypothetical user interface: users are always able to interact with the system (and so to send new requests) even if they are waiting an answer for another submitted request.\\

\section{Message structure}
\label{message_structure}

Once the protocol and synchronism choice had been made, it was necessary to decide which format was the best for requests, responses and notifications, for both server side and client side messages.\\

To take the right choice we had to consider a lot of aspects.\\

First of all, it was important to check and understand what the ``onMessage'' and the ``sendMessage'' methods (shown in the \emph{\nameref{websocket_in_osgi}} section) allow in terms of accepted parameters and performed operations.

As described in the Jetty implementation of the two methods, they accept only strings, and not generic POJO as usually expected.\\

Thus, at this point, considering that we would only send strings, it was necessary to understand what was the best format that messages had to use to provide a service as standard as possible.

Consequently, we checked what is usually done in other projects and we found that in almost all projects in which the WebSocket protocol is implemented, the messages are formatted in JSON, an open standard format that uses human-readable text (see the following \emph{\nameref{json_subsection}} subsection for more details).

In addition, there is not a common message structure with standard or common fields that should have been used.\\

Hence, except on the use of JSON, we did not have any constraints related to messages' format and/or required information, so we had to base our choice on considerations specifically related to Dog and its existing methods and classes.\\

In turn, we focused our attention on the functionalities that our API would have to provide to developers: the main aim of WebSocket API is to supply methods that would let programs interact with the gateway, and it is exactly what the REST API already did. Furthermore, the gateway should be able to send notifications and/or other information asynchronously to external applications.\\

So, two option has been considered:
\begin{itemize}
\item
use an HTTP like format, with actions (PUT, POST, GET, DELETE), path and parameters;
\item
use a new schema with new fields.
\end{itemize}

Obviously, the first choice would have let us reuse existing REST API methods, instead the second one would have let us define new and more efficient fields.\\

At the end, the choice was made considering that Java lets reuse existing class (by metaprogramming: we will explain the concept in the Implementation chapter (\emph{\nameref{metaprogramming}}), and so, choosing the first format (HTTP like) we would have implement less and cleaner methods than with the other one.\\

Consequently, we decided to implement a JSON structure with an HTTP like format.


\subsection{Updated Dog architecture}

In order to apply the \textit{Don’t Repeat Yourself} (D.R.Y.) principle, aiming at reducing repetition of information and code, we have designed the architecture shown in \myfig{\ref{fig:updated_dog_architecture}}.\\

\begin{figure}[htb]
\centerline{\includegraphics[width=0.5\paperwidth]{images/updated_dog_architecture.png}}
\caption{How WebSocket API interacts with other system components}
\label{fig:updated_dog_architecture}
\end{figure}

As we can see the WebSocket API was designed to:
\begin{itemize}
\item
wrap all the existing REST API methods for all the devices interactions (get their information or status, execute commands … ); it was realized by the use of metaprogramming, that is the ability of a program to inspect existing external code in order to invoke its methods or functions;
\item
communicate directly with the other Dog components (e.g., the Dog Core Layer) for all the actions related to notifications (register/unregister on a specific notification topic or send a notification).
\end{itemize}

Thus, even if the user sends requests and commands only to the WebSocket endpoint, in the first case the WebSocket API interacts with the REST API invoking the right method, instead in the second one it interacts directly with the other Dog components receiving notifications events or subscribing/unsubscribing a specific notification topic.\\

\subsection{JSON}
\label{json_subsection}

JSON \cite{json_website} or JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and a web application, as an alternative to XML.\\

JSON's basic types are:
\begin{itemize}
\item
Number, double-precision floating-point format in JavaScript;
\item
String, double-quoted Unicode, with backslash escaping;
\item
Boolean;
\item
Array, an ordered, comma-separated sequence of values enclosed in square brackets; the values do not need to be of the same type;
\item
Object, an unordered, comma-separated collection of key:value pairs enclosed in curly braces; the ':' character separates the key and the value. The keys must be strings and should be distinct from each other;
\item
null, empty.
\end{itemize}

Insignificant "whitespaces" may be added freely around ``structural characters''.\\

The example shown in \mylist{\ref{json_message_example}} presents the JSON representation of an object that describes a person. The object has string fields for first name and last name, a number field for age, an object representing the person's address and an array of phone number objects.\\


\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}
\end{minted}
\caption{Generic sample JSON message} 
\label{json_message_example}
\end{listing}

Moreover, JSON is supported in most of existing programming languages and, specifically, in Java.\\

We decided to use a multi-purpose Java library for processing JSON data format: \textbf{Jackson} \cite{jackson_website}, that let us simplify and speed up all the parsing processes.

We will discuss and explain how does it work in the Implementation chapter (\emph{\nameref{messages_management}}).


\subsection{Presentation message}

In order to analyze all the possible messages that the WebSocket endpoint is able to understand, we can start from the Presentation one, that is the first message sent at the beginning of the communication.

As soon as the connection will be established, a presentation message should be sent to the client with the following information.
\begin{itemize}
\item
\textbf{clientId}: unique client identifier (decided by the server);
\item
\textbf{messageType}: type of the message. In this case this field should contain the value: ``info'';
\item
\textbf{type}: content type. In this case this field should contain the value: ``presentation''.
\end{itemize}

A presentation message example is shown in \mylist{\ref{presentation_json_example}}.

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId":"1f7170d4",
  "messageType":"info",
  "type":"presentation"
}
\end{minted}
\caption{Presentation JSON example} 
\label{presentation_json_example}
\end{listing}


\subsection{Requests}

When the connection has been established, it should be simple to communicate with the server: the developer has only to send a JSON formatted message with the fields shown in the following list (the order should be not important, and empty fields should not be sent).

\begin{itemize}
\item
\textbf{clientId}: unique client identifier (it should be taken from the presentation message);
\item
\textbf{sequenceNumber}: number that should identify the request. By this number, it should be possible to identify to which request corresponds the response just received;
\item
\textbf{messageType}: type of the message. In this case it should contain the value ``request'';
\item
\textbf{action}: action that has to be performed on the server. The value of this field should depend on the fact that we decided to extend REST API implementing an HTTP-like format, so the content of this field should correspond to HTTP verbs. Possible values:
\begin{itemize}
\item
GET;
\item
POST;
\item
PUT;
\item
DELETE.
\end{itemize}
\item
\textbf{endPoint}: It should correspond to the path we should send to REST API to access a resource.
\item
\textbf{parameters}: depending on the endPoint it should be necessary to indicate some parameters, and so this should be the right field in which they should be inserted.
\end{itemize}

A request message example is shown in \mylist{\ref{request_json_example}}.

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "action":"GET",
  "endPoint":"/api/devices/MeteringPowerOutlet_3/status"
}
\end{minted}
\caption{Request JSON example} 
\label{request_json_example}
\end{listing}

\subsection{Responses}
All the responses consist of JSON formatted messages that contains the following fields.

\begin{itemize}
\item
\textbf{clientId}: unique client identifier;
\item
\textbf{sequenceNumber}: Number that should identify the request to which the response corresponds;
\item
\textbf{messageType}: type of the message. In this case it should contain the value: ``response'';
\item
\textbf{action}: It should indicate what was the action performed on the server (it is a response to a request, so it should contain the same value as the request). Possible values:
\begin{itemize}
\item
GET;
\item
POST;
\item
PUT;
\item
DELETE.
\end{itemize}
\item
\textbf{action}: It should correspond to the endPoint contained in the request;
\item
\textbf{response}: Content of the response (it should be, in turn, in JSON format).
\end{itemize}

A response message example is shown in \mylist{\ref{response_json_example}}.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "GET",
  "endPoint" : "/api/devices/MeteringPowerOutlet_3/status",
  "response" :
    {
      "id" : "MeteringPowerOutlet_3",
      "description" : "Presa di corrente domotica wifi",
      "active" : true,
      "status" :
        {
           "SinglePhaseActiveEnergyState" :
           [
              {
                 "value" : "0.0 kWh"
              }
           ],
           "OnOffState" :
           [
              {
                 "value" : "off"
              }
           ],
           "SinglePhaseActivePowerMeasurementState" :
           [
              {
                 "value" : "0.0 W"
              }
           ]
        }
    }
}
\end{minted}
\caption{Response JSON example}
\label{response_json_example}
\end{listing}


\subsubsection{Commands responses}
\label{commands_responses}

As already described, the Dog gateway provides an interface to communicate with different devices in a vendor-independent way and one of its aims is to let programs send commands to devices.\\

By the way, here we have to point out that we can only \textbf{SEND} commands to them, so it means that we cannot know if the command is actually executed over the device or not: the device can only send a status change notification, but it cannot be treated as response to command.

Thus, considering that the answers to commands can only indicate if the message was successfully sent or not, we should only have two possible responses to a command:
\begin{itemize}
\item
``Command executed successfully'': it should mean that there were not exceptions in the execution, and so that the command was successfully sent to the device;
\item
``Command execution failed'': it should mean that we were not able to send the request to the device (so we will be sure that command was not executed).\\
\end{itemize}

The command responses should have the same structure of the other responses, so these values should be contained within the ``response'' field.

In \mylist{\ref{command_response_json_example}} we have an example of command response.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}
{
  "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "PUT",
  "endPoint" : "/api/devices/MainsPowerOutlet_2/commands/on",
  "response" :
  {
    "result" : "Command executed successfully"
  }
}
\end{minted}
\caption{Command response JSON example}
\label{command_response_json_example}
\end{listing}

\subsection{Notifications}
\label{notifications_design}

A notification consists of a JSON formatted message that contains the fields shown in the following list.
\begin{itemize}
\item
\textbf{clientId}: unique client identifier;
\item
\textbf{sequenceNumber}: number that should identify the request to which the response corresponds. Used only for registration and unregistration of notifications;
\item
\textbf{messageType}: type of the message. In this case it should contain the value: ``info'';
\item
\textbf{type}: content type. Possible values:
\begin{itemize}
\item
notification, that should be used every time the message contains a notification (usually sent by server);
\item
notificationRegistration, that should be used every time the message contains a notification Registration (usually sent by client);
\item
notificationUnregistration, that should be used every time the message contains a notification Unregistration (usually sent by client).
\end{itemize}
\item
\textbf{action}: action that was performed on the server. It should be used only for registration and unregistration of notifications and in this two cases it should contain the value: ``PUT'';
\item
\textbf{notification}: content of the notification (it should be, in turn, in JSON format). It should be used only for the notifications sent by the server;
\item
\textbf{parameters}: to subscribe one or more specific notification it should be necessary to fill this field with the list of wanted notifications. It should contain:
\begin{itemize}
\item
a single value ( e.g., ``parameters`` : ``SinglePhaseActivePowerMeasurementNotification`` )
\item
a list of notifications: (e.g., ``parameters`` : [ ``SinglePhaseActivePowerMeasurementNotification`` , ``TemperatureNotification`` ]).
\end{itemize}
The name of notifications should correspond to the ``notificationTopic'' field contained in the event generated on the server.
\item
\textbf{endPoint}: it should indicate the notification we want to subscribe. It should contain all the information needed by the server to subscribe a notification. There should be four possible combinations.
\begin{itemize}
\item
Subscribe/Unsubscribe \textbf{all the notifications} for \textbf{all devices}: in this case we have to send the following value: ``api/\-devices/\-notifications'';
\item
Subscribe/Unsubscribe \textbf{all the notifications} for a \textbf{specific device} (identified by an ``id''): in this case we have to send the following value: ``api/\-devices/\-\{id\}/\-notifications'', where the value contained between ``\{\}'' indicates the id of the device;
\item
Subscribe/Unsubscribe \textbf{some notifications} for \textbf{all devices}: in this case we have to send the list of notifications in the ``parameters'' field and here (in the ``endPoint'' field) the value: ``api/\-devices/notifications''.
\item
Subscribe/Unsubscribe \textbf{some notifications} for a \textbf{specific device} (identified by an ``id''): in this case we to send the list of notifications in the ``parameters'' field and here (in the ``endPoint'' field) the value: ``api/\-devices/\-\{id\}/\-notifications''. The value contained between ``\{\}'' indicates the id of the device;

\end{itemize}

\end{itemize}

In \mylist{\ref{notification_registration_example}}, \mylist{\ref{notification_unregistration_example}} and \mylist{\ref{notification_example}} we can find, in turn, a notification registration example (ALL notifications for a SPECIFIC device), a notification unregistration example (SOME notifications for a SPECIFIC device), and a notification example.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "type":"notificationRegistration",
  "action":"PUT",
  "endPoint":"/api/devices/MeteringPowerOutlet_3/notifications"
}
\end{minted}
\caption{Notification Registration (ALL notifications for a SPECIFIC device) example} 
\label{notification_registration_example}
\end{listing}

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "type":"notificationUnregistration",
  "action":"PUT",
  "endPoint":"/api/devices/MeteringPowerOutlet_3/notifications",
  "parameters":
  	[
  		"SinglePhaseActivePowerMeasurementNotification",
  		"TemperatureNotification"
  	]
}
\end{minted}
\caption{Notification Unregistration (SOME notifications for a SPECIFIC device) example} 
\label{notification_unregistration_example}
\end{listing}

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId" : "3cabdc0f",
  "messageType" : "info",
  "type" : "notification",
  "notification" :
  {
    "notificationTopic" : "SinglePhaseActivePower
    					MeasurementNotification",
    "notificationName" : "newActivePowerValue",
    "deviceUri" : "MeteringPowerOutlet_3",
    "powerValue" : "0.0 W"
  }
}
\end{minted}
\caption{Notification example} 
\label{notification_example}
\end{listing}

\chapter{Implementation}
\label{implementation_chapter}

After the design phase, we can go to analyze all the steps taken in the Implementation phase.\\

We can divide this phase into six incremental steps:
\begin{itemize}
\item
in the first part, we discuss about the REST API modification needed to completely fit the HTTP specifications;
\item
then, in the second one, we discuss about the actions performed to implement a simple WebSocket server that was only able to open and close a connection and to receive strings as messages;
\item
in the third section, we speak about the message management and the Jackson project that let us parse JSON formatted messages;
\item
in the fourth one, we show how we have invoked existing REST API methods, without long if-clauses and/or the duplication of code;
\item
in the fifth, we explain how we have generated notifications with information contained in OSGi events and how we have managed the notification registration process;
\item
finally, the last section explains how our APIs could be used by developers, presenting a typical workflow with examples in both Java and JavaScript languages.\\
\end{itemize}


\section{REST API modification}


As already discussed, we would reuse all methods and annotations provided by REST API, so in the first step of this phase we have analyzed the existing API to understand if it was actually possible.\\

The \emph{\nameref{rest_api}} section reported in the second chapter, shows what the REST API provides in terms of requests that should be sent to the server for obtaining information about some specific resources and/or devices.

Moreover, we considered the fact that even if each HTTP request should respect the HTTP specifications returning relevant HTTP status code, the existing APIs did not actually do it.

For this reason, in order to obtain well-done methods that could be invoked in the WebSocket implementation, our first effort was related to the modification of the REST API to fit these specifications and return a significant value as result.\\

Hence, let us start from the analysis of the following list reporting all the REST API methods that needed a modification. Near the name of the specific method there is a brief explanation of its function and the name of the bundle that contains it.\\

Then, looking at \mytab{\ref{table:method_responses_after_modification}} we can understand what are the status codes that they should return with the indication of their specific meaning.

\begin{itemize}
\item
\texttt{updateDeviceLocation}, for update the device location, and present in the DeviceAPI package;
\item
\texttt{updateDeviceDescription}, that lets update the device description in the DeviceAPI package;
\item
\texttt{executeCommand}, that lets send commands to devices in the DeviceAPI package;
\item
\texttt{addNewFlat}, that lets add a new flat to existing environment in the EnvironmentAPI package;
\item
\texttt{updateFlat}, that lets update a flat in the existing environment in the EnvironmentAPI package;
\item
\texttt{addNewRoomInFlat}, that lets add a new room to an existing flat in the EnvironmentAPI package;
\item
\texttt{updateRoomInFlat}, that lets update a room in an existing flat in the EnvironmentAPI package;
\end{itemize}


\begin{center}
\begin{fslongtable}{| p{4cm} | p{4cm} | p{6cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Method}} & \multicolumn{1}{|c|}{\textbf{Status code}} & \multicolumn{1}{|c|}{\textbf{Meaning}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line

\multirow{3}{*}{\parbox{4cm}{\textbf{updateDeviceLocation}}} & \texttt{200 Ok} & the location was successfully modified \\
 & \texttt{412 Precondition Failed} & the location was not modified because the Device Factory or the HouseModel is not available \\
 & \texttt{304 Not Modified} & the location was not modified due to an unknown error \\ [0.5ex]
\hline
\multirow{3}{*}{\parbox{4cm}{\textbf{updateDeviceDescription}}} & \texttt{200 Ok} & the description was successfully modified \\
 & \texttt{412 Precondition Failed} & the description was not modified because the Device Factory or the HouseModel is not available \\
 & \texttt{304 Not Modified} & the description was not modified due to an unknown error \\ [0.5ex]
\hline
\multirow{2}{*}{\parbox{4cm}{\textbf{executeCommand}}} & \texttt{200 Ok} & the command was successfully sent to the device \\
 & \texttt{417 Expectation Failed} & it was not possible to send the command to the device due to an unknown error\\ [0.5ex]
\hline
\multirow{2}{*}{\parbox{4cm}{\textbf{addNewFlat}}} & \texttt{201 Created} & the flat was successfully added \\
 & \texttt{304 Not Modified} & the flat was not added due to an unknown error \\ [0.5ex]
\hline
\multirow{3}{*}{\parbox{4cm}{\textbf{updateFlat}}} & \texttt{200 Ok} & the flat was successfully updated \\
 & \texttt{412 Precondition Failed} & it was not possible to update the flat, because it does not exist \\
 & \texttt{304 Not Modified} & the flat was not updated due to an unknown error \\ [0.5ex]
\hline
\multirow{2}{*}{\parbox{4cm}{\textbf{addNewRoomInFlat}}} & \texttt{201 Created} & the room was successfully added \\
 & \texttt{304 Not Modified} & the room was not added due to an unknown error \\ [0.5ex]
\hline
\multirow{3}{*}{\parbox{4cm}{\textbf{updateRoomInFlat}}} & \texttt{200 Ok} & the room was successfully updated \\
 & \texttt{412 Precondition Failed} & it was not possible to update the room, because it does not exist \\
 & \texttt{304 Not Modified} & the room was not updated due to an unknown error \\ [1ex] % [1ex] adds vertical space
\hline

\caption{Method responses after modification} % title of Table
\label{table:method_responses_after_modification} % is used to refer this table in the text
\end{fslongtable}
\end{center}


Thus, after the analysis of all methods that has to be changed, it was time to understand how Jersey lets generate HTTP response codes respecting HTTP specifications.\\

As we know (we have already discussed it in \emph{\nameref{how_dog_exposes_rest_api}}), Jersey allows to define specific annotations to provide easy implementations of methods that have to reply to HTTP requests.\\
However, it does not provide any annotation to manage specific HTTP response codes, and so, if we need to answer with a specific HTTP response code to a request, it is required to generate a ``WebApplicationException'', a runtime exception that builds an HTTP response with the status code passed as argument.\\

Thus, for example, if we want to generate a ``404 (Not Found)'' status code, we can simply use the instruction listed in the following  \mylist{\ref{404_in_jersey}}.\\

\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=0mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
 throw new WebApplicationException(Response.Status.NOT_FOUND);

\end{minted}
\caption{``\texttt{404 (Not Found)}'' status code generation in Jersey}
\label{404_in_jersey}
\end{listing}

Consequently, considering all these considerations, we have finally modified the shown methods.\\

\section{WebSocket server implementation}


The next step in the implementation process, was the creation of a simple WebSocket server able to interact with updated version of REST API.\\

Thus, what we made is:
\begin{itemize}
\item
create a new bundle: \texttt{it.polito.elite.dog.communication.ws}, that should implement the WebSocket API.
\item
import the packages implementing the REST API to let our bundle use its exposed methods and services;
\item
create and modify the \texttt{component.xml} file (important because we want to use Declarative Services as mechanism to deal with dynamic nature of services) to reference the right services.\\
\end{itemize}

Then, considering what we had designed in the previous chapter, it was time to understand how we might implement a WebSocket server using Jetty (\cite{jetty_website}) in OSGi.\\


First of all, it was necessary to download (from \cite{jetty_maven_repository}) the Jetty WebSocket package, implementing the OSGi Jetty WebSocket bundle, and to import it in our bundle.\\
Then, in order to implement all needed methods, we had to create 2 classes:
\begin{itemize}
\item
\texttt{WebSocketEndPoint}, that extends the class \texttt{org\-.eclipse\-.\-jetty.\-w\-e\-b\-s\-o\-c\-k\-e\-t\-.\-W\-e\-b\-S\-o\-c\-k\-e\-t\-S\-e\-r\-v\-l\-e\-t};
\item
\texttt{WebSocketImplementation}, that implements the class \texttt{org.\-eclipse.\-jetty.\-w\-e\-b\-s\-o\-c\-k\-e\-t\-.\-WebSocket.\-OnTextMessage}.\\
\end{itemize}


The first one is responsible of the servlet registration at a given URI path (e.g., ``/dogws''), and the implementation of the \texttt{doWebSocketConnect} method, that is the method called every time a user connects to the server and so that has to instantiate the second class (\texttt{WebSocketImplementation}).\\

Instead, the second, is responsible of implementing methods that manage connections and messages (the sendMessage method is not mentioned because it is not customizable):
\begin{itemize}
\item
``onClose(int statusCode, String reason)'', called every time a connection is closed;
\item
``onOpen(Connection connection)'', called every time a connection is opened;
\item
``onMessage(String data)'', called every time a message is received.\\
\end{itemize}



Even if the first two methods (\texttt{onClose} and \texttt{onOpen}) seem to be useless in terms of user interaction, they are actually the most important one, because they let us uniquely identify each user: every time a user connects to the WebSocket server, a \texttt{WebSocketEndPoint} is instantiated, and consequently, a \texttt{WebSocketImplementation} class is instantiated, too.
Moreover, as a result, the \texttt{onOpen} method is called and so it could be used to fill in a user list.\\

Therefore, we used the last part of the string that identifies the instantiation (i.e., if we have the following string \texttt{it.\-polito.\-elite.\-dog.\-c\-o\-m\-m\-u\-n\-i\-c\-a\-t\-i\-o\-n\-.\-w\-s\-.\-W\-e\-b\-S\-o\-c\-k\-e\-t\-I\-m\-p\-l\-e\-m\-e\-n\-t\-a\-t\-i\-o\-n\-@\-4\-2\-1\-1\-4\-2\-5\-3}, we use only the number that follows the ``@'': \texttt{42114253}) to create a user id and so to recognize each user; hence, we used the \texttt{onOpen} method to fill in the user list, and the \texttt{onClose} one to empty it.\\

Finally, at this first step of the implementation process, we have instantiated the Http Service with the service provided by the Jetty implementation, and we have implemented a simple \texttt{onMessage} method to have a plain working WebSocket server that was able to open a connection with a client.\\

Consequently, in order to add functionalities to this simple and empty server, we went to the next step that aims to manage receiving messages and get the right information from them.


\section{Messages management}
\label{messages_management}

As we know, the task of sending messages is entrusted to the \texttt{sendMessage} method (it is a non re-definable method provided by the Jetty WebSocket package), instead, the task of receiving them is entrusted to the \texttt{onMessage} one, that is part of our class.

As both of them accept only strings as input, and considering that we had decided to use JSON formatted messages, we needed to implement some codes that had to convert information from or to JSON formatted strings.\\

For this reason, we decided to search for the best way to do it, and even if we had found a lot of alternatives, the best choice for us was the ``Jackson Project'' (\cite{jackson_website}), that was already used in the REST API.

Thanks to its well done tutorials and to its comprehensive documentation, it has been very simple to convert JSON formatted strings.
In fact, Jackson allows to extract Plain Old Java Objects (``POJO'') from pieces of JSON, or vice versa, by simply declaring a class that is made up as described in the example shown below.\\

If, for example, we want to parse the following JSON formatted message:\\


\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
{
  "clientId":"1f7170d4",
  "messageType":"info",
  "type":"presentation"
}
\end{minted}
\caption{Presentation JSON example}
\end{listing}

we have to simply create a class (for example we will name it \texttt{PresentationJsonClass}) with the content contained in \mylist{\ref{presentation_json_class_example}}.\\

\begin{listing}[htbp]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}     
public class PresentationJsonClass {
	// id of the client
	private String clientId;
	// type of the message sent by the user
	private String messageType;
	// type of the request/response/info
	private String type;
	
	// get "clientId"
	public String getClientId()
	{
		return clientId;
	}
	
	// setters for "clientId"
	public void setClientId(String clientId)
	{
		this.clientId = clientId;
	}
	
	// get "messageType"
	public String getMessageType()
	{
		return messageType;
	}
	
	// setters for "messageType"
	public void setMessageType(String messageType)
	{
		this.messageType = messageType;
	}
	
	// get "Type"
	public String getType()
	{
		return type;
	}
	
	// setters for "Type"
	public void setType(String type)
	{
		this.type = type;
	}
}
\end{minted}
\caption{PresentationJsonClass example}
\label{presentation_json_class_example}
\end{listing}

Thus, in the class we need:
\begin{itemize}
\item
a variable for each JSON object we want to extract from the message;
\item
a ``setter'' method that should aim to set the corresponding variable with the value passed as argument. Its name should be made up by the word ``set'' followed by the capitalized name of the variable, and it is required for each JSON object, too;
\item
a ``getter'' method that should aim to return the value of the corresponding variable. Its name should be made up by the word ``set'' followed by the capitalized name of the variable, and it is required for each JSON object, too.\\
\end{itemize}

Finally, to actually parse JSON code we have to use one of the following methods.
\begin{itemize}
\item
\texttt{readValue}: it lets convert a string containing JSON code to java POJO objects. It needs the class defining the JSON structure (the \texttt{PresentationJsonClass} class of the example) as input and returns an object that belongs to the same class;
\item
\texttt{writeValueAsString}: it lets convert a java POJO object to a string containing the corresponding JSON code. As input, it requires only a variable that belongs to the class defining the JSON structure (the \texttt{PresentationJsonClass} class of the example) filled by ``setter'' methods.\\
\end{itemize}

In \mylist{\ref{conversion_example}} we show a complete conversion example referred to the structure shown in the previous example: at first we set the value of the variables contained in the class and then we convert the whole POJO structure to string.


\begin{listing}[htb]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=true,
	xleftmargin=21pt,
	tabsize=4]{js}
//set the value of the variables contained in the class
PresentationJsonClass presentationExample = new PresentationJsonClass();
presentationExample.setClientId("1234qwe2");
presentationExample.setMessageType("info");
presentationExample.setType("presentation");
//convert the whole POJO structure to string
String result = this.mapper.writeValueAsString(presentationExample);
\end{minted}
\caption{Conversion example}
\label{conversion_example}
\end{listing}


\section{Metaprogramming}
\label{metaprogramming}

At this point, we had a complete and working WebSocket server that was able to open/close a connection with a client, and parse JSON formatted messages, so the next step was related to the implementation of the methods responsible for the execution of requested actions.\\

In order to achieve this goal, we started from the observation that all the REST API methods were uniquely identified by a pair of JAX-RS annotations: the Path annotation and the HttpMethod annotation (GET, PUT, POST or DELETE)).\\

We were simply looking for a plain way to invoke a method using the information contained in the request, aiming at avoiding the use of lengthy and incomprehensible if-clauses and/or the duplication of existing code.
Thus, we had only to understand what Jersey did to invoke a method by its annotations.\\

In brief, Jersey uses the so-called metaprogramming, that is the ability of a program to inspect existing external code in order to invoke its methods or functions. In fact Jersey:
\begin{itemize}
\item
creates an instance of the class containing the needed methods and their annotations;
\item
browse all methods checking if their annotation corresponds to the researched one.\\
\end{itemize}

Therefore, we needed, and so we have implemented, a method (whose name is ``getRightClass'') that, depending on the content of the \texttt{endPoint} field contained in the received message, would have performed the following actions:
\begin{itemize}
\item
select the class in which the method addressed by the first part of \texttt{endPoint} is;
\item
select, if present, the right method addressed by the second part of \texttt{endPoint};
\item
return the right Class.\\
\end{itemize}

\begin{figure}[htb]
\centerline{\includegraphics[width=0.7\paperwidth]{images/generic_class_diagram.png}}
\caption{Simplified class diagram reporting the components involved in metaprogramming}
\label{fig:generic_class_diagram}
\end{figure}

To better understand how the metaprogramming was used in our case, we can look at \myfig{\ref{fig:main_client_view}}.
It shows a simplified class diagram in which we can identify all the bundles involved in the metaprogramming.

As we can see, at the center of all the interactions there is the WebSocket bundle (\texttt{it.polito.elite.dog.communication.ws}) that interacts with various other bundles and components.\\

First of all it interacts with the end user devices providing interfaces to its methods (API); then it collaborates with the two bundles included in the Dog Communication Layer: the Device and the Environment bundle; the WebSocket bundle cooperates with them by invoking their methods to retrieve information (or send commands to) about the devices and/or the environment.

Moreover, the WebSocket bundle interacts with the OSGi event bundle in order to manage notifications and get information from them.
Finally, it contacts the configuration file to get required parameters needed for its configuration.\\

However, coming back to the specific actions performed by the method that implement the invocation, it should be useful to look at an example to better understand what it actually does.\\

If the \texttt{endPoint} field (contained in the JSON formatted request) contains the value \texttt{/api\-/environment\-/flats}, the method will select at first the \texttt{EnvironmentRESTApi} class, because the first part of \texttt{endPoint} field is \texttt{/api\-/environment}, and then, if it contains a method annotated by the \texttt{/flats} Path annotation, it will return that class as result.\\

However, we have omitted another check that the method has to do before returning the class: the selection of the right method has to be made considering the \texttt{HttpMethod} annotation, too. In fact, if the \texttt{action} field of the request contains the value \texttt{GET}, it must look for the method annotated by the \texttt{/flats} Path annotation and the \texttt{GET} HttpMethod annotation, too.\\

Hence, at this point, with the class returned by this method we might have simply called the required method by the \texttt{invoke} instruction made available by the \texttt{java.\-lang.\-reflect.\-Method} class, keeping its result and inserting it in our JSON response.\\

However, there was an additional task to consider.

As we have already discussed, not all REST API methods returned a value as result: only methods corresponding to \texttt{GET} HttpMethod annotation answered with contents; the other ones generated an exception that forced Jersey to answer with an HTTP code response. Thus, it was necessary to intercept these exception and return:
\begin{itemize}
\item
a \texttt{Command executed successfully} message as successful result;
\item
a \texttt{Command execution failed} message as unsuccessful result.\\
\end{itemize}


Nevertheless, as already discussed in \emph{\nameref{commands_responses}}, these 2 messages indicates only if the method ends with or without any trial of execution (Unsuccessful message).

This is caused by the fact that the system cannot know if the command sent to the device was actually executed, and so its ``OK'' result can only indicate if the sending process went right or not.

So, to know if the execution went right it is necessary to wait for a state change notification or to ask a device status with a specific request.\\

\section{Notifications}

The last step in the implementation process was related to the notifications.\\

As already discussed in the design chapter, even if the notification manager was a completely new part, we decided to use for notifications the same structure used for the other messages (i.e., the messages used to invoke REST API methods as well as return their results).\\

However, as we have already discussed it, we can go directly to the analysis of all the procedures that brought us to the final implementation of our WebSocket API.\\

\subsection{Manage OSGi events}

The first things to understand were:
\begin{itemize}
\item
what notifications are;
\item
who generates them;
\item
which are the event fields that contains interesting information.\\
\end{itemize}

Let us start from the first and the second points: each device is able to generate and send information about its status and/or about its status changes.
These information are, obviously, sent to the gateway that would be able to generate internal understandable messages.\\

Therefore, our first effort was related to the registration of our bundle as listener for events generated by the OSGi EventAdmin bundle responsible for retrieving information from the notifications: we have simply modified the \texttt{component.xml} file and partial transformed the \texttt{WebSocketEndPoint} class.

Specifically, we have modified the \texttt{WebSocketEndPoint} class so that, becoming an implementation of the \texttt{org.osgi.service.event.EventHandler} class, it had to implement the \texttt{handleEvent(Event event)} method responsible for events processing.\\


With this in mind, let us go through the third point.
The information contained in each event are not known in advance, but there are two fields that are always present:
\begin{itemize}
\item
\texttt{notificationTopic}: we used it to know if the specific notification had to be sent to a user;
\item
\texttt{deviceUri}: it could be used to identify the device that had sent it.\\
\end{itemize}

Thus, now that we understood who generates the events, and what they should contain, it should seem too simple to generate and send a JSON formatted notification: we should only extract the content of important known fields, create the notification with information contained in them, and attach all the unknown data to it.\\

However, another problem exists: every time a user opens a connection with the server, a new instance of WebSocketImplementation is instantiated, but the \texttt{handleEvent} method is called only by the last, related to the last connected user, opened instance of it; it means that if a connection is closed and the instance is de-instantiated, the called instance is the one instantiated before it.\\

So it is also necessary to store a list of all instances to let system browse trough it and send the notifications to all users that had subscribed them.

Obviously, the list is not a simple list containing only the correspondence between users and their subscribed notifications, but it is a more complex object: it is an HashMap of HashMap (\emph{HashMap<String, HashMap<String, ArrayList<String>>>}).

Specifically, its fields represent:
\begin{itemize}
\item
the first key contains the clientId;
\item
the second key contains the deviceUri (it corresponds to event's deviceUri field);
\item
the last Array contains the list of notifications subscribed for the specific user and the specific deviceUri.
\end{itemize}

So, the next step was the implementation of the methods that should fill in and empty the user list, registering and unregistering notifications.\\

\subsection{Notification Registration}

As discussed in the \emph{\nameref{design_chapter}} chapter, we have to guarantee the registration/unregistration of four types of subscriptions:
\begin{itemize}
\item
subscribe/unsubscribe ALL the notifications for ALL devices;
\item
subscribe/unsubscribe ALL the notifications for a SPECIFIC device (identified by an ``id'');
\item
subscribe/unsubscribe some notifications for ALL devices;
\item
subscribe/unsubscribe some notifications for a SPECIFIC device (identified by an ``id'').\\
\end{itemize}

As described in the \emph{\nameref{notifications_design}} section, if a user wants to subscribe all notifications has to leave empty the field related to the device id. So, the first thing to do in the method that actually manages the registration and unregistration processes, was to check if parameters received were empty or not: in the former case we had to fill each of them with an ``all'' value.\\

Then, we had to implement the code responsible for the real registration: it had to fill in the list of notifications subscribed by each user, but taking care of the already contained values.

If, for example, an ``all'' value was already contained, and the user has asked to register a specific notification, it has to advice the user with a ``Notification registration failed'' message without any modification of the list.

Or, if an all unsubscription was required, it has to unsubscribe all notifications, even if they are related to a specific device or a specific notification.\\


Consequently, to summarize, every time a user sends a notification registration / unregistration request, our method gets all the information contained in the request, check if it is an ``all'' registration/unregistration or not, and then fill in or empty the list taking care to perform the right action.\\

Finally, it is important to say that, we have implemented a mechanism by which if something goes wrong, the state of the list is brought back to the state held at the moment of the request reception.

Thus, in this case, a message sent by the server indicates exactly if the notification was subscribed or not (and not only that the request was successfully sent or not).


\section{Usage workflow}
\label{usage_workflow}

At the end of this chapter, we show what a developer should do in a typical scenario in which he wants to implement a simple application that uses our WebSocket API.\\

Let us suppose the developer wants to build an application that, at start-up, shows the list of all the rooms present in the building and lets user click on them to show the list of all contained devices, to control them.

Each device should be shown with the following information:
\begin{itemize}
\item
its name and description;
\item
the list of all its states;
\item
the commands available for it.\\
\end{itemize}

Furthermore, let us suppose he would like to show all the notifications related to all possible devices, with the possibility to stop receiving them whenever he wants.\\

\subsection{Connection through ws protocol}

The most important action that should be performed is connect our application to the server.\\

Thus, supposing that the WebSocket server is executed on a remote service accessible at the uri ``ws://<dog-address>:8080/dogws'', let us analyze the operations that should be performed with two different programming languages:

\begin{itemize}
\item
\textbf{Java}\\

If we want to connect to a WebSocket server in Java, we have to import the two classes \texttt{org.\-eclipse.\-jetty.\-websocket.\-client.\-WebSocketClient}, and \texttt{org.\-eclipse.\-jetty.\-websocket.\-client.\-ClientUpgradeRequest} and to implement the class shown in \mylist{\ref{java_connection}}.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{java}
	    
@WebSocket
public class WebSocketClass
{
	WebSocketClient client = new WebSocketClient();
	// open the connection
	client.start();
	ClientUpgradeRequest request = new ClientUpgradeRequest();

	// connect
	client.connect(this, "ws://<dog-address>:8080/dogws", request);

	// we need to keep the connection open
	try
	{
		return barrier.await();
	}
	catch (BrokenBarrierException e)
	{
		e.printStackTrace();
	}
}

\end{minted}
\caption{Simple class implementing a WebSocket Java connection}
\label{java_connection}
\end{listing}

\item
\textbf{JavaScript}\\

If we want to connect to a WebSocket server in JavaScript we have to implement the code shown in \mylist{\ref{javascript_connection}}.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
// open the connection
websocket = new WebSocket("ws://<dog-address>:8080/dogws");
//define the action that should be done when the connection will be opened
websocket.onopen = function(evt) { alert(evt.data) };
//define the action that should be done when the connection will be closed
websocket.onclose = function(evt) { alert(evt.data) };
//define the action that should be done when a message will be received
websocket.onmessage = function(evt) { alert(evt.data) };
//define the action that should be done when an error will occur
websocket.onerror = function(evt) { alert(evt.data) };
		
\end{minted}
\caption{Simple class implementing a WebSocket JavaScript connection}
\label{javascript_connection}
\end{listing}

\end{itemize}


As we can see, in both examples, it is necessary to use the ``ws'' (WebSocket) protocol.\\

The answer to a connection request is a presentation message in which the server indicates the clientId: the uniquely identifier that the client should send in each request.

The \mylist{\ref{presentation_example}} shows an example of presentation message.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}

{
  "clientId":"1f7170d4",
  "messageType":"info",
  "type":"presentation"
}
		
\end{minted}
\caption{Simple presentation message}
\label{presentation_example}
\end{listing}

\subsection{Obtain the list of all rooms}
\label{obtain_list_of_rooms}

To obtain the list of all rooms contained in our flat (let us suppose its name is ``My\_flat''), we should send a JSON formatted message similar to the one shown in \mylist{\ref{json_for_all_rooms}}, and the answer received from the server should be like the one shown in \mylist{\ref{response_for_all_rooms}}.\\


\begin{listing}
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "action":"GET",
  "endPoint":"/api/environment/flats/My_flat/rooms"
}
		
\end{minted}
\caption{Sample JSON formatted message needed to obtain the list of all available rooms}
\label{json_for_all_rooms}
\end{listing}


\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
{
 "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "GET",
  "endPoint" : "/api/environment/flats/My_flat/rooms",
  "response" :
  {
    "rooms" :
	[
		{
			"ceiling" :
			{
				"id" : "ceiling",
				"class" : "Ceiling"
			},
			"floor" :
			{
				"id" : "floor",
				"class" : "Floor"
			},
			"id" : "storageRoom",
			"walls" :
			[
				{
					"id" : "wall",
					"class" : "Wall"
				}
			],
			"class" : "StorageRoom"
		}
	]
  }	
				
\end{minted}
\caption{Sample response to a request that has required the list of all rooms}
\label{response_for_all_rooms}
\end{listing}

Thus, let us analyze the Java and JavaScript code needed to send this request:
\begin{itemize}
\item
\textbf{Java}

In \mylist{\ref{java_for_all_rooms}} we show the Java code needed to send the specific request.\\
As described in \emph{\nameref{messages_management}}, we use Jackson to parse JSON formatted string, so the class \texttt{WebSocketJsonDataGeneric} is the class that implements the JSON structure.

Moreover, the \texttt{ObjectMapper} is the Jackson class that let us actually parse data.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{java}

ObjectMapper mapper = new ObjectMapper();
WebSocketJsonDataGeneric webSocketJsonData = new WebSocketJsonDataGeneric();
webSocketJsonData.setClientId("1f7170d4");
webSocketJsonData.setSequenceNumber(String.valueOf(1));
webSocketJsonData.setMessageType("request");
webSocketJsonData.setAction("GET");
webSocketJsonData.setEndPoint("/api/environment/flats/My_flat/rooms");
try
{
	// try to parse the message in JSON format
	String request = mapper.writeValueAsString(webSocketJsonData);
	// try to send the message just parsed
	this.webSocketClass.sendMessage(request);
}
catch (JsonProcessingException e)
{
	// it was not possible to parse the request
	e.printStackTrace();
}
		
\end{minted}
\caption{Simple Java code needed to obtain the list of all rooms}
\label{java_for_all_rooms}
\end{listing}

\item
\textbf{JavaScript}\\

In \mylist{\ref{javascript_for_all_rooms}} we show the JavaScript code needed to send the specific request.\\

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

var myJSONObject = {};
myJSONObject["clientId"] = "1f7170d4";
myJSONObject["sequenceNumber"] = 1;
myJSONObject["messageType"] = "request";
myJSONObject["action"] = "GET";
myJSONObject["endPoint"] = "/api/environment/flats/My_flat/rooms";
var message = JSON.stringify(myJSONObject, replacer);
websocket.send(message);
\end{minted}
\caption{Simple JavaScript code needed to obtain the list of all rooms}
\label{javascript_for_all_rooms}
\end{listing}

\end{itemize}

\subsection{Obtain the list of all devices}

To obtain the list of all devices contained in a room it is necessary to get the list of devices contained in the whole environment and then check what are actually contained in the room.

So, to get the list of all devices contained in the environment we should send a JSON formatted message similar to the one shown in \mylist{\ref{json_for_all_devices}}.

The response will be similar the one already shown in the previous subsection:
it will contains the clientId, the sequenceNumber, the messageType, the action, the endPoint field (containing the same endPoint of the request), and the response.\\

In the response field we will have a JSON formatted structure containing the list of all devices with further information about their description, their location and the possible commands executable on them.\\


\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
		
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "action":"GET",
  "endPoint":"/api/devices/"
}
		
\end{minted}
\caption{Sample JSON formatted message needed to obtain the list of all devices}
\label{json_for_all_devices}
\end{listing}


Thus, to obtain the devices contained in a specific room we have simply to scroll down all the received list of devices, check their \texttt{isIn} field and take only devices that are contained in the needed room (so the devices in which \texttt{isIn} field contains the id of the needed room).\\


The Java and JavaScript code should be similar to the one shown in the previous examples, so we will not show it again. It is only necessary to modify the value of the \texttt{EndPoint} field content to the value \texttt{/api/devices}.\\


\subsection{Obtain the list of all the states related to a device}

As already discussed, to obtain the list of all the states related to a specific device (e.g., ``MeteringPowerOutlet\_3'') we should send a message similar to the one shown in \mylist{\ref{json_for_all_states}}, and the answer should be like the one shown in \mylist{\ref{response_for_all_states_of_a_device}}.


\begin{listing}
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
		
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "action":"GET",
  "endPoint":"/api/devices/MeteringPowerOutlet_3/status"
}
		
\end{minted}
\caption{Sample JSON formatted message needed to obtain the list of all status device}
\label{json_for_all_states}
\end{listing}


\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
{
  "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "GET",
  "endPoint" : "/api/devices/MeteringPowerOutlet_3/status",
  "response" :
    {
      "id" : "MeteringPowerOutlet_3",
      "description" : "Presa di corrente domotica controllabile via wifi",
      "active" : true,
      "status" :
        {
           "SinglePhaseActiveEnergyState" :
           [
              {
                 "value" : "0.0 kWh"
              }
           ],
           "OnOffState" :
           [
              {
                 "value" : "off"
              }
           ],
           "SinglePhaseActivePowerMeasurementState" :
           [
              {
                 "value" : "0.0 W"
              }
           ]
        }
    }
}
				
\end{minted}
\caption{Sample response to a request that has required the list of all states related to a specific device}
\label{response_for_all_states_of_a_device}
\end{listing}

Here the Java and JavaScript code is already similar to the one shown in the \emph{\ref{obtain_list_of_rooms}} example, so we will not show it again. It is only necessary to modify the value of the \texttt{EndPoint} field content to the value \texttt{/api/devices/MeteringPowerOutlet\_3/status}.\\


\subsection{Subscribe all notifications}

After all the requests needed to obtain information, it is time to discuss about the requests needed to subscribe and unsubscribe notifications.\\

To subscribe all notifications related to all devices, we should send a JSON fomatted message similar to the one shown in \mylist{\ref{json_notification_subscription}}, and the answer should be like the one shown in \mylist{\ref{response_to_notification_registration}}.


\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
		
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "type":"notificationRegistration",
  "action":"PUT",
  "endPoint":"/api/devices/notifications"
}
		
\end{minted}
\caption{Sample JSON formatted message needed to subscribe all notifications for all devices}
\label{json_notification_subscription}
\end{listing}


\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
{
 "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "PUT",
  "endPoint" : "/api/devices/notifications",
  "response" :
  {
    "result" : "Registration completed successfully"
  }
}
\end{minted}
\caption{Sample message obtained as response to a notification registration request}
\label{response_to_notification_registration}
\end{listing}

Thus, let us analyze the code that should let us send the request to the server:
\begin{itemize}
\item
\textbf{Java}

In \mylist{\ref{java_notifications_subscription}} we show the Java code needed to send the request to subscribe all notifications related to all devices.

As described in \emph{\nameref{messages_management}}, we use Jackson to parse JSON formatted strings, so the class \texttt{WebSocketJsonDataGeneric} is the class that implements the JSON structure.

Moreover, the \texttt{ObjectMapper} is the Jackson class that lets us actually parse data.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{java}

ObjectMapper mapper = new ObjectMapper();
WebSocketJsonDataGeneric webSocketJsonData = new WebSocketJsonDataGeneric();
webSocketJsonData.setClientId("1f7170d4");
webSocketJsonData.setSequenceNumber(String.valueOf(1));
webSocketJsonData.setMessageType("request");
webSocketJsonData.setType("notificationRegistration");
webSocketJsonData.setAction("PUT");
webSocketJsonData.setEndPoint("/api/devices/notifications");
try
{
	// try to parse the message in JSON format
	String request = mapper.writeValueAsString(webSocketJsonData);
	// try to send the message just parsed
	this.webSocketClass.sendMessage(request);
}
catch (JsonProcessingException e)
{
	// it was not possible to parse the request
	e.printStackTrace();
}
		
\end{minted}
\caption{Simple Java code needed to subscribe all the notifications related to all devices}
\label{java_notifications_subscription}
\end{listing}

\item
\textbf{JavaScript}
In \mylist{\ref{javascript_notifications_subscription}} we show the JavaScript code needed to send the request to subscribe all notifications related to all devices.

\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

var myJSONObject = {};
myJSONObject["clientId"] = "1f7170d4";
myJSONObject["sequenceNumber"] = 1;
myJSONObject["messageType"] = "request";
myJSONObject["type"] = "notificationRegistration";
myJSONObject["action"] = "PUT";
myJSONObject["endPoint"] = "/api/devices/notifications";
var message = JSON.stringify(myJSONObject, replacer);
websocket.send(message);
\end{minted}
\caption{Simple JavaScript code needed to subscribe all the notifications related to all devices}
\label{javascript_notifications_subscription}
\end{listing}

\end{itemize}


\subsection{Unsubscribe all notifications}


To unsubscribe all notifications related to all devices, we should send a JSON formatted message similar to the one shown in \mylist{\ref{json_notification_unsubscription}}, and the answer should be like the one shown in \mylist{\ref{response_to_notification_unregistration}}.



\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
		
{
  "clientId":"1f7170d4",
  "sequenceNumber":"1",
  "messageType":"request",
  "type":"notificationUnregistration",
  "action":"PUT",
  "endPoint":"/api/devices/notifications"
}
		
\end{minted}
\caption{Sample JSON formatted message needed to unsubscribe all notifications for all devices}
\label{json_notification_unsubscription}
\end{listing}



\begin{listing}[H]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
{
 "clientId" : "1f7170d4",
  "messageType" : "response",
  "sequenceNumber" : "1",
  "action" : "PUT",
  "endPoint" : "/api/devices/notifications",
  "response" :
  {
    "result" : "Unregistration completed successfully"
  }
}
\end{minted}
\caption{Sample message obtained as response to a notification unregistration request}
\label{response_to_notification_unregistration}
\end{listing}


Here, the Java and JavaScript code is similar to the one shown in the previous notification registration example, so we will not show it again. It is only necessary to modify the \texttt{type} field content to the value \texttt{notificationUnregistration} instead of \texttt{notificationRegistration}.

\chapter{Results}
\label{results_chapter}

In this chapter we discuss some tests performed with the developed WebSocket API. Specifically, we report the design and the development of a simple application realized in Java and aimed at qualitatively evaluating the API.

Moreover, we compare the performances achieved by the WebSocket API implementation with the performances achieved by the REST API one.\\

\section{Client application}

The purpose of this step was to implement an application that, showing an example of interaction with the API, would let written code be re-used in future works.\\

Consequently, the first effort was related to the design and implementation of a client API library: it provides some methods for each possible request accepted by the endpoint. These methods are responsible of retrieving information received as argument, create the corresponding JSON formatted request and then send it to the endpoint.\\

To explain with more details the concept, we can look at the following example.

We know that the gateway is able to perform the action indicated in a request similar to the one depicted in \mylist{\ref{new_flat_request}}, that aims at creating a new flat in the environment.

\begin{listing}
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	xleftmargin=25pt,
	tabsize=4]{js}
	
POST http://www.mydog.com/api/environment/flats

-- REQUEST-BODY: --

{
	"id" : "loft",
	"class" : "Flat",
	"description" : "The loft in the city center",
	"rooms":[
		{
			"id" : "kitchen",
			"class" : "Kitchen",
			"description" : "The kitchen with a wonderful view"
		},
		{
			"id" : "bedroom",
			"class": "Bedroom",
			"description" : "My bedroom"
		}
	]
}
		
\end{minted}
\caption{Sample request that aims to create a new flat}
\label{new_flat_request}
\end{listing}

Thus, we have created a new method (shown in \mylist{\ref{new_flat_method}}), naming it ``addNewFlat'', that, keeping the configuration of the new Flat as argument, generates the corresponding JSON formatted message that has to be sent to the gateway to perform this action.\\

\begin{listing}[htbp]
\begin{minted}[frame=single,
	fontsize=\small,
	framesep=3mm,
	linenos=false,
	tabsize=4]{js}
	
public int addNewFlat(Flat addedFlat)
{
  if (this.clientId != null)
  {
    // increment the sequenceNumber, so that every message has a
    // different sequenceNumber
    this.sequenceNumber++;
    // create the Json message representing the request that has to be
    // sent to the server
    WebSocketJsonDataGeneric webSocketJsonData = new WebSocketJsonDataGeneric();
    webSocketJsonData.setClientId(this.clientId);
    webSocketJsonData.setSequenceNumber(String.valueOf(this.sequenceNumber));
    webSocketJsonData.setMessageType(messageType.REQUEST.toString());
    webSocketJsonData.setAction(action.POST.toString());
    webSocketJsonData.setEndPoint("/api/v1/environment/flats");
    
    String flatJson;
    try
    {
      // parse the parameter in json format
      flatJson = this.mapper.writeValueAsString(addedFlat);
      webSocketJsonData.setParameters(flatJson);
    }
    catch (JsonProcessingException e1)
    {
      // if it can't parse the json received we can't add the flat
      return 0;
    }
    try
    {
      // try to parse the message in Json format
      String request = this.mapper.writeValueAsString(webSocketJsonData);
      // try to send the message just parsed
      this.webSocketClass.sendMessage(request);
    }
    catch (JsonProcessingException e)
    {
      // it was not possible to parse the request
      e.printStackTrace();
      return 0;
    }
    // return the sequenceNumber of the request
    return this.sequenceNumber;
  }
  else
    return 0;
}
		
\end{minted}
\caption{Method implemented to let user create a new flat}
\label{new_flat_method}
\end{listing}

Analyzing the code of the example (\mylist{\ref{new_flat_method}}), there is a first part in which, after a check on the ``clientId'', we use the Jackson library (we discuss about it in \emph{\nameref{messages_management}}) to create a JSON formatted message including the information received as method arguments. Then we try to send the message to the gateway, returning:
\begin{itemize}
\item
the sequenceNumber, if the client API was actually able to send the message;
\item
the 0 value, if the client API was not actually able to send the message due to an any kind of problem.\\
\end{itemize}

Summarizing, we have created a client API library, implementing as many methods as the requests accepted by the gateway are.

This library should be reused from any developers that want to implement their own Java application interacting with Dog through WebSocket.\\

After all, using JavaFX, a GUI library for Java SE 7, we have realized the simple end-user application built considering the typical workflow discussed in the \emph{\nameref{usage_workflow}} section. Such an application has been split into two different parts:
\begin{itemize}
\item
the ``controller'' of the application, i.e., the package that provides all methods needed to get and elaborate data; it is the part responsible of communication with the developed library;
\item
the ``View'', i.e., the part that realizes the output representation of the information.\\
\end{itemize}

Therefore, we can analyze its specific behaviour.
At startup such an application sends different requests to the server:
\begin{itemize}
\item
it asks for the list of all the rooms contained in the environment;
\item
it asks for the list of all devices present in the home (with all the information related to them);
\item
it asks for the list of all device's states;
\item
it asks for the registration of all notifications about all available devices.\\
\end{itemize}


Then, as soon as the required information are available, it shows a view similar to the one depicted in \myfig{\ref{fig:main_client_view}}, that presents the list of all available rooms and exposes all arriving notifications in the bottom of the window.\\


\begin{figure}[htb]
\centerline{\includegraphics[width=0.7\paperwidth]{images/client1.png}}
\caption{Main client view: List of all rooms - The notifications are activated}
\label{fig:main_client_view}
\end{figure}


Furthermore, within the main view, it is possible to select (clicking on the corresponding button) a specific room for seeing all the contained devices with their status, as shown in \myfig{\ref{fig:list_of_devices}}.\\

Moreover, it is possible to unregister/register all the notifications by pressing the pause button: looking at the two shown images it is possible to note that in the first one the notifications are activated, instead in the second one they are stopped.\\


\begin{figure}[htb]
\centerline{\includegraphics[width=0.7\paperwidth]{images/client2.png}}
\caption{Screenshot of the client app showing the list of devices contained in the living room - The notifications are disabled}
\label{fig:list_of_devices}
\end{figure}


\section{Performances analysis}

After the implementation of the sample application, it was the time to analyze the performances of our WebSocket API comparing them with the REST API.\\


To calculate the time needed by the two different technologies, we have performed two different tests, \begin{itemize}
\item
one in JavaScript that sends all the possible requests in sequence to the WebSocket endpoint on the gateway;
\item
the other one in bash, that sends all the possible requests in sequence to the REST endpoint.\\
\end{itemize}

These two scripts allowed to measure the time spent by the two API implementation to reply to a request.

Moreover, by sending all the possible requests accepted by the server, they highlight some problems and bugs hard to discover without them.\\

On the whole, we can go through the analysis of the results.\\

In order to obtain information about the time spent by the REST and the WebSocket API in almost all typical situations, we have performed eight different tests into two distinct situations:
\begin{itemize}
\item
Local requests: we sent each request within the same LAN in which the gateway was;
\item
Remote requests: we sent each request from an external network; in this case the time will be affected by various wide network issues (e.g., NAT traversal or hardware firewall traversal), and it is the reason why we decided to look at the performances achieved in this situation, too.
\end{itemize}

Related results are reported in the following subsections and in Appendix \emph{\ref{appendix_a}}.

We can see that in the tables showing the WebSocket results there is a row absent in the REST ones: the ``open connection''.
The reason is that with WebSocket is possible to use the same connection for all the requests, and so the time needed to open the connection has to be considered only at the beginning. Instead, the REST API needs to open a new connection for each request, so, even if the last table (the table with the average values) shows a 0 value for the ``open connection'' row, it is included in all the times shown.\\


\subsection{Local requests}

\mytab{\ref{table:local_rest_api_performances}} shows the time needed to receive responses using the REST API in all the eight tests done, instead \mytab{\ref{table:local_websocket_api_performances}} shows the time needed using the WebSocket API, always in all the eight done tests.

In both of them there are sixteen different sent messages corresponding to all the possible requests that the endpoint is able to accept. As we can see, the reported values are almost similar between the eight tests and show that the WebSocket is faster than REST, even if the difference is not so great in the local tests.\\

On the other hand, \mytab{\ref{table:local_average_performances}} shows an average value calculated over the eight tests, and it become more evident the fact that WebSocket is usually faster than REST: even if there is a situation in which REST seems faster than WebSocket (actually the two value are very similar and differs only for 2 milliseconds), the total value demonstrates that in a typical situations in which a lot of requests are sent, the WebSocket protocol is the best choice.\\

As additional consideration, we have to note that the average times are not so much different between the two technologies: the reason is concerned to the fact that the WebSocket implementation has a further work flow depending on the notifications management.

Even if there are not registered notifications, the bundle implementing the WebSocket server has to however manage events arriving from the notifications bundle, so, even though the two solutions could appear similar in terms of time spent to response to the same request, it is not so because the WebSocket one has to manage the events.\\

\begin{center}
\begin{fslongtable}{| p{8.5cm} | c | c | c | c |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{REST average}} & \multicolumn{1}{|c|}{\textbf{WebSocket average}}\\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
Open connection & - & 3 ms \\ [0.5ex]
\hline
GET /api/v1/devices & 33.38 ms & \textbf{22.88 ms} \\ [0.5ex]
\hline
GET /api/v1/devices/MainsPowerOutlet\_2 & 22.50 ms & \textbf{10.38 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/location & 32.88 ms & \textbf{14.25 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/description & 29.75 ms & \textbf{13.13 ms}\\ [0.5ex]
\hline
GET /api/v1/devices/status & 22.50 ms & \textbf{8.25 ms}\\ [0.5ex]
\hline
GET /api/v1/devices/MainsPowerOutlet\_2/status & 23.88 ms & \textbf{5.63 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/commands/on & 127.13 ms & 129.13 ms\\ [0.5ex]
\hline
GET /api/v1/environment & 83.13 ms & \textbf{7.25 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats & 21.25 ms & \textbf{8.25 ms}\\ [0.5ex]
\hline
POST /api/v1/environment/flats & 30.38 ms & \textbf{15 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft & 22.88 ms & \textbf{4.63 ms}\\ [0.5ex]
\hline
PUT /api/v1/environment/flats/loft & 32.63 ms & \textbf{14.25 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft/rooms & 24.00 ms & \textbf{4.75 ms}\\ [0.5ex]
\hline
POST /api/v1/environment/flats/loft/rooms & 34.25 ms & \textbf{14.13 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft/rooms/bedroom & 22.63 ms & \textbf{4.00 ms}\\ [0.5ex]
\hline
PUT /api/v1/environment/flats/loft/rooms/bedroom & 27.88 ms & \textbf{13.38 ms}\\ [0.5ex]
\hline %inserts single line
\multicolumn{1}{|r|}{\textbf{TOT.}} & 591.05 ms & \textbf{292.29 ms}\\ [1ex] % [1ex] adds vertical space
\hline %inserts single line


\caption{Local average performances} % title of Table
\label{table:local_average_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}


\subsection{Remote requests}

In this subsection we show and discuss the results obtained in terms of time spent to receive the response, from an external network (the gateway and the end-user device responsible for the requests are in different remote networks).\\

\mytab{\ref{table:remote_rest_api_performances}} shows the time needed to receive responses using the REST API in all the eight done tests, instead \mytab{\ref{table:remote_websocket_api_performances}} shows the time needed using the WebSocket API, always in all the eight tests.\\

In both of them there are sixteen different sent messages corresponding to all the possible requests that the endpoint is able to accept. Differently with respect to the local situation, here we can see that the values shown in the REST endpoint test table, are not so similar between the eight tests. It should be caused by network usage: at the moment of the tests, the network was, surely, differently used for other activities in the various tests.

Moreover, even if with less impact than in the REST tests, the WebSocket table shows the same effect.\\

On the other hand, \mytab{\ref{table:remote_average_performances}} shows an average value calculated over the eight tests, and shows how WebSocket is usually faster than REST: the total value demonstrates that in a typical situations in which a lot of requests are sent, the WebSocket is the best choice.\\


Finally, we can notice that in the remote tests the differences between the two technologies become harder than the ones in the local tests.


\begin{center}
\begin{fslongtable}{| p{8.5cm} | c | c | c | c |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{REST average}} & \multicolumn{1}{|c|}{\textbf{WebSocket average}}\\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line
Open connection & - & 1.50 ms \\ [0.5ex]
\hline
GET /api/v1/devices & 274.28 ms & \textbf{82.25 ms} \\ [0.5ex]
\hline
GET /api/v1/devices/MainsPowerOutlet\_2 & 162.60 ms & \textbf{42.13 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/location & 178.44 ms & \textbf{39.63 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/description & 93.17 ms & \textbf{34.00 ms}\\ [0.5ex]
\hline
GET /api/v1/devices/status & 93.15 ms & \textbf{32.25 ms}\\ [0.5ex]
\hline
GET /api/v1/devices/MainsPowerOutlet\_2/status & 88.89 ms & \textbf{27.50 ms}\\ [0.5ex]
\hline
PUT /api/v1/devices/MainsPowerOutlet\_2/commands/on & 198.36 ms & \textbf{131.63 ms}\\ [0.5ex]
\hline
GET /api/v1/environment & 128.66 ms & \textbf{31.88 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats & 95.44 ms & \textbf{30.13 ms}\\ [0.5ex]
\hline
POST /api/v1/environment/flats & 161.04 ms & \textbf{34.50 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft & 237.75 ms & \textbf{28.75 ms}\\ [0.5ex]
\hline
PUT /api/v1/environment/flats/loft & 163.24 ms & \textbf{32.63 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft/rooms & 184.10 ms & \textbf{27.88 ms}\\ [0.5ex]
\hline
POST /api/v1/environment/flats/loft/rooms & 147.02 ms & \textbf{30.50 ms}\\ [0.5ex]
\hline
GET /api/v1/environment/flats/loft/rooms/bedroom & 164.01 ms & \textbf{26.50 ms}\\ [0.5ex]
\hline
PUT /api/v1/environment/flats/loft/rooms/bedroom & 181.79 ms & \textbf{32.13 ms}\\ [0.5ex]
\hline %inserts single line
\multicolumn{1}{|r|}{\textbf{TOT.}} & 2551,94 ms & \textbf{639.60 ms}\\ [1ex] % [1ex] adds vertical space
\hline %inserts single line



\caption{Remote average performances} % title of Table
\label{table:remote_average_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}


\chapter{Conclusions and future works}

In this chapter we summarize all the work done within this thesis concentrating our attention on the efforts made and the acquired knowledges that would be useful for future works.\\

Looking at the purposes of this thesis, that aimed at providing an asynchronous ongoing and full duplex connection over the Internet to the Dog gateway, we can easily say that we have reached all of them.\\

Let us start from the choice of the protocol made at the beginning of the design process.

Looking at a solution that provides an asynchronous and full duplex communication between end-user devices and gateways, after a depth analysis of existing technologies and protocols, we have found the technology that respected all our specifications: the WebSocket protocol.\\

The WebSocket protocol was selected because, in addition to the provided features, it is supported within the most popular programming languages and browsers and, specifically, it is easily integrable in an OSGi environment. 

Another reason is that it provides a full duplex communication between a server and a client, and so the server is able to send information as soon as they are available.

Moreover, it seems to be faster than its competitors, specifically faster than the REST solutions that use polling to retrieve updated information and ask for system changes.\\

Then, we analyzed the choices concerning the connection type (i.e., the choice between a synchronous or an asynchronous connection) and the message structure (i.e., the required fields and the data format).

Deciding to use metaprogramming for avoiding the use of lengthy and incomprehensible if-clauses and/or the duplication of existing code to perform the same actions already supported by REST API, we have created a message structure that enables the definition of clean methods that invoke REST API methods to set and get information from the gateway.

Furthermore, we chose to use asynchronous communications because our main purpose was to provide a way to send notifications as soon as they are available.\\

Equally important and of particularly interesting, was the implementation phase.
The reason of this statement resides in the new knowledges acquired by learning how to invoke methods reusing JAX-RS annotations.

The study of Jersey behaviour was very useful to understand how Java let developers use annotations to invoke methods that are declared in classes developed by others.

Moreover, it was enlightening the study needed to implement notification manager: in order to register our bundle as listener of events generated as notifications, we have analyzed the OSGi behaviour to understand what were the actions needed to retrieve information from generated events.\\

Finally, we have written detailed documentation about the usage of such API, providing a Java example that could be used as start point for future works and a client API library that implements the methods needed for creating JSON formatted messages for all the possible requests accepted from the WebSocket end point.\\

\section{Future works}

Every time a software developer or a software research team, decides to implement an API that could let other programmers use her software product, is because she believes that there are a lot of possible future works that could use her solution.\\


Starting from a simple application that is able to turn a light on, and going to an application that could let automatically open/close a window depending on the temperature of the room, we can find various applications in which Dog can help developers create their own custom software for a vendor-independent domotic environments.\\

Moreover, considering specifically the WebSocket API, it can help software engineers provide faster and more interactive applications that could be widely spread in the existing domotic world.\\

In this thesis, concentrating only on the Dog WebSocket endpoint, we have realized a simple application that provides only basic functionalities to show how a developer could implement his own application using our client library API (represented in the \emph{\nameref{results_chapter}} chapter).

Thus, the first work that could be done in the future is related to the development of a complete application that should let user send all possible commands to the gateway, and subscribe/unsubscribe every kind of notifications.\\

Moreover, considering that every software born with a lot of hidden errors, it should be useful to implement a complete set of test cases to check all the Dog features and find all existing (if they actually exist) bugs.\\

Another possible future work could be updating of all the external packages and bundles used by our API: the current WebSocket API version, uses a lot of external bundles (e.g., Jetty at version 8.1.10 or Jackson at version 1.9.2) and considering that everyone continues to improve its features, it should be useful to update them in order to correct possible bugs and/or provide more efficiency services.\\

Furthermore, thinking about the fact that the JAX-RS connector (used to expose REST API) has improved its features implementing the support to SSE, it should be useful to implement it in Dog for providing another method to access its functionalities and so increase its spread.\\

Also, considering that at the moment the Rules REST API is not yet completed, it was not possible to implement support for it; thus, a further possible future work is its implementation within the WebSocket API.\\

Finally, in order to extend Dog to as many application fields as possible, it could be profitable to implement examples and client API libraries for any kind of programming language, so that developers can easily integrate it in their own applications.\\

\begin{appendices}
\chapter{Detailed results}
\label{appendix_a}


\begin{center}
\begin{fslongtable}{| p{3cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{test 1}} & \multicolumn{1}{|c|}{\textbf{test 2}} & \multicolumn{1}{|c|}{\textbf{test 3}} & \multicolumn{1}{|c|}{\textbf{test 4}} & \multicolumn{1}{|c|}{\textbf{test 5}} & \multicolumn{1}{|c|}{\textbf{test 6}} & \multicolumn{1}{|c|}{\textbf{test 7}} & \multicolumn{1}{|c|}{\textbf{test 8}}\\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line

GET /api/v1/devices & 34 ms & 40 ms & 34 ms & 35 ms & 34 ms & 22 ms & 33 ms & 35 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2 & 20 ms & 25 ms & 26 ms & 28 ms & 25 ms & 27 ms & 14 ms & 15 ms \\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/location & 32 ms & 39 ms & 34 ms & 34 ms & 37 ms & 24 ms & 31 ms & 32 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/description & 38 ms & 38 ms & 24 ms & 25 ms & 25 ms & 21 ms & 34 ms & 33 ms \\ [0.5ex]
\hline
GET /api/v1/devices/ status & 26 ms & 23 ms & 25 ms & 26 ms & 20 ms & 26 ms & 21 ms & 13 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2/status & 26 ms & 26 ms & 20 ms & 25 ms & 27 ms & 24 ms & 22 ms & 21 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/commands/on & 127 ms & 130 ms & 130 ms & 140 ms & 128 ms & 124 ms & 115 ms & 123 ms\\ [0.5ex]
\hline
GET /api/v1/environment & 81 ms & 78 ms & 85 ms & 83 ms & 83 ms & 86 ms & 79 ms & 90 ms \\ [0.5ex]
\hline
GET /api/v1/environment/ flats & 15 ms & 22 ms & 24 ms & 24 ms & 28 ms & 26 ms & 13 ms & 18 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats & 39 ms & 39 ms & 36 ms & 36 ms & 18 ms & 32 ms & 17 ms & 26 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft & 24 ms & 26 ms & 20 ms & 21 ms & 24 ms & 23 ms & 22 ms & 23 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft & 39 ms & 41 ms & 24 ms & 25 ms & 37 ms & 32 ms & 33 ms & 30 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms & 26 ms & 25 ms & 22 ms & 27 ms & 20 ms & 25 ms & 22 ms & 25 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats/loft/rooms & 42 ms & 33 ms & 36 ms & 30 ms & 31 ms & 36 ms & 34 ms & 32 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms/ bedroom & 26 ms & 27 ms & 24 ms & 21 ms & 15 ms & 21 ms & 23 ms & 24 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft/rooms/ bedroom & 41 ms & 28 ms & 38 ms & 18 ms & 18 ms & 33 ms & 22 ms & 25 ms\\ [0.5ex]
\hline %inserts single line
\multicolumn{1}{|r|}{\textbf{TOT.}} & \textbf{636 ms} & \textbf{640 ms} & \textbf{602 ms} & \textbf{598 ms} & \textbf{570 ms} & \textbf{582 ms} & \textbf{535 ms} & \textbf{565 ms} \\ [1ex] % [1ex] adds vertical space
\hline %inserts single line

\caption{Local REST API performances} % title of Table
\label{table:local_rest_api_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}


\begin{center}
\begin{fslongtable}{| p{3cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{test 1}} & \multicolumn{1}{|c|}{\textbf{test 2}} & \multicolumn{1}{|c|}{\textbf{test 3}} & \multicolumn{1}{|c|}{\textbf{test 4}} & \multicolumn{1}{|c|}{\textbf{test 5}} & \multicolumn{1}{|c|}{\textbf{test 6}} & \multicolumn{1}{|c|}{\textbf{test 7}} & \multicolumn{1}{|c|}{\textbf{test 8}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line

Open connection & 3 ms & 1 ms & 4 ms & 4 ms & 5 ms & 4 ms & 2 ms & 1 ms\\ [0.5ex]
\hline
GET /api/v1/devices & 37 ms & 16 ms & 20 ms & 26 ms & 21 ms & 28 ms & 18 ms & 17 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2 & 6 ms & 19 ms & 7 ms & 12 ms & 9 ms & 7 ms & 10 ms & 13 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/location & 14 ms & 13 ms & 18 ms & 18 ms & 17 ms & 10 ms & 14 ms & 10 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/description & 16 ms & 12 ms & 16 ms & 17 ms & 18 ms & 8 ms & 10 ms & 8 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ status & 13 ms & 6 ms & 6 ms & 4 ms & 11 ms & 7 ms & 8 ms & 11 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2/status & 4 ms & 7 ms & 10 ms & 4 ms & 8 ms & 4 ms & 4 ms & 4 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/commands/on & 125 ms & 124 ms & 127 ms & 124 ms & 123 ms & 122 ms & 124 ms & 164 ms\\ [0.5ex]
\hline
GET /api/v1/environment & 10 ms & 4 ms & 6 ms & 7 ms & 4 ms & 11 ms & 8 ms & 8 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats & 11 ms & 4 ms & 8 ms & 7 ms &  4 ms & 15 ms & 7 ms & 10 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats & 20 ms & 16 ms & 13 ms & 17 ms & 12 ms & 15 ms & 13 ms & 14 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft & 5 ms & 3 ms & 4 ms & 9 ms & 4 ms & 5 ms & 3 ms & 4 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft & 15 ms & 14 ms & 12 ms &  15 ms & 24 ms & 11 ms & 12 ms & 11 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms & 4 ms & 4 ms & 5 ms & 9 ms & 5 ms & 4 ms & 3 ms & 4 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats/loft/rooms & 16 ms & 13 ms & 13 ms & 17 ms & 19 ms & 11 ms & 11 ms & 13 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms/ bedroom & 9 ms & 3 ms & 3 ms & 3 ms & 5 ms & 3 ms & 3 ms & 3 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft/rooms/ bedroom & 16 ms & 15 ms & 12 ms & 13 ms & 11 ms & 13 ms & 13 ms & 14 ms\\
\hline
\multicolumn{1}{|r|}{\textbf{TOT.}} & \textbf{324 ms} & \textbf{274 ms} & \textbf{284 ms} & \textbf{306 ms} & \textbf{300 ms} & \textbf{278 ms} & \textbf{263 ms} & \textbf{309 ms}\\[1ex] % [1ex] adds vertical space
\hline %inserts single line

\caption{Local WebSocket API performances} % title of Table
\label{table:local_websocket_api_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}



\begin{center}
\begin{fslongtable}{| p{3cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{test 1}} & \multicolumn{1}{|c|}{\textbf{test 2}} & \multicolumn{1}{|c|}{\textbf{test 3}} & \multicolumn{1}{|c|}{\textbf{test 4}} & \multicolumn{1}{|c|}{\textbf{test 5}} & \multicolumn{1}{|c|}{\textbf{test 6}} & \multicolumn{1}{|c|}{\textbf{test 7}} & \multicolumn{1}{|c|}{\textbf{test 8}}\\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line

GET /api/v1/devices & 389 ms & 128 ms & 139 ms & 127 ms & 285 ms & 874 ms & 115 ms & 138 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2 & 98 ms & 95 ms & 86 ms & 93 ms & 90 ms & 650 ms & 101 ms & 88 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/location & 104 ms & 88 ms & 111 ms & 97 ms & 99 ms & 741 ms & 82 ms & 105 ms \\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/description & 102 ms & 82 ms & 84 ms & 81 ms & 97 ms & 99 ms & 99 ms & 102 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ status & 103 ms & 99 ms & 84 ms & 85 ms & 99 ms & 98 ms & 99 ms & 78 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2/status & 97 ms & 87 ms & 80 ms & 97 ms & 75 ms & 96 ms & 78 ms & 100 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/commands/on & 205 ms & 190 ms & 196 ms & 216 ms & 201 ms & 209 ms & 185 ms & 186 ms\\ [0.5ex]
\hline
GET /api/v1/environment & 151 ms & 111 ms & 104 ms & 113 ms & 124 ms & 166 ms & 129 ms & 131 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats & 102 ms & 83 ms & 103 ms & 86 ms & 84 ms & 100 ms & 100 ms & 106 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats & 84 ms & 103 ms & 82 ms & 100 ms & 83 ms & 655 ms & 82 ms & 100 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft & 85 ms & 73 ms & 82 ms & 111 ms & 94 ms & 678 ms & 97 ms & 682 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft & 82 ms & 84 ms & 95 ms & 105 ms & 101 ms & 81 ms & 102 ms & 656 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms & 97 ms & 80 ms & 116 ms & 812 ms & 95 ms & 79 ms & 98 ms & 96 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats/loft/rooms & 81 ms & 80 ms & 100 ms & 503 ms & 99 ms & 132 ms & 82 ms & 100 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms/ bedroom & 79 ms & 80 ms & 102 ms & 677 ms & 83 ms & 102 ms & 90 ms & 99 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft/rooms/ bedroom & 126 ms & 95 ms & 102 ms & 762 ms & 100 ms & 84 ms & 89 ms & 94 ms\\ [0.5ex]
\hline
\multicolumn{1}{|r|}{\textbf{TOT.}} & \textbf{1984 ms} & \textbf{1559 ms} & \textbf{1666 ms} & \textbf{4068 ms} & \textbf{1810 ms} & \textbf{4844 ms} & \textbf{1627 ms} & \textbf{2860 ms} \\ [1ex] % [1ex] adds vertical space
\hline %inserts single line

\caption{Remote REST API performances} % title of Table
\label{table:remote_rest_api_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}


\begin{center}
\begin{fslongtable}{| p{3cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} | p{1cm} |} % (c c -> 2 centered columns  - l=left, r=right)
\hline %inserts double horizontal lines
\multicolumn{1}{|c|}{\textbf{Request}} & \multicolumn{1}{|c|}{\textbf{test 1}} & \multicolumn{1}{|c|}{\textbf{test 2}} & \multicolumn{1}{|c|}{\textbf{test 3}} & \multicolumn{1}{|c|}{\textbf{test 4}} & \multicolumn{1}{|c|}{\textbf{test 5}} & \multicolumn{1}{|c|}{\textbf{test 6}} & \multicolumn{1}{|c|}{\textbf{test 7}} & \multicolumn{1}{|c|}{\textbf{test 8}} \\ [0.5ex] % inserts table heading
\hline
% inserts single horizontal line

Open connection & 1 ms & 1 ms & 2 ms & 2 ms & 1 ms & 2 ms & 1 ms & 2 ms\\ [0.5ex]
\hline
GET /api/v1/devices & 131 ms & 83 ms & 68 ms & 85 ms & 65 ms & 65 ms & 83 ms & 78 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2 & 67 ms & 39 ms & 57 ms & 39 ms & 32 ms & 29 ms & 37 ms & 37 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/location & 91 ms & 40 ms & 26 ms & 36 ms & 31 ms & 24 ms & 37 ms & 32 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/description & 46 ms & 38 ms & 29 ms & 38 ms & 27 ms & 26 ms & 34 ms & 34 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ status & 41 ms & 36 ms & 32 ms & 33 ms & 24 ms & 26 ms & 32 ms & 34 ms\\ [0.5ex]
\hline
GET /api/v1/devices/ MainsPowerOutlet\_2/status & 35 ms & 30 ms & 22 ms & 32 ms & 21 ms & 21 ms & 30 ms & 29 ms\\ [0.5ex]
\hline
PUT /api/v1/devices/ MainsPowerOutlet\_2/commands/on & 135 ms & 134 ms & 122 ms & 133 ms & 125 ms & 141 ms & 132 ms & 131 ms\\ [0.5ex]
\hline
GET /api/v1/environment & 45 ms & 31 ms & 26 ms & 36 ms & 24 ms & 26 ms & 34 ms & 33 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats & 30 ms & 30 ms & 24 ms & 32 ms & 24 ms & 28 ms & 34 ms & 39 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats & 49 ms & 39 ms & 27 ms & 36 ms & 29 ms & 26 ms & 38 ms & 32 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft & 31 ms & 31 ms & 25 ms & 30 ms & 22 ms & 30 ms & 32 ms & 29 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft & 40 ms & 39 ms & 30 ms & 36 ms & 22 ms & 30 ms & 32 ms & 32 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms & 31 ms & 30 ms & 22 ms & 32 ms & 22 ms & 24 ms & 32 ms & 30 ms\\ [0.5ex]
\hline
POST /api/v1/environment/ flats/loft/rooms & 33 ms & 39 ms & 23 ms & 35 ms & 26 ms & 25 ms & 32 ms & 31 ms\\ [0.5ex]
\hline
GET /api/v1/environment/ flats/loft/rooms/ bedroom & 30 ms & 30 ms & 23 ms & 29 ms & 22 ms & 20 ms & 30 ms & 28 ms\\ [0.5ex]
\hline
PUT /api/v1/environment/ flats/loft/rooms/ bedroom & 40 ms & 37 ms & 28 ms & 34 ms & 27 ms & 26 ms & 35 ms & 30 ms\\ [0.5ex]
\hline
\multicolumn{1}{|r|}{\textbf{TOT.}} & \textbf{876 ms} & \textbf{707 ms} & \textbf{586 ms} & \textbf{698 ms} & \textbf{544 ms} & \textbf{569 ms} & \textbf{685 ms} & \textbf{661 ms}\\[1ex] % [1ex] adds vertical space
\hline %inserts single line

\caption{Remote WebSocket API performances} % title of Table
\label{table:remote_websocket_api_performances} % is used to refer this table in the text
\end{fslongtable}
\end{center}

\end{appendices}
\begin{thebibliography}{9}


\bibitem{osgi_book} Addison Wesley, {\em OSGi and Equinox: Creating Highly Modular Java\texttrademark  Systems},  Jeff Mcaffer, Paul Vanderlei, Simon Archer - 14/feb/2010.


\bibitem{elite_website}
\url{http://elite.polito.it/} ,
``e-Lite website'',

\bibitem{home_automation_definition}
\url{http://en.wikipedia.org/wiki/Home_automation} ,
``Home automation definition'',

\bibitem{what_is_osgi}
\url{http://www.osgi.org/Technology/WhatIsOSGi} ,
``What is OSGi: OSGi Alliance definitions'',

\bibitem{what_is_osgi_wikipedia}
\url{http://en.wikipedia.org/wiki/OSGi} ,
``Definition of OSGi on Wikipedia'',


\bibitem{osgi_specification}
\url{http://www.osgi.org/download/r5/osgi.core-5.0.0.pdf} ,
``OSGi Core Release 5 Specification'',

\bibitem{event_admin_bundle}
\href{http://dz.prosyst.com/pdoc/mBS_SH_SDK_7.2.0/um/runtime/osgi/docs/framework/bundles/osgi/eventadmin/eventadmin.html}{http://dz.prosyst.com/pdoc/mBS\_SH\_SDK\_7.2.0/um/runtime/osgi/docs\\/framework/bundles/osgi/eventadmin/eventadmin.html} ,
``Event Admin Bundle specification and implementation'',

\bibitem{jax-rs_documentation}
\url{https://jax-rs-spec.java.net/nonav/2.0/apidocs/index.html} ,
``JAX-RS documentation'',



\bibitem{jersey_website}
\url{https://jersey.java.net/} ,
``Jersey: RESTful Web Services framework'',


\bibitem{websocket_definition}
\url{http://en.wikipedia.org/wiki/WebSocket} ,
``Websocket definition'',


\bibitem{websocket_specification}
\url{http://tools.ietf.org/html/rfc6455} ,
``Specification of PROPOSED STANDARD for The WebSocket Protocol'',


\bibitem{websocket_implementation_example}
\href{https://cwiki.apache.org/confluence/display/TUSCANYWIKI/Develop+websocket+binding+for+Apache+Tuscany}{https://cwiki.apache.org/confluence/display/TUSCANYWIKI/Develop+\-websocket+\-binding+\-for+\-Apache+\-Tuscany} ,
``WebSocket implementation example'',


\bibitem{websocket_api_working_draft}
\url{http://www.w3.org/TR/2009/WD-websockets-20091222/} ,
``The Web Sockets API - W3C Working Draft 22 December 2009'',


\bibitem{html_italian_introduction_to_websocket}
\url{http://www.html.it/articoli/introduzione-ai-websocket/} ,
``Introduction to WebSocket'',


\bibitem{websocket_official_website}
\url{http://www.websocket.org/} ,
``WebSocket official site'',


\bibitem{jetty_website}
\url{http://www.eclipse.org/jetty/} ,
``Jetty website'',

\bibitem{jetty_websocket_osgi_bundle}
\url{http://mvnrepository.com/artifact/org.eclipse.jetty/jetty-websocket/8.1.10.v20130312} ,
``Jetty WebSocket OSGi bundle'',



\bibitem{sse_definition}
\url{https://jersey.java.net/documentation/2.3.1/sse.html} ,
``Server-Sent Events (SSE) Support - SSE definition'',

\bibitem{polling}
\url{http://en.wikipedia.org/wiki/Polling_(computer_science)} ,
``Polling definition'',

\bibitem{websocket_polling_comparison}
\url{http://www.peterbe.com/plog/are-websockets-faster-than-ajax} ,
``Are WebSockets faster than AJAX?'',

\bibitem{polling_and_its_alternatives}
\url{http://en.wikipedia.org/wiki/Comet_(programming)} ,
``Polling and its alternatives'',

\bibitem{polling_alternatives2}
\href{http://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet}{http://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet} ,
``Polling alternatives'',

\bibitem{dog_2.0_source_code}
\url{http://github.com/dog-gateway} ,
``Dog 3.0 source code'',

\bibitem{dog_website}
\url{http://dog-gateway.github.io} ,
``Dog website'',


\bibitem{dogont_description}
\url{http://elite.polito.it/dogont} ,
``DogOnt description'',


\bibitem{what_is_rest}
\url{http://www.restapitutorial.com/lessons/whatisrest.html} ,
``What is rest'',


\bibitem{jersey_osgi}
\url{http://wiki.eclipse.org/Jetty/Feature/Jetty_OSGi} ,
``Jetty on OSGi'',


\bibitem{osgi_jax_rs_connector}
\url{https://github.com/hstaudacher/osgi-jax-rs-connector} ,
``OSGi - JAX-RS Connector '',

\bibitem{advantages_disadvantages_of_synchronous_ssynchronous_communications}
\href{http://javaj2eeplanet.blogspot.it/2011/05/advantages-disadvantages-of-synchronous.html}{http://javaj2eeplanet.blogspot.it/2011/05/advantages-disadvantages-of-synchronous.html} ,
``Advantages and Disadvantages of Synchronous and Asynchronous Communications'',

\bibitem{synchronous_and_asynchronous_communication}
\href{http://etec.ctlt.ubc.ca/510wiki/Synchronous_and_Asynchronous_Communication:Tools_for_Collaboration}{http://etec.ctlt.ubc.ca/510wiki/Synchronous\_and\_Asynchronous\_Communication:\\Tools\_for\_Collaboration} ,
``Synchronous and Asynchronous Communication'',

\bibitem{json_website}
\url{http://www.json.org/} ,
``JSON website'',


\bibitem{jackson_website}
\url{https://github.com/FasterXML/jackson} ,
``Jackson Project Website: a multi-purpose Java library for processing JSON data format'',

\bibitem{jetty_maven_repository}
\url{http://mvnrepository.com/artifact/org.eclipse.jetty/jetty-websocket} ,
``Jetty Maven Repository'',


\bibitem{Semprini_thesis}
\url{http://elite.polito.it/files/thesis/fulltext/SempriniLuca.pdf} ,
``Semprini's thesis used for information about Dog and Osgi'',

\end{thebibliography}

\end{document}
