Adaptive Aspect-Oriented Programming in AspectJ Karl J. Lieberherr Northeastern University.

Slides:



Advertisements
Similar presentations
ASTA Aspect Software Testing Assistant Juha Gustafsson, Juha Taina, Jukka Viljamaa University of Helsinki.
Advertisements

1 Shyness in Programming Karl Lieberherr Demeter Research Group Northeastern University Boston.
1 Why do we need XAspects Structure-shyness –Can build DSL objects using constructors and use AspectJ to implement meaning of DSL objects. Is inconvenient.
Overview of AspectJ Aspect Oriented Software Development Seminar Technion presented by Oren Mishali.
3/7/2003Bioinformatics1 How To Address Rapidly Changing Data Representations in an Evolving Scientific Domain Using Aspect-oriented Programming Techniques.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
University of British Columbia Software Practices Lab CAS Seminar 06 Fluid AJ - A Simple Fluid AOP Tool Terry Hon Gregor Kiczales.
Integration of Demeter and AspectJ (DAJ) John J. Sung.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Outline Introduction Problem Statement Object-Oriented Design Aspect-Oriented Design Conclusion Demo.
3/7/2003Bioinformatics1 How To Address Rapidly Changing Data Representations in an Evolving Scientific Domain Using Aspect-oriented Programming Techniques.
Introduction to Aspect Oriented Programming Presented By: Kotaiah Choudary. Ravipati M.Tech IInd Year. School of Info. Tech.
Master’s Thesis Defense: Aspectual Concepts John J. Sung.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Integrating Independent Components with On-Demand Remodularization based on OOPSLA 2002 paper by Mira Mezini Klaus Ostermann Prepared by Karl Lieberherr.
The Java Programming Language
Expression evaluation E : S | C. S = int. C = Op E E. Op : A | M. A = “+”. M = “*”.
Aspect Oriented Programming Sumathie Sundaresan CS590 :: Summer 2007 June 30, 2007.
3/7/2003 ABB rapid change 1 How To Address Rapidly Changing Data Representations in an Evolving Scientific Domain Using Aspect-oriented Programming Techniques.
Slides for Gregor Kiczales Two versions –short version: Crosscutting capabilities for Java and AspectJ through DJ (4 viewgraphs only) –long version: Controlling.
AOSD1 Aspect-Oriented Software Design Karl Lieberherr Theo Skotiniotis.
AOP-1 Aspect Oriented Programming. AOP-2 Aspects of AOP and Related Tools Limitation of OO Separation of Concerns Aspect Oriented programming AspectJ.
Master’s Thesis Defense: Aspectual Concepts John J. Sung.
John J. Sung TA Consulting. Motivation for TraversalJ KL Enterprises identified AOP Enter into the AOP market early Add value by adding traversals to.
AOP Foundations Doug Orleans Karl Lieberherr. What we did earlier AOP languages have the following main elements: –a join point model (JPM) wrt base PL.
Features of AOP languages AOP languages have the following main elements: –a join point model (JPM) wrt base PL –a specification language for expressing.
Region Pointcut for AspectJ Shumpei Akai Shigeru Chiba Muga Nishizawa.
1 Modularization of crosscutting concerns Write this public class Shape { protected double x_= 0.0, y_= 0.0; protected double width_=0.0, height_=0.0;
Inter-Type Declarations in AspectJ Awais Rashid Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
AspectJ – AOP for Java Tom Janofsky. Instructor at Penn State Abington Consultant with Chariot Solutions JUG Member.
Course Progress Lecture 1 –Java data binding: Basket example: UML class diagram -> class dictionary without tokens-> language design -> class dictionary.
Demeter Aspects We study techniques for the emerging area of Aspect-Oriented Software Development and focus on the following areas:  Aspectual Collaborations.
Checking LoD in AspectJ Show the idea, not the details. How can we precisely express it in a programming language?
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
DJ: traversal-visitor-style programming in Java Josh Marshall/ Doug Orleans Want to add more on traversal through collections and Aspectual Components.
问题 Code scattering Blocks of duplicated code Blocks of complementary code, and different modules implementing complementary parts of the concern Code.
Comparison of Different AOP Approaches Presented by: Xiaojing Wang.
Lorenz: Visitor Beans: An Aspect-Oriented Pattern Aspect-oriented pattern: describes a solution to a tangling problem in a particular context.
AOP/cross-cutting What is an aspect?. An aspect is a modular unit that cross-cuts other modular units. What means cross-cutting? Apply AOP to AOP. Tease.
CSC450 Software Engineering Devon M. Simmonds University of North Carolina, Wilmington 1.
AspectScope: An Outline Viewer for AspectJ Programs Michihiro Horie, Shigeru Chiba Tokyo Institute of Technology, Japan.
UCI Feb 031 Adaptive Aspect-Oriented Programming in AspectJ Karl J. Lieberherr Northeastern University Joint work of Demeter Research Group.
Why Should You Care About Aspect-Oriented Programming? Karl Lieberherr CCIS.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
COM1205 TraversalJ Project* Pengcheng Wu Feb.25,2003.
AOP with AspectJ Awais Rashid, Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
AO Mechanisms in Demeter1 Discussion with Gregor Kiczales at UBC Ontology of AOP Ontology is the study of what there is, an inventory of what exists. An.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Caching: An Optimization Aspect. Class Diagram for Base Item +name : String +check() : int Simple +weight : int +check() : int Container +capacity : int.
Jesse proposal1 Jesse’s proposal Karl Lieberherr.
Features of AOP languages AOP languages have the following main elements: –a join point model (JPM) wrt base PL –a specification language for expressing.
UCI Feb 031 Adaptive Aspect-Oriented Programming in AspectJ Karl J. Lieberherr Northeastern University Joint work of Demeter Research Group.
Modern Programming Tools And Techniques-I
Crosscutting Capabilities for Java and AspectJ through DJ
Lecture 12 Inheritance.
Aspect-Oriented Programming with the Eclipse AspectJ plug-in
Discussion with Gregor Kiczales at UBC
For John.
Demeter Aspects Who We Are Aspectual Collaborations
A Short Introduction to Adaptive Programming (AP) for Java Programmers
An Empirical Study of the Demeter System
A Short Introduction to Adaptive Programming (AP) for Java Programmers
Better Separation of Crosscutting Concerns with Aspectual Components
LoD in AspectJ Karl Lieberherr.
AOSD and the Law of Demeter: Shyness in Programming
Declarative Techniques for Improving Aspect Orthogonality
Aspect Oriented Programming
Adaptive Programming in JAsCo
Presentation transcript:

Adaptive Aspect-Oriented Programming in AspectJ Karl J. Lieberherr Northeastern University

Adaptive? A program is adaptive if it changes its behavior according to its context. Adaptive programs: Concurrency policy, Distribution policy, Logging Aspect, Adaptive Method, Law of Demeter Checker in AspectJ Possible contexts –Java program or its execution tree –UML class diagram or object diagram

Adaptive Aspects abstract public aspect RemoteExceptionLogging { abstract pointcut logPoint(); after() throwing (RemoteException e): logPoint() { log.println(“Remote call failed in: ” + thisJoinPoint.toString() + “(” + e + “).”); } public aspect MyRMILogging extends RemoteExceptionLogging { pointcut logPoint(): call(* RegistryServer.*.*(..)) || call(private * RMIMessageBrokerImpl.*.*(..)); } abstract

A Different Kind of Adaptive Aspect abstract aspect CapabilityChecking { pointcut invocations(Caller c): this(c) && call(void Service.doService(String)); pointcut workPoints(Worker w): target(w) && call(void Worker.doTask(Task)); pointcut perCallerWork(Caller c, Worker w): cflow(invocations(c)) && workPoints(w); before (Caller c, Worker w): perCallerWork(c, w) { w.checkCapabilities(c); }

A more complex adaptive aspect: Law of Demeter Checker (Object Form) aspect Check { … after(): Any.MethodCall{ // call (* *(..)); // check whether // thisJoinPoint.getTarget() // is a preferred supplier // object }

Observation Many AspectJ programs are adaptive (designed for a family of Java programs) –Context: Java program or its execution tree Enabling features in pointcuts: *, cflow Want to improve the adaptive capabilities of AspectJ: AspectJ still leads to tangling and duplication.

public aspect FileSystemTraversals { public void CompoundFile.listAll() { FileLister v = new FileLister(); eachFile(v); void CompoundFile.eachFile(…) { … if (contents != null) eachFile_crossing_contents(newTokens); } void CompoundFile. eachFile_crossing_contents(…) { this.contents.eachFile(tokens); } // much more }

Example of an Adaptive Method in AspectJ (DAJ) aspect FileSystemTraversals { declare traversal: void listAll(): "from CompoundFile to File" (FileLister); }

Another Adaptive Method aspect FileSystemTraversals { declare strategy: eachFile: "intersect(from CompoundFile to File, down)"; declare traversal: void listAll(): eachFile(FileLister); declare strategy: down: "from * bypassing -> *,parent,* to *"; }

What To Do class FileLister { Stack path = new Stack(); void before(File file) { path.push(file.name);} void after(File file) { System.out.print("."); Iterator it = path.iterator(); it.next(); while (it.hasNext()) System.out.print("/" + it.next()); System.out.println(); path.pop();} } High-level AspectJ advice using dynamic join points!

Excursion What is a good infrastructure for this? Goes back to the old theme of Crista: domain-specific aspect languages.

Aspect-Oriented Programming with Extensible Plugins How can we integrate numerous domain specific aspect languages? Idea: Use AspectJ as basic aspect language and translate domain specific aspect languages to AspectJ. Case study: Redo DAJ in this style.

Interfaces of Aspects For functionality –Expects –Provides For join points –Import –Export

Kinds of Aspects Class Dictionary Aspect Traversal Aspect Traversal Advice Aspect AspectJ Aspect Class Everything reduced to classes and AspectJ aspects

Kinds of Aspects Class Dictionary Aspect –Imports: nothing (is a sink) –Exports: class graph nodes and edges –Expects: nothing (is a sink) –Provides: parser, numerous traversal advice (print, copy, display, check, equal) Traversal Aspect –Imports: class graph nodes and edges –Exports: dynamic join points during traversal –Expects: traversal advice –Provides: (adaptive) methods Import and export Join points Dynamic/lexical Provide and expect Something executable

Kinds of Aspects Traversal Advice Aspect –Imports: object graph slice nodes and edges –Exports: dynamic join points during visitor methods –Expects: methods –Provides: visitor methods (advice) AspectJ Aspect –Imports: class graph nodes, dynamic join points –Exports: dynamic join points during advice –Expects: abstract methods and pointcuts –Provides: advice, introductions Import and export Join points Dynamic/lexical Provide and expect Something executable

ClassDictionary Aspect aspect FileSys [ClassDictionary] { FileSystem = CompoundFile EOF. File : SimpleFile | CompoundFile common Ident. SimpleFile = "simple". CompoundFile = "compound" FileList [ CompoundFile]. FileList ~ "(" { File } ")". } Join point examples EBNF

Traversal Aspect aspect FileSystemTraversals [Traversal] { declare strategy: eachFile: "intersect(from CompoundFile to File, down)"; declare traversal: void listAll() : eachFile(FileLister); declare strategy: down: "from * bypassing -> *,parent,* to *"; declare strategy: up: "from * bypassing -> *,contents,* to *"; } Happens to be AspectJ code

Need for Glue The class dictionary aspect and traversal aspect. Use name mapping: –CompoundFile, File, parent, content Need to check whether there is a path from CompoundFile to File in the class graph that is exported from the class dictionary aspect.

Glue Aspect aspect FileSystemMethods [Cd_Traversal] { default name map; // FileSys.CompoundFile = FileSystemTraversals.CompoundFile // etc. }

AspectJ Aspect aspect FileSystemMethods [AspectJ] { File CompoundFile.getFile(Ident name) { for (Iterator it = contents.iterator(); it.hasNext();) { File file = (File) it.next(); if (file.name.equals(name)) return file; } return null; }

Traversal Advice Aspect aspect FileLister [TraversalAdvice] { Stack path = new Stack(); void before(File file) { path.push(file.name);} void after(File file) { System.out.print("."); Iterator it = path.iterator(); it.next(); while (it.hasNext()) System.out.print("/" + it.next()); System.out.println(); path.pop();} } Happens to be a Java class

AC Aspect aspect BackLink [AC] { participant Source { expected Vector targets; aspectual RV associate(ModifyM e){{ RV rv= e.invoke(); e.t.back = this; return rv; }} } participant Target { Source back; } participant ModifyM { expected Target t; }

AC Aspect aspect cachedbase [AC] { attach backlink, caching, adapt { Item += Target, adapt.Item { … } Container += Source { around void addItem( …, Item t, …) do associate; … }

Ordinary Java Class class Main { public static void main(String[] args) { FileSystem fs = FileSystem.parse(new File(args[0])); Commands script = Commands.parse(new File(args[1])); script.interpret(fs.root); System.out.println(" Status of File System "); fs.root.listAll(); }

Law of Demeter (Join Point Form) JPT(ID) = [ ID] List(ID) List(JPT) [ ID]. List(S) ~ {S}.

JPT(ID) = [ ID] List(ID) List(JPT) [ ID]. List(S) ~ {S}. J r1.foo1() a1.bar() t2.foo2() r3.foo2() E target t2 args {a1,a2} target t2 ret r1 target null ret r3

Generic Law of Demeter (Join Point Form) Definition 1: The LoD_JPF requires that for each join point J, target(J) is a potential preferred supplier of J. Definition 2: The set of potential preferred suppliers to a join point J, child to the enclosing join point E, is the union of the objects in the following sets:

Argument rule: the args of the enclosing join point E, including the target Associated rule: the associated values of E: the ret values of the children of E before J whose target is the target of E or whose target is null. Generic Law of Demeter (Join Point Form)

aspect LoD extends Violation { pointcut LoD_JPF(): //LoD definition ArgumentRule() || AssociatedRule(); pointcut ArgumentRule(): if(thisEnclosingJoinPoint.getArgs().contains(thisJoinPoint.getTarget()); pointcut AssociatedRule(): if(thisEnclosingJoinPoint.hasSelfishChild(thisJoinPoint.getTarget())); }

Pseudo Aspect LoD is a ``pseudo'' aspect because it cannot run in the current implementation of AspectJ, which doesn't allow declare warning to be defined on any pointcut with an if expression.

Join Point Form The pointcuts ArgumentRule and AssociatedRule select the ``good'' join points. ArgumentRule selects those join points whose target is one of the arguments of the enclosing join point;

Join Point Form AssociatedRule selects those join points whose target is in the set of locally returned ID's, and the ID's created in the siblings of the current node.

LoD for Fred (D. Orleans) The set of potential preferred suppliers to a message-send expression M in the body of a branch B is the union of the objects in the following sets: the argument list A of the decision point E that caused the invocation of B; the associated values of E, that is, –the results of message-send expressions M' in the body of B before M whose argument lists A' intersect with A; –instances that were created in the control flow of the body of B before M. Fred (AOSD 02): simplest AOP language: decision points, branches

Map Dynamic Object Form (DOF) to LoD_JPF We use LoD_JPF pointcut to check DOF: –Dynamic join point model is mapped to JPT. Object is mapped to ID. Method invocations are mapped to JPF join points. The enclosing join point is the parent in the control flow.

Map Lexical Class Form (LCF) to LoD_JPF We use LoD_JPF to check LCF as follows. –Lexical join point model is mapped to JPT. Lexical join points are nodes in the abstract syntax tree –Class is mapped to ID. –Join points are signatures of call sites. The enclosing join point is the signature of the method in which the call site resides. To run the aspect, a suitable ordering has to be given to the elements of children: all constructor calls, followed by local method calls, followed by the other join points.

AspectJ code In AOSD 2003 paper with David Lorenz and Pengcheng Wu

package lawOfDemeter; public abstract class Any { public pointcut scope(): !within(lawOfDemeter..*) && !cflow(withincode(* lawOfDemeter..*(..))); public pointcut StaticInitialization(): scope() && staticinitialization(*); public pointcut MethodCallSite(): scope() && call(* *(..)); public pointcut ConstructorCall(): scope() && call(*.new (..)); public pointcut MethodExecution(): scope() && execution(* *(..)); public pointcut ConstructorExecution(): scope() && execution(*.new (..)); public pointcut Execution(): ConstructorExecution() || MethodExecution(); public pointcut MethodCall(Object thiz, Object target): MethodCallSite() && this(thiz) && target(target);

public pointcut SelfCall(Object thiz, Object target): MethodCall(thiz, target) && if(thiz == target); public pointcut StaticCall(): scope() && call(static * *(..)); public pointcut Set(Object value): scope() && set(* *.*) && args(value); public pointcut Initialization(): scope() && initialization(*.new(..)); } Class Any continued

package lawOfDemeter.objectform; import java.util.*; abstract class ObjectSupplier { protected boolean containsValue(Object supplier){ return targets.containsValue(supplier); } protected void add(Object key,Object value){ targets.put(key,value); } protected void addValue(Object supplier) { add(supplier,supplier); } protected void addAll(Object[] suppliers) { for(int i=0; i< suppliers.length; i++) addValue(suppliers[i]); } private IdentityHashMap targets = new IdentityHashMap(); }

package lawOfDemeter.objectform; public aspect Pertarget extends ObjectSupplier pertarget(Any.Initialization()) { before(Object value): Any.Set(value) { add(fieldIdentity(thisJoinPointStaticPart), value); } public boolean contains(Object target) { return super.containsValue(target) || Percflow.aspectOf().containsValue(target); } private String fieldIdentity(JoinPoint.StaticPart sp) { … } private static HashMap fieldNames = new HashMap(); }

package lawOfDemeter.objectform; aspect Check { private pointcut IgnoreCalls(): call(* java..*.*(..)); private pointcut IgnoreTargets(): get(static * java..*.*); after() returning(Object o):IgnoreTargets() { ignoredTargets.put(o,o); } after(Object thiz,Object target): Any.MethodCall(thiz, target) && !IgnoreCalls() { if (!ignoredTargets.containsKey(target) && !Pertarget.aspectOf(thiz).contains(target)) System.out.println( " !! LoD Object Violation !! " + thisJoinPointStaticPart/*[*/ + at(thisJoinPointStaticPart)/*]*/); } private IdentityHashMap ignoredTargets = new IdentityHashMap();}

package lawOfDemeter.objectform; aspect Percflow extends ObjectSupplier percflow(Any.Execution() || Any.Initialization()){ before(): Any.Execution() { addValue(thisJoinPoint.getThis()); addAll(thisJoinPoint.getArgs()); } after() returning (Object result): Any.SelfCall(Object,Object) || Any.StaticCall() || Any.ConstructorCall() { addValue(result); }

AOSD