SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Introducción a AspectJ Mauricio Quezada 07/01/11
Lo que queremos publicImportantcomplexMethod() {// applicationlogiconly returnanImportantResult;   }
Como es en realidad… publicImportantcomplexMethod() {	LOG.log(“Enteringthemethod..”); // complexlogic... mutex.lock(); // more complexlogic... cipher.encrypt(message); // ... Connection con = getConnection(); // ... returnanImportantResult;   }
Aspectos Modularizancross-cuttingconcerns
Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso …
Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso … before(): call(complexMethod(..))     { 	  LOG.log(“Callingtehmethod”);   }
AspectJ Lenguaje orientado a aspectos para Java Define su propio Join Point Model: Joinpoints + pointcuts + advices = aspect
¿Qué es el Join Point Model? Es el modelo que define cuáles son los: JoinPoints: Puntos de ejecución Ej. Llamada de un método, lanzamiento de una excepción Pointcut: Predicados que “atrapan” a los joinpoints Ej. Llamar al método foo(), lanzar una excepción de tipo Exception Advice: Acción a realizar dado un pointcut
En AspectJ pointcutmove(): call(publicvoidFigureElement.setXY(int,int)); before(): move() { System.out.println(“abouttomove”); } after(): move() {  System.out.println(“moved”); }
Wildcards *Account= UserAccount, AdminAccount, ... java.*.Date = java.util.Date, java.sql.Date, ... javax..*Model+ = TableModel + subclasses+ TreeModel + subclasses + ...
Pointcuts call(publicvoidAccount.*(int)); call(* *.*(int)) ||call(* *.*(double)); execution(public !final * *.*(..))  &&within(Dao+);
Pointcuts pointcutcreditOp(Accountacc, floatamt) :call (voidAccount.credit(float)) && target (acc) && args (amt); pointcut creditOp2(Accountacc, floatamt) : execution (voidAccount.credit(float)) && this(acc) 	&& args (amt);
Advices before(): call(* Account.*(..)) { ... } after(): call(...) { ... } Objectaround(): move() { // ... Objectret = proceed(); // ... returnret; }
Sí capitán, estamos listos! Ejemplos
Log abstractaspect Log { abstractpointcutmyClass(); pointcutmyConstr(): myClass() && execution(new(..)); pointcutmyMethod(): myClass() && execution(* *(..));
Log (2) after() throwing (Error e): myMethod() { LOG.getInstance().write(e); } before(): myConstr() { LOG.getInstance().write		(“Creatingobject”); } }
Log (3) publicaspectLogMyClassesextends Log { pointcutmyClass(): within( Account ) || within( Dao+ ) || within( Controller ); }
TimerLog publicabstractaspectTimerLog { abstractpointcutmyMethod(); before(): myMethod () { Timer.start(); System.out.println( 		“Timerstarted at “ + t.startTime); 	} }
Transparent RMI public interface Receiver extendsRemote { publicvoidreceive(Stringname, Object[] params) 	throwsRemoteException; } abstractaspectTransparentRMI { abstractpointcutmyInterceptedClass(); pointcutclientCall(Object[] arg): myInterceptedClass()  		&& execution(void *.*(..))  		&& args(arg);
Transparent RMI (2) voidaround(Object[] arg): clientCall(arg) { 	Receiver r = null; 	r = (Receiver) Naming.lookup(“rmi://...”); r.receive( thisJoinPoint.getSignature().getName(), arg);  } }
Access Control aspectIdentificationperthis(this(Client)) { publicSubjectsubject = null; } aspectAuthenticationpercflow(serviceRequest()) { privateSubjectsubject; pointcutserviceRequest(): call(* ServerInterface+.service(..));
Access Control (2) pointcutauthenticationCall(Objectcaller): this(caller) && serviceRequest() && if(Identification.hasAspect(caller)); publicSubjectgetSubject() { returnsubject; 	}
Access Control (3) before(Objectcaller): authenticationCall(caller) { Identification id = 				  		Identification.aspectOf(caller); if(id.subject == null) { // askforlogin subject = id.subject; } else { throwanException; 	} 	} }
Access Control (4) aspectAuthorization { pointcutcheckedMethods(): within(Server) &&execution(* service(..)); Objectaround(): checkedMethods() { Authenticationauth = Authen.aspectOf(); Subjectsubject = auth.getSubject(); if(checkForPermission) returnproceed();} }
Inter-Typedeclarations declare parents: banking.entities* implementsIdentifiable; declare warning: : get(public !final *.*) || set(public *.*) : “Should use a getteror setter method”;
Cache publicabstractaspect Cache {Map _cache = new HashMap();abstractpointcutcacheMe(Object o);Objectaround(Object o): cacheMe(o) {ObjectinCache = _cache.get(o);if(inCache == null) {inCache = proceed(o);		_cache.put(o, inCache); 	}returninCache;} }
Pero yo no programo en Java…
Pero yo no programo en Java… <script type=“text/javascript”> varpointcut = AspectScript.Pointcuts.call(foo); varadvice = function() {  alert("Callingfoo");  	}; AspectScript.before(pointcut, advice); </script>
Pero yo no programo en Java… require ‘aquarium’ classAccount includeAquarium::DSL before :calls_to=> [:credit, :debit] br />		do |join_point, object, *args| object.balance= read_from_database… end
Otras implementaciones de aspectos AspectC / AspectC++ AspectScript* (Javascript) Aquarium (Ruby) MetaclassTalk (Smalltalk) Spring AOP JBoss AOP etc * hecho en Chile
Conclusiones Los aspectos permiten modularizarcross-cuttingconcerns AspectJ es un lenguaje bastante expresivo, pero limitado Muy útiles en ambientes de desarrollo
Referencias AspectJ Project http://www.eclipse.org/aspectj/ AJDT (Eclipse plugin) http://www.eclipse.org/ajdt/ Slides de CC71P – Objetos y Aspectos http://pleiad.dcc.uchile.cl/teaching/cc71p Howaspectorientedprogramming can helptobuildsecure software http://people.cs.kuleuven.be/~bart.dedecker/pubs/aspects.pdf AspectScripthttp://www.pleiad.cl/aspectscript/ Mis tareas de CC71P :-P

Weitere ähnliche Inhalte

Was ist angesagt?

Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
Jussi Pohjolainen
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
Kim Hunmin
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
Multi client
Multi clientMulti client
Multi client
ganteng8
 

Was ist angesagt? (20)

Computer networkppt4577
Computer networkppt4577Computer networkppt4577
Computer networkppt4577
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...
 
02 - Basics of Qt
02 - Basics of Qt02 - Basics of Qt
02 - Basics of Qt
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
 
Writing more complex models (continued)
Writing more complex models (continued)Writing more complex models (continued)
Writing more complex models (continued)
 
Play image
Play imagePlay image
Play image
 
14 thread
14 thread14 thread
14 thread
 
Multi client
Multi clientMulti client
Multi client
 
Heap overflows for humans – 101
Heap overflows for humans – 101Heap overflows for humans – 101
Heap overflows for humans – 101
 
Коварный code type ITGM #9
Коварный code type ITGM #9Коварный code type ITGM #9
Коварный code type ITGM #9
 

Ähnlich wie Introduccion a AspectJ

Java remote method invocation
Java remote method invocationJava remote method invocation
Java remote method invocation
Van Dawn
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
NETFest
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
Transaction Management Tool
Transaction Management ToolTransaction Management Tool
Transaction Management Tool
Peeyush Ranjan
 

Ähnlich wie Introduccion a AspectJ (20)

Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Introdução à programação orientada para aspectos
Introdução à programação orientada para aspectosIntrodução à programação orientada para aspectos
Introdução à programação orientada para aspectos
 
Step-by-step Development of an Application for the Java Card Connected Platform
Step-by-step Development of an Application for the Java Card Connected PlatformStep-by-step Development of an Application for the Java Card Connected Platform
Step-by-step Development of an Application for the Java Card Connected Platform
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
Java remote method invocation
Java remote method invocationJava remote method invocation
Java remote method invocation
 
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Job Managment Portlet
Job Managment PortletJob Managment Portlet
Job Managment Portlet
 
Transaction Management Tool
Transaction Management ToolTransaction Management Tool
Transaction Management Tool
 
Java RMI
Java RMIJava RMI
Java RMI
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 
Informatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptInformatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.ppt
 

Mehr von Mauricio Quezada (6)

Línea de tiempo Movimiento Estudiantil 2011
Línea de tiempo Movimiento Estudiantil 2011Línea de tiempo Movimiento Estudiantil 2011
Línea de tiempo Movimiento Estudiantil 2011
 
Aspectos y seguridad
Aspectos y seguridadAspectos y seguridad
Aspectos y seguridad
 
Proofs of Partial Knowledge and Simplified Design of Witness Hiding Protocols
Proofs of Partial Knowledge and Simplified Design of Witness Hiding ProtocolsProofs of Partial Knowledge and Simplified Design of Witness Hiding Protocols
Proofs of Partial Knowledge and Simplified Design of Witness Hiding Protocols
 
Monitorizando aplicaciones con AspectJ
Monitorizando aplicaciones con AspectJMonitorizando aplicaciones con AspectJ
Monitorizando aplicaciones con AspectJ
 
Criptografía y Teoría de Juegos
Criptografía y Teoría de JuegosCriptografía y Teoría de Juegos
Criptografía y Teoría de Juegos
 
Cómo compartir un Secreto
Cómo compartir un SecretoCómo compartir un Secreto
Cómo compartir un Secreto
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Introduccion a AspectJ

  • 1. Introducción a AspectJ Mauricio Quezada 07/01/11
  • 2. Lo que queremos publicImportantcomplexMethod() {// applicationlogiconly returnanImportantResult; }
  • 3. Como es en realidad… publicImportantcomplexMethod() { LOG.log(“Enteringthemethod..”); // complexlogic... mutex.lock(); // more complexlogic... cipher.encrypt(message); // ... Connection con = getConnection(); // ... returnanImportantResult; }
  • 5. Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso …
  • 6. Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso … before(): call(complexMethod(..)) { LOG.log(“Callingtehmethod”); }
  • 7. AspectJ Lenguaje orientado a aspectos para Java Define su propio Join Point Model: Joinpoints + pointcuts + advices = aspect
  • 8. ¿Qué es el Join Point Model? Es el modelo que define cuáles son los: JoinPoints: Puntos de ejecución Ej. Llamada de un método, lanzamiento de una excepción Pointcut: Predicados que “atrapan” a los joinpoints Ej. Llamar al método foo(), lanzar una excepción de tipo Exception Advice: Acción a realizar dado un pointcut
  • 9. En AspectJ pointcutmove(): call(publicvoidFigureElement.setXY(int,int)); before(): move() { System.out.println(“abouttomove”); } after(): move() { System.out.println(“moved”); }
  • 10. Wildcards *Account= UserAccount, AdminAccount, ... java.*.Date = java.util.Date, java.sql.Date, ... javax..*Model+ = TableModel + subclasses+ TreeModel + subclasses + ...
  • 11. Pointcuts call(publicvoidAccount.*(int)); call(* *.*(int)) ||call(* *.*(double)); execution(public !final * *.*(..)) &&within(Dao+);
  • 12. Pointcuts pointcutcreditOp(Accountacc, floatamt) :call (voidAccount.credit(float)) && target (acc) && args (amt); pointcut creditOp2(Accountacc, floatamt) : execution (voidAccount.credit(float)) && this(acc) && args (amt);
  • 13. Advices before(): call(* Account.*(..)) { ... } after(): call(...) { ... } Objectaround(): move() { // ... Objectret = proceed(); // ... returnret; }
  • 14. Sí capitán, estamos listos! Ejemplos
  • 15. Log abstractaspect Log { abstractpointcutmyClass(); pointcutmyConstr(): myClass() && execution(new(..)); pointcutmyMethod(): myClass() && execution(* *(..));
  • 16. Log (2) after() throwing (Error e): myMethod() { LOG.getInstance().write(e); } before(): myConstr() { LOG.getInstance().write (“Creatingobject”); } }
  • 17. Log (3) publicaspectLogMyClassesextends Log { pointcutmyClass(): within( Account ) || within( Dao+ ) || within( Controller ); }
  • 18. TimerLog publicabstractaspectTimerLog { abstractpointcutmyMethod(); before(): myMethod () { Timer.start(); System.out.println( “Timerstarted at “ + t.startTime); } }
  • 19. Transparent RMI public interface Receiver extendsRemote { publicvoidreceive(Stringname, Object[] params) throwsRemoteException; } abstractaspectTransparentRMI { abstractpointcutmyInterceptedClass(); pointcutclientCall(Object[] arg): myInterceptedClass() && execution(void *.*(..)) && args(arg);
  • 20. Transparent RMI (2) voidaround(Object[] arg): clientCall(arg) { Receiver r = null; r = (Receiver) Naming.lookup(“rmi://...”); r.receive( thisJoinPoint.getSignature().getName(), arg); } }
  • 21. Access Control aspectIdentificationperthis(this(Client)) { publicSubjectsubject = null; } aspectAuthenticationpercflow(serviceRequest()) { privateSubjectsubject; pointcutserviceRequest(): call(* ServerInterface+.service(..));
  • 22. Access Control (2) pointcutauthenticationCall(Objectcaller): this(caller) && serviceRequest() && if(Identification.hasAspect(caller)); publicSubjectgetSubject() { returnsubject; }
  • 23. Access Control (3) before(Objectcaller): authenticationCall(caller) { Identification id = Identification.aspectOf(caller); if(id.subject == null) { // askforlogin subject = id.subject; } else { throwanException; } } }
  • 24. Access Control (4) aspectAuthorization { pointcutcheckedMethods(): within(Server) &&execution(* service(..)); Objectaround(): checkedMethods() { Authenticationauth = Authen.aspectOf(); Subjectsubject = auth.getSubject(); if(checkForPermission) returnproceed();} }
  • 25. Inter-Typedeclarations declare parents: banking.entities* implementsIdentifiable; declare warning: : get(public !final *.*) || set(public *.*) : “Should use a getteror setter method”;
  • 26. Cache publicabstractaspect Cache {Map _cache = new HashMap();abstractpointcutcacheMe(Object o);Objectaround(Object o): cacheMe(o) {ObjectinCache = _cache.get(o);if(inCache == null) {inCache = proceed(o); _cache.put(o, inCache); }returninCache;} }
  • 27. Pero yo no programo en Java…
  • 28. Pero yo no programo en Java… <script type=“text/javascript”> varpointcut = AspectScript.Pointcuts.call(foo); varadvice = function() { alert("Callingfoo"); }; AspectScript.before(pointcut, advice); </script>
  • 29. Pero yo no programo en Java… require ‘aquarium’ classAccount includeAquarium::DSL before :calls_to=> [:credit, :debit] br /> do |join_point, object, *args| object.balance= read_from_database… end
  • 30. Otras implementaciones de aspectos AspectC / AspectC++ AspectScript* (Javascript) Aquarium (Ruby) MetaclassTalk (Smalltalk) Spring AOP JBoss AOP etc * hecho en Chile
  • 31. Conclusiones Los aspectos permiten modularizarcross-cuttingconcerns AspectJ es un lenguaje bastante expresivo, pero limitado Muy útiles en ambientes de desarrollo
  • 32. Referencias AspectJ Project http://www.eclipse.org/aspectj/ AJDT (Eclipse plugin) http://www.eclipse.org/ajdt/ Slides de CC71P – Objetos y Aspectos http://pleiad.dcc.uchile.cl/teaching/cc71p Howaspectorientedprogramming can helptobuildsecure software http://people.cs.kuleuven.be/~bart.dedecker/pubs/aspects.pdf AspectScripthttp://www.pleiad.cl/aspectscript/ Mis tareas de CC71P :-P