ASPECT ORIENTATED PROGRAMMING COMP 319 University of Liverpool










![Aspect example (Hello World) public class Main { public static void main(String[] args) { Aspect example (Hello World) public class Main { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-11.jpg)

![Point cut definitions //call is the most common joinpoint type call([access modifier] return. Type Point cut definitions //call is the most common joinpoint type call([access modifier] return. Type](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-13.jpg)


![Join points public static void main(String argsv[]) { hello(); call } Public static void Join points public static void main(String argsv[]) { hello(); call } Public static void](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-16.jpg)





![Types of Advice • after() returning [(type expr)] - called after normal execution of Types of Advice • after() returning [(type expr)] - called after normal execution of](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-22.jpg)
![Types of Advice • type around() [throws exception] - executes in place of a Types of Advice • type around() [throws exception] - executes in place of a](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-23.jpg)























- Slides: 46

ASPECT ORIENTATED PROGRAMMING COMP 319 © University of Liverpool slide 1

The problem • Code scattering class Bank. Account { public void transfer(int amount, Bank. Account to. Account) { try { Log. transferring. Money(); if (authenticated(username, password) { // do transfer } } catch (Transaction. Exception texc) { Log. store. Exc(texc); } COMP 319 © University of Liverpool slide 2

Concerns and Cross cut concerns • Concern examples, banking - Transfer between accounts - Product statement - Make billing payment • Cross cut concerns - Security/authentication - Logging - Transaction handling COMP 319 © University of Liverpool slide 3

Cross cut concern problems • Scattering • Duplication - Code cloning • Tangling - Concerns not properly separated COMP 319 © University of Liverpool slide 4

Cross cutting concern examples and approaches • Persistence - Object-relational mapping • Internationalization - Resource bundling • Code mobility - Pre-processing • Error handling - Chained exceptions, error return codes COMP 319 © University of Liverpool slide 5

Definitions • Cross-cutting – Identify areas of code where common functionality exists • Advice – The code to be injected • Joinpoint – Where one or more aspects can be applied • Pointcut – A collection of joinpoints • Aspect – General term for where advice and point-cuts are combined COMP 319 © University of Liverpool slide 6

Terminology • Weaving – Integrating applications and aspects (e. g. Aspect. J is an “aspect weaver”) - Compile-time – Can produce integrated source-code, but typically only produces woven byte-code. - Run-time – Aspects are applied “on the fly” (typically when classes are loaded) COMP 319 © University of Liverpool slide 7

AOP Platforms Aspect. J Spring JBoss AOP Aspect. Werkz - Now working with Aspect. J • Java Aspect Components (JAC) • • COMP 319 © University of Liverpool slide 8

Aspect. J • Now an Eclipse project (http: //eclipse. org/aspectj/) - Developed at Xerox PARC - Released 2001 • Latest version (Aspect. J 5) is a collaboration of Aspect. J and Aspect. Werkz • AJDT - Aspect. J Development Tools plug -in for Eclipse COMP 319 © University of Liverpool slide 9

Aspect definition Aspect package com. aspect; public aspect Demo. Aspect { Point-cut pointcut setter. Notification() : call(* *. set*(. . )); before() : setter. Notification(){ System. out. println("setting data. . . "); } Advice } COMP 319 © University of Liverpool slide 10
![Aspect example Hello World public class Main public static void mainString args Aspect example (Hello World) public class Main { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-11.jpg)
Aspect example (Hello World) public class Main { public static void main(String[] args) { // TODO Auto-generated method stub hello(); } public static void hello() { System. out. println("Hello"); } } COMP 319 © University of Liverpool slide 11

Aspect Example Hello. World public aspect Hello { pointcut hello. Call() : execution( * Main. hello(. . )); after() : hello. Call() { System. out. println("World!!!"); } } COMP 319 © University of Liverpool slide 12
![Point cut definitions call is the most common joinpoint type callaccess modifier return Type Point cut definitions //call is the most common joinpoint type call([access modifier] return. Type](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-13.jpg)
Point cut definitions //call is the most common joinpoint type call([access modifier] return. Type package. Class. Name. method(args)); //Examples call(* *. *(. . )); //Note: “. . ” is also a wildcard call(public * *. set*(. . )); call(void *. set*(. . )); call(* *. set*(int)); call(String com. foo. Customer. set*(. . )); call(* com. foo. Customer+. set*(. . )); //”+” cross-cuts children call(public void com. . *. set*(int)); call(* *. set*(int, . . , String)); COMP 319 © University of Liverpool slide 13

Defining a pointcut • pointcut name. Of. Point. Cut() : definition; • pointcut setters() : call(public * *. set*(. . )); COMP 319 © University of Liverpool slide 14

Types of Join point • call(method expr) - when a method is called • execution(method expr) - when a method is executed • handler(exception expr) - when a catch block is executed COMP 319 © University of Liverpool slide 15
![Join points public static void mainString argsv hello call Public static void Join points public static void main(String argsv[]) { hello(); call } Public static void](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-16.jpg)
Join points public static void main(String argsv[]) { hello(); call } Public static void hello() { execution try { } catch (Exception e) { handler } } COMP 319 © University of Liverpool slide 16

Types of Join points • get(field expr) - when a field is read • set(field expr) - when a field is set - pointcut setting. Length() : set( int Setter. Monitor. Example. length); • staticinitialization(class expr) - when a static block of a class is executed COMP 319 © University of Liverpool slide 17

Types of Join points • initialization(constructor expr) - when a constructor is executed • preinitialization(constructor expr) - when inherited constructors are executed • adviceexecution() - when an advice block is executed COMP 319 © University of Liverpool slide 18

Adding Advice pointcut every. Call() : call(* *. *(. . )); before() : every. Call(){ System. out. println(“Advice called before method"); } after() : some. Point. Cut(){ System. out. println("Advice called after each method"); } COMP 319 © University of Liverpool slide 19

Anonymous point cuts in Advice before() : call(* *. *(. . )) { System. out. println("Injecting advice. . . "); } // point cut doesn’t have name COMP 319 © University of Liverpool slide 20

Types of Advice • before() - Before call or body • after() returning • after() throwing • after() • around() COMP 319 © University of Liverpool slide 21
![Types of Advice after returning type expr called after normal execution of Types of Advice • after() returning [(type expr)] - called after normal execution of](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-22.jpg)
Types of Advice • after() returning [(type expr)] - called after normal execution of the joinpoint • after() throwing [(exception expr)] - called if the execution of the joinpoint throws the specified exception • after() - executes regardless (sort of like finally) COMP 319 © University of Liverpool slide 22
![Types of Advice type around throws exception executes in place of a Types of Advice • type around() [throws exception] - executes in place of a](https://slidetodoc.com/presentation_image_h2/07eae9e09736ff6bec397377d9c96552/image-23.jpg)
Types of Advice • type around() [throws exception] - executes in place of a joint point of execution - You can stop or replace code execution - To call the original code, use proceed() COMP 319 © University of Liverpool slide 23

Types of Advice • withincode(method expr) - true if joinpoint is within defined method • within(type expr) - true if joinpoint is within defined type (i. e. class definition) COMP 319 © University of Liverpool slide 24

Exception handling in Advice • after() throwing - Intercepts at method level, before the catch() block • handler(exception type) - Intercepts at the catch() block • declare soft : exception type - Wraps any exception as a Runtime. Exception (which consequently no longer needs to be declared in the throws clause of the method) COMP 319 © University of Liverpool slide 25

Exception handling advice before(java. io. File. Not. Found. Exception exc) : handler(java. io. File. Not. Found. Exception ) && args(exc) { System. out. println("Could not find file. . . message is "+exc. get. Message()); } COMP 319 © University of Liverpool slide 26

Point cut operators • if(expr) - evaluate boolean expression • withincode(method expr) - true if joinpoint is within defined method • within(type expr) - true if joinpoint is within defined type COMP 319 © University of Liverpool slide 27

Point cut operators • this(type expr) - true when joinpoint matches source object • target(type expr) - true when joinpoint matches target object • args(type expr) - true for any joinpoint matching argument type list COMP 319 © University of Liverpool slide 28

Getting at the context • Sometimes we want to get at - The instance of this, which is being used at the point of call - The target instance - Example fred. get. X(); // fred is the target - The arguments (x and y) - Example fred. set. Position(x, y) COMP 319 © University of Liverpool slide 29

Getting the context • Declaring the context, type - before(Bank. Account account) : • Declares the context type in the point cut, for example. . before(Bank. Account account) : target(account) && authentication. Needed() && (!execution(* Bank. Account. authenticate(. . ))) { account. authenticate(); } - Question … Why do we have !execute(* Bank. Account(authenticate()) COMP 319 © University of Liverpool slide 30

Arguments example pointcut setting. Length(int length) : set( int Setter. Monitor. Example. length) && args(length); void around(int input. Length) : setting. Length 1(input. Length) { System. out. println("Trying to set length to "+input. Length); if (input. Length<5) { proceed(input. Length); } else { System. out. println("Skipping length setting length too large"); } } COMP 319 © University of Liverpool slide 31

Point cut logical operators • && - Logical AND • || - Logical OR • ! - Logical NOT COMP 319 © University of Liverpool slide 32

this. Join. Point. to. String() this. Join. Point. get. Kind() // call, execution, set, get this. Join. Point. get. Signature(); System. out. println("this. Join. Point. get. Source. Locatio n(): " + this. Join. Point. get. Source. Location(); // source code line number this. Join. Point. get. Target(); // target object this. Join. Point. get. This(); // source object COMP 319 © University of Liverpool slide 33

this. Joint. Point example package testaspect; public class Aspect. Reflection. Example { public void greet() { Greeter greeter=new Greeter("Seb"); greeter. greet("Hello "); } public static void main(String argvs[]) { Aspect. Reflection. Example instance=new Aspect. Reflection. Example(); instance. greet(); } COMP 319 © University of Liverpool slide 34

this. Joint. Point example package testaspect; public class Greeter { private String name=""; public void good. Morning() { System. out. println("Good morning "+name); } public void greet(String message) { System. out. println(message+name); } public Greeter(String name) { this. name=name; } } COMP 319 © University of Liverpool slide 35

this. Join. Point example package testaspect; public aspect Reflect. Aspect { pointcut greetings(Greeter example) : call(* *. Greeter. greet(. . )) && target(example); before(Greeter example) : greetings(example) { System. out. println("this: " + this); System. out. println("this. Join. Point. to. String(): " + this. Join. Point. to. String() ); System. out. println("this. Join. Point. get. Kind(): " + this. Join. Point. get. Kind() ); System. out. println("this. Join. Point. to. Long. String(): " + this. Join. Point. to. Long. String() ); System. out. println("this. Join. Point. to. Short. String(): " + this. Join. Point. to. Short. String() ); System. out. println("this. Join. Point. get. Class(): " + this. Join. Point. get. Class() ); System. out. println("this. Join. Point. get. Signature(): " + this. Join. Point. get. Signature() ); System. out. println("this. Join. Point. get. Source. Location(): " + this. Join. Point. get. Source. Location() ); System. out. println("this. Join. Point. get. Target(): " + this. Join. Point. get. Target() ); System. out. println("this. Join. Point. get. This(): " + this. Join. Point. get. This() ); } } COMP 319 © University of Liverpool slide 36

this. Joinpoint this: testaspect. Reflect. Aspect@3 a 3 ee 284 this. Join. Point. to. String(): call(void testaspect. Greeter. greet(String)) this. Join. Point. get. Kind(): method-call this. Join. Point. to. Long. String(): call(public void testaspect. Greeter. greet(java. lang. String)) this. Join. Point. to. Short. String(): call(Greeter. greet(. . )) this. Join. Point. get. Class(): class org. aspectj. runtime. reflect. Join. Point. Impl this. Join. Point. get. Signature(): void testaspect. Greeter. greet(String) this. Join. Point. get. Source. Location(): Aspect. Reflection. Example. java: 6 this. Join. Point. get. Target(): testaspect. Greeter@37 dd 7056 this. Join. Point. get. This(): testaspect. Aspect. Reflection. Example@2 afa 3 ac 1 COMP 319 © University of Liverpool slide 37

Modifying target classes • Inter type declarations - Aspect can add methods, field and constructors to external class aspect Security. Checks boolean Bank. Account. authenticated=false; public void Bank. Account. authenticate() { if (authenticated) return; // TO DO more authentication code } public Bank. Account. new(String password, String name, String pin) { } } COMP 319 © University of Liverpool slide 38

Modifying target classes • You can also use inter-type declarations to change the inheritance, to add new interface or new super class • New parent must be sub-class of existing parent public aspect Change. Structure { declare parents: Bank. Account implements Serializable; declare parents: Bank. Account extends Secure. Object; } COMP 319 © University of Liverpool slide 39

Intertype declarations, compile control • declare parent • declare warning - Compiler warnings result from joinpoints • declare error - Compiler errors result from joinpoints • declare precedence - Define aspect precedence COMP 319 © University of Liverpool slide 40

Encouraging logging, using warnings • Simple example - From Matt Chapman, AJDT Committer public aspect Enforce. Logging{ pointcut scope(): within(*); pointcut printing(): get(* System. out) || get(* System. err) || call(* Throwable+. print. Stack. Trace()); declare warning : scope() && printing(): "don't print, use the logger"; } COMP 319 © University of Liverpool slide 41

Class watcher example • Monitors all calls to setters • If data changes - Dirty flag=true • Application can use this to - Save data only if dirty flag=true, saves unrequired writes - Data can be discarded from cache if dirty flag=false - Supports lazy writing caches - Help data integraty testing COMP 319 © University of Liverpool slide 42

Watcher Example public aspect Watch. Setters { // just to invoke test code below public static void main(String[] args) { Client. handle. Timer(new Timer()); } private static final Class[] GETTER_ARG_TYPES = new Class[]{}; private static final Object[] GETTER_ARGS = new Object[]{}; private static final Object NONE = new Object(); public interface IWatched {} /** true if new value sent to any setter */ private boolean IWatched. dirty; /** false if unable to maintain dirty b/c no privileges, no getter. . . */ private boolean IWatched. dirty. Valid = true; /** clients can use dirty flag */ public boolean IWatched. is. Dirty() { return dirty; } /** clients handle case when dirty flag is invalid */ public boolean IWatched. is. Dirty. Valid() { return dirty. Valid; } COMP 319 © University of Liverpool slide 43

Watcher example (Pointcut) • public pointcut setters(IWatched watched) : target(watched) && execution(void IWatched+. set*(*)); // advice uses args[0] COMP 319 © University of Liverpool slide 44

Watch timer advice void around(IWatched watched) : setters(watched) && if (watched. dirty. Valid) { // get value by invoking getter method Object value = NONE; // no value String getter. Name=“”; try { getter. Name = "g" + this. Join. Point. get. Signature(). get. Name(). substring(1); Method method = watched. get. Class(). get. Method(getter. Name, GETTER_ARG_TYPES); value = method. invoke(watched, GETTER_ARGS); } catch (Throwable t) { } ; if (NONE == value) { watched. dirty. Valid = false; proceed(watched); return; } // compare value with arg being set - pointcut has exactly 1 parm Object arg = this. Join. Point. get. Args()[0]; if (!(null == arg ? value == null : arg. equals(value))) { proceed(watched); watched. dirty = true; }} COMP 319 © University of Liverpool slide 45

Watcher Example Persistence if (!(null == arg ? value == null : arg. equals(value))) { proceed(watched); watched. dirty = true; String table. Name=this. Join. Point. get. Target(). get. Class(). get. Name(); table. Name=table. Name. replace(". ", "_"); String sql="update "+table. Name+" set "+getter. Name. substring(3)+"='"+arg. to. String()+"' where id='"+watched. id+"'"; System. out. println("sql : "+sql); } COMP 319 © University of Liverpool slide 46