• Aucun résultat trouvé

of of of CORE

N/A
N/A
Protected

Academic year: 2022

Partager "of of of CORE"

Copied!
241
0
0

Texte intégral

(1)
(2)
(3)
(4)
(5)

ACORE GENERIC META-MODEL FOR ASPECT-ORIENTED PROGRAMMING LANGUAGES

by

©Farhana Eva Alam

in partial fulfillment of the requirements for the degree of

Department of Computer Science Memorial University of Newfoundland

September 2010 St.John's,Newfoundland,Canada

(6)

Abstract

Aspect Oriented Software Development (AOSD) has its roots in the need to deal with requirements that cut across the primary modularization of a software system. On the programming level, mature, industrial-strength tools like the de-facto standard Aspecll exist. However, on the modeling level, there is as yet little support for AOSD.

Previous work, which was platform specific, has provided support for only AspectJ.

However, as Aspecll does not support dynamic aspect-orientation, the developed model only provides support for static AOSD. Building on previous work, using standard UML extension mechanisms, this research developsUMLmodeling support for both static and dynamic AOSD. Comparing language and aspect-oriented features ofAspectJ,AspectS and AspectML, asa frrst step to our generic profile,wepresenta profile which supports only static part of Aspecll and AspectS. This helps us to figure out the modeling elements that are required for dynamic profile but missing in the current profile. As the second step, a generic but only dynamic profile (does not provide support for static AOSD) is presented. These two profiles clearly show the difference between static and dynamic AOP in modeling level. We use the above steps and develop the final generic profile that allows existing UML tools to express AOSD models. The developed model ensures modeling support for both static and dynamic AOSD from the same profile. To verify the necessity and correctness of the profiles used as working steps, we apply each of those to several examples. Furthermore,the generic profile is applied to examples from AspectJ and AspectS to make sure that it can express both static and dynamic AOSD. Code generation is done by working from theUML XMI(XML Model [nterchange) format, the standard UML serialization.

(7)

This is one of the standardized mechanisms and is therefore compatible with existing modeling tools. Existing work has demonstrated the use of XSLT (XML Stylesheet Language Transforms) for generating XMI to AspectJ code. We leverage that mechanism. As a proof-of concept, we implement XSLTs that generates valid code for ourtargetlanguages(AspectJ,AspectS).

(8)

Acknowledgments

[would like to express my deepest gratitude to my supervisors, Dr. JoergEvermann and Dr. Adrian Fiech.Ithas been my good fortune to have the opportunityofworking with them. [ would like to thank them their remarkable help, encouragement and support to carryon my research work.

I am also deeply grateful for the financial support of the School of Graduate Studies, Memorial University. Further, a special thanks to the Department of Computer Science, without its resources and administrative help it would not be possible to pursue my Master's degree at Memorial University. In addition, I am also grateful to the writing center of Memorial University for checking the entire thesis.

I want to express my endless gratitude towards my parents, sister, in-law family members and relatives for inspiring me with their unbound love, faith,and support to continue my graduate school career. My sincere appreciation to my husband Refaul Ferdous who gave me all kinds of support and taken extra care of me and our five months old baby girl Waniya who was born at the middle of my thesis writing.

And finally, looking back over my study period at Memorial University, this thesis would not be possible without the support of few peoples. Specially, I would like to thank Morsheda Mamataz, Kamrunnahar Eamy, Nigar Sultana, Madhabi Roy, Wendy Khandakar, Naushaba Sheikh, Asma Dewan, Negar Noor, Shazli Khan, Kazi Tayubul Haq, Reedwanul Islam, Wasirnul Bari, Shakil Ahmed, Shibly Rahaman, Matthias Tilsner, and Riobard Zhan for their moral support and help. They also have made my life here more joyful and happy.

(9)

Table of Contents

Acknowledgments iv

Listof Figures ...

Chapter1 1

INTRODUCTION 1

1.1 Separation of Cross-cutting Concerns ....

1.2 ModularizationofCross-cuttingConcerns 2

1.3 Aspect-orientedPrograrnming .

1.4 1.5 1.6

Chapter2 13

AN OVERVIEW OF AOP LANGUAGES 13 2.1 Running Exarnple ...

2.3.1 An Overview of AspectS 27

(10)

AOP Approaches: Static and Dynamic 62

3.2 Dynamic AOP... .. 65

Chapter4 71

AOP LANGUAGE FEATURE COMPARISION 71

4.1 AspectJ,AspectSandAspectML. .

ChapterS 105

ASPECT-ORIENTED MODELING IN UML 105

5.1 Related Works ..

5.2 Our Approach ..

5.3 ModelingElements ...

5.3.1 5.3.2 5.3.3 5.3.4 5.3.5

(11)

5.5 Profile for Dynamic AOP ..

5.6

Comparison with AspectJprofile ....

. 128

... 135

Chapter6 151

APPLICATION EXAMPLE 151

6.1 Example-l : Modeling SenderClassSpecificJoinPoint.. ..

(12)

CODE GENERATION 176 7.1 ApplicationoftheXSLTforAspectJ ....

Discussion 199

Chapter9 207

CONCLUSION 207

REFERENCES 211

(13)

.. .. 148

.. 150

. 202

List of Tables

Table2.I:Mappingofexposedjoinpointstopointcutdesignators ..

Table 2.2: Access Specification.... .. 27

Table4.I:Pointcutoperators in AspecU and AspectS.... .. 95 Table 4.2: Exposed join point categories of AspecU, AspectS and AspectML. 100 Table 4.3: Pointcuts those are not available in AspectS and AspectML. 101 Table 4.4: AspectS Pointcuts that can or cannot be emulated using AspecU 102 Table 4.5: Imitating the AspectS join point selection using AspecU 102 Table 5.1: Pointcuts that can be modeled using the meta-class CFlowJoinpoint..

Table 5.2: Reusing elements from AspectJ Profile without modification ..

Table 5.3: Reusing elements from AspectJ Profile with modification ...

Table 5.4: Elements omitted from AspectJ Profile ....

Table 5.5: New elements in the Generic profile ..

Table 8.1: AspecU Profile VS Generic Profile .

(14)

List of Figures

Figure 1.1: Additional codes in each method of Inventory class Figure 1.2: lmplementation ofabanking system (Redrawn after [1])... .. 5 Figure 2.1: Output of the shopping-cart program with "logging" 17 Figure 2.2: An AspectJ file named HelloWorld.... . 19

Figure 2.3: A class named Test inJava... . 20

Figure 2.4: An example ofa named pointcut (adapted from [I] 22 Figure 2.5: Output of the ShoppingCartexample in AspectJ.... .. 26 Figure 2.6: Opening system browser in Squeak... .. 28 Figure 2.7: Workspace and transcript window in Squeak.... . . 29

Figure2.8:DynamicweavinginAspectS... .. 31

Figure 2.9: Testing a method introduction using AslntroductionAdvice 35 Figure 2.10: Weaving of AfterHelloWorld Aspect.... .. 37 Figure 2.11: Weaving of AfterHelloWorldRlS Aspect.... .. 38 Figure 2.12: Weaving of AfterHelloWoridSCS Aspect... . 39 Figure 2.13: Weaving of AfterHelloWorldSIS Aspect.... .. 40 Figure 2.14: Workspace code and output of the factorial example.. .. . .43 Figure2.15: Transcript for Class First Attribute Example.... .. 43 Figure 2.16: Transcript for Class All But First Attribute Example .44 Figure 2.17: Transcript for Instance First AltributeExample ....

Figure 2.18: Transcript for Instance First Altribute Example.... .. 46 Figure2.19: Workspace and Transcript for Super First Attribute Example .48 Figure 2.20: Transcript for Super All But First Attribute Example ....

Figure 2.21: Workspace codes for ShoppingCartexample in AspectS 52 Figure 2.22: Output for ShoppingCart example in AspectS... . 53 Figure 2.23: The advices of Listing 2.34 were triggered wheneverthefunctions mentioned in thejoin points were called from Listing2.35 ...

Figure 3.1: User interface for modified ShoppingCartprogram ..

Figure 3.2: User interface for Dynamic SboppingCart Program ..

.. ...61 ... 63

. 66

(15)

Figure3.3:0utputofdynamicShoppingCartprograrn.... . 67

Figure4.1: Output of the above example.... . 74

Figure 4.2: Workspace and output for exception handling example in SmaliTalk 78 Figure 4.3: Workspace and output for exception handling example in AspectS 79

Figure 4.4: Aspect instantiation.... . 82

Figure 4.5 Output of aspect precedence example in AspectJ ...

Figure 4.6: Workspace and output for aspect precedence example in AspectS 84

Figure 4.7: Printing arguments in AspectS.... . 92

Figure 4.8: [nstalling and uninstalling BeforeHelloWorld Aspect... . 97 Figure 4.9: Result of installing and uninstalling AjterHelloWorld aspect 97

Figure 5.1: AspectJProfile... . 108

Figure 5.2: Our AOP Approach in Context (adapted from [12]). Figure 5.3: Cross cutting concern as package extension (adapted from [I 2]) Figure 5.4: Aspect as a class extension in new profile. Figure 5.5: Advice as a class extension in new profile.

Figure5.6:Joinpointasaclassextensioninnewprofile.... . 115 Figure 5.7: Joinpoint compositions in the profile.... . 117 Figure 5.8: ExecutionJoinpointin new profile.... . 119 Figure 5.9: ExceptionJoinpointas a class extension... . 120 Figure 5.10: PropertyJoinpointas a class extension.... . 121

Figure5.II:CFlowJoinpointasaclassextension... . 122

Figure 5.12: lntroductionasa class extension ....

Figure 5.13: Profile for Static AOP ...

Figure 5.14: Pointcut as a structural feature extension ...

Figure5.15:JPColiectionasastructuralfeatureextension 131 Figure 5.16: AdviceColiection as a structural feature extension... . . 132 Figure 5.17: install and uninstallas behavioral featureextension 134

Figure 5.18: Profile for Dynamic AOP.... . 135

Figure 5.19: Associations with the meta-classes for join point cornposition 138 Figure 5.20: Core generic meta-model forAOP languages.... . 139 Figure 5.21: Aspect as a class extension in AspectJ profile[12] 141 Figure 6.1: Base model of the example with call join point ....

(16)

Figure 6.2; Static model of senderClassSpecific join point examp Ie 154 Figure 6.3; Dynamic model of senderClassSpecific join point example 156

Figure6.4;BasemodelofCFlowJoinPointExample 157

Figure 6.5; Static cross-cutting concern ofcflowjoin point example 158 Figure 6.6; Dynamic cross-cutting concern of cflow join point example 160 Figure 6.7; Base model of exception join point example ....

Figure 6.8; Static cross-cutting concern ofcflowjoin point example 162 Figure 6.9; Dynamic cross-cutting concern of exception join point examp Ie 163 Figure 6.10; Base model of property join point example... . 164 Figure 6.1 I; Static cross-cutting concern of property join pointexampIe 166 Figure 6.12; Dynamic cross-cutting concern of property join point exampie 168 Figure 6.13; Base model of shopping-cart example ....

Figure 6.14; Static cross-cutting concern of the shopping-cart exampie Figure 6.15; Dynamic cross-cutting concern of the shopping-cart example Figure 7.1; Main templates in the XSLT for AspectJ....

Figure 7.2; Main templates in the XSLT for AspectS.... . . 178 Figure7.3;AnapplicationofthegenericprofiledevelopedinSection6.1.2.1 180 Figure 7.4; An application of the generic profile developed in Section 6.5.2.1 182 Figure7.5;AnapplicationofthegenericprofiledevelopedinSection6.2.2.1 183 Figure 7.6; An application of the generic profile developed inSection 6.3.2.1 185 Figure7.7;AnapplicationofthegenericprofiledevelopedinSection6.4.2.1 186 Figure7.8;AnapplicationofthegenericprofiledevelopedinSection6.3.2.2 188 Figure 7.9; An application of the generic profile developed in Section6.5.2.2 190 Figure 7.10; An application of the generic profile developed in Section 6.2.2.2 193 Figure 7.1 1; An application of the generic profile developed inSection6.3.2.2 195 Figure7.12;AnapplicationofthegenericprofiledevelopedinSection 6.4.2.2

(17)

. 25

. 28

. 28

. 30

. 31

List of Listings

Listing2.lltemciass.... . 14

Listing 2.2 Inventoryclass.... . 14

Listing2.3ShoppingCortclass ...

Listing 2.4 ShoppingCartOperator ciass.... . 16

Listing 2.5 Testciass.... . 16

Listing 2.6 Testclass(modiliedversion-2). Listing 2.7 TraceAspectAspectinAspectJ . Listing 2.8 Testciass in Squeak ...

Listing2.9delivermethodofTestciassinSqueak . Listing 2.10 BeforeHelloWorld Aspect in AspectS . Listing 2.1IAsJoinPointDescriptorClassinAspectS .

Listing 2.12 PointcutmAS~)eCI" ,L.

Listing 2.13 adviceBefore method of BeforeHelloWorld Aspect... . 33 Listing 2.14 adviceAfler method of AflerHello World Aspecl. 33 Listing 2.15 adviceArolind method of ArolmdHello World Aspect 34 Listing2.16advicelntromethodof/ntroHelloWorldAspect... .34 Listing 2.17 adviceException method of AspectHandler Aspect.... . 36 Listing2.18adviceAflermethodofAflerHelloWorldRiSAspect. 38 Listing 2.19 newMethod method of NewTest Class .... . 39 Listing 2.20 AsFactoriaIMClass....

Listing 2.21 initializemethodofAsFactoriaIMClass... . .41 Listing 2.22 other method of AsFactoria1M Class.... . .41 Listing 2.23 factorial method of AsFactoriaIMClass .41 Listing 2.24 adviceTrace method of Trace Aspect... . .42 Listing 2.25 factorialM method of FactorialMClass .... . .47

Listing 2.26 SubFactorialM Class.... .. . .47

Listing2.27factorialMmethodofSubFactorialMClass.... . .47 Listing 2.28 adviceTrace method ofAspectSliperFirstMAspect .48

(18)

Lisling2.29adviceTracemethodofAspectSuperFirstMAspeCI

Listing 2.30 Creating ilems in AspectML... .. 57

Listing 2.31 Functions related 10 Invenlory.... .. 58

Listing 2.32 Functions related 10 Shopping Cart 59

Listing 2.33 A FunclionofShoppingCartOperalor.... . 60 Lisling2.34advices in AspectML for ShoppingCart example.... . 60

Listing 2.35 Codes 10 test the program.... . 61

Listing 3.1 Aspect Enabling/Disabling at Runtime.... .. 64

Listing3.2CodeforStartbutton..... .. 67

Listing 3.3 Code for Stop button.... . 68

Lisling 3.4 Code for Start Log button... .. 68

Lisling3.5CodeforStopLogbutton ....

Lisling3.6Passingpointcutasargumenl ...

Listing 3.7 Class Definition of AspectLogger ...

Listing3.8Classmethod . Listing 3.9 Instance method ..

Listing3.IOThemethodadviceLogging ....

. 69

.. 69

. 69

Listing4.ITestclass... .. 73

Listing 4.2 TestAspectaspect 73

Listing 4.3 Conslructor in Item class.... . 74

Listing 4.4 A settermelhod in AspectS.... .. 76

Lisling4.5Advisinglhesettermelhodw... .. 76

Listing 4.6 Exception handler execution join point.... .. 76

Lisling4.7 AspectHandler aspect in AspeclJ.... . 77

Listing 4.8 Signaling exception in SmaIlTalk.... . 78 Listing 4.9 Advising an exceplion handler join poinl in AspeclS .. 79 Listing 4.10 Class initialization in AspectS... .. 80

Listing4.11 AnaspectinAspeclS... .. 82

Listing4.12AbstractmelhodofAsAbstractAspectaspect.... . . 85 Listing 4. 13 InberitinganabslractaspectinAspeclS... . 86 Listing4.14MelhodofSubAbstractAspectaspecl... . 86 Lisling4.15senderClassSpecificpoinlcutinAspectS.... .. 87

(19)

. 155

. 155

Lisling4.16RepresenlalionofsenderClassSpecificpoinlculinAspeCI!

Lisling4.17ctFirsIClasspoinlculinAspecIS 88

Lisling4.18RepresenlalionofclFirslClasspoinlculinAspectJ 88 Listing 4. 19 cfAllButFirslClass poinlcul in AspecIS.... . 89 Listing 4.20 RepresenlalionofcfAlIButFirslClasspoinlculinAspectJ 89

Lisling4.21 UsingcflowpoinlculofAspectJ.... . 89

Lisling4.22 clFirslSuperpoinlcul in AspecIS.... . 89

Listing 4.23 RepresenlalionofclFirslSuperpoinlculin AspectJ 90 Lisling4.24cfAIIButFirsISuperpoinlculinAspecIS.... . 90 Listing 4.25 Represenlalion ofcfAIIButFirslSuperpoinlcul in AspectJ 90

Listing 4.26 Prinlingargumenl in AspecIS.... . 92

Lisling4.27PrinlingargumenlinAspectJ... . 92

Lisling4.28PoinlculobjeclsinAspecIS.... . 94

Listing 4.29 EmulalingLisling4.28 in AspectJ.... . 94 Lisling4.30lnslallingand uninslallingolheraspecl as parlofan advice block 96

Lisling5.IFieldaccesspoinlculsofAspectJ 122

Listing5.2lnlroducingafieldandamelhodusingAspectJ.... . 125 Lisling 5.3 Pseudocode for Dynamic AOP ....

Lisling6.IAnexampleofacallpoinlculinAspectJ....

Lisling6.2 AfterHelloWorldaspecl in AspecIS ....

Lisling6.3 advice ofAfterHelloWorldaspecl....

Lisling6.4DynamicweavinginAspecIS .

Lisling6.5 An example offield accesspoinlCUIS in AspectJ... . 165 Lisling6.6 EmulaledAspectJ's field access poinlculS in AspecIS.. .. . 167 Lisling6.7PseudocodelhaluseslheelemenlspresenledinFigure6.12 168 Listing6.8Theshopping-cartexampleinAspectJ... . 171 Lisling6.9Pseudocodelhaluseslheelemenlspresenled in Figure 6.15 175 Lisling7.ICodegeneralionforlhemodelshowninFigure7.3... ... 181 Lisling7.2 Code generalion forlhe model shown in Figure 7.4 182 Listing 7.3 Codegeneralion for a model shown in Figure 7.5.... . 184 Lisling 7.4 Code generalion forlhe model shown in Figure 7.6.... . 185 Lisling7.5 Code generalion forlhe model shown in Figure 7.7 186

(20)

Listing 7.6 Code generation for the model shown in Figure 7.8 Listing 7.7 Code generation for the model shown in Figure 7.9 191 Listing 7.8 Code generation for the model shown in Figure 7.10 193 Listing 7.9 Code generation for the model shown in Figure 7.1 I 195 Listing7.10CodegenerationforthemodelshowninFigure7.12 197

(21)

Olaprerl:Introduction

Chapter!

INTRODUCTION

1.1Separation of Cross-cutting Concerns

Separation of concerns (SoC) isa fundamental principle insoftwareengineering.lt entails breaking down a program into distinct parts called concerns. Concerns are some specific requirements that must be addressed to satisfy the0verallsystemgoal while designing a system. A set of concerns that compose the entire software system can be classified into two categories: core concerns and cross-cutting concerns [I).

Core concerns capture the basic functionalityofasystem, whereas the cross-cutting concerns capture the features shared by many of the core concerns. All prograrnming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing procedures, modules, objects, classes or methods. For example, languages like C++, Java and C#, which belong to the family of object-oriented programming (OOP) languages, support modularizing of core concerns. These languages can separate the concerns by encapsulating them into objects. However, features like logging, persistence, and security disobey this form of encapsulation as they are shared arnong many of the core concerns and cannoteasily be fitted into the OOP approach [1,2,3). Furthermore, the OOP paradigm often forces the designer to create a coupling among the core concerns and the cross-cutting concerns in the software system. A program implemented in Java for a Shopping Center which includes items, inventory, and carts can be a sirnple exarnplethatclearly shows how the crosscutting concerns like logging are not modularized in OOP

(22)

OJapterl:IntrodLJCtiOl1

implementations. We assume that the program consists of several classes like Item, Inventory, and ShoppingCart, each of which contains multiple melhods. To see which methods are being executed during runtime, a programmer needs to implement some logging feature such as print statement within each method in this program as shown in Figure 1.1.

Figure 1.1: Additional codes in each method oflnventoryclass

Thesame printing statement, which can be considered as cross-cutting concern,is added to all the methods. Theseprintingstatementscannoteasilybemodularizedasa separate entity and does not remain in the form of encapsulation. Section 1.2 illustrates the consequences of non-modularized cross-cutting concerns in software design and implementation.

1.2 ModularizationofCross-cuttingConcerns

Cross-cutting concerns that are non-modularized often lead to code tangling or code scattering. Code tangling is caused when multiple concerns are considered several times while implementing a module. On the other hand, code scattering occurs while

(23)

O1apter1: Introduction

implementing a single concern in several modules. The example of the shopping-cart program (Section1.1 )shows code scattering, since the same printing statement logging feature is implemented in several classes. However, implementing features like security and persistence in each class of the same example will introduce code tangling in the same system.

A program containing either code scattering or code tangling is always difficulttobe traced or evaluated, since adding some new code or doing some minor modifications may require the programmer to edit the entire program.Italso reduces the chances of code reuse. Furthermore,developingasystemwiththesenon-modularizedconcernsis always time consuming and may contribute to low productivity in software development [I]. For example, if someone wants to change the logging messages in the shopping-cart example lhenhe needs to modify all the existing print statements.

Thus code tangling and code scattering cause undesirable system complexity and

1.3Aspect-oriented Programming

Therearemanyprogramming problemsinvolvingimportantconcernslike transactions,security,distribution, or logging where OOP techniquesarenotsufficient to clearly capture all of the important design decisions the program must implement [2, I]. Tbe need for modularizingand encapsulating those concerns gives rise to the concept of aspect-oriented programming (AOP). AOP provides a new programming technique that clearly expresses programs involvingcross-cuttingconcerns,including appropriate isolation, composition and reuse of the code [2].

(24)

O1apter1: Introduction

1.3.1 AOPMethodology

The methodology for developing a system in AOP is similar to other methodologies.

A system developed with AOP requires the following steps [I]:

a) Identifying the concerns:

In this step, the requirements are decomposed to identify core concerns and cross- cutting concerns of the system. Forexarnple, the core concerns of the shopping-cart example are the concerns related to item, shopping cart, inventory and shopping cart operator. The crosscutting concern for this example is the loggingfunctionalitythatis scattered and repeated in the core modules.

b) Implementing the conccrns:

In this step, each concern identified in the previous step will be implemented separately. Forthecoreconcems,thebaselanguageofthatparticularAOP language is chosen for implementation. On the other hand, cross-cutting concerns are implemented separately in stand-alone units calledaspects(see Section 1.3.2). For example, if Java is chosen as the base methodology for the shopping-cart problem thenthecoreconcernsareimplementedasclassesexcludingtheloggingfunctionality However, being a cross-cutting concern, logging functionality will beimplementedas a separate unit, known as anaspect.

c) Forming the final system:

In this step, the final system is formed according to some rules known as "weaving rules" specified within the aspect.AnaspectlVeaver,which isacompiler-likeentity,

(25)

O1apterl:IntroductiOll

composes the final system by combining the core and crosscutting modules througha process called weaving.

Figure1.2,takenfrom[I),showsthedifferencebetweentwodifferent implementationsof abanking systemwithloggingfunctionality. Inboth implementations,thesystem includes several client modules such as the accounting module, the ATM module and the database module. The first implementation is done using OOP methodology, where the code tangling occurs between all the modules needing the logging module [I).

~ 1'"- -::::::..,-

-- D

~ B Er/EFE

~ -- D

Figure 1.2: Implementationofa banking system (Redrawnafler [I))

AOP implementation for the same banking system (right part of Figure 1.2) shows the modularizationoflogging functionality where none of the clients contain code for logging. Furthermore, logging becomes modularized as the crosscutting logging requirements are now mapped directly only to the logging aspect. With such modularization, any changes to requirements affect only the loggingaspectbutnotthe clients. Using AOP methodology, client code remains completely isolated and unchanged. Thus, AOP facilitates programs with improved traceability, higher modularization, easier system evolution and more code reuse.

(26)

(1Japterl:Introduetion

1.3.2AOP Language Implementation

As the AOP paradigm is gaining much industry support, we have several AOP implementations for existing programming languages. For example, AspecU [3] for Java, AspectC++ for C++ [4], Aspect# forC#[5], AspectS [6] for SmallTalk/Squeak [7]andAspectML[8]for ML aresome of the popular AOP language implementations.

1.3.2.1Basic Terminology:

The followings are some standard terms used in Aspect-oriented programming·

a) Join point:

Ajoin pointis a point in the dynamic control flowofanapplication. Thus a join point can for instance represent a call to a method, execution ofa method, the event of setting a field or the event of handling an exception. For example, AspectJexposes severalcategoriesofjoinpointssuchas:methodjoinpoints,constructorjoinpoints, field access join points and class initialization join points [I]. On the other hand, it does not expose join points for loops, super calls, throws clauses, multiplestatements

b)Pointcut:

Apointcutis a means to specify the weaving rules. It selects join points that satisfy those rules and collects program execution context at those points. Some AOP language implementations such as AspectJ [3] have a special language construct for pointcuts, whereas some other languages like AspectS [9] do not have any dedicated pointcutlanguage.

(27)

O1apterl:Introduction

c) Advice:

Adviceisa means of specifying code to run at a join point that has been selectedbya pointcul.

d) Aspect:

The combination of one or more point·cuts and advices is termedanaspecl.

e) Static crosscutting:

lnAOp,weoftenfindthatinadditiontoaffectingdynamicbehaviorusingadvice,itis necessary for aspects to affect the static structure in a crosscutting manner. While dynamic crosscutting modifies the execution behavior of the program, static crosscutting modifies the static structure of the types-the classes,interfaces,and otheraspects--andtheircompile·timebehavior.

1.3.2.2Join Point Model

Each AOP implementation has its own Join Point Model (JPM) which defines three things:

(i) When tbe advice can run, (ii) A way to specify pointcuts and (iii) A means of specifying code to run at ajoinpoinl.

JPMs of different AOP implementations can be compared based on the following

Thejoinpnintsexposed,

How pnintcuts are specified,

(28)

C11apterl:lntroduction

The operations pennitted at the join points, and

Thestructuralenhancementsthatcanbeexpressedsuchasstaticcrosscutting.

The AOP implementations of some of the languages are described in detail in the next chapter.

1.4 Aspect-oriented Modeling

Aspect-oriented modeling (AOM) supports modularization of cross-cutting concerns at the software design level. Most AOM techniques focus on providing modeling capabilities for the core AOSD concepts, usually as extensions to the Unified Modeling Language (UML).

UML [10] is a standardized general-purpose modeling language in the fields of software engineering. UML is managed, and was created by the Object Management Group (OM G). To date UML is not only used to model application structure, behavior, and architecture, but also business process anddatastructureo

UML, along with the Meta Object Facility (MOF)\, provides a key foundation for OMG's Model-Driven Architecture, which unifies every step of development and integration from business modeling, through architectural and application modeling, to development, deployment, maintenance, and evolution [10].

A model can be either platfonn-independent or platfonn-specific. A platfonn- independent model (PIM) is a model of a software system or business system that is independent of the specific technologicalplatfonn used to implementit. Aplatfonn-

(29)

O1apterl:Introduction

specific model (PSM) is a model ofa software or business system that islinkedtoa specific technological platform (e.g. a specific programming language, operating system or database).

UML allows both PIM and PSM. Besides this, it provides a mechanism known as profile. Profiles are the standard mechanism to extend UML. The profile mechanism exists within UML so models applying a profile are fully UML compatible. A UML model applying a profile is UML, and any UML tool can process it [II].

While there has been prior work on extending UML to AOM, most of the extensions expand UML either by introducing new meta-model classes or new notation elements without providing meta-level support. Furthermore, many of the existing AOM approaches are programming language specific and allow modelingonthep latform specific model (PSM) level. While AOP language implementations are rapidly maturing, a platform independent model is necessary to increase the reusability of system. [t will also ease the communication between developers from different backgrounds. Building on previous work [12], this research presents a core generic meta-model, which is a profile based on the core features of some AOP languages.

Core features are selected by comparing some of the AOP language extensions.

As AOP paradigm is rapidly maturing we have AOP language extensions for many of the existing programming languages such as Java, C, C++, SmallTalk, Haskell, ML, PHP and XML. However, in this research we only study the features of AspectJ, AspectS and AspectML. AspectJ is chosen because it is considered as the flTst complete and powerful language extension for AOP. It possesses a wide variety of AOP language features. Features of other AOP language extensions (e.g. AspectC,

(30)

(hapter1: Introduction

AspectC++) for existing languages that follow OOP approach (E.g. C, C++) can be consideredassubsetsofthefeaturesofAspect!.

Like Aspect!, AspectS follows OOP approach. However, because AspectS supports dynamic AOP (will he discussed in Chapter}), it is also considered for this study.

Thisisa fact that the use of several languages provides some generality. As a result, we wanted to keep aAOP language extension of an existing language(e.g. Haskell, ML, etc) that belongs to the family of functional language. Since AspectML is well developed and widely used among these languages, it is also includedinourstudy.

1.5 Objectives The objectives of this research are:

TostudyAOP languages in order to identify their sirnilarities and differences.

To develop a platform independent UML-based model (PIM), which will be a UML profile for the AOP paradigm. The model will allow aspect modeling to be used within existing, mature software tools.

To develop an example of atransformation fromaPIM to platform-specificcode.

To find a way to handle the features unique to theAOP languages that we are studying.

1.6Thesis Structure

ChapterI introduces AOP paradigm.Itsbows the necessity of the paradigm.Italso introduces both aspect-oriented programming and aspect-oriented modeling along with the basic terminology used for these two.

(31)

OJapterl:Introduction

Chapter 2 provides a broad overview of AOP languages that we study. This helps the reader who is not very familiar with AOP to develop some idea of AOP languages. A running example and its implementation in three different languagesallow us to have a comparative picture of the languages that we study.

Chapter 3 focuses on two different AOP approaches: static and dynamic. Since the languages that we study do not follow a single approach from these two ,this chapter providesadetailedoverviewoftheseapproaches.ltalsodoesexplain the difference betweendynarnic and static AOP.

Chapter 4 compares the three languages that we study. This chapter provides a detailed overview of different features of each language. The runningexample is used to demonstrate how the different languages can be used to implement a solution to the same problem. Thus it helps to select the core featuresofAOP languages.

Chapter 5 elaborates the discussion on AOM. It includes some of the prior works relatedtoourresearch.italsoaimstodevelopagenericUML"profile"thatcanbe used to model aspect-oriented system.

Chapter 6 demonstrates the application of the developed profile. it illustrates base model for fiveexarnples. The developed profile is applied to both static and dynarnic model for each exarnple.

Chapter 7 presents code generation for each application shown in Chapter 6. it presents XSLTs to generate Aspectl and AspectS code from the model to which the generic profile is applied.

ChapterS focuses on overall discussion on this research. it includes the importance and limitations of the developed profile.

(32)

O1apter1: introduction

Chapter 9 presents the summary and conclusion of this research work.It also highlights some possible future works that can be done byextendingthis research.

(33)

C1Japter2:M OverviewofAOP Languages

Chapter 2

AN OVERVIEW OF AOP LANGUAGES

2.1Running Example

The Shopping-Cart problem given in[I]is an example that clearly shows how code scattering occurs in a conventional implementation when some features such as logging are added to it.Italso reveals the necessity of modularizing cross-cutting concerns. The basic functionalities of Shopping-Cart without logging are implemented using the following classes:Item class, Inventory class, ShoppingCart class, ShoppingCartOperator class and a Test class.

Listing 2.1 represents theItem Class. This class models the items which can be purchased. This class has a constructor and three public methods:getIdO,getPriceO andtoStringO. ThegetIdO and thegetPriceO methods provide the identifier and price of the item respectively.ThetoStringO method simply sets the formatofanitemtoa string.

(34)

Chapter2:AtlOverviewofAOP Languages

Listing2.1Ilemclass public class Item {

privateStrinq_id;

float""'price;

Item(Strinqid,floatprice)

}....price=price;

publicStringgetID(){

returnid;

}

publicfloatgetPrice(){

}returnyrice;

publicStringtoStrinq(){

return"Item:"+id;

The Inventory class, shown in Listing 2.2, represents the list of items available for purchasing. This class has two public methods: addItemO and removeItemO. Both of tbese methods take an item as argument which can be added to nr removed from the existing item inventory using these two methods.

Llsdn2.2Invenloryclass importjava..util.*;

public class Inventory { privateList_items=newVector();

public vcid addltem(Item item){ items.add(item);

)

public void removeltem(Item item){ _items.remove(item);

TheShoppingCartclassshown in Listing 2.3 represents the listofitemsinashopping cart of a customer. The two public methods addltemO and removeltemO are respectively used to add and delete specific items fromtheshoppin gcart's item list.

(35)

(1Japter2:MOverviewofAOPLanguages

Listing2.3ShoppingCartclass importjava.uti.l.*;

publicclassShoppingCart{

::~~::eV~~:tad~:::(;t:wi::~07();

}_items.add(item);

public void removeltem(Item item){ items.remove(item);

I I

The ShoppingCartOperator class is used to model the operations related to a purchase. This class has two static public methods: addShoppingCartitemO and removeShoppingCartitemO.The purpose of these two methods is to update both lists:

inventory and shopping cart. The method addShoppingCartitemO is used to model a

"purchase of an item" by adding an item to the shopping cart and deletingthesame item from the inventory. On the other hand removeShoppingCartItemO is used to model a "return of an item" by removing an item from the shopping cart and adding it back to the inventory. The entire ShoppingCartOperator class with all the above mentioned methods is shown below in Listing 2.4

(36)

OIapter2:AAOverviewofAOP Languages

Listing2.4ShoppingCartOperatorclass publicclassShoppinqCartOperator{

public static voidaddShoppinqCartltem(ShoppingCartSC, Inventory inventory, Item item) { inventory.removeltem(i.tem);

sc.addltem{item):

I

public static void removeShoppinqCartltem(ShoppingCart sc, Inventory inventory, Item item){ sc.removeltem(item);

}inventory.addltem(item);

I

Listing 2.5 shows the Test class that tests the functionality of the classes discussed above. This class does not print any text message as output. However,w ithin the class, at first, three items are added to the inventory list. Then, using the method addShoppingCartltem of ShoppingCartOperator class, two of the previously added item are added to the list of shopping cart, and are deleted from the Iistofinventory.

Li,ling2.5Testcl...

public class Test {

publicstaticvoidmain(Strinq[]arqs){

Inventory inventory=new Inventory():

ltemiteml=new Item("l",30);

ltemitem2=newltem("2",31);

ltemitem3=new Item("3",32);

i.nventory.addltem(item1);

inventory.addltem(item2);

inventory.addltem(item3);

ShoppingCartsc=newShoppingCart();

ShoppingCartOperator.addShoppi.ngCartltem(sc, inventory, i.teml);

ShoppingCartOperator.addShoppingCartltem(sc, inventory, item2);

I

done in a similar fashion as in [I] by using the library class provided in lava for

(37)

(1Japter2:MOverviewofAOPLanguages

logging. Listing 2.6 shows the modified version ofTestclass with logging functionality.

Listing 2.6 Testclass(modifiedversion-2) java.uti1.Date;

class Test {

staticvoidmain(Strinq[]arqs){

Datedate=newDate();

System.out.println(date+"Testmain"+"\nINFO:

Entering");

//restof the method's body should be same

Instead of using the Java library classLogger, for simplicity, belterperformance, and code reuse (in laterSections),weuse some conventional print statementsintheabove example. In order to see the execution information as shown in Figure 2.1, it is required to write the same type of logging code inside each related class and its

Figure 2.1: Output of the shopping-cartprograrn with "logging"

(38)

(1Japter2:MOverviewofAOP Languages

The repetition of this same logging code in several classes of this system is introducingcodescanering.Furthermodificationtothissystemcanalsolead to more formsofcodescaneringand code tangling. AOP language implementations provide the techniques to solve the code tangling and code scanering problems. Brief overviews of some of the AOP language implementations are given in the following sections along with some examples. Our running example shopping-cart is also implemented in each of the discussed AOP languages.

2.2 AspectJ

2.2.1 An Overview of AspectJ

AspectJ[3] is a widelyused,general purpose, aspect-oriented language extension to the Java prograrnming language. BeinganextensiontoJava,everyvalidJavaprogram canbeexecutedasa valid AspectJ program. AspectJ adds to Java new constructs to specify the weaving rules programmatically:aspect, join point, pain/cut, advice, introduction and compile-time declaration.The class files produced by an AspectJ compiler conform to the Java byte-code specification. As a result,theseclassfilescan be executed by any compliant Java virtual machine (YM). Since it uses Java as the base language and retains all the benefits of Java, it is easy for programmersfroma JavabackgroundtounderstandtheAspectJlanguage.AnAspectJfileshouldbesaved with.ajextensionand can include constructs from Java and AspectJ inil.

2.2.1.1 Aspect

InAspectJ,anaspect is like a class in Java. It can include data members andmethods and can have access specifications, but it cannot be instantiated directly. An aspect

(39)

(1Japter2:AnOverviewofAOP Languages

can have an access specifier (visibility) of "privileged" in order to read and write the private members of the classes it is crosscutting [I].Itcan extend classes and abstract aspects, as well as implement interfaces. However, to reduce complexity, aspect inheritance is limited to only inheriting from abstract aspects but not from concrete aspects [3]. Moreover, an aspect can be embedded inside classes and interfacesasa nested aspect. Figure 2.2 shows an AspectJ file where aspect HelloWorld is declared as a public aspect. !tcontains a pointcut and an advice in its body. However it is possible to modify the aspect by including some regular variables and methods in it.

pointcutd~11v~rMl!~~agl!() : call(ItTest.. deliver ( bet'ore():delivt!!rMessaqe(){

Syst.em.out..prlnt("HelloWorlci!");

I

Figure 2.2: An AspectJ file named HelloWorld

2.2.1.2JoinPoint

AspectJ allows adding new behavior in some special parts or areas known as join pointsofaprogram.InAspectJ, the join points are mainly exposed as: method join points, constructor join points, field access join points, exception ha ndlerexecution joinpoints,classinitializationjoinpoints,objectinitializationjoin points, object pre- initialization join points and advice execution join points. On the other hand, loops, super calls, throws clauses, or multiple statements are not exposed as join points in AspectJ. Each of the above mentioned categories of exposed join points can include one or more types ofjoin points. For example, the methodjoinpointcategoryexposes

(40)

O1apterl:IVlOverviewofAOPLanguages

both method calls and executions. Figure 2.3 sbows a Java class named Test in which both the method call and method execution join points are exposed when an AspectJ file is used in parallel to select those as pointcuts.

Figure 2.3: A class named Test in Java

InAspectJ,apointcutcan both specify a single join point ina system and match a set of join points. It can be either anonymous or named. A named pointcut is defined using tbe keyword paintcut and can have access specifiers. On the other hand, an anonymous pointcut can be specified as part of an advice [I].

Join points in AspectJ are specified using pointcut designators. The pointcut designators match join points in AspectJ eitberby capturing join points based onthe category to which they belong or by capturing join points based on matching the execution circumstances under which they occur. AspectJ allowsthefollowing types of pointcuts:

(41)

C1>apter2:AroOverviewofAOP Languages

a) Kindedpointcuts:

Each exposed join point mentioned earlier has a specific pointeutdesignator, which is used to capture a join point from the program flow. However, all of these pointeut designators follow a particular format of syntax. Asaresult, they fall into the category ofkinded pointeu!. Table 2.1, taken from [I] shows the mapping between each exposed join point and its corresponding pointeut designator.

Table 2.1: Mapping of exposed join points to pointeutdesignators

The signature to be used in each pointeut designator is clearly described in both [I]

and [13] along with examples. However, the following (Figure 2.4) is a simple example ofa named pointeut where the name of the pointeut is deliverMessage.

As the signature part contains a method signature,looking at the above table it is c1early visible that this pointeut selects a method call join point, i.e. the call to the delivermethod of TeSI c1ass showed in Figure 2.3.

(42)

O1apter2:Pl10verviewofAOPLanguages

Figure 2.4:Anexampleofa named pointcut (adapted from [I]

b) Controi-flowbasedpointcuts

These pointcutscapturejoin points based on the control flow of join points captured by another pointcut [I]. InAspectJ,control-flowbasedpointcutscan be categorized as

i.cflowO

ThecjlowOpointcuttakes a pointcut as argument and captures all the join points in the control flow of the specified pointcut, including the join points matching the pointcutitself.

ii.cFlowBelowO:

The cFlowBelowO pointcut takes a pointcut as argument and captures all the join points in the control flow of the specifiedpointcut, excluding the join points matching thepointcutitself.

c) Lexicai-structurebased pointcut

Lexical-structure based pointcuts capture join points occurring inside a segment of source code of specified classes, aspects and methods [I]. There are two pointcuts in this category:

(43)

Chapter2: An OverviewofAOP Languages

i. witilinO

The witilinOpointcut is used to capture all the join point specified withinthebodyof thespecifiedclassesoraspects,includingthenestedclasses[l].

ii. witilincodeO

The witilincodeO pointcuts can have the fonns like withincode(MethodSignature) or withincode(ConstructorSignature). They are used to capture all the join points inside a lexical structureofa method or a constructor, as well as any local classes in them [I]

d) Executionobjectpointcuts

These pointcuts match the join points based on the typesoftheobjectsatexecution time. They are also used to expose the context of the specified join point. This category consists of the followingpointcuts:

i.tilisO

til isrefers to the current object. Therefore,thetilisO pointcutselects all the join points associated with the current object.

ii.targetO

targetrefers to the object on which the method is called. The targetO pointcut is usually used with method call join point.Itis used to select thejoinpointsassociated with the object on which the method is invoked.

(44)

O1apter2:Pl10verviewofAOPLanguages

e) Argumenlpoinlculs(argsQ)

TheargsOpointcut can expose the context at the matched join point. The empty bracket after the name ofthepointcut indicates that it does not expose the context of thejoinpoint.

f)Conditional check pointcuts(if0)

Conditional checkpointcut captures join points on the basis of some conditional check at the join point [I]

Advices of AspectJ are similar to methods of Java. But they have some differences as

Cannot be called directly (it is the system'sjob to execute it)

Does not have an access specifier

AspectJ allows different types of ad vices as a means to specify code to run at a join point.

Advice is invoked automatically by the AOP runtime when the pointcut matches the join point. AspectJsupports following three types of advices:

a) Before advice:

Before advice allows adding new behavior before the specified join po int.

(45)

Chapter2: M OverviewofAOP Languages

b) After advice:

After advice allows adding new behavior after the specified join point

c) Around advice:

Around advice has the ability to bypass the join point, allow ittoexecute as it is, or execute it with changed context.

2.2.1.5 Static Crosscutting

AspeetJ allows static crosscutting (also known asintroduction)./ntroductionaffeets the static structure of programs through crosscutting. Usingin trodlIction it is possible to introduce changes to the classes, interfaces, and aspects of the system [1].

2.2.2 Running Example in AspectJ

When implementing the running example ShoppingCart in AspeetJ, the base model is kept without any logging code. As shown in Listing2.7,theerosseuttingeoneernsare modularized in an aspect namedTraceAspect. The pointeut named traeeMethodsO selects all the method execution join points specified bythewildeardsintheprogram flow, except those within the lexical scope of theTraceAspectaspeet.

Listing 2.7TraceAspectAspect in AspectJ importjava.util.Date;

importorg.aspectj.lanq.*;

public aspect TraceAspect{

poi.ntcuttraceMethodsO

:executi.on(*·,*( .. »'&!within(TraceAspect);

before():traceMethods(){

Datedate=newDate();

Siqnaturesig=thisJoinPointStaticPart.getSignature();

System.out.println(clate+""

+siq.qetDeclaringType().getName()+" "+sig.getName()+"\n

(46)

OJapter2:MOverviewofAOPLanguages

INFO: Entering");

}

ThepointcuttraceMethodsO is then advised by the before advice, which places the logging code before each of the method execution specified by the pointcut itself.

Figure 2.5 shows the output of the ShoppingCart example implemented in Aspect!.

Although this implementation produces the same output as the one (Figure 2.4) produced by the example implemented without aspects, the difference here is that a programmer does not need to write logging code in each method of each class. As a result, in the current implementation the crosscutting concerns are modularized.

Therefore, the logging feature does not create codetanglingorscatteringinthis example.

Wed Jun 03 00:53:23 NDT 2Q09 Testmaln INFO:E:nterlng

WedJun03 OO:S3:21NDT2009 Invencoryaddltem INFO:Enterlng

WedJun 03 00:53:24 NOT 2009 Invencoryaddltem INFO: Eneerlno

Wed Jun 03 00:53:21 NDT2009 Inventoryaddltem INFO: Entering

Wed Jun03 00:53:2'9: NDT2009 ShoppinqCartOperatoraddShopplngCareItem INFO: Encering

WedJun0300:53:2'!NDT2009Inventoryremoveleem INFO:E:nter1nq

Wed Jun 03 00:53:24 NDT 2009 ShopplnqCart addlt:em INFO: Eneerinq

Wed Jun 03 OO:53:24NDT2009 ShoppinqCartOperatoraddShoppinlJCareItern INFO: Enter1nq

WedJun0300:53:24NDT2009Inventoryremovelt~

INFO: En1:erlng

Wed Jun 03 00:53:24 NOT 2009 Shoppi.nqCartaddI~em INFO: Ente:rinq

Figure 2.5: Output of the ShoppingCart example in Aspect!

(47)

Chapter2:IVlOverviewofAOPLanguages

2.3 AspectS

2.3.1 An Overview of AspectS

AspectS [6] is an AOP implementation for the Smalltalk or Squeak' environment.It mainly draws on the results of twoprojects: AspecU[3], and John Brant's MethodWrappers'[14j.lnitscurrentimplementation,AspectSisrealizedusingplain Smalltalk only, changing neither Smalltalk's syntax nor its virtual machine. As a result, AspectS also complies with following language properties of SmallTalk:

Everything(e.g.c1ass,instancesofclass,etc)isanobject.

All communications are done using method passing between objects.

Classes inherit via single inheritance.

Thedefauitaccessspecificationisasfollows:

Table 2.2: Access Specification AspectS

All the examples related to AspectS are written in this text usingSqueakversion3.8 and AspectS version 0.6.6. AspectS version 0.6.6 is available in [9]

2Squeak isanopen,highly portable Smalltalk·gO implementation. Itsvirtualmachineiswrittenentircly in Smalltalk.The terms Squeak and Smalltalkareused intcrchangeablyin thistext.

JMethodWrnppers is a powerful mechanism to add behavior to a compiled Small talk method

Références

Documents relatifs

Figure 5 — Relative importance of promoter, untranslated and coding regions for predicting gene expression in different species and conditions For each condition, the 30 most

Espe- cially the pure water jet simulations, which give good agree- ment with the fit, show that without a random distribution of abrasive masses nor a velocity gradient in the

We will show that technosymbiosis is based on (a) a sense of mastery of technological uses, (b) a representation of the benefits of a mutual adaptation between human beings

Figure II.12 | Gasification solid conversion as a function of time, for sunflower seed shells and rice husks, in the case of chars produced directly in the TGA (raw biomass) or in

Dans le cadre de ce stage, nous nous intéressons au lien éventuel entre la présence d’un ensemble de micro-habitats sur la biodiversité de 3 groupes

Integrating the power spectral densities of the magnetic and electric fields in the 10 to 500 Hz frequency range shows that the energy density of waves is higher inside the

In this paper we have developed representer theorems for convex regularized inverse problems (1.1), based on fundamental properties of the geometry of convex sets: the solution set

It is not a problem if the contact person is not totally familiar with the topic 6 , but he/she must indicate the stakeholders having the most diverse opinions possible for each