Upload
mauricio-quezada
View
1.543
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Algunos ejemplos utilizando el lenguaje de aspectos para java AspectJ An introduction to AspectJ Some examples using the aspect's language AspectJ
Citation preview
Introducción a AspectJ
Mauricio Quezada07/01/11
Lo que queremos
public Important complexMethod() {// application logic onlyreturn anImportantResult;
}
Como es en realidad…
public Important complexMethod() {LOG.log(“Entering the method..”);// complex logic...mutex.lock();// more complex logic...cipher.encrypt(message);
// ...Connection con = getConnection();// ...return anImportantResult;
}
Aspectos
• Modularizan cross-cutting concerns
Aspectos
• Modularizan cross-cutting concerns– Logging, seguridad, sincronización, control de acceso …
Aspectos
• Modularizan cross-cutting concerns– Logging, seguridad, sincronización, control de acceso …
before(): call(complexMethod(..)) {
LOG.log(“Calling teh method”);
}
AspectJ
• Lenguaje orientado a aspectos para Java
• Define su propio Join Point Model:
Join points + pointcuts + advices = aspect
¿Qué es el Join Point Model?
• Es el modelo que define cuáles son los:
– Join Points: Puntos de ejecución• Ej. Llamada de un método, lanzamiento de una excepción
– Pointcut: Predicados que “atrapan” a los join points• Ej. Llamar al método foo(), lanzar una excepción de tipo Exception
– Advice: Acción a realizar dado un pointcut
En AspectJ
pointcut move(): call(public void FigureElement.setXY(int,int));
before(): move() {System.out.println(“about to move”);
}
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(public void Account.*(int));
call(* *.*(int)) || call(* *.*(double));
execution(public !final * *.*(..)) && within(Dao+);
Pointcuts
pointcut creditOp(Account acc, float amt) :call (void Account.credit(float))&& target (acc)&& args (amt);
pointcut creditOp2(Account acc, float amt) :execution (void Account.credit(float))&& this(acc)&& args (amt);
Advices
before(): call(* Account.*(..)) { ... }
after(): call(...) { ... }
Object around(): move() {// ...Object ret = proceed();// ...return ret;
}
Sí capitán, estamos listos!
Ejemplos
Log
abstract aspect Log {abstract pointcut myClass();
pointcut myConstr():myClass() && execution(new(..));
pointcut myMethod():myClass() && execution(* *(..));
Log (2)
after() throwing (Error e):myMethod() {
LOG.getInstance().write(e);}
before(): myConstr() {LOG.getInstance().write
(“Creating object”);}
}
Log (3)
public aspect LogMyClasses extends Log {
pointcut myClass():within( Account ) ||within( Dao+ ) ||within( Controller );
}
TimerLog
public abstract aspect TimerLog {abstract pointcut myMethod();
before(): myMethod () {
Timer.start();System.out.println(“Timer started at “ + t.startTime);
}
}
Transparent RMI
public interface Receiver extends Remote {public void receive(String name, Object[] params) throws RemoteException;
}
abstract aspect TransparentRMI {abstract pointcut myInterceptedClass();
pointcut clientCall(Object[] arg):myInterceptedClass() && execution(void *.*(..)) && args(arg);
Transparent RMI (2)
void around(Object[] arg): clientCall(arg) {Receiver r = null;
r = (Receiver) Naming.lookup(“rmi://...”);r.receive(
thisJoinPoint.getSignature().getName(),arg);
}}
Access Control
aspect Identification perthis(this(Client)) {public Subject subject = null;
}
aspect Authentication percflow(serviceRequest()) {private Subject subject;
pointcut serviceRequest():call(* ServerInterface+.service(..));
Access Control (2)
pointcut authenticationCall(Object caller):this(caller) &&serviceRequest() &&if(Identification.hasAspect(caller));
public Subject getSubject() {return subject;
}
Access Control (3)
before(Object caller): authenticationCall(caller) {
Identification id = Identification.aspectOf(caller);
if(id.subject == null) {// ask for loginsubject = id.subject;
} else {throw anException;
}}
}
Access Control (4)
aspect Authorization {pointcut checkedMethods():
within(Server) &&execution(* service(..));
Object around(): checkedMethods() {Authentication auth =
Authen.aspectOf();Subject subject = auth.getSubject();if(checkForPermission)
return proceed();}
}
Inter-Type declarations
declare parents: banking.entities* implements Identifiable;
declare warning:: get(public !final *.*) || set(public *.*): “Should use a getter or setter method”;
Cachepublic abstract aspect Cache {Map _cache = new HashMap();
abstract pointcut cacheMe(Object o);
Object around(Object o): cacheMe(o) {Object inCache = _cache.get(o);
if(inCache == null) {inCache = proceed(o);_cache.put(o, inCache);
}return inCache;
}}
Pero yo no programo en Java…
Pero yo no programo en Java…
<script type=“text/javascript”>
var pointcut = AspectScript.Pointcuts.call(foo);
var advice = function() { alert("Calling foo");
};
AspectScript.before(pointcut, advice);
</script>
Pero yo no programo en Java…
require ‘aquarium’class Account include Aquarium::DSL before :calls_to => [:credit, :debit] \ 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 modularizar cross-cutting concerns
• 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• How aspect oriented programming can help to build secure
software http://people.cs.kuleuven.be/~bart.dedecker/pubs/aspects.pdf
• AspectScripthttp://www.pleiad.cl/aspectscript/
• Mis tareas de CC71P :-P