Introducción a AspectJMauricio Quezada07/01/11
Lo que queremospublicImportantcomplexMethod() {// applicationlogiconlyreturnanImportantResult;  }
Como es en realidad…publicImportantcomplexMethod() {	LOG.log(“Enteringthemethod..”);// complexlogic...mutex.lock();// more complexlogic...cipher.encrypt(message);// ...Connection con = getConnection();// ...returnanImportantResult;  }
AspectosModularizancross-cuttingconcerns
AspectosModularizancross-cuttingconcernsLogging, seguridad, sincronización, control de acceso …
AspectosModularizancross-cuttingconcernsLogging, seguridad, sincronización, control de acceso …before(): call(complexMethod(..))     {	  LOG.log(“Callingtehmethod”);  }
AspectJLenguaje orientado a aspectos para JavaDefine 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ónEj. Llamada de un método, lanzamiento de una excepciónPointcut: Predicados que “atrapan” a los joinpointsEj. Llamar al método foo(), lanzar una excepción de tipo ExceptionAdvice: Acción a realizar dado un pointcut
En AspectJpointcutmove(): 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 + ...
Pointcutscall(publicvoidAccount.*(int));call(* *.*(int)) ||call(* *.*(double));execution(public !final * *.*(..)) &&within(Dao+);
PointcutspointcutcreditOp(Accountacc, floatamt) :call (voidAccount.credit(float))&& target (acc)&& args (amt);pointcut creditOp2(Accountacc, floatamt) :execution (voidAccount.credit(float))&& this(acc)	&& args (amt);
Advicesbefore(): call(* Account.*(..)) { ... }after(): call(...) { ... }Objectaround(): move() {// ...Objectret = proceed();// ...returnret;}
Sí capitán, estamos listos!Ejemplos
Logabstractaspect 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 );}
TimerLogpublicabstractaspectTimerLog {abstractpointcutmyMethod();before(): myMethod () {Timer.start();System.out.println(		“Timerstarted at “ + t.startTime);	}}
Transparent RMIpublic 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 ControlaspectIdentificationperthis(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) {// askforloginsubject = 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-Typedeclarationsdeclare parents: banking.entities* implementsIdentifiable;declare warning:: get(public !final *.*) || set(public *.*): “Should use a getteror setter method”;
Cachepublicabstractaspect 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’classAccountincludeAquarium::DSLbefore :calls_to=> [:credit, :debit] \		do |join_point, object, *args|object.balance= read_from_database…end
Otras implementaciones de aspectosAspectC / AspectC++AspectScript* (Javascript)Aquarium (Ruby)MetaclassTalk (Smalltalk)Spring AOPJBoss AOPetc* hecho en Chile
ConclusionesLos aspectos permiten modularizarcross-cuttingconcernsAspectJ es un lenguaje bastante expresivo, pero limitadoMuy útiles en ambientes de desarrollo
ReferenciasAspectJ 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/cc71pHowaspectorientedprogramming can helptobuildsecure software http://people.cs.kuleuven.be/~bart.dedecker/pubs/aspects.pdfAspectScripthttp://www.pleiad.cl/aspectscript/Mis tareas de CC71P :-P

Introduccion a AspectJ