introduccion a aspectj

32
Introducción a AspectJ Mauricio Quezada 07/01/11

Upload: mauricio-quezada

Post on 26-May-2015

1.538 views

Category:

Technology


0 download

DESCRIPTION

Algunos ejemplos utilizando el lenguaje de aspectos para java AspectJ An introduction to AspectJ Some examples using the aspect's language AspectJ

TRANSCRIPT

Page 1: Introduccion a AspectJ

Introducción a AspectJ

Mauricio Quezada07/01/11

Page 2: Introduccion a AspectJ

Lo que queremos

public Important complexMethod() {// application logic onlyreturn anImportantResult;

}

Page 3: Introduccion a AspectJ

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;

}

Page 4: Introduccion a AspectJ

Aspectos

• Modularizan cross-cutting concerns

Page 5: Introduccion a AspectJ

Aspectos

• Modularizan cross-cutting concerns– Logging, seguridad, sincronización, control de acceso …

Page 6: Introduccion a AspectJ

Aspectos

• Modularizan cross-cutting concerns– Logging, seguridad, sincronización, control de acceso …

before(): call(complexMethod(..)) {

LOG.log(“Calling teh method”);

}

Page 7: Introduccion a AspectJ

AspectJ

• Lenguaje orientado a aspectos para Java

• Define su propio Join Point Model:

Join points + pointcuts + advices = aspect

Page 8: Introduccion a AspectJ

¿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

Page 9: Introduccion a AspectJ

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”);

}

Page 10: Introduccion a AspectJ

Wildcards

*Account = UserAccount, AdminAccount, ...

java.*.Date = java.util.Date, java.sql.Date, ...

javax..*Model+ = TableModel + subclasses + TreeModel + subclasses + ...

Page 11: Introduccion a AspectJ

Pointcuts

call(public void Account.*(int));

call(* *.*(int)) || call(* *.*(double));

execution(public !final * *.*(..)) && within(Dao+);

Page 12: Introduccion a AspectJ

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);

Page 13: Introduccion a AspectJ

Advices

before(): call(* Account.*(..)) { ... }

after(): call(...) { ... }

Object around(): move() {// ...Object ret = proceed();// ...return ret;

}

Page 14: Introduccion a AspectJ

Sí capitán, estamos listos!

Ejemplos

Page 15: Introduccion a AspectJ

Log

abstract aspect Log {abstract pointcut myClass();

pointcut myConstr():myClass() && execution(new(..));

pointcut myMethod():myClass() && execution(* *(..));

Page 16: Introduccion a AspectJ

Log (2)

after() throwing (Error e):myMethod() {

LOG.getInstance().write(e);}

before(): myConstr() {LOG.getInstance().write

(“Creating object”);}

}

Page 17: Introduccion a AspectJ

Log (3)

public aspect LogMyClasses extends Log {

pointcut myClass():within( Account ) ||within( Dao+ ) ||within( Controller );

}

Page 18: Introduccion a AspectJ

TimerLog

public abstract aspect TimerLog {abstract pointcut myMethod();

before(): myMethod () {

Timer.start();System.out.println(“Timer started at “ + t.startTime);

}

}

Page 19: Introduccion a AspectJ

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);

Page 20: Introduccion a AspectJ

Transparent RMI (2)

void around(Object[] arg): clientCall(arg) {Receiver r = null;

r = (Receiver) Naming.lookup(“rmi://...”);r.receive(

thisJoinPoint.getSignature().getName(),arg);

}}

Page 21: Introduccion a AspectJ

Access Control

aspect Identification perthis(this(Client)) {public Subject subject = null;

}

aspect Authentication percflow(serviceRequest()) {private Subject subject;

pointcut serviceRequest():call(* ServerInterface+.service(..));

Page 22: Introduccion a AspectJ

Access Control (2)

pointcut authenticationCall(Object caller):this(caller) &&serviceRequest() &&if(Identification.hasAspect(caller));

public Subject getSubject() {return subject;

}

Page 23: Introduccion a AspectJ

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;

}}

}

Page 24: Introduccion a AspectJ

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();}

}

Page 25: Introduccion a AspectJ

Inter-Type declarations

declare parents: banking.entities* implements Identifiable;

declare warning:: get(public !final *.*) || set(public *.*): “Should use a getter or setter method”;

Page 26: Introduccion a AspectJ

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;

}}

Page 27: Introduccion a AspectJ

Pero yo no programo en Java…

Page 28: Introduccion a AspectJ

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>

Page 29: Introduccion a AspectJ

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

Page 30: Introduccion a AspectJ

Otras implementaciones de aspectos

• AspectC / AspectC++• AspectScript* (Javascript)• Aquarium (Ruby)• MetaclassTalk (Smalltalk)• Spring AOP• JBoss AOP• etc

* hecho en Chile

Page 31: Introduccion a AspectJ

Conclusiones

• Los aspectos permiten modularizar cross-cutting concerns

• AspectJ es un lenguaje bastante expresivo, pero limitado

• Muy útiles en ambientes de desarrollo

Page 32: Introduccion a AspectJ

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