58

POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

POLITECNICO DI MILANO

Corso di Laurea Magistrale in Ingegenria Informatica

Dipartimento di Elettronica e Informazione

CONTEXT-AWARE APPLICATIONSDEVELOPMENT: A COMPARISON OF

DIFFERENT APPROACHES

Relatore: Prof. Fabio A. Schreiber

Tesi di Laurea Magistrale di:

Matteo Rovero, Matricola 766309

Anno Accademico 2012/2013

Page 2: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Contents

Ringraziamenti v

Abstract vi

Estratto vii

1 Introduction 11.1 Structure of the thesis . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Adaptive and context-aware systems 32.1 Context distribution . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Situations and Pervasive computing . . . . . . . . . . . . . . . . 62.3 Solutions at programming language level . . . . . . . . . . . . . . 6

3 Aspect-oriented Programming 83.1 Cross-cutting concerns . . . . . . . . . . . . . . . . . . . . . . . . 83.2 Aspects, Join-points and Pointcuts . . . . . . . . . . . . . . . . . 9

4 Context-oriented Programming 124.1 Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4.1.1 Layers dynamic composition . . . . . . . . . . . . . . . . 13

5 Behavioral Programming 175.1 Behaviors and b-threads . . . . . . . . . . . . . . . . . . . . . . . 175.2 Synchronization protocol . . . . . . . . . . . . . . . . . . . . . . . 185.3 Internal and External Events . . . . . . . . . . . . . . . . . . . . 19

6 Paradigms comparison 206.1 Events for triggering . . . . . . . . . . . . . . . . . . . . . . . . . 236.2 Context management . . . . . . . . . . . . . . . . . . . . . . . . . 246.3 Behavioral variations performance . . . . . . . . . . . . . . . . . 256.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

7 PerLa 287.1 PerLa Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

7.1.1 CDT model . . . . . . . . . . . . . . . . . . . . . . . . . . 297.1.2 Context Queries . . . . . . . . . . . . . . . . . . . . . . . 317.1.3 Context Manager . . . . . . . . . . . . . . . . . . . . . . . 33

i

Page 3: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

8 COP and PerLa comparison 358.1 Context management . . . . . . . . . . . . . . . . . . . . . . . . . 358.2 Behavioral variations performance . . . . . . . . . . . . . . . . . 378.3 Which choice at design stage? . . . . . . . . . . . . . . . . . . . . 428.4 Is there the possibility of an integration? . . . . . . . . . . . . . . 43

ii

Page 4: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

List of Figures

2.1 Layered context model . . . . . . . . . . . . . . . . . . . . . . . . 5

3.1 Cross-cutting concerns example . . . . . . . . . . . . . . . . . . . 9

7.1 O�ce example CDT . . . . . . . . . . . . . . . . . . . . . . . . . 307.2 PerLa architecture with Context Manager . . . . . . . . . . . . . 34

8.1 CDT of the o�ce example with a new air conditioner . . . . . . 408.2 PerLa and the adaptive part of the application on top . . . . . . 448.3 Architecture of the �nal adaptive application on top of PerLa

implemented with COP . . . . . . . . . . . . . . . . . . . . . . . 46

iii

Page 5: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

List of Tables

6.1 Table of comparison between the three paradigms . . . . . . . . . 21

iv

Page 6: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Ringraziamenti

Ringrazio particolarmente il Prof. Fabio Schreiber che ha seguito il mio lavorocon la massima disponibilità, professionalità e partecipazione. Inoltre ringraziol'ing. Romolo Camplani e l'ing. Emanuele Panigati che mi hanno fornito utiliindicazioni su come procedere.

Un pensiero va a tutti i miei amici conosciuti durante la carriera universi-taria, in particolare Luigi, Matteo, Andrea, Marco, Federico, Giorgio, Ettore,Riccardo e Dario.In�ne ringrazio le persone che maggiormente lo meritano e cioè i miei genitorie tutti i miei famigliari, i quali mi hanno sempre sostenuto e aiutato durantetutta la mia vita.

v

Page 7: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Abstract

The adaptation capacity of software is one of the most important topics insoftware engineering nowadays, in particular in pervasive and ubiquitous com-puting areas. In this thesis I describe and analyze three di�erent program-ming paradigms in order to understand their features and di�erences. There-after, I shall compare them in the �eld of context-aware pervasive systems. Ishall discuss also the di�erences between the solutions at architectural level(components-oriented development) and at language level.

vi

Page 8: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Estratto

La capacità di adattamento del software è una delle principali questioni insoftware engineering, in particolare negli ambiti del pervasive and ubiquitouscomputing. In questa tesi descriverò e analizzerò tre diversi paradigmi di pro-grammazione per capire le loro speci�che peculiarità e di�erenze. Successi-vamente, proporrò una comparazione tra essi nel campo di sistemi pervasivicontext-aware. Discuterò anche le di�erenze tra soluzioni a livello architetturale(sviluppo basato su componenti) e a livello di linguaggio.

vii

Page 9: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 1

Introduction

In the recent years, we have witnessed rapid advances in the enabling tech-nologies for mobile and ubiquitous computing, such as the increasing perva-sive computing paradigm, embedded sensor technologies and di�usion of wiredand wireless communication protocols. In pervasive computing cheap, intercon-nected computing devices are able to support users and other systems in a widerange of tasks. These emerging technologies require a design shift from existingdesktop computing technologies, because pervasive applications must operatein highly dynamic environments, reducing as much as possible the involvementof the users.

For these reasons pervasive applications needs to be very sensitive to context.In general the term context can be de�ned as the whole amount of informationavailable in a speci�c situation. Usually, the relevant information useful todetermine the current situation is related to many di�erent entities, such asenvironment states, locality, time, users, etc.... Context must not be consideredas a static block of information, but it changes constantly in agreement withthe evolution of all the entities involved, i.e. contextual information rarelyremains valid over time, but it acquires a particular meaning only under speci�cconditions and depending on circumstances.

In computer science there is a considerable number of di�erent de�nitions.According to [SAW94, P98] context is the complete set of information to an-swer to the questions where?, who?, why?, when? and what?, i.e. context isany information that can be used to characterize the situation of the involvedentities.

In a pervasive computing environment, basic services can be provided byphysical devices for acquiring and rendering information. More advanced ser-vices are delivered by active devices that can act as service aggregators to ap-plications involving communication with numerous services and assisting users.

Although not strictly necessary to the service function, context generallyimpacts its choice and behavior. Moreover, depending on the context, systembehavior must be dynamically adapted.The goal of this thesis is to analyze di�erent approaches designed to supportdynamically adaptive behaviors in context-aware pervasive applications.

1

Page 10: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

1.1 Structure of the thesis

The thesis is organized as follow:

• In Section 2 the basic concepts behind context, context distribution, sit-uation computing, context-awareness and sw adaptivity are presented.Moreover, di�erent solutions to deal with context and behavioral varia-tions are introduced, in particular at programming language level.

• In Section 3, Section 4 and Section 5 the following programming paradigmsare respectively discussed: Aspect-oriented Programming, Context-orientedProgramming and Behavioral Programming.

• In section 6, a theoretical comparison of these paradigms is proposed inorder to show advantages and disadvantages of each one in general and,in particular, for what concern pervasive applications development.

• In section 7, the PerLa framework is presented as example of component-based solution for the management of pervasive environments, in particu-lar the part that concerns context management.

• In section 8, Context-oriented Programming and PerLa Context Languageare compared, the respective features are highlighted in order to showin what circumstances and for what functionality and purposes they arebest suited. Finally, a possible integration between the two approaches isdiscussed and a proposal to extend PerLa functionality is introduced.

2

Page 11: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 2

Adaptive and context-aware

systems

Scientists and engineers have made signi�cant e�orts to design and developadaptive systems. These systems are able to adapt their behavior according tospeci�c changes belonging to two categories: internal changes include all pre-conceived events that occur within the system and able to modify the systemstate while external changes are related to environment and users interactionsand are caused by external events. These systems address adaptivity in variousconcerns, including performance, security, fault management, etc... While adap-tive systems are used in a number of di�erent areas, sw engineers focus on theirapplication in the software domain, called self-adaptive software. Researchersin this area have proposed several solutions to incorporate adaptation mecha-nisms into software systems. Self-adaptive software aims at adjusting variousentities or attributes in response to changes in the self and in the context of asoftware system. By self, we mean the whole body of the software, while thecontext encompasses everything in the operating environment that a�ects theproperties of the system and its behavior. In recent years, there has been anincreasing demand to deal with particular issues, such as managing system com-plexity, correctly handling unexpected conditions, changing priorities, policiesand conditions at run-time.

Sw adaptivity must respect two important properties[MKMSKC04]:

1. Introspection: program has to know its actual behavior exactly in everysituation.

2. Intercession: system has to be able to modify itself basing on observationsor occurred events.

The second property is strictly connected to the basic idea of context. An adap-tation mechanism is expected to trace system changes and to take appropriateactions according to the designed rules and this target can be achieved throughmonitoring all entities that can directly a�ect the behavior of the whole swsystem or a group of modules.

The central concept of adaptivity can be summarized with this de�nition[CdLG09]:�Adaptive systems are able to adjust their behavior in response to their percep-tion of the environment and the system itself�.

3

Page 12: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

On the other hand, a system able to retrieve data, to build and manage contextsand to properly reason on them, is called context-aware.

In context-aware systems context follows these pieces of the whole environ-ment in which it operates:

• Computing environment : available processors, devices accessible for userinput and display, network capacity, connectivity and costs of computing.

• User environment : location, collection of nearby people, and social situa-tion.

• Physical environment : all external phenomena relevant for the system.

In [P98] a context-aware system is de�ned as follow: �A system that providesservices or information to the users according to the context�.

Adaptivity and context-awareness are strictly linked and in many real situa-tions can even be interchangeable. However, context-awareness is more relatedto �information tailoring�, i.e. it refers to the ability of the system to knowexactly at any time the current contextual information and to provide it whenrequired, while adaptivity refers to the execution of behavioral variations in re-sponse to changes of all entities that can a�ect the behavior of the system, alsothe internal sw itself. Despite from a conceptual point of view these two featuresare separate, indeed a context-aware application must also be able to adapt it-self to context, it would be useless to know context, without being capable ofperforming any kind of action in response. For this reason we can assume thata full context-aware application naturally needs adaptivity.

In recent past, many di�erent models for the development of context-awareapplications have been proposed and substantially each of those is based on anarchitectural level design.The most widespread framework created to support context management andadaptivity is Context Toolkit[SDA99]. It simpli�es the building of context-aware applications using the Java programming language.

Its current main features are:

• Abstraction of contexts, sensors, and actuators using Widgets.

• Resource Discovery of distributed components.

• Rule-based, reasoning modeling for context-aware applications throughEnactors.

• Machine learning, reasoning modeling for context-aware applications.

• Explanations of application behavior and reasoning through the Intelligi-bility Toolkit.

• Control, facility through the Enactor framework.

The most important components are the Widgets, which are responsible forseparating the details of sensing context from actually using it. They abstractthe details of how the context is sensed from applications and other contextcomponents that need the context. Context toolkit Widgets can be thought ofas similar to GUI widgets, but applied to sensors and actuators that would be

4

Page 13: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 2.1: Layered context model

common in ubiquitous and pervasive computing systems. Each context com-ponent is responsible for some small set of contexts that is captured from asensor.

This framework represents an example of the inter-relationship betweenadaptations and context. In fact, it provides speci�c components for contextmanagement, but also speci�c components for the encoding of behaviors, calledServices.

2.1 Context distribution

Pervasive and ubiquitous applications have often to deal with distributed en-vironments. Trying to �nd a unique context model to cover all possible infor-mation that each local instance must provide, can be very complex and notadequately e�ective. Designing a dedicated and independent context for eachinstance can be a much better solution.

The Context Toolkit framework introduces a rough concept of context dis-tribution. In fact, each context Widget is responsible for a piece of context thatis captured from a sensor. The main problem of a distributed architecture isthe complexity of univocally reasoning on di�erent separated contexts. Contextdistribution is related to two di�erent concepts:

1. Context model distribution, i.e. how the global context is split in manysub-contexts, each one with speci�c attributes and properties.

2. Reasoning on the distributed context, i.e. how the system utilizes theoutcome of a sub-context for a bigger piece of context.

In [KPKY11] the context model is composed by several layers. The highest levelrepresents the global context of the system, while the lower levels represent thecontexts of any source of information. This abstract model shows a hierarchicaltree-like structure, which is very useful and manageable in many real situations.

The attributes represent any type of data that is relevant for the contextand the reasoning process on it and they are the atomic information unit usedby the local instances to determine their context. Higher level contexts areinferred from lower levels contexts, without considering directly the original

5

Page 14: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

local information. The performance given by this model is very high: it allowsto delegate the management of di�erent pieces of context to di�erent parts ofthe system and also the reasoning on them to many independent entities, and,furthermore, the con�dence of higher level contexts is increased by adding thecon�dence of lower level contexts.

2.2 Situations and Pervasive computing

In mathematical situation theory[M10] the concept of situation is de�ned as theset of things that are happening and the conditions that exist at a particulartime and place, whereas context is the situation within which something existsor happens, and that can help to explain it. Hence, context provides informationthat can be used to characterize the situation of an entity.

In other approaches the term situation takes another meaning. In situa-tional computing[ANH07] situations are viewed as logically aggregated pieces ofcontext, which instead is considered as the mere information on a geographicallocation and knowledge about that location. In this case situation is synony-mous of user activity and context is a simple set of temporal and spatial data.

In [L05] situation and activity are not interchangeable and activity can beconsidered as a type of contextual information which can be used to characterizea situation.Situations and pervasive computing are strictly tied. With the whole amountof data continuously provided by devices, the application behavior must changeaccording to the evolving situation.

In situational computing, many di�erent models to represent situations andcontext have been proposed. In [ANH07] it is utilized the Fuzzy Logic theory toinfer the actual situation of the user and to reason about imperfect contextualinformation, in [RBVCM07] the context is modeled as a network of situationsand then implemented both in a deterministic ad in a nondeterministic way.The �rst case is based on Petri nets, while the second one is based on Markovmodels.

In this thesis the context model used is the CDT model of PerLa, in whicheach node represents a speci�c piece of context. Furthermore, the CDT modelcan be viewed as a proper implementation of the abstract model presented inthe previous section, so it is very suitable for distributed systems.

2.3 Solutions at programming language level

Until 10 years ago there were only solutions at architectural-level to deal withcontext and sw adaptivity. In the recent past, researchers tried to �nd otherways to deal with those issues and, particularly, the focus has shifted on solu-tions at lower level, i.e. at the programming language level. For this reason re-searchers began to move in the direction of embedding context management andcontext-dependent behavioral variations directly in the program code. Thus, thedesign phase of the application and consequently its implementation would re-sult cost-e�ective. Of course, the implementation should result easier in case ofcomplex and large systems, for which a knotty design implies also an expensiveincrease of complexity in code implementation and maintenance.

6

Page 15: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

A context-aware application �ts its behavior according to conditions arisingduring execution. These conditions are always related to three di�erent entities,as previously said: system, user and environment. The user interacts activelyor passively with the system. The system adapts his behavior dynamically, ac-cording to its internal and external information. The environment is everythingthat is external to the relationship and interaction between user and system,but that can a�ect the behavior of both.

Consequently, these applications must deal with three types of behavioralvariation: User-dependent, Environment-dependent, System-dependent.The �rst one is due to information provided by the users, on purpose or auto-matically. The second one is substantially everything not given by the control�ow in the program execution. The last one is related to the possibility of thesystem to modify its behavior, depending on its own current state, historicalinformation, or dependencies to other system parts or subsystems.

It is clear that the capacity of the system to adapt its behavior, accordingto its knowledge of the whole global context, is the most important aspect. Themore information a system is able to retrieve, aggregate and manage, the moreaccurate will be its reasoning on it and consequently its ability to understandthe situation, in which it must operate. Hence, every solution at language levelproposed by sw engineers must allow programmers to reach the goal to developa full context-aware application, able to properly achieve each one of the threetype of variation.

Behavioral variations refer both to alternate among di�erent behaviors, switch-ing the system from the current behavior to a new one, and to perform, atexecution time, a partial or complete modi�cation of the normal behavior.

In the last ten years some paradigms have been proposed to support usualobject-oriented and modular programming languages in context and events man-agement, behavior identi�cation and modi�cation. In this work I shall presentthree programming paradigms belonging to this scope: Aspect-Oriented Pro-gramming, Context-oriented Programming and Behavioral Program-ming.

So far, the adoption of a solution at the programming language level is con-sidered an alternative to a solution at the architectural level, since this kindof programming paradigm was born to ease the design phase, removing, in thisway, the requirement of project dedicated components to achieve the same func-tionality. In current literature, the possibility to integrate the two techniquesin real applications is not considered.

In the examples which follow, I shall refer, for each one of these paradigmsto the Java language and to its respective libraries: AspcetJ, Jcop and Bpj.

7

Page 16: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 3

Aspect-oriented Programming

Aspect-oriented Programming (AOP) [KLMMVLI97, AOPinJavaWS] is the�rst and most widespread paradigm created to support sw adaptation and evo-lution. AOP has been developed to tackle the problem of Cross-cutting inprogram code. This is a major problem of object-oriented and functional pro-gramming languages and it can a�ect many part of a program. AOP was bornto support normal programming languages with some dedicated features to dealwith some events which can occur in the program control �ow and could a�ectthe normal behavior of the system.

3.1 Cross-cutting concerns

A concern in computer science is de�ned as a speci�c set of information whicha�ects the code of a program. Generally speaking, a concern can be bothan abstract concept relevant to the design phase of the program, such as theabstract de�nition of an object or a component, and a low level property, suchas a function signature. All concerns must be separated from each other in orderto allow the optimization of a speci�c aspect of the program independently ofothers. In this way a program can be developed in many di�erent and separatesections, each one involved in the speci�cation of a particular concern. However,there is a particular kind of concerns which cannot be expressed in normal OOPlanguages with separate sw entities. These concerns are called Cross-cuttingconcerns [CMJvdB07] and they can a�ect multiple concerns of the program.They involve changes in many places across the system. The most commonare synchronization, resources access control, monitoring, interactions amongobjects or errors detection. This phenomenon is often related to code scatteringand tangling, but it is a more complex concept. To explain this concept Ipropose this simple example:

In an application, some interactions between some concerns have been de-signed. Considering Figure 3.1, nodes are the objects of the program whileedges represent a relationship between two nodes, such as the requirement ofsynchronization between them. This relationship can be thought as a bidirec-tional function f between a source node and a target node, such as f(s) = t andf(t) = s. Of course this is only an abstract model, in fact this function says onlythat a bound exists between the two concerns, and it has not a real pragmatical

8

Page 17: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 3.1: Cross-cutting concerns example

meaning.In the example in Figure 1. there are two source concerns and three target

concerns.

S1 crosscuts s2 on target t2, in fact an intersection is present between thetwo concerns. Of course this is an abstraction and in real cases it is morecommon that concerns do not crosscut each other directly by a single edgebut they can be related among di�erent paths of concerns, called Cross-cuttingPatterns[CMJvdB07], which denote the situation where source and target arerelated to each other through trace dependencies. The abstract intersectionbetween two concerns at design level, causes a lot of problems in the programcode, such as an increase of useless code and unusual errors.

Starting from this intuitive explanation of the concept of Cross-cutting, in[CMJvdB07] the authors provide a formal de�nition of the three main issues thatcan a�ect relations among concerns and consequently the code of a program, inorder to clarify the di�erence among them:

Scattering: a concern is scattered if it is a source and has more than one target.

Tangling: a concern is tangled if it is a target and is related to more than onesource.

Cross-cutting: s1 cross-cuts s2 if s1 has more than one target and one of thesetargets is in a relationship with s2 too.

3.2 Aspects, Join-points and Pointcuts

Object-oriented and functional languages do not provide solutions to solve theissues listed above. To provide a solution, the Aspect-Oriented programming

9

Page 18: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

paradigm has been introduced in sw engineering scenario.AOP focuses on implementing cross-cutting concerns as separate modules

that can modify the behavior of base application modules. These modules arecalledAspects, which are new program constructs used to capture cross-cuttingconcerns of a sw system in separate program entities. The application classeskeep their usual responsibilities while each aspect captures the cross-cuttingbehavior. Avoiding cross-cutting, code scattering and tangling are solved conse-quently, hence the code of the program results more clear, consistent and easyto understand and manage for programmers. .

Aspects must suitably coordinate with other parts of the program, other-wise they are absolutely useless. They coordinate with other sw modules andcomponents in speci�c points of the program code, called join-points. A join-point represents a spot in the program which speci�es when an aspect should beexecuted, for example, in case of a method invocation or an exception raising.The piece of code, associated to a join-point, that must be executed is locatedin the pointcut statement. A pointcut picks out a set of join points based onde�ned parameters, as explicit function names or function names speci�ed bywildcards (execution(* *(..), call(* set(..))). When one or more join-points ina pointcut have been activated, additional code is executed, modifying in thisway the normal behavior of the program. Thus, the pointcut exposes data fromthe execution context of those join points. The additional code is encapsulatedin the construct advice , and it can be executed before, after or around thejoin-point. A particular pointcut, called c�ow , identi�es join points based onwhether they occur in the dynamic context of other join-points. Pointcuts canbe de�ned in a class or in an aspect.

Inter-type declarations provide a way to express crosscutting concerns af-fecting the structure of modules. Also known as open classes, this enables pro-grammers to declare in one place members or parents of another class, typicallyin order to combine all the code related to a concern in one aspect.

Of course, programmers must always check that the new program behavior,provided by an aspect, does not create problems to the execution of the behav-iors of other parts of the program. Aspects must work on their own separately.

Furthermore, a join-point can be considered as a single event for the program.In a pointcut, the code of the advice speci�es how the system must respondcorrectly to a speci�c fact, de�ned by a join-point, occurred in the control �owof the program. For example, considering the synchronization concern, thepointcut which deals with synchronization among threads, describes obviouslymany join-points, but each of them covers a speci�c aspect of the process andthis aspect is separated by others. A join-point could represent the release of ashared resource by a thread, and this is viewed as a single aspect of the entireprocess of synchronization among threads and also a speci�c unique event forthe program.

So far I treated static AOP, according to AspcetJ. The process of integrationbetween aspect code and normal code, called aspect weaving [KHHKPLGI03], isexecuted at compile time. The library provides a compiler, called aspect weaver.It reads the aspect-oriented code and generates appropriate object-oriented codeintegrating the aspects. Any parts of the program that are una�ected by advicesare compiled just as they would be by a standard Java compiler. To extend AOPfunctionality, in order to allow to deal with dynamic, at run-time variations, ithas been used in combination with metaprogramming.

10

Page 19: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Due to this lack, new frameworks for this particular purpose have beendeveloped. In static AOP, weaving occurs at compile time, thus the advices areincluded into the compiled bytecode.In dynamic AOP, weaving occurs on the �y while creating the bytecode, sobytecodes related to aspects are added at run-time.

For the Java platform a lot frameworks have been implemented, such asAspectJ are AspectWerkz [B04], CaesarJ[AGMO06] and JBossAOP [S04], etc....In next sections I'll refer to static AOP for what regards syntax aspects of thecode, whereas to its dynamic version when I shall treat its implications in realcases, in particular in comparison with the other two paradigms.

11

Page 20: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 4

Context-oriented

Programming

Context-oriented Programming (COP) [SGP12, MHMMK10, HCN08] enablesthe expression of behavioral variations depending on the current context. Alot of libraries have been introduced to implement COP in most of commonprogramming languages, such as Java, Python, etc... COP treats contextualinformation explicitly and provides a complete support to behavior adaptationat run-time. In this paradigm the focus is entirely moved to context, in thesense that COP, unlike AOP, was born exactly to enable context-dependentadaptivity.

The driving idea of COP can be expressed formally in these terms: when acontext is veri�ed during the execution of a program, it must be able to performa determined set of variations.Context for COP is simply intended as any set of information, which is compu-tationally accessible by any part of the system and may determine behavioralvariations.

The other main concept of COP is the behavioral variation. Each behavioralvariation is related to a speci�c piece of context and can be activated and deac-tivated dynamically at run-time. They allow dynamic activation of a behavioralchange and they represent the modularization unit of such piece of behavior.To create a connection in the program between the contextual information anddynamic behavioral variations, many di�erent solutions have been proposed.However, the layer-based model is by far the most widespread, so I will alwaysrefer to it.

4.1 Layers

Layers are entities which group related context-dependent behavioral variationsand contain partial method de�nitions that implement the functionality of abehavioral variation. Layers can be activated and deactivated dynamically atrun-time. They are identi�ed by the construct layer , which is the equivalent ofthe aspect in AOP. Depending on the current context, di�erent layers will beselected for further program executions. Several solutions have been proposedin COP for layers activation. In JCop library, layers are �rst-class entities,

12

Page 21: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

which can either be de�ned within the classes for which they provide behavioralvariations (layer-in-class), or in a dedicated top-level layer similar to an aspect(class-in-layer). However, the �rst case is the most relevant, because all thepossible variations are directly encapsulated in classes which need adaptations.Layer activation is dynamically scoped: it a�ects the behavior of the programnot only for the method calls syntactically inside the code block, but also forall the calls triggered in turn.

In the Simulation of a Mobile Community example, presented by professorMalte Appeltauer in JCOP web site, an example of layers in a simple smallapplication is provided. The application allows to navigate users cellphonesover a map of Berlin. Changes to the rendering of the cellphone displays areimplemented by layers. For instance, the layer MiniMap takes responsibilityof adaptations, in fact it de�nes which portion of the entire city map mustbe shown, according to the position of the user, while context information ischecked at every predetermined time interval with the method updateContex-tInformation(). If the current context is changed, the layer MiniMap must beactivated, and a new portion of the map is loaded.

This simple application is quite signi�cant, inasmuch it shows the relation-ship between context and behavioral variations in COP.

4.1.1 Layers dynamic composition

Context-dependent behavioral variations are represented as partial method de�-nitions. Partial methods provide a di�erent behavior compared to base methods,which are the de�ned methods to describe the normal behavior. Methods nota�ected by layers are called plain methods while those involved in layers com-position are called layered. The base method is executed when no active layerprovides a corresponding partial method, and at least one partial method de�ni-tion. The dispatch mechanism is intuitive: when activated, layered method callsare dispatched to the partial method provided by the layer. Partial methods canbe executed before, after, or around the base method. This approach is similarto the advice of AOP. If many di�erent layers provide a partial de�nition of thesame method during composition, the execution can proceed to the next partialde�nition until there are no more and then to the base method de�nition.

Keywords with and without provide an explicit layer composition, becausethey specify which layers must be activated (deactivated) for the scoped block.

13

Page 22: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

In this simple example the with statement activates the layers HelloLayer andWorldLayer, which de�ne a partial method de�nition of the base method print().When the execution of the partial method of HelloLayer reaches the proceedinstruction, WorldLayer is activated and its partial method is executed. Whenlayers are no active, the base method de�ned in the class HelloWorld is executed.

However an explicit layer composition, based on with statements, is notgood enough in many cases, for this reason a lot of activation mechanisms havebeen proposed in years.The choice of which adaptation mechanism has to be used depends on the designof the application. For example, if the adaptation concerns only speci�c entitiesthat require local modi�cations, per-object activation can be the best solution.Otherwise, if the adaptation must be performed on many objects in control �ow,dynamically scoped mechanisms allow the activation to be locally controlled andlet the behavioral adaptation propagate along the �ow of execution.

For the goal of this work I focus on dynamically scoped activation and inparticular on declarative layer composition and conditional composition.

14

Page 23: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Event-based composition

Dynamically scoped activation is a general model in which with statementsactivate a sequence of layers in the code block.

In a pervasive environment, context is obviously event-based, and events canbe synchronous, especially those bounded to changes in environment and system,or asynchronous, such as those related to users interaction. JCop providesspeci�c constructs for declarative and event-based composition.

Declarative layer composition model consists of a logic concatenation of pred-icates, which represent events, and a composition block, which contains somewith (or without) statements. Moreover, it introduces two new constructs toprovide a behavior similar to AOP, in order to solve the problem of scatteredwith statements: the keyword on identi�es an event in program execution �ow,that is very similar to pointcut of AOP, and a optional keyword in to bind theobject on which the composition declaration should be evaluated. Also from asyntactic point of view, the on statement is similar to a pointcut.

This model is a good solution, in particular in case of composition based onpredictable events.In situations that are connected with unexpected events, the explicit speci�-cation of those events with on statements can be complex and could becomereally verbose.

For this reason JCop introduces the when statement in addition to theon statements. This predicate speci�es an expression, that represent an eventoccurred in the program control �ow, and if this expression is evaluated to true,layered methods in the code block are activated. Composition made with whenstatements is called conditional.

The on statement speci�es the points �where� composition takes place, whereasthe when statement allows to declare �when� the layers composition must start.

Since declarative and event-based composition statements are independentof speci�c objects, they should be de�ned in a dedicated location. For thisreason, JCop provides a �rst-class context construct. Like layers, contextsare special singleton types that can not be instantiated. The construct can host

15

Page 24: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

both declarative and event-based composition statements and auxiliary methodsand �elds.

For a more complete explanation of those layers composition models see[MHMMK10].

16

Page 25: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 5

Behavioral Programming

Scenario-based programming is a paradigm for systems description and design.It uses autonomous modal speci�cations of �pieces of behavior� to tell the systemunder development, what it can do, must do or may not do under appropri-ate conditions. The primary example of a tool for scenario-based programmingis the visual language of live sequence charts (LSC)[HK02], which extendsclassical sequence diagrams with modalities, and which introduces new and in-teresting ways for generating and executing system behaviors.

The main characteristics of scenario based programming include a naturalmean for incremental development, by the addition of autonomous scenarios,and encoding of requirements and use cases in ways that re�ect the manner inwhich people typically think about system behavior.

Starting from this descriptive scenario-based approach, oriented to cases andscenarios formalization, the Behavioral Programing (BP) [HMW10][HMW12]paradigm has been developed. It allows to build reactive systems incrementallyfollowing the expected chain of behaviors. The basic idea behind BP is tocompose a bunch of simultaneously executing state machines. Each machinerepresents a behavior. So in BP many behaviors can coexist at the same time,but, of course, there can be no con�ict among them.

BP encodes behaviors and the coordination mechanism among them in anordinary programming language, in this case the Java language, alongside thecoding of individual objects with their own behavior. This work can be donewithout relying on a special purpose programming language and virtual envi-ronment.

5.1 Behaviors and b-threads

Following the idea of a behavior expressed by a state machine, it is natural to seeeach behavior as an individual component. In BP behaviors are represented byspecial modules, called b-threads. Each b-thread runs in parallel to the otherb-threads and when a b-thread reaches a point that requires synchronization,it waits until all other b-threads reach the synchronization points in their ownexecution �ow. At synchronization point each b-thread speci�es three sets ofevents:

Requested Events: set of events from which an event is chosen for triggering

17

Page 26: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

by the b-thread, which also must be noti�ed when any of themoccurs.

Waited-for Events: triggering of these events must be noti�ed to the b-thread,but these are only watched, not requested by the b-thread.

Blocked Events: triggering of these events is forbidden.

For a formal de�nition of those sets of events see [HMW10].Each element of these sets is associated with the corresponding action exe-

cutable by a b-thread at synchronization point:

Requesting an event: b-thread asks to be noti�ed when it occurs and pro-poses it for the triggering, if the event is not blocked.

Waiting for an event: b-thread asks to be noti�ed or resumed when it trig-gers.

Blocking for an event: b-thread suspends the occurrence of events that couldbe requested by other b-threads.

5.2 Synchronization protocol

After that all sets of events, according to the scenarios de�ned at design stage,have been identi�ed, the rules to coordinate the triggering of events and behav-iors come into play.

The steps of the protocol follow:

1. When a b-thread reaches a point that requires synchronization, it waitsuntil all other b-threads reach synchronization points in their own �ow,and proposes its sets of events.

2. All b-threads are at a synchronization point, so an event, that is requestedby at least one b-thread and is not blocked by any b-thread, is chosen.

3. The selected event is triggered and each b-thread that either requested itor is waiting for it is resumed.

4. The resumed b-threads continue their execution up to next synchroniza-tion point.

When more than one event is requested and not blocked it is necessary to de�nea policy to choose the proper event. For example the choice criteria can berandom or can depend on a sort of priority order.

The logic of each behavior is coded as a method supplied by the program-mer, which in turn invokes the method bSync(requestedEvent, waitedForEvent,blockedEvent) to synchronize with other behaviors. This method must be en-closed in each b-thread. The activation state of a behavior can be checked atrun-time calling the method takeControl(). The main problem a�ecting BPsynchronization protocol is that, if one b-thread fails to synchronize, the entireapplication stops and must be manually restarted.

18

Page 27: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

5.3 Internal and External Events

For the goal of this work it is essential to understand how BP can be used in realapplications, in particular how it allows to perform variations which are linkedto external and asynchronous events (for example, those user-dependent). InBP, external events are those not triggered by b-threads.

External events are substantially treated in the same way as internal eventsby the behavioral part. The part of the application implemented with thecommon object-oriented language, in which BP is embedded, can detect externalevents and then introduce them at synchronization points. For example, inBPJ library the events of BP are normal instances of the class Event (or itssubclasses), therefore they can be easily �imported� in the behavioral code.

The mechanism to integrate the behavioral part of the system with otherspart is based on the concept of super-steps. A super-step is a macro phasebetween the occurrence of two external events, i.e. it represents the period oftime in which the behavioral part of the system is active.

The mechanism of super-steps is:

1. The �rst super-step begins when the system starts.

2. Internal events are triggered until there are no more such events to trigger.

3. The behavioral part halts, waiting for an external event.

4. The occurrence of an external event, introduced as a behavioral one, marksthe beginning of a new super-step.

This simple scheme allows to deal with the innate asynchronous property ofexternal events and synchronism of the internal events at the same time.

19

Page 28: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 6

Paradigms comparison

Having presented AOP, COP and BP paradigms I want to focus on a comparisonbetween them, in order to understand which paradigm can be considered moresuitable for the development of distributed context-aware pervasive applications.Regarding AOP, as introduced in previous paragraph, I will consider it in itsdynamic version for two reasons: 1) context in pervasive computing is dynamicand events occur at run-time; 2) COP and BP are born to deal with dynamicsituations, therefore it makes no sense to consider static AOP for a theoreticalcomparison with them.

In table 6.1 the main general features of the three paradigms are summarized.

Syntax modi�cation requirement AOP and COP paradigms require spe-cial constructs to enforce their semantic features. AOP introduces theconstruct aspect and other speci�c keywords, such as pointcut , advise ,etc.... On the other hand, COP utilize the construct layer and manyothers statements, depending on the underlying language and the speci�clibrary. While AOP libraries are fairly standardized, those of COP couldsupport the same semantic meaning in many di�erent syntactic ways. Thisis a very important aspect because for a programmer, it is quite easy towork with AOP in a programming language rather than in another and tolearn a new library for another language requires minimal e�ort, insteadmoving from a language to another with COP is not as much manageable.This lack of uniformity among di�erent COP libraries is simply due tothe fact that COP is more recent than AOP. BP, unlike the other twoparadigms, provides only new semantic features to the underlying pro-gramming language, thus it does not require syntactic changes. From thepoint of view of syntax, b-threads are common threads, the bySync()function is a standard method and events are instances of the superclassEvent, which is de�ned for all languages for which a BP library has beendeveloped. Whereas with AOP and COP normal code (for instance thatrelated to common OOP languages) is mixed respectively with �aspect�and �contextual� code, with BP only the normal code exists. Therefore,with BP, programmers have not to know new particular constructs, butexclusively what b-threads describe and how the synchronization protocolworks.

20

Page 29: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Table 6.1: Table of comparison between the three paradigms

Support for dynamic required As previously introduced, COP and BP fo-cus on behavioral variations at run-time, whereas AOP is born to deal withcross-cutting concerns through aspects weaved at compile-time. To addnew features supporting run-time modi�cation, this paradigm was used incombination with metaprogramming. Subsequently, a lot of frameworkshave been developed to make AOP dynamic by dynamic weaving of as-pects. Dynamic weaving consists of adding (removing) aspects to (from)the system at run-time, without need for recompilation or rebooting, i.e.it allows to activate and deactivate dynamically aspects, including aspectspreviously unknown. All frameworks developed for Java (and AspectJ) al-low to indicate which entities must be involved in the dynamic executionusing XML �les or JavaDoc-like annotations. The latter provide a wayto add metadata to the aspect class, rather than specifying it in a sepa-rate de�nition �le. Dynamic AOP allows not only to implement dynamicactivation of aspects, but also to support context-based adaptations. Onthe other hand, COP directly provides all features necessary to performcontext-based behavioral variations at run-time, without the need for us-ing metaprogramming or more di�erent frameworks. However, dynamicweaving of aspects could simulate COP layer activation and behavior ingeneral, using pointcuts and advice, but their speci�cation and implemen-tation could become de�nitely complex.

Sw modularization AOP allows to encapsulate cross-cutting concerns in ded-icated modules separate from others, so it's clear that this paradigm fo-cuses particularly on sw modularization. For this reason AOP is adoptedin di�erent �elds, such as computer security, service providers, sw main-tenance and many others, i.e. wherever sw engineering may be necessary.COP does not introduce abstractions for sw modularization, in fact a layerde�nition is spread among many modularization units, rather, it provides

21

Page 30: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

functionality for dynamic context-based composition of cross-cutting con-cerns and behavioral variations. COP is more suitable for performingbehavioral variations, rather than for sw structuring. However, choosingdeclarative layer composition and, in particular, conditional compositionmodels can be solved code scattering and cross-cutting issues quite easily.On the other hand, BP allows to code scenarios (behaviors) in dedicatedsw components (modules), so it can be certainly considered a modularprogramming technique. With BP, the resulting product is modular, inthat new behaviors can be �exibly added and removed to change systemfunctionality. However BP does not focus on implementation of everysingle aspect related to the program code, such as errors detection or ex-ceptions handling, but on the synchronization of all the possible scenarios,established at design phase following requirements, in which applicationshould run. BP does not deal with cross-cutting concerns, but, as COP,on behavioral variation at run-time. Furthermore, AOP concern and BPscenario are not equivalent, in fact, the �rst can represent both an abstractconcept, such as inter-relationship between components, and a pragmaticconcept related to the program code, whereas the second one has only ahigh level meaning. Trying to utilize b-threads and events of BP to achievean outcome comparable to AOP aspects is mostly useless, because it wouldrequire a lot of e�ort to do it, without obtaining an acceptable result.

Design simpli�cation The �rst development stage of a sw application is tounderstand requirements correctly and, after that, the design phase be-gins. At this stage often requirements are formalized, de�ning use casesand scenarios. BP is born to use directly scenarios for programming.Therefore, the design phase is a crucial part of the development of an ap-plication implemented with BP. If scenarios have been de�ned in a wrongway or if they are inconsistent with requirements or among them, at im-plementation stage those problems can not be solved, but they could onlybe detected at testing stage. For this reason, BP requires a huge e�orton the part of sw engineers in order to correctly design the applicationscenarios, just as common OOP languages. On the other hand, one of themain reasons for the development of COP is to ease the work to do in theapplication design, providing all mechanisms to avoid the de�nition of ad-hoc sw components to perform context-based behavioral variations. AlsoAOP allows to reduce the impact of design in application development,in fact aspects remove the need to identify cross-cutting concerns and todesign dedicated components to deal with them. As previously pointedout, dynamic AOP could be adapted to show a behavior similar to COP,so it can simplify design also for what concerns behavioral variations.

Incremental development Modular programming languages are by their na-ture oriented to incremental development and sw evolution. One of themain advantages of BP is the option to implement the application incre-mentally in modules in agreement with requirements and scenarios. Itallows, in fact, to add new properties, de�ned by b-threads, avoiding tochange the rest of the actual code of the program. The only constraintis that new b-threads, added at a later time, must be synchronized andconsistent with others. With BP sw evolution goes hand in hand with re-quirements evolution. Also COP paradigm supports sw evolution thanks

22

Page 31: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

to the possibility to embed layers in classes: adding new behavioral vari-ations forces to modify only modules a�ected by the proper layers, andnot all existing modules and, in this way, each class encapsulates all itspossible behaviors, facilitating the understanding of the program. Finally,since AOP heavily focuses on sw modularization, it is obviously a reallygood solution for sw evolution. Adding or removing aspects from the sys-tem does not require editing a�ected class de�nitions, and this is validboth for static AOP and for dynamic AOP.

Scoping In COP, the concept of scope is related to the layers activation, trig-gered by the execution of a with statement at a speci�c moment. Withdynamic layers composition, behavioral variations activation in COP isdynamically scoped. During the composition process, a sequence of layersis activated by with statements, following the designed pattern of par-tial method calls, allowing to associate partial behavioral variations withthe classes they belong to, and, at the same time, changing their speci�cbehavior depending on context. In static AOP scope is related to thelexical one of pointcuts and join-points. The scope of a pointcut is theenclosing class declaration, and it matches any join-point, in the speci�edtype, following the de�ned signature of its parameters. In dynamic AOPscope is also related to aspects. For example, in JBossAOP there is thepossibility to set manually the scope of an aspect, in this way it becomepossible to indicate when an instance of the aspect should be created. Anaspect instances can be created on demand per virtual machine, per class,per instance, or per join-point. On the other hand, since BP paradigmdoes not introduce syntactic changes, scope follows the same rule of theunderlying programming language.

So far I focused on general semantic and syntactic di�erences between the threeparadigms, while, from now, I will focus on how they can perform context-speci�c behavioral variations at run-time.

6.1 Events for triggering

For the three paradigms, context is prominently based on events: each one per-forms a speci�c variation, starting from a speci�c event occurred during execu-tion. The problem of �guring out which event is relevant in a speci�c momentduring execution, is delegated to the context model, and the implementationmust be consistent with it. Each one of the three paradigms uses events in itsown way to trigger behaviors.

BP provides the features to trigger behaviors by sequences of events. BPis particularly suitable for this purpose, because the possibility to wait for andblock b-threads at synchronization points allows to manage sequences of eventsquite easily. However this is not valid for events not raised in the behavioralpart of the system, in fact external events are treated as individual events. Theevent that launch a new super-step is provided by the �non-behavioral� part, soit does not directly concern BP.

In AOP only a single event at a time can be considered, due to the restrictionsimposed by join-points. In fact a join-point represents a single event in programcontrol �ow at a given point, and triggering behaviors following rich sequences

23

Page 32: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

of events with aspects, should require a complex management in the aspectcode. A solution could be to de�ne dedicated aspects to obtain a sort of eventsblocking/unblocking mechanism similar to BP, but it could cause a large increasein aspect code and in program complexity substantially equivalent to doing itwith the underlying language, without involving AOP.

In JCop library, behavioral variations are performed activating a sequenceof layers, but this process can be started only by a single event. Howeverother frameworks allows to consider patterns of events for behaviors triggering.EventCJ [KAM10] allows to de�ne contexts per instance by declaring eventsand context transition rules: an event triggers context transitions and a contexttransition rule changes active layers of each object, according to how contextsare changed in response to events. Transition rules can be de�ned specifyinga single event or sequence of events. However, in general, sequences of eventscan be created using the �normal� code and then delivered to �contextual� part(implemented with COP) for layers activation, avoiding the need to use a newspeci�c library.

6.2 Context management

In the previous sections I provided an abstract concept of context, not focusingtoo much on its practical implications. For all the three paradigms context canbe viewed as any accessible information relevant for the system. However, if adata element does not produce, directly or indirectly, a change in the context,it is not treated as �contextual information�. Contextual information is handledby the system to adapt itself dynamically.

In context-aware pervasive applications, contextual information is princi-pally related to observable data retrieved by sensors. However, in many cases,a set of data can be considered an event. For example, consider a system thatis monitoring a user, who is moving across many rooms. When the user movesfrom a room to another one, the system �ags this fact as an event. This eventis detected composing some data obtained by di�erent active sensors, placed indi�erent locations. Instead, the number of active sensors at a speci�c momentis treated as a simple datum, not as an event occurrence. This is an importantdistinction, in particular in relation to BP, because it is particularly based onevents.

Furthermore, each paradigm allows to utilize information, both external andinternal, to determine the context.COP is designed properly to combine both type of information in order toprovide behavioral variations. External and internal information can be mergedto provide the current context of the system or of a group of its components.Nevertheless AOP has not been developed for the speci�c goal of reacting tocontext changes, in its dynamic version, it provides all features necessary tohandle both external and internal information.

Context for BP is totally determined by events. BP consider internal andexternal information as two di�erent entity. In particular the �behavioral part�is not aware of what is happening outside, both while it runs and it halts,until it receives an event, from the �non-behavioral part� of the system. Ofcourse BP can be used to develop the entire application, i.e. not splittingthe system in a behavioral and non-behavioral part. In this scenario, each

24

Page 33: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

module corresponds to a b-thread and each event is generated internally. Inthis way it is possible to deal simultaneously with any contextual aspect relatedto users, environment and system, but this implies a signi�cant increase insystem complexity. However, both dynamic AOP and COP allow to deal withthese situations with much less e�ort and with better results.

Another main point is that each paradigm does not enforce uniqueness ofcontext and di�erent parts of the application, for example di�erent threads, canlive in di�erent contexts and therefore adapt their behavior di�erently. This as-pect is obvious for BP, due the presence of b-threads, but also dynamic AOP andCOP, being modular languages, are very adapt for distributed environments.

After these considerations, context design remains outside from the goals ofthe paradigms, because it is a task of programmers to de�ne consistent contex-tual rules ad-hoc for the application. In fact, COP, BP and AOP are based onadapting the system according to context, rather than on describing di�erentcontextual scenarios.

6.3 Behavioral variations performance

This section treats the most important task of the three paradigms: how theyperform behavioral variations. As stated above, AOP was more focused on swmodularization and on separating cross-cutting concerns, whereas COP and BPwas born for this particular goal, however, with dynamic extensions, AOP canbe reasonable comparable to other two paradigms.

The main important di�erence between COP and BP is that COP makeschanges, more or less considerable, to the normal behavior whereas BP enforcesthe synchronized alternation of di�erent behaviors, which can also run simul-taneously. In COP the composition process can involve a di�erent number oflayers, allowing in this way to compose the system behavior, according to theactual context, while the synchronization mechanism of BP actives, at eachsynchronization point, a new behavior (b-thread), so, although the di�erencesbetween two behaviors are minimal, they are treated as completely di�erententities. The programmers must check that two b-threads are not too muchoverlapped, as this may cause a loss in performance. However, this could notbe an easy task to deal with in scenarios de�nition at design stage. With COPinstead, it is possible both to make simple behavioral variations, activating asmall number of layers, and to build new behaviors, involving more layers, and,in this ways, it can result more �exible in many situations. On the other hand,the more an application grows, the more the complexity of behavioral variationsperforming with layers composition increases, insomuch as it could require a lotof e�ort in order to properly design layers and their composition, reaching alevel comparable to that required by scenarios de�nition of BP.

Finally, with dynamic AOP, it is possible to perform behavioral variations ina way that could be substantially equivalent to COP, also obtaining quite similarresults. In fact, with dynamic AOP you can de�ne an aspect to provide propervariation to the required component: an aspect can replace entirely a layer, theonly di�erence is that a layer is de�ned in the class where the variation takesplace, whereas the aspect is de�ned in a dedicated spot. This feature can bee�ective in situations where it is not easy to de�ne a priori all possible behavioralvariations, as with AOP can add further variations by just putting them in a

25

Page 34: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

new aspect. Furthermore, it is possible to de�ne an aspect into another aspectto propagate variations to manage complex scenarios at run-time.

However, although the results could be similar, COP is more suitable forthis goal, because with layers spread among all objects that require behavioralvariations, the program results more clear and intuitive both to understandand to implement in comparison with aspects structure, also considering thatdynamic AOP needs dedicated frameworks to enable the dynamic weaving ofaspects.

On the other hand, dynamic AOP is the best solution for systems monitoring,because monitoring is one of the most common cross-cutting concerns in anadaptive system.

6.4 Conclusions

From the analysis of the speci�c features of the three paradigms and of thedi�erences between them, it emerges that they are suitable in many di�erent�elds.

Behavioral Programming falls in Arti�cial Intelligence �eld: it is very suit-able for distributed applications based on the execution at run-time of actionsin response of particular sets (or sequence) of events. It allows, in fact, to easilyimplement the designed behavior that the application (instance) has to assumewhen some events occur, i.e. in those situation where a sequence of events oc-currence brings automatically to a new global scenario, whereby the application(instance) must run.

For now, dynamic AOP can be considered the most widespread solutionfor the development of autonomic systems, because it provides speci�c featuresfor dealing with cross-cutting concerns. Moreover, dynamic AOP makes it ex-tremely easy to add functionality to an existing system, since this can be doneby leaving the original code base untouched. It is a natural solution wheneverit is necessary to add autonomic capabilities to an existing system that was notconceived to support them.

Finally, Context-oriented programming can be considered the best paradigmsfor dynamic adaptation: it provides all the necessary features to perform context-speci�c behavioral variations at run-time.COP comes into play, when the development of the application starts fromscratch, it can not be adopted later. It is the better solution to perform behav-ioral variations in general, approaching the entire development process bottom-up. Adaptable parts of the application are enclosed into with statements, whileadaptations are de�ned inside layers, leading to self-explanatory code.

Furthermore, COP is not a simple event-driven paradigm but it's able touse the entire situation, in which it is running, given by the information on theenvironment, the system and the user.The idea of context in COP, in fact, is close to the concept of situation inthe situation computing �eld and this allows, to implement applications able toadapt itself also in unpredictable scenarios.

Moreover, the �exibility of layers composition mechanism is more adequatein many di�erent real situations than the synchronization mechanism betweenb-threads of BP, due the possibility to propagate the variations towards severalmodules, also in not completely expected ways.

26

Page 35: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

After the comparison between the three di�erent solutions at programminglanguage level, it remains to compare the COP paradigm with component-basedsolutions. For this scope I will present how the context is managed in thePerLa middleware and, in particular, how its components perform behavioralvariations, as example of solution at architectural-level.

27

Page 36: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 7

PerLa

PerLa[SCFMR12] is a language developed at Politecnico di Milano to managemodern pervasive systems. PerLa adopts the database metaphor of the pervasivesystem: such approach is data-centric and relies on a SQL-like query language.PerLa queries allow to retrieve data from the pervasive environment, to prescribehow the data have to be processed and stored and to specify the behaviors ofthe devices.

For this reason, PerLa framework provides a middleware to manage andaggregate collected data, to perform some intermediate computations and tosave �nal results into DB tables, hiding the complexity of the underlying systemto the user. One of the main advantages of PerLa for the user is that the e�ortto write code and the time to con�gure the whole system as desired is minimal.

The PerLa framework is characterized by a high scalability: new nodes,containing new types of devices, can be dynamically added to the network, witha speci�c plug & play mechanism. Introducing a simple XML �le which describesthe features of the new device to be attached to the network, the middlewarewill automatically create all modules necessary for the device management.

The language is composed by four types of queries:

• Low level queries (LLQ) allow to sample data and set all parametersof the devices or groups of devices of the same type, such as samplingfrequency, data selection criteria and some immediate computations onsampled data.

• High level queries (HLQ) allow to de�ne the elaboration on �nal resultscoming from di�erent nodes.

• Action queries (AQ) provide the mechanisms to change devices param-eters or to send commands to actuators.

• Context queries (CQ) allow to de�ne everything concerning the con-texts.

In Perla the information is continuously provided in form of independent datastreams. Each LLQ creates a data stream and HLQs de�ne speci�c compu-tations on one or more data streams. Data streams creation and managementare delegated to the middleware and the user is unaware of each intermediateoperation. At the end of the data processing, the persistence component saves�nal results on a DB.

28

Page 37: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

7.1 PerLa Context

The PerLa framework provides a dedicated query language to manage context:with PerLa, developers can create not only several di�erent contexts for di�erentgroups of sensors, but also the rules to merge di�erent contexts and to enact, foreach particular user under a particular situation, the actions to be performedon/by the WSN. Currently, in fact, the actions to execute in response to contextchanges are limited to actuators setting, for example, you can force a group oflights to turn on when night falls and set the brightness level.

With PerLa queries, de�ning new contexts and contextual rules becomes verycomfortable: it is su�cient to know the PerLa language to be able to createany contextual scenario for di�erent situations, directly using data retrievedby sensors, without needing to know which components of the middleware areinvolved.

PerLa adopts the Context Dimension Tree (CDT) model to represent thepossible contexts. This is an important aspect, because the framework providesalready a context model, thus, the application designers are not forced to designa new logical model. With PerLa statements, dedicated to the de�nition of theCDT, you already have a structured and consistent model for de�ning contextualrules.

Two di�erent types of entities have been developed for context managementin PerLa:

• an extension of the existing PerLa language syntax, called Context Lan-guage (CL), in order to declare explicitly the CDT, contexts and actionsto perform.

• a dedicated component, called Context Manager (CM), in order tomaintain and manage the declared CDT, to detect active contexts andto perform the desired actions.

CL include two di�erent types of statements:

• CDT declaration statements, which allow to de�ne the CDT, its dimen-sions and attributes.

• Context creation statements, which allow to declare a context on a de�nedCDT and to control its activation state.

Obviously, declared contexts have no meaning without the corresponding CDT.

7.1.1 CDT model

One of the �rst task to accomplish, when the development of a context-awarepervasive application starts, is the design of the context model, and this couldresult one of the most critical activity in the entire development process. ThePerLa framework provides the CDT as context model.

The CDT models all possible contexts of the environment, as a labeled treecomposed of dimensions and concepts nodes:

• dimensions abstracts di�erent characteristics of the environment.

• concepts represent the sets of values that can take the dimensions.

29

Page 38: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 7.1: O�ce example CDT

The designer can model the environment using the preferred granularity, nest-ing more than one level of dimensions with the unique restriction that everydimension can only have concept children and vice versa.

The attribution to a dimension of a value generate a context element. Acontext is de�ned by the composition of many context elements.Moreover, dimensions and concepts can include some parameters, useful in casethat one of them may have many di�erent instances. This feature can be veryimportant in case of distributed environment, in fact, it becomes possible torecognize di�erent contextual meaning from two dimensions, de�ned in the sameway, but pertaining to two di�erent instances.

The CDT proposed in the Figure 7.1 models a simple common situation ina o�ce. Sensors collect data on the temperature and the energy consumptionof the room and in the room there is an air conditioner.Overload condition is veri�ed when the value, which indicate the energy con-sumption, reaches a certain threshold, while the overheat condition indicateswhen the temperature sensed in the room is too high.

When both conditions are veri�ed, the �re risk increases drastically.

The syntax of the CL to de�ne this CDT is:

CREATE DIMENSION RiskCREATE CONCEPT OverheatWHEN Temperature > 35CREATE CONCEPT OverloadWHEN Consumption > 100CREATE CONCEPT FireWHEN Temperature > 45 AND Consumption > 150

CREATE DIMENSION LocationCREATE CONCEPT O�ceCREATE ATTRIBUTE $Id

30

Page 39: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

The attribute Id includes the possible instances of the dimension O�ce.The $ element is mandatory before the speci�ed variable in every CREATEATTRIBUTE statement, because it indicates that the value is supplied bythe application at run-time.

The CDT model is very simple and intuitive to create and modify and, more-over, it can be incrementally and dynamically extended, adding new dimensionsand values to the current entities when needed.This model can be considered as a particular implementation of the generallayer-based context model proposed by [KPKY11].

In fact, a context C can be formalized as the conjunction of one or morecontext elements (C = (Dimension = Value)), and the information provided bythe lower level nodes can be used by the higher level nodes for the correspondingcontexts as values to attribute to their dimensions.

7.1.2 Context Queries

This type of queries allows to de�ne contexts over the designed CDT and tocontrol contexts activation by de�ning contextual blocks, which are composedof four fundamental clauses, called components:

• ACTIVATION component is used to declare a context.

• ENABLE component allows to set the actions to perform when the cor-responding context is active.

• DISABLE component allows to establish the actions to perform whenthe corresponding context is not active.

• REFRESH component instructs the middleware on how often it mustcontrols context activation.

In this CL query is reported how the context for the monitoring of the risk ofoverheat is created for the CDT in the Figure 2.

CREATE CONTEXT OverheatMonitoringACTIVE IF Location = o�ce (ID) // o�ce () returns the o�ce

instance with the corresponding ID

AND Risk = OverheatREFRESH EVERY 1hON ENABLE (OverheatMonitoring) :

SELECT Temperature, IDSAMPLING EVERY 15 m

EXECUTE IF EXISTS (Temperature)

SET PARAMETER o�ce_cond = TRUEON DISABLE (OverheatMonitoring) :

DROP OverheatMonitoring

SET PARAMETER o�ce_cond = FALSE

This simple CL query sets the parameters which de�ne how to monitorthe temperature for the context and the action, which is turning on the air

31

Page 40: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

conditioner, to perform when the temperature reaches the critical threshold,settled by the corresponding concept.

In simple environments, like the one presented in the previous example,de�ning dimensions and concepts of the CDT and contexts over it is not acomplex task for the designer.However, when you need to declare many contexts for a CDT with a highernumber of nodes, the task of declaring them using the aforementioned syntaxbecomes rapidly unfeasible. For this reason, PerLa CL has been extended witha speci�c feature, which enable the middleware to automatically build the con-textual block starting from some contextual block components, called partials.

PerLa CL allows to separate a contextual block in more partials block.

ON ENABLE (FireMonitoring)SELECT Temperature, ConsumptionSAMPLING EVERY 40mEXECUTE IF (o�ce_cond = TRUE)

This query can be split in two di�erent blocks

This new feature introduces the concept of Automatic Composition of con-textual block. This idea was reported in [BQT12].The designer must only associate one or more partial components with eachcontext element of the CDT. The system is able to compose a contextual block,combining the partial components associated with the context elements of theCDT. The designer must always specify how the composition takes place. Fora deeper explanation of these concepts see [STCV12], in which two di�erentcomposition techniques and the general syntax to declare the association of thepartial components with the CDT context elements are reported.

The most interesting kind of contextual blocks composition is the run-timeapproach. It focuses on the association of partial components with the con-text elements of the CDT and on the composition of a contextual block, duringsystem execution, when its relative context is recognized as active by the mid-dleware.

Moreover, introducing at any time new contexts while the system runs, theuser can get to de�ne all the possible situations in which the application oper-ates. For this reason, the developers must not know at design stage all possibledi�erent situations which can a�ect system behavior, but, when they �nd new

32

Page 41: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

unexpected situations later, they can only declare a new context with the cor-responding query, without having to directly intervene in the operational partsof the system.

7.1.3 Context Manager

This component has been introduced in the PerLa middleware to accomplishthree di�erent tasks:

1. creation and maintenance of the CDT.

2. to �nd out active and inactive contexts at any instant of time.

3. execute some operations de�ned by contexts declaration.

CM performs the actions settled by the CL: considering the example of the o�ce,it checks that the period of time de�ned by the REFRESH clause has elapsed,and when it happens, it updates the context, and turns on the air conditionerif the temperature in the room reaches the established threshold.

Furthermore, it supervises the association of the proper sensors for the cor-responding concept. It checks the condition de�ned by the WHEN clause in theconcept declaration, in order to know which sensors satisfy it for that concept.

To verify when a context is active at a certain moment, CM checks thiscondition: if a device is associated to a concept, it means that a dimensionin the CDT is assuming that value. If this condition is satis�ed by each pair<Dimension, Value>, then the context is active.

Subsequently, an extension, to support the CM to deal with possible con�ictsbetween contexts has been designed. For a complete presentation of this partsee [PPP11].

With CM the new architecture of PerLa is shown in the Figure 7.2.

Finally, PerLa is a powerful framework for the development of context-awarepervasive applications. The CDT model allows to de�ne incrementally newcontexts for the application, and it is very �exible in situations which requirea frequent recon�guration of the devices, which may involve new types of data.Moreover, its queries, with a SQL-like syntax, are easily manageable by users.

The middleware works with contexts de�ned over the designed CDT, hidinghow the tasks are performed and the complexity of the whole system in general,providing the user with only the �nal tailored information.PerLa adopts the component-based model for context management and behav-ioral adaptation.

33

Page 42: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 7.2: PerLa architecture with Context Manager

34

Page 43: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Chapter 8

COP and PerLa comparison

Component-based architectures are considered as an alternative solution toCOP.

As presented in previous sections, COP focuses on activation at run-timeof context-dependent behavioral variations, particularly it provides features toperform directly the variation of the modules involved, starting from some sig-ni�cant contextual information. However, how the contexts are declared andmanaged must be de�ned at design stage. COP eliminates the need to de�nededicated modules to enable adaptivity, but it is not suitable for the design ofproper rules for context management.

On the other hand, the PerLa framework provides already a general contextmodel: the CDT. The designer must only declare a dedicated CDT, with CLqueries, for the application, and middleware is responsible for its management.This is a really useful feature, because starting from scratch to design a dedicatedcontext model, especially for large and distributed applications, could be verydi�cult, and the chances that some kind of inconsistencies occur or some kindof contextual information has not be properly modeled, are considerably high.

PerLa contextual features, at least for now, focus heavily on data, and theactions that can be performed, in response to contextual changes, are quitelimited.In fact, contextual features have above all the role of data �tailors�, i.e. theyallow the user to de�ne which data, retrieved by sensors, must be selected in aspeci�c situation. The actions permitted are substantially limited to the acti-vation or deactivation of devices or to the setting of some sampling parametersor to a limited range of tasks performed by some actuators, as represented inthe o�ce example of the previous section.

8.1 Context management

PerLa has been designed to work with several data streams, containing the sam-ples obtained by devices. With CL, the designer can de�ne a sort of contextualdynamic view on a data stream.So PerLa with its queries allows to monitor the entire lifecycle of the information:

1. Con�guring the sensors dynamically and �on the �y�.

35

Page 44: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

2. De�ning how the sensors must work and which data must be retrieved.

3. De�ning how to group and aggregate the rough data and some intermedi-ate operations on them.

4. Managing the �nal information contained in data streams.

5. Declaring di�erent contexts, how to compose them during system execu-tion and set the actions to perform according to their changes.

PerLa LLQ allow to set how the devices must work: the sampling intervals,which data must be selected and the computation to be performed on sampleddata. Instead, COP is not directly aware of how information is provided, in factit is not directly responsible of sensors, but it uses the information provided bythem, to perform behavioral variations.

Moreover, PerLa has been designed to manage several data streams, andthis is a very useful feature, because it enables to obtain data continuously.Designing from scratch an application to deal with several data streams is ab-solutely not an easy task. Adopting COP, the developers must implement amechanism to monitor in the correct way continuous data sources, in order toprovide contextual information. PerLa already includes all the features to createand manage data streams.

Moreover, PerLa is very suitable for context distribution. CDT model dealsnaturally with contexts belonging to di�erent groups of sensors and to dis-tributed instances of the application. The nodes at the lower level of the treecould be used to abstract several instances of a dimension, creating local CDTfor each instance. In this way, you can distribute the context data to di�erentlocations, leading to the introduction of a combined CDT comprising a pri-mary CDT and one or more local CDTs. An example of the CDT distributionis provided by the Green Move application, in which a local CDT is main-tained locally to user devices and is used to complete the context-based data�ltering[PRST12].

Also COP is oriented to application distribution, in fact, several threads mayexist for each local instance and adapt their behavior di�erently. However, withCOP it is possible only to implement the behavioral variations of the instancesand not how the local contexts and the primary context are combined. Theimplementation of a mechanism to compose information coming from di�erentlocal contexts, in order to infer a higher level context can not be supported byCOP.

COP supports the implementation of behavioral variations which cross-cutthe application, but it is not a good approach for monitoring in general, asstated above.For this reason, it may become necessary to introduce dedicated components togenerate signi�cant contextual information, starting from rough data providedby sensors, and to decide which layers activate on the application. For exam-ple, you can choose to implement the adequate number of threads to manageinformation across several modules (also located in di�erent instances) and toactivate some layers for each one of them accordingly, or to design a dedicatedcomponent to address both. An intuitive solution is precisely that to intro-duce some components, with similar features to the PerLa Context Manager.

36

Page 45: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

These new components would have di�erent tasks: monitoring sampling devices,building and managing contexts and then starting COP layers composition.

PerLa middleware already has the components designed for these purposes,the CM for what concerns context management and actions performing andother low level components of the middleware for what regards data sourcesmonitoring, and their operational impact is not directly observable by the user.PerLa CL relieves designers of the responsibility to develop correctly dedicatedcomponents for context management, and in a complex pervasive environment,this could result a rather complex task. COP allows to eliminate the need tospecify dedicated components for behavioral variations performing, but not fordata sources monitoring.

8.2 Behavioral variations performance

The concept of the ENABLE and DISABLE clauses of PerLa CL could lookapparently comparable to that of with and without statements of COP. Con-sidering the ENABLE statement, it sets which data must be provided, and thanit utilizes these data to change some parameters, according to the correspondingconcept in the CDT.

So if the context is active and the condition in the WHEN clause of thecorresponding concept is satis�ed by a sensed value a established action is per-formed. In the o�ce example, the context OverheatMonitoring checks everyhour if, in the set of data provided by a group of devices, there is a value inthe temperature �eld higher than the settled threshold, and if it �nds it, the airconditioner is turned on.

PerLa CL has been designed for the creation of a direct inter-relationshipbetween context model, data and adaptations: it allows to de�ne: which dataa�ect a context, how sub-contexts can be composed to create another higherlevel contexts, and which actions must be executed when changes in activecontexts are detected. Contexts monitor the PerLa data streams and directlyexecute some actions.

Instead COP, does not provide already a monitoring mechanism: who decideto develop an application with COP, must design how to retrieve the meaningfulcontextual information, starting from scratch, with no supports.

With the CDT and the possibility to de�ne new contexts, composing othercontexts at run-time, it is possible to set the desired number of actions.Taking an extension of the o�ce example, a smoke detector and an air outlethave been installed in the room. So, a new concept Smoke has been added to thedimension Risk in the previous CDT and a new context SmokeMonitoring hasbeen declared. Smoke and Fire are related: when the �re starts the �re alarmmust be activated, and if the smoke in the room reaches a too high level the airoutlet is opened. Moreover, if in the room there is only the presence of smokefor unknown reasons the �re alarm is activated anyway. The smoke detector isa sampling opacimeter and the smoke level in the room is represented by theopacity value of smoke, measured in m−1. The new dimension Smoke is:

CREATE CONCEPT SmokeWHEN Opacity > 1

The context SmokeMonitoring is:

37

Page 46: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

CREATE CONTEXT SmokeMonitoringACTIVE IF Location = o�ce (ID)

AND Risk = SmokeREFRESH EVERY 1hON ENABLE (SmokeMonitoring) :

SELECT Opacity, IDSAMPLING EVERY 10 m

EXECUTE IF EXISTS (Smoke)

SET PARAMETER air_outlet = TRUE

SET PARAMETER alarm = TRUEON DISABLE (SmokeMonitoring) :

DROP SmokeMonitoring

SET PARAMETER air_outlet = FALSE

SET PARAMETER alarm = FALSE

The context FireMonitoring must not be changed, so there are two di�erentcontexts, although closely related, that activates the alarm. If there is a �rein the room, surely there is also the presence of smoke, in this way if for someexternal reasons, the temperature sensor stops to work the smoke detector cansignal the �re anyway. However, this involves an overlap of tasks between thetwo contexts, although this is not a considerable issue for PerLa.

Treating COP, with and without statements can (de)activate several behav-ioral variations, each one corresponding to a partial method. In order to providea theoretical comparison between PerLa and COP, I adopt the conditional com-position approach for next examples, due to the presence of the structure contextand when clause.

To implement the o�ce example with COP, it is not enough to de�ne layersand when they have to be activated, but, also, a external mechanism to monitorchanges in context. An intuitive solution could be the introduction of a threadto monitor the temperature and the risk of �re, and a thread to monitor thesmoke level in the room. With COP, we can de�ne only a context structure toencapsulated changes related to smoke detector. In fact, we can assume thatthe activation of the �re alarm is the �normal� behavior, whereas the activationof both actuators represents a variation.

The thread SmokeMonitoring sleeps every ten minutes and, when resumed,it controls the smoke level in the room, and if it detects a value of opacityexceeding 1m−1, it calls the method smokeRisk(). When this method is called,the with statement will active the SmokeLayer in the class ActiveActuators.

38

Page 47: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

The partial method activeAlarm(), when SmokeLayer has been activated,switches to �open� the state of the air outlet when a high amount of smoke isdetected. When the layer is deactivated, the state of the actuator is switchedto �close�.

This example shows that context in COP is more driven by events thanrough data, and this is valid not only in JCop but also in all other libraries forother programming languages. It provides adaptation on something occurredduring system execution.

Moreover, PerLa CL creates a direct connection between monitoring andadaptations: the context FireMonitoring is automatically activated and it checksimmediately the current temperature value, in order to determine if the airconditioner must be turned on or not.

This PerLa query introduces other similarities with COP, at least from a con-ceptual point of view. The concepts of partial components and partial methodscould be considered based on the same idea of composing di�erent entities toprovide a new behavior, and PerLa context query and COP context structurecontain dedicated statements to declare when context changes and which actionsmust be executed in response.

However, PerLa partial components and context entities concern contextcomposition and adaptations as a whole, i.e. from composition of di�erent basicdata to obtain a new higher concept, to the performance of combined actions.They covers both data management and behavioral variations.To reinforce this idea, consider an extension of the usual o�ce example. Anew con�gurable air conditioner has been installed in the room. It can work indi�erent modalities, depending of di�erent properties of the room environment:

• Dry: to decrease the tumidity,

• Fan: to set the fan speed,

• Cool: to lower the temperature.

39

Page 48: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 8.1: CDT of the o�ce example with a new air conditioner

The corresponding CDT is:

The concept Temperature has not been changed, the concept Humidity setsthe condition of the activation of the dry mode, while the concept Ventilationindicates the amount of air that must leak out from the air conditioner.

The dimension Speed indicates the current speed of the fan, and it is usedto adjust the speed later, founding on the values of humidity and temperature.

CREATE CONCEPT HumidityWHEN Humidity > 40

CREATE CONCEPT VentilationWHEN air_conditioner = �true�

CREATE DIMENSION SpeedCHILD OF VentilationCREATE CONCEPT SlowWHEN Speed < 10CREATE CONCEPT NormalWHEN Speed BETWEEN 10 AND 20CREATE CONCEPT SpeedyWHEN Speed BETWEEN 21 AND max

CREATE CONTEXT TemperatureMonitoring

40

Page 49: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

ACTIVE IF Location = o�ce (ID)

AND Fan = TRUEREFRESH EVERY 30mON ENABLE (TemperatureMonitoring) :

SELECT Temperature, IDSAMPLING EVERY 10 m

EXECUTE IF EXISTS (Temperature)

SET PARAMETER air_conditioner = �cool�ON DISABLE (TemperatureMonitoring) :

DROP TemperatureMonitoring

The context HumidityMonitoring is specular. Instead, the context Ventila-tionMonitoring is composed by the others two contexts, because it needs thetemperature and humidity values, and another part in order to set the new fanspeed. Speed is the current value of the fan speed, while air_conditioner_speedrepresents the new speed that the air conditioner must take.

This composed query is more complex than those of the previous situation.In this case there is an overlap between the data required by contexts: theVentilationMonitoring needs the current temperature and humidity values asthe two partial contexts, however this is de�nitely not a problem in PerLa,because the middleware deals with both to provide data and to perform actions,also taking into account that the complexity of the underlying system is entirelyhidden to the user. The two partial contexts deals with the setting of the airconditioner state, while the composed context sets the fan speed. This examplehighlights how it is simple to coordinate the execution of several actions relatedto di�erent contexts with PerLa CL.

Furthermore, PerLa can be adopted for applications performance monitor-ing. Sensors can be con�gured for this purpose and the collected data can beused to change the working parameters of the monitored application, in orderto increase its e�ciency. For example, if you want to decrease the application

41

Page 50: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

response time in case of heavy workload, at the risk of increasing the energy con-sumption, you have to design the proper dimensions and concepts in the CDTand then to introduce a simple CL query and PerLa middleware will addressthe request.

It is su�cient to know SQL to adopt PerLa for context speci�cation in per-vasive environments, with the only assignment of con�guring the system. Theapplication developers must declare which are the signi�cant context changesfor the entities of the environment in di�erent situations and which actions themiddleware must perform, without having to implement anything at operationallevel.

On the other hand, COP and particularly dynamic AOP can provide behav-ioral variations for events generated by the program code of the application, i.e.for events not related to samples retrieved by devices, but to the interactionsamong internal objects or modules of the applications. PerLa has not beendeveloped for these purposes, therefore, to deal with cross-cutting concerns aprogramming paradigm is the only possible choice. PerLa supports the devel-opment of context-aware applications in each aspect, while COP and dynamicAOP support the development of self-adaptive sw systems.

8.3 Which choice at design stage?

COP introduces the problem of deciding which programming language andwhich corresponding library are the most appropriate for the application, andin case of complex and critical pervasive systems also the choice of the layerscomposition mechanism becomes a signi�cant issue. For example, dynamicallyscoped activation approaches are convenient when all the entities in the control�ow are context-dependent, while per-object activation is a suitable solutionwhen behavioral variations partially cross-cut the application structure, and itcould happen that the choice made at design stage may prove wrong duringdevelopment.

The research on COP languages is still in an early stage, and there are noprototypes of medium to large size to validate the features provided by COP.This could cause the occurrence of unexpected problems during the developmentof the application, especially in case of large and critical systems.

Furthermore, in a pervasive application, the monitoring of the entities, fromwhich retrieve context data, is a crucial aspect. As stated above, COP cannot be considered a good solution for this particular task, not only in a directcomparison with PerLa framework, but even with dynamic AOP. In fact, dy-namic AOP allows to separate cross-cutting concerns, such as monitoring, withminimum impact on the code. However, in real current applications, dynamicAOP is almost exclusively used to monitor the application performance and toprovide dynamic adaptions accordingly.

On the other hand, PerLa is a complete support to manage all the entitiesinvolved in the pervasive environments. It provides all features to con�guredynamically devices, to set how the devices must work and which data they mustsample, a middleware to manage intermediate data and to create data streams,a language to query the system and �nally to manage di�erent contexts. PerLaalso allows to add new functionalities very easily, in fact, you must only installnew devices in the network, de�ne what they have to do with LLQ, declare the

42

Page 51: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

new contexts, and the middleware will create automatically the proper modulesto manage new entities introduced into the system, also while the applicationsruns, without having to manually edit the operational sw. It �covers� all themost important aspects of the application, not only those related to context.

COP, instead, can be used as a support for the normal programming lan-guages, in order to implement context-based behavioral variations. For this goal,COP is a better solution to adopt at design stage than PerLa. If the uniquepurpose is the implementation of the adaptive part of an application, the bestpossible solution is COP, also compared to BP and dynamic AOP. For exam-ple, COP can be adopted for the development of web servers, GUI applications,etc... Moreover, these paradigms can be adopted for the design of self-adaptivesw systems, hence in applications that need adaptations in response to changesin itself.

As to context, PerLa and COP are on two di�erent levels: PerLa take re-sponsibility for context model declaration and management, contexts de�nitionand parameters setting, while COP only supports context-dependent behavioralvariations implementation.

8.4 Is there the possibility of an integration?

Apparently, the �rst answer might be yes.The most intuitive solution should be to delegate to PerLa everything re-

lated to sensors con�guration, intermediate computations on data and contextsdeclaration and management, and to use COP to perform behavioral variations,using the information provided by PerLa.

Of course, this consideration can be valid only if the development of theapplication is in its initial stage, so that it is possible to adopt PerLa and COPsimultaneously in order to implement the new application, involving them inthe whole development process.

With PerLa CL you can de�ne the CDT and contexts on it. With COP,contexts are no longer useful to declare which actions perform, but they can beconsidered only containers of contextual data. Considering that PerLa createsseveral data streams, including the values retrieved by sensors, a context canbe viewed as particular context data stream, i.e. a normal PerLa stream,properly adjusted to provide only data related to that context, de�ned by de-signers. This operation can be actuated by CM: it manages CDT and contexts,and creates contextual streams accordingly. Some simple actions, such as thoseof the o�ce examples, can be still performed by CM.

On the other hand, with COP you can handily use the information inserted incontext data streams to implement desired behavioral variations. The program-mers have only to care about the de�nition of layers, with statements, partialmethods, etc..., for the entities, whose normal behaviors must be dynamicallyadapted.

Hence, PerLa can be used for the monitoring of external entities, while COPcan be used to perform behavioral variations, which involve di�erent modulesin the program control �ow, and can cross-cut the application.

This idea is shown in Figure 8.2.

As stated above, the CM provides contextual information to the adaptive

43

Page 52: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 8.2: PerLa and the adaptive part of the application on top

44

Page 53: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

part of the application, in the form of data streams. What remains to design ishow these streams of data can be handled by the application.Considering the o�ce example, the OverheatMonitoring context creates a sortof view, which checks every forty minutes the temperature value, sampled bythe proper group of sensors. In this case a real stream is not created, but thecontext provides a simple value each forty minutes, hence the assignment of theepithet view. However, if it is necessary to declare complex contexts, whichare always active and provide continuously data, it is unavoidable to work withdata streams.

Now, suppose that instead of setting the state of the air conditioner, thiscontext is used by the adaptive part of the application. For this purpose, it isnot signi�cant considering the temperature sample, but the fact that the currenttemperature value, obtained at the moment of the activation of the context, hasreached the established threshold value. In this way, contextual information issubstantially passed to COP in form of �events� (or sequence of events), so itbecomes easier to handle.

The adaptive part can �see� the occurrence of events by the introduction ofdedicated threads, whose task is to monitor the contexts. So when a context isdeclared with PerLa CL, a corresponding component must be implemented tomonitor it and to activate the layers in the proper application modules.

So in the previous �gure, a new level, containing the monitor threads,must be added to the new application.

Context streams enter in the �layer�, containing monitor threads. Thesethreads must manage data and activate the proper layers accordingly.This solution can be adopted in large and complex applications, where a con-siderable number of modules, belonging to di�erent parts of the application,need adaptations. Applications that need to continuously change, depending ona huge amount of contextual information, on a large number of heterogeneousentities can be supported both by PerLa and by COP.

Although this solution may be taken into account, it does not provide a realintegration between the two treated actors. In fact, PerLa provides contextualdata while COP perform behavioral variations for the application on top, but itis necessary to design dedicated components to provide the proper informationto COP. These components form a kind of intermediate layer that separates theinformation source and the adaptive part of the application.

An alternative solution may be to extend PerLa CL with the option of di-rectly launching scripts, programs, functions or even applications from contextqueries. In this way, a direct connection between information and behavioralvariations is created. The application designers can de�ne a di�erent indepen-dent behavior for each context, not needing to implement intermediate compo-nents for data and context management. PerLa middleware takes responsibilityof every aspect related to context management and to start the correct behav-ior accordingly. The CM acquires a decisive role, it must supervise the contextactivation state in order to avoid any possible inconsistent situation, which, inthis scenario, could be impossible to handle.

This idea can be linked to that of BP, i.e. activating a new independentbehavior when required. However, while in BP the alternation of di�erent be-haviors is based on the occurrences of events of sequence of events, in PerLacontext and behavior can be regarded as a unique indivisible �block�, entirely

45

Page 54: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Figure 8.3: Architecture of the �nal adaptive application on top of PerLa im-plemented with COP

46

Page 55: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

driven by data provided by sampling devices. Moreover, this solution e�ectivelyeliminates the need to attach a complete application on top of PerLa, allow-ing to split it in di�erent �sub-applications�, each aimed at a speci�c task andnaturally related to the corresponding context.

47

Page 56: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

Bibliography

[KLMMVLI97] Gregor Kiczales, John Lamping, Anurag Mendhekar, ChrisMaeda, Cristina Videira Lopes, Jean-Marc Loingtier, JohnIrwin, Aspect-Oriented Programming. In: Proceedings ofthe European Conference on Object-Oriented Programming(ECOOP), Springer-Verlag, Finland. 1997

[AOPinJavaWS] Aspect-Oriented Programming in Java web site.http://www.voelter.de/data/articles/aop/aop.html

[CMJvdB07] José María Conejero, Juan Hernández, Elena Jurado, Klaasvan den Berg, Crosscutting, what is and what is not?: A For-mal de�nition based on a Crosscutting Pattern. Technical Re-port TR28_07, University of Extremadura. 2007

[SGP12] Guido Salvaneschi, Carlo Ghezzi, Matteo Pradella, Context-oriented programming: a software engineering perspective.Journal of Systems and Software, v.85, n.8, p.1801-1817. 2012

[MHMMK10] Malte Appeltauer, Robert Hirschfeld, Hidehiko Masuhara,Michael Haupt, and Kazunori Kawauchi, Event-Speci�c Soft-ware Composition in Context-Oriented Programming. In: Pro-ceedings of the 9th international conference on Software com-position, Malaga, Spain. 2010

[HCN08] Robert Hirschfeld, Pascal Costanza, Oscar Nierstrasz,Context-oriented Programming. Journal of Object Tecnology,v.7, n.3, p. 125�151. 2008

[KHHKPLGI03] Gregor Kiczales, James Hugunin, Erik Hilsdale, Mik Kersten,Je� Palm, Crista Lopes, Bill Griswold, and Wes Isberg, As-pect Oriented Programming. In: Proceedings of the EuropeanConference on Object-Oriented Programming. 2003

[S04] Dave Schweisguth, Second-generation aspect-oriented pro-gramming. 2004

[B04] Jonas Bonér ,What are the key issues for commercial AOPuse - how does AspectWerkz address them? In: Proceedingsof the 3rd international conference on Aspect-oriented softwaredevelopment, p.5-6, Lancaster, UK. 2004

48

Page 57: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

[AGMO06] I. Aracic, V. Gasiunas, M. Mezini and K.Ostermann, Overviewof CaesarJ, Transactions on Aspect-Oriented Software Devel-opment I. LNCS, Vol. 3880, pp. 135 - 173. 2006

[HK02] Harel, D., Kugler, H.: Synthesizing state-based object systemsfrom LSC speci�cations. International Journal of Foundationsof Computer Science. In: Proceedings of the Fifth Int. Conf. onImplementation and Application of Automata (CIAA 2000).Lecture Notes in Computer Science, Springer-Verlag. 2002

[HMW10] David Harel, Assaf Marron, Gera Weiss, Programming Coordi-nated Behavior in Java. In: Proceedings of the 24th Europeanconference on Object-oriented programming, Maribor, Slove-nia. 2010

[HMW12] David Harel, Assaf Marron, Gera Weiss, Behavioral Program-ming. 2012

[M10] Sa�d Mechkour, Overview of Situation Theory and its applica-tion in modelling context. University of Fribourg, Switzerland.2010

[ANH07] C.B. Anagnostopoulos, Y. Ntarladimas, S. HadjiefthymiadesSituational computing: An innovative architecture with im-precise reasoning. Journal of Systems and Software, v.80, n.12,p. 1993�2014. 2007

[L05] Loke, S.W., Representing and reasoning with situations forcontext-aware pervasive computing: a logic programming per-spective, The Knowledge Engineering Review, v.19, n.3, p.213-233. 2005

[RBVCM07] Patrick Reignier, Oliver Brdiczka, Dominique Vaufreydaz,James L Crowley, Jer^ome Maisonnasse, Context Aware En-vironments : from Speci�cation to Implementation. ExpertSystems, v.24, n.5, p. 305�320. 2007

[KAM10] Tetsuo Kamina, Tomoyuki Aotani, Hidehiko Masuhara, De-signing Event-based Context Transition in Context-orientedProgramming. Proceedings of the 2nd International Workshopon Context-Oriented Programming, p.1-6, Maribor, Slovenia.2010

[KPKY11] Chun Kyung Lee, Thi Hien Pham, Hee Seong Kim, Hee YongYoun, Similarity based Distributed Context Reasoning withLayer Context Modeling. Computer Software and ApplicationsConference (COMPSAC), IEEE 35th Annual, p. 320 - 325.2011

[BQT12] C. Bolchini, E. Quintarelli, L. Tanca, Carve: Context-awareautomatic view de�nition over relational databases. Informa-tion Systems, Accepted manuscript. 2012

49

Page 58: POLITECNICO DI MILANOarerespectivelydiscussed: Aspect-orientedProgramming, Context-oriented Programming and Behavioral Programming. In section 6, a theoretical comparison of these

[STCV12] Fabio Schreiber, Letizia Tanca, Romolo Camplani, D. Viganò,Pushing context-awareness down to the core: more �exibil-ity for the PerLa language. In: Proceedings of 6th Interna-tional Workshop on Personalized Access, Pro�le Management,and Context Awareness in Databases, p. 1-6, Istanbul, Turkey.2012

[PPP11] Giovanni Pirotta, Gianluca Pisati, Dario Pozzi, Risoluzionedi Con�itti tra Contesti in Sistemi Pervasivi. Politecnico diMilano. 2011

[PRST12] E.Panigati, A. Rauseo, F. A. Schreiber, L. Tanca, Aspects ofPervasive Information Management: an Account of the GreenMove System. Computational Science and Engineering (CSE),IEEE 15th International Conference on, p. 648 - 655. 2012

[SCFMR12] F. A. Schreiber, R. Camplani, M. Fortunato, M. Marelli, andG. Rota. Perla: A language and middleware architecture fordata management and integration in pervasive informationsystems. IEEE Trans. Software Eng., v.38, n.2, p.478�496.2012

[SAW94] B. Schilit, N. Adams, R. Want. Context-Aware Computing Ap-plications. In: Proceedings of the 1st International Workshopon Mobile Computing Systems and Applications, p. 85-90,Santa Cruz, CA, USA, IEEE. 1994

[P98] J. Pascoe. Adding Generic Contextual Capabilities to Wear-able Computers. In: Proceedings of the 2nd IEEE Inter-national Symposium on Wearable Computers (ISWC'98),p.92-99, Pittsburgh, PA, USA IEEE.1998

[MKMSKC04] P. K. McKinley, S. Masoud Sadjadi, E. P. Kasten, B. H.C.Cheng. Composing Adaptive Software. IEEE Computer, p.56-64. 2004

[DA99] A. K. Dey, G. D. Abowd. Towards a Better Understanding ofContext and Context-Awareness. Workshop on the what, who,where, when and how of context-awareness, CHI, USA. 1999

[SDA99] D. Sabler, A. K. Dey, G. D. Abowd. The Context Toolkit:Aiding the Development of Context-Enabled Applications. InProceedings of CHI'99, Pittsburgh, PA, USA. 1999

[CdLG09] B. H. Cheng, R. de Lemos, H. Giese, Software engineering forself-adaptive systems: A research roadmap. In Proceedings ofSoftware Engineering for Self-Adaptive Systems. LNCS, vol.5525. 2009

50