SlideShare una empresa de Scribd logo
1 de 56
Architecture technique applicative   Aspects Techniques Framework Java IBM « AspectJ 1.5 » Programmation Orientée Aspect   ( Aspect Oriented Programming ) Ajout transparent de services techniques dans le code métier Outil de développement : Plug-in Elipse AJDT 1.2 / 1.3 « Découpler le code technique du code métier » Publication : juillet 2005 Catégorie : veille technologique Auteur : Jimmy Michel SIMEON Version éditoriale : 2.0.0.0, le 14 mars 2006 avancé simple expert Niveau : Public : Architecte Dévelopeur Manager
Emergence de la programmation orientée Aspect ,[object Object],[object Object]
Historique de la Programmation Orientée Aspect ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Historique du Framework Java « AspectJ »  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Acteurs du marché AOP (bonne pratique AOP des experts en développements) Rod Johnson : Framework  Spring AOP , AOP alliance  auteur du livre «J2EE without EJB»  Conteneurs léger (couplage lâche) vs conteneur lourd (couplage fort),  Bill Burke : Leader  JBoss AOP AOP alliance Jonas Bonér : framework AspectWerkz  BEA Systems AspectWerkz fusionne avec AspectJ !   Aspect Oriented Programming (Frameworks AOP),  Separation Of Concerns (SoC).   Gregor Kiczales XEROX PARC : père de l’AOP et du framework AspectJ AspecJ appartient à la communauté  Eclipse / IBM
Objectifs de AOP (1) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Objectifs de AOP (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Découpler le code technique du code fonctionnel ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Visualisation des catégories d’aspects techniques  dans un programme Identification des Aspects techniques !
Modularité d’une préoccupation transverse ,[object Object],Code technique Code métier AOP Aspect(s) package org.apache.tomcat.session; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.apache.tomcat.catalina.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.tomcat.util.StringManager; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Standard implementation of the <b>Manager</b> interface that provides * no session persistence or distributable capabilities, but does support * an optional, configurable, maximum number of active sessions allowed. * <p> * Lifecycle configuration of this component assumes an XML node * in the following format: * <code> *  &lt;Manager className=&quot;org.apache.tomcat.session.StandardManager&quot; *  checkInterval=&quot;60&quot; maxActiveSessions=&quot;-1&quot; *  maxInactiveInterval=&quot;-1&quot; /> * </code> * where you can adjust the following parameters, with default values * in square brackets: * <ul> * <li><b>checkInterval</b> - The interval (in seconds) between background *  thread checks for expired sessions.  [60] * <li><b>maxActiveSessions</b> - The maximum number of sessions allowed to *  be active at once, or -1 for no limit.  [-1] * <li><b>maxInactiveInterval</b> - The default maximum number of seconds of *  inactivity before which the servlet container is allowed to time out *  a session, or -1 for no limit.  This value should be overridden from *  the default session timeout specified in the web application deployment *  descriptor, if any.  [-1] * </ul> * * @author Craig R. McClanahan * @version $Revision: 1.1.1.1 $ $Date: 2000/05/02 21:28:30 $ */ public final class StandardManager extends ManagerBase implements Lifecycle, Runnable { // ----------------------------------------------------- Instance Variables /** * The interval (in seconds) between checks for expired sessions. */ private int checkInterval = 60; /** * Has this component been configured yet? */ private boolean configured = false; /** * The descriptive information about this implementation. */ private static final String info = &quot;StandardManager/1.0&quot;; /** * The maximum number of active Sessions allowed, or -1 for no limit. */ protected int maxActiveSessions = -1; /** * The string manager for this package. */ private StringManager sm = StringManager.getManager(&quot;org.apache.tomcat.session&quot;); /** * Has this component been started yet? */ private boolean started = false; /** * The background thread. */ private Thread thread = null; /** * The background thread completion semaphore. */ private boolean threadDone = false; /** * Name to register for the background thread. */ private String threadName = &quot;StandardManager&quot;; // ------------------------------------------------------------- Properties /** * Return the check interval (in seconds) for this Manager. */ public int getCheckInterval() { return (this.checkInterval); } /** * Set the check interval (in seconds) for this Manager. * * @param checkInterval The new check interval */ public void setCheckInterval(int checkInterval) { this.checkInterval = checkInterval; } /** * Return descriptive information about this Manager implementation and * the corresponding version number, in the format * <code>&lt;description&gt;/&lt;version&gt;</code>. */ public String getInfo() { return (this.info); } /** * Return the maximum number of active Sessions allowed, or -1 for * no limit. */ public int getMaxActiveSessions() { return (this.maxActiveSessions); } /** * Set the maximum number of actives Sessions allowed, or -1 for * no limit. * * @param max The new maximum number of sessions */ public void setMaxActiveSessions(int max) { this.maxActiveSessions = max; } // --------------------------------------------------------- Public Methods /** * Construct and return a new session object, based on the default * settings specified by this Manager's properties.  The session * id will be assigned by this method, and available via the getId() * method of the returned session.  If a new session cannot be created * for any reason, return <code>null</code>. * * @exception IllegalStateException if a new session cannot be *  instantiated for any reason */ public Session createSession() { if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) throw new IllegalStateException (sm.getString(&quot;standardManager.createSession.ise&quot;)); return (super.createSession()); } // ------------------------------------------------------ Lifecycle Methods /** * Configure this component, based on the specified configuration * parameters.  This method should be called immediately after the * component instance is created, and before <code>start()</code> * is called. * * @param parameters Configuration parameters for this component *  (<B>FIXME: What object type should this really be?) * * @exception IllegalStateException if this component has already been *  configured and/or started * @exception LifecycleException if this component detects a fatal error *  in the configuration parameters it was given */ public void configure(Node parameters) throws LifecycleException { // Validate and update our current component state if (configured) throw new LifecycleException (sm.getString(&quot;standardManager.alreadyConfigured&quot;)); configured = true; if (parameters == null) return; // Parse and process our configuration parameters if (!(&quot;Manager&quot;.equals(parameters.getNodeName()))) return; NamedNodeMap attributes = parameters.getAttributes(); Node node = null; node = attributes.getNamedItem(&quot;checkInterval&quot;); if (node != null) { try { setCheckInterval(Integer.parseInt(node.getNodeValue())); } catch (Throwable t) { ;  // XXX - Throw exception? } } node = attributes.getNamedItem(&quot;maxActiveSessions&quot;); if (node != null) { try { setMaxActiveSessions(Integer.parseInt(node.getNodeValue())); } catch (Throwable t) { ;  // XXX - Throw exception? } } node = attributes.getNamedItem(&quot;maxInactiveInterval&quot;); if (node != null) { try { setMaxInactiveInterval(Integer.parseInt(node.getNodeValue())); } catch (Throwable t) { ;  // XXX - Throw exception? } } } /** * Prepare for the beginning of active use of the public methods of this * component.  This method should be called after <code>configure()</code>, * and before any of the public methods of the component are utilized. * * @exception IllegalStateException if this component has not yet been *  configured (if required for this component) * @exception IllegalStateException if this component has already been *  started * @exception LifecycleException if this component detects a fatal error *  that prevents this component from being used */ public void start() throws LifecycleException { // Validate and update our current component state if (!configured) throw new LifecycleException (sm.getString(&quot;standardManager.notConfigured&quot;)); if (started) throw new LifecycleException (sm.getString(&quot;standardManager.alreadyStarted&quot;)); started = true; // Start the background reaper thread threadStart(); } /** * Gracefully terminate the active use of the public methods of this * component.  This method should be the last one called on a given * instance of this component. * * @exception IllegalStateException if this component has not been started * @exception IllegalStateException if this component has already *  been stopped * @exception LifecycleException if this component detects a fatal error *  that needs to be reported */ public void stop() throws LifecycleException { // Validate and update our current component state if (!started) throw new LifecycleException (sm.getString(&quot;standardManager.notStarted&quot;)); started = false; // Stop the background reaper thread threadStop(); // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; session.expire(); } } // -------------------------------------------------------- Private Methods /** * Invalidate all sessions that have expired. */ private void processExpires() { long timeNow = System.currentTimeMillis(); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; int maxInactiveInterval = session.getMaxInactiveInterval(); if (maxInactiveInterval < 0) continue; int timeIdle = // Truncate, do not round up (int) ((timeNow - session.getLastAccessedTime()) / 1000L); if (timeIdle >= maxInactiveInterval) session.expire(); } } /** * Sleep for the duration specified by the <code>checkInterval</code> * property. */ private void threadSleep() { try { Thread.sleep(checkInterval * 1000L); } catch (InterruptedException e) { ; } } /** * Start the background thread that will periodically check for * session timeouts. */ private void threadStart() { if (thread != null) return; threadDone = false; thread = new Thread(this, threadName); thread.setDaemon(true); thread.start(); } /** * Stop the background thread that is periodically checking for * session timeouts. */ private void threadStop() { if (thread == null) return; threadDone = true; thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { ; } thread = null; } // ------------------------------------------------------ Background Thread /** * The background thread that checks for session timeouts and shutdown. */ public void run() { // Loop until the termination semaphore is set while (!threadDone) { threadSleep(); processExpires(); } } } StandardManager StandardSessionManager package org.apache.tomcat.session; import java.io.IOException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.tomcat.catalina.*; import org.apache.tomcat.core.Context; import org.apache.tomcat.core.Request; import org.apache.tomcat.core.Response; import org.apache.tomcat.core.SessionManager; import org.apache.tomcat.util.SessionUtil; /** * Specialized implementation of org.apache.tomcat.core.SessionManager * that adapts to the new component-based Manager implementation. * <p> * XXX - At present, use of <code>StandardManager</code> is hard coded, * and lifecycle configuration is not supported. * <p> * <b>IMPLEMENTATION NOTE</b>:  Once we commit to the new Manager/Session * paradigm, I would suggest moving the logic implemented here back into * the core level.  The Tomcat.Next &quot;Manager&quot; interface acts more like a * collection class, and has minimal knowledge of the detailed request * processing semantics of handling sessions. * <p> * XXX - At present, there is no way (via the SessionManager interface) for * a Context to tell the Manager that we create what the default session * timeout for this web application (specified in the deployment descriptor) * should be. * * @author Craig R. McClanahan */ public final class StandardSessionManager implements SessionManager { // ----------------------------------------------------------- Constructors /** * Create a new SessionManager that adapts to the corresponding Manager * implementation. */ public StandardSessionManager() { manager = new StandardManager(); if (manager instanceof Lifecycle) { try { ((Lifecycle) manager).configure(null); ((Lifecycle) manager).start(); } catch (LifecycleException e) { throw new IllegalStateException(&quot;&quot; + e); } } } // ----------------------------------------------------- Instance Variables /** * The Manager implementation we are actually using. */ private Manager manager = null; // --------------------------------------------------------- Public Methods /** * Mark the specified session's last accessed time.  This should be * called for each request by a RequestInterceptor. * * @param session The session to be marked */ public void accessed(Context ctx, Request req, String id) { HttpSession session=findSession(ctx, id); if( session == null) return; if (session instanceof Session) ((Session) session).access(); // cache the HttpSession - avoid another find req.setSession( session ); } // XXX should we throw exception or just return null ?? public HttpSession findSession( Context ctx, String id ) { try { Session session = manager.findSession(id); if(session!=null) return session.getSession(); } catch (IOException e) { } return (null); } public HttpSession createSession(Context ctx) { return  manager.createSession().getSession(); } /** * Remove all sessions because our associated Context is being shut down. * * @param ctx The context that is being shut down */ public void removeSessions(Context ctx) { // XXX XXX a manager may be shared by multiple // contexts, we just want to remove the sessions of ctx! // The manager will still run after that ( i.e. keep database // connection open if (manager instanceof Lifecycle) { try { ((Lifecycle) manager).stop(); } catch (LifecycleException e) { throw new IllegalStateException(&quot;&quot; + e); } } } /** * Used by context to configure the session manager's inactivity timeout. * * The SessionManager may have some default session time out, the * Context on the other hand has it's timeout set by the deployment * descriptor (web.xml). This method lets the Context conforgure the * session manager according to this value. * * @param minutes The session inactivity timeout in minutes. */ public void setSessionTimeOut(int minutes) { if(-1 != minutes) { // The manager works with seconds... manager.setMaxInactiveInterval(minutes * 60); } } } ServerSessionManager package org.apache.tomcat.session; import org.apache.tomcat.util.*; import org.apache.tomcat.core.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.http.*; /** * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] */ public class ServerSessionManager implements SessionManager { private StringManager sm = StringManager.getManager(&quot;org.apache.tomcat.session&quot;); private static ServerSessionManager manager; // = new ServerSessionManager(); protected int inactiveInterval = -1; static { manager = new ServerSessionManager(); } public static ServerSessionManager getManager() { return manager; } private Hashtable sessions = new Hashtable(); private Reaper reaper; private ServerSessionManager() { reaper = Reaper.getReaper(); reaper.setServerSessionManager(this); reaper.start(); } public void accessed( Context ctx, Request req, String id ) { ApplicationSession apS=(ApplicationSession)findSession( ctx, id); if( apS==null) return; ServerSession servS=apS.getServerSession(); servS.accessed(); apS.accessed(); // cache it - no need to compute it again req.setSession( apS ); } public HttpSession createSession(Context ctx) { String sessionId = SessionIdGenerator.generateId(); ServerSession session = new ServerSession(sessionId); sessions.put(sessionId, session); if(-1 != inactiveInterval) { session.setMaxInactiveInterval(inactiveInterval); } return session.getApplicationSession( ctx, true ); } public HttpSession findSession(Context ctx, String id) { ServerSession sSession=(ServerSession)sessions.get(id); if(sSession==null) return null; return sSession.getApplicationSession(ctx, false); } // XXX // sync'd for safty -- no other thread should be getting something // from this while we are reaping. This isn't the most optimal // solution for this, but we'll determine something else later. synchronized void reap() { Enumeration enum = sessions.keys(); while (enum.hasMoreElements()) { Object key = enum.nextElement(); ServerSession session = (ServerSession)sessions.get(key); session.reap(); session.validate(); } } synchronized void removeSession(ServerSession session) { String id = session.getId(); session.invalidate(); sessions.remove(id); } public void removeSessions(Context context) { Enumeration enum = sessions.keys(); while (enum.hasMoreElements()) { Object key = enum.nextElement(); ServerSession session = (ServerSession)sessions.get(key); ApplicationSession appSession = session.getApplicationSession(context, false); if (appSession != null) { appSession.invalidate(); } } } /** * Used by context to configure the session manager's inactivity timeout. * * The SessionManager may have some default session time out, the * Context on the other hand has it's timeout set by the deployment * descriptor (web.xml). This method lets the Context conforgure the * session manager according to this value. * * @param minutes The session inactivity timeout in minutes. */ public void setSessionTimeOut(int minutes) { if(-1 != minutes) { // The manager works with seconds... inactiveInterval = (minutes * 60); } } } SessionInterceptor package org.apache.tomcat.request; import org.apache.tomcat.core.*; import org.apache.tomcat.util.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.http.*; /** * Will process the request and determine the session Id, and set it * in the Request. * It also marks the session as accessed. * * This implementation only handles Cookies sessions, please extend or * add new interceptors for other methods. * */ public class SessionInterceptor extends  BaseInterceptor implements RequestInterceptor { // GS, separates the session id from the jvm route static final char SESSIONID_ROUTE_SEP = '.'; int debug=0; ContextManager cm; public SessionInterceptor() { } public void setDebug( int i ) { System.out.println(&quot;Set debug to &quot; + i); debug=i; } public void setContextManager( ContextManager cm ) { this.cm=cm; } public int requestMap(Request request ) { String sessionId = null; Cookie cookies[]=request.getCookies(); // assert !=null for( int i=0; i<cookies.length; i++ ) { Cookie cookie = cookies[i]; if (cookie.getName().equals(&quot;JSESSIONID&quot;)) { sessionId = cookie.getValue(); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromCookie(true); } } } String sig=&quot;;jsessionid=&quot;; int foundAt=-1; if( debug>0 ) cm.log(&quot; XXX RURI=&quot; + request.getRequestURI()); if ((foundAt=request.getRequestURI().indexOf(sig))!=-1){ sessionId=request.getRequestURI().substring(foundAt+sig.length()); // rewrite URL, do I need to do anything more? request.setRequestURI(request.getRequestURI().substring(0, foundAt)); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromURL(true); } } return 0; } // XXX what is the correct behavior if the session is invalid ? // We may still set it and just return session invalid. /** Validate and fix the session id. If the session is not valid return null. *  It will also clean up the session from load-balancing strings. * @return sessionId, or null if not valid */ private String validateSessionId(Request request, String sessionId){ // GS, We piggyback the JVM id on top of the session cookie // Separate them ... if( debug>0 ) cm.log(&quot; Orig sessionId  &quot; + sessionId ); if (null != sessionId) { int idex = sessionId.lastIndexOf(SESSIONID_ROUTE_SEP); if(idex > 0) { sessionId = sessionId.substring(0, idex); } } if (sessionId != null && sessionId.length()!=0) { // GS, We are in a problem here, we may actually get // multiple Session cookies (one for the root // context and one for the real context... or old session // cookie. We must check for validity in the current context. Context ctx=request.getContext(); SessionManager sM = ctx.getSessionManager();  if(null != sM.findSession(ctx, sessionId)) { sM.accessed(ctx, request, sessionId ); request.setRequestedSessionId(sessionId); if( debug>0 ) cm.log(&quot; Final session id &quot; + sessionId ); return sessionId; } } return null; } public int beforeBody( Request rrequest, Response response ) { String reqSessionId = response.getSessionId(); if( debug>0 ) cm.log(&quot;Before Body &quot; + reqSessionId ); if( reqSessionId==null) return 0; // GS, set the path attribute to the cookie. This way // multiple session cookies can be used, one for each // context. String sessionPath = rrequest.getContext().getPath(); if(sessionPath.length() == 0) { sessionPath = &quot;/&quot;; } // GS, piggyback the jvm route on the session id. if(!sessionPath.equals(&quot;/&quot;)) { String jvmRoute = rrequest.getJvmRoute(); if(null != jvmRoute) { reqSessionId = reqSessionId + SESSIONID_ROUTE_SEP + jvmRoute; } } Cookie cookie = new Cookie(&quot;JSESSIONID&quot;, reqSessionId); cookie.setMaxAge(-1); cookie.setPath(sessionPath); cookie.setVersion(1); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); cookie.setVersion(0); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); return 0; } /** Notification of context shutdown */ public void contextShutdown( Context ctx ) throws TomcatException { if( ctx.getDebug() > 0 ) ctx.log(&quot;Removing sessions from &quot; + ctx ); ctx.getSessionManager().removeSessions(ctx); } }
Vocabulaire technique de l’AOP (1) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Vocabulaire technique de l’AOP (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Principes de l’AOP  ,[object Object],[object Object],[object Object],Tissage à l’exécution (dynamique)  ou à la compilation (tissage statique)   Besoins Tissage Spectre des préoccupations modules Business logic
Couplage fort du code technique et métier  (l’évolution du code technique impacte le code métier) Design Pattern, Conteneur J2EE (Tx, sécurité, etc.) Etc. Besoins techniques Logique Domaine Données utilisateurs Couplage Couplage couplage couplage couplage Application Métier  Processus et domaine métier Données Métier Accès aux données métier Interface  Utilisateur Présentation (projet) Multi-médias Navigation Intégration ressources
Couplage fort du code technique et métier  (l’évolution du code technique impacte le code métier) Présentations Logiques Domaines Code métier ressources ©  Auteur : jimmy Siméon Framework, Design Pattern, Composant (utilise) utilisateurs Code technique   Le code technique utilise les API techniques via un couplage par implémentation (utilise) Conception technique Couplage fort Couplage fort Sans AOP Code technique Aspects Sécurité Transaction ACID Communication Distante (RMI, etc.) Persistance Cache, pool, log, etc. Conteneur logiciel API technique
Découpler les couches techniques et métiers (Programmation Orientée Aspects et Architecture Orientée Service) utilisateurs Présentations Logiques Domaines ressources Code des Aspects techniques (Préoccupations transverses) (Appels aux APIs Techniques, utilisation de Design Pattern) Code métier  (instances de classes simples), (tissage) Conteneur logiciel (utilise) API techniques Couplage faible Couplage faible Avec AOP Aspects
Aspect dans un page JSP (Java Server Pages) Code JSP Java Server Pages Page.jsp Compilateur JSP jspc Servlet Page_jsp.java Compilateur AspectJ ajc p-code tissé Page_jsp.class MyAspect.class Aspect MyAspect.aj (ou MyAspcet.java) Aspectjrt.jar Public  pointcut  pcd(HttpServvletRequest rq,  HttpServletResponse rs):  execution (* * MyServlet.doGet(HttpSerletRequest,  HttpServletResponse)) &&  args (rq, rs); before (HttpServletRequest rq, HttpServletResponsse rs)  throws IOException : pcd(rq, rs) { //Code de l’advice } %RACINE_PROJET% MyWebApp source jsp classes lib Aspectjrt.jar Page.jsp Page_jsp.java MyAspect.java Page_jsp.class MyAspect.class
« Design Patterns » transparent (orienté Aspect) ,[object Object],[object Object],[object Object],[object Object],[object Object]
Extraire le code technique puis le propager dans le code métier au dernier moment !  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],AOP myths and realities,  http://www-128.ibm.com/developerworks/java/library/j-aopwork15/ 14 Feb 2006,  Ramnivas Laddad  ( ramnivas @ aspectivity . com ),  AOP@ Work
Trois type de Tissages du code métier ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Syntaxe du descripteur de point de coupe AspectJ (PCD : PointCut Descriptor) PointCut Descriptor visibility-modifier   publiic, private, Protected, package ParameterList
Annotations dans AspectJ 5 (version 1.5) Descripteur de déploiement AspectJ (Schéma identique à AspectWerkz) Contexte exposé par les annotations
Code d’une application de e-Banking  ,[object Object],public class ATMBean  implements SessionBean  { javax.ejb.SessionContext ejbContext; javax.transaction.UserTransaction ut; public void transfer(int fromAcctID,int toAcctId,double amount) throws InsufficientFundsException, FinderException { // find accounts ... ut=ejbContext.getUserTransaction(); ut.begin(); try { fromAccount.withdraw(amount); toAccount.deposit(amount); ut.commit(); } catch(Exception ex) { ut.rollback(); throw new EJBException(&quot;transaction rollbacked&quot;); } } public void ejbCreate() {...} public void ejbRemove() {...} public void ejbActivate() {...} public void ejbPassivate() {...} public void setSessionContext(javax.ejb.SessionContext sc) { ejbContext=sc; } } Exemple d’utilisation des aspects métier technique métier technique technique
Modularisation des Aspects techniques ,[object Object],public  aspect SessionBeanAspect  { declare parents:  ATM implements SessionBean; javax.ejb.SessionContext ATM.ejbContext;. public void ATM.ejbCreate() throws CreateException {...} public void ATM.ejbRemove() {...} public void ATM.ejbActivate() {...} public void ATM.ejbPassivate() {...} public void ATM.setSessionContext(SessionContext sc) {...} } public  aspect TransactionAspect  { javax.transaction.UserTransaction ATM.ut; before():  call(* Account.withdraw(..)) && withincode(* ATM.transfer(..)) { ut=ejbContext.getUserTransaction(); ut.begin(); } after():  call(* Account.deposit(..)) && withincode(* ATM.transfer(..)) { ut.commit(); } after() throwing(Exception ex) throws EJBException : call(* Account.withdraw(..)) || call(* Account.deposit(..)) { ut.rollback(); throw new EJBException(&quot;transaction rollbacked&quot;); } } Exemple d’utilisation des aspects Inter-type definition Ce qui fait qu’une classe soit un EJB Ce qui fait qu’une classe soit transactionnelle Technique « Aspect  Transaction » Technique « Aspect EJB »
Code métier épuré des aspects du code technique public  class ATM  { public void  transfer (int fromAcctID,int toAcctId,double amount) throws InsufficientFundsException, FinderException  { // find accounts ... fromAccount.withdraw(amount); toAccount.deposit(amount); } } Exemple d’utilisation des aspects
Code AOP « AspectJ » dans Eclipse plug-in AJDT classe d’aspect, pointcut, types before() after() et around() Plusieurs PCD et Advice par Aspect Chaque Advise est associé à un PCD   marqueur PCD : Descripteur de Point de Coupe
Perspective du Plug-in AJDT dans Eclipse  (Cross Reference et Outline)
Visualiseur d’aspects  (Pointcut « execution » et advise « before et after »)
Annotations AspectJ 1.5 décrivant un aspect  @Aspect, @Pointcut, @Before et introspection de type JoinPoint Annotations = Jdk 1.5 et AspectJ 1.5 (la classe métier)
Configuration XML « META-INF/aop.xml »  tissage LTW (Load-Time Weaving)
Composition d’Aspects ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
AOP approche orthogonale à la POO Approche  orthogonale Classe Aspect1 Classe Aspect2 Tissage du code Greffon (Advise) Méthode d’aspect (code à injecter) Point de jonction Point de coupe Descripteur de point de coupe (points de jonctions à atteindre)  Ordonnancement de la projection des aspects Aspect abstrait ©  Auteur : jimmy Siméon
Décompilation d’une classe tissée par un Aspect Après le Tissage d’un Aspect Classe métier décompilée
Décompilation de la classe Java d’Aspect Classe d’Aspect décompilée
Développement d’aspects en équipe Développeurs d’Aspects techniques Modules d’aspects Développeurs du code Métier Code métier Conteneur technique Tissage et déploiement Architecte d’Aspect Intégrateur Frameworks,  design patterns,… Aspects techniques transverses,… Framework AOP, design Pattern AOP ©  Auteur : jimmy Siméon Extraction  des aspects
Benchmark AOP réalisé par Alexandre VASSEUR  http://docs.codehaus.org/display/AW/AOP+Benchmark Valeurs des données en nano seconde
Tisseurs d'aspects pour différents langages  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Avantages ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Rodin : Le penseur
Désavantages ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Rodin : Le penseur
Qu’est-ce que nous réserve l’avenir ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Rodin : Le penseur
Bibliographie utilisée pour cette présentation  et  e-Bibliographie ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Martin Fowler :  Design Pattern IoC / DI  (Inversion of Control /  Dependancy Injection) « The Hollywood principle : Don’t call us, we’ll call you » (DIP : Dependency Injection Principle)
Bibliographie D’autres livres disponibles  en librairies (hors bibliographie) : Professional programming Software 2.0 « Introducing AspectJ », page 32 Russ Miles, author of the AspectJ Cookbook (O’Reilly) and Senior Technologist for General Dynamics United Kingdom Limited (russellmiles@mac.com)
e-Bibliographie ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
ANNEXE
Le créateur du Framework AspectJ Undergraduate Study M.I.T. (1978-1983);  Research Staff, MIT Lab for Computer Science (1980-1983);  Member of Technical Staff, Symbolics Inc. (1983-1984);  Member of Research Staff, Xerox PARC (1984-1999);  Manager, Software Design Area, Xerox PARC (1992-1999);  Principal Scientist, Xerox PARC (1996-1999);  Professor, University of British Columbia (1999-);  Xerox/Sierra Systems/NSERC Software Design Chair, UBC (1999-). The University of British Columbia 2329 West Mall Vancouver, BC Canada V6T 1Z4  Mr Grégor KICZALES MIT
Outils AJDT « AspectJ Development Tools » plug-in Eclipse
Installation de AJDT 1.2 (1)
Installation de AJDT 1.2 (2)
Plug-in Eclipse « AJDT 1.2 »
Framework AspectJ 1.5 dans AJDT 1.2
Run-Time «  aspectrt.jar  »
Plug-in AJDT 1.3.0 et 1.2.1 Load-time Weaving (AJDT 1.2.1 and 1.3.0). Qu’est-ce qui a changé (refactoring) Crosscutting Comparison view
« Design Patterns » applicables à l’AOP
Outil AspectBrowser plug-in Eclipse ( University of California, San Diego)   Department of Computer Science  and Engineering University of California, San Diego Plug-in Eclipse Open Source Fonctions pour les Aspects : Création, Visualisation Graphique,  Colorisation du code, Recherche Outils sous licence : « Common Public License »
Outil ActiveAspect plug-in Eclipse ( University  of British Columbia ) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],http://www. cs . ubc . ca / labs / spl / projects / activeaspect /
Analyse du modèle existant

Más contenido relacionado

La actualidad más candente

Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...ENSET, Université Hassan II Casablanca
 
Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...ENSET, Université Hassan II Casablanca
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiENSET, Université Hassan II Casablanca
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 
Programmation orientee aspect 201401 - Ensim
Programmation orientee aspect 201401 - EnsimProgrammation orientee aspect 201401 - Ensim
Programmation orientee aspect 201401 - EnsimLaurent Broudoux
 
Cours design pattern m youssfi partie 1 introduction et pattern strategy
Cours design pattern m youssfi partie 1 introduction et pattern strategyCours design pattern m youssfi partie 1 introduction et pattern strategy
Cours design pattern m youssfi partie 1 introduction et pattern strategyENSET, Université Hassan II Casablanca
 
Programmation orienté aspect
Programmation orienté aspectProgrammation orienté aspect
Programmation orienté aspectmeriem sari
 
Java 110605092007-phpapp02
Java 110605092007-phpapp02Java 110605092007-phpapp02
Java 110605092007-phpapp02Eric Bourdet
 
Application Spring MVC/IOC & Hibernate
Application Spring MVC/IOC & HibernateApplication Spring MVC/IOC & Hibernate
Application Spring MVC/IOC & HibernateInes Ouaz
 
Présentation de JEE et de son écosysteme
Présentation de JEE et de son écosystemePrésentation de JEE et de son écosysteme
Présentation de JEE et de son écosystemeStéphane Traumat
 
Spring par la pratique chap-7 - mvc
Spring par la pratique  chap-7 - mvcSpring par la pratique  chap-7 - mvc
Spring par la pratique chap-7 - mvcFlorent Breton
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 

La actualidad más candente (20)

Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
 
Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...Mohamed youssfi support architectures logicielles distribuées basées sue les ...
Mohamed youssfi support architectures logicielles distribuées basées sue les ...
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
Chap 02 poo en java
Chap 02 poo en javaChap 02 poo en java
Chap 02 poo en java
 
Programmation orientee aspect 201401 - Ensim
Programmation orientee aspect 201401 - EnsimProgrammation orientee aspect 201401 - Ensim
Programmation orientee aspect 201401 - Ensim
 
Struts
StrutsStruts
Struts
 
Cours design pattern m youssfi partie 1 introduction et pattern strategy
Cours design pattern m youssfi partie 1 introduction et pattern strategyCours design pattern m youssfi partie 1 introduction et pattern strategy
Cours design pattern m youssfi partie 1 introduction et pattern strategy
 
Maven et industrialisation du logiciel
Maven et industrialisation du logicielMaven et industrialisation du logiciel
Maven et industrialisation du logiciel
 
Programmation orienté aspect
Programmation orienté aspectProgrammation orienté aspect
Programmation orienté aspect
 
Jeu jee session
Jeu jee sessionJeu jee session
Jeu jee session
 
Java 110605092007-phpapp02
Java 110605092007-phpapp02Java 110605092007-phpapp02
Java 110605092007-phpapp02
 
Application Spring MVC/IOC & Hibernate
Application Spring MVC/IOC & HibernateApplication Spring MVC/IOC & Hibernate
Application Spring MVC/IOC & Hibernate
 
Spring & SpringBatch FR
Spring & SpringBatch FRSpring & SpringBatch FR
Spring & SpringBatch FR
 
Présentation de JEE et de son écosysteme
Présentation de JEE et de son écosystemePrésentation de JEE et de son écosysteme
Présentation de JEE et de son écosysteme
 
Spring par la pratique chap-7 - mvc
Spring par la pratique  chap-7 - mvcSpring par la pratique  chap-7 - mvc
Spring par la pratique chap-7 - mvc
 
Cours design pattern m youssfi partie 6 proxy
Cours design pattern m youssfi partie 6 proxyCours design pattern m youssfi partie 6 proxy
Cours design pattern m youssfi partie 6 proxy
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Support de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfiSupport de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfi
 
Tuto spring
Tuto springTuto spring
Tuto spring
 

Similar a Aspect avec AspectJ

20081113 - Nantes Jug - Apache Maven
20081113 - Nantes Jug - Apache Maven20081113 - Nantes Jug - Apache Maven
20081113 - Nantes Jug - Apache MavenArnaud Héritier
 
Chaine de production pipeline
Chaine de production   pipelineChaine de production   pipeline
Chaine de production pipelineNicolas wallerand
 
Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Xavier NOPRE
 
PFE PSA Peugeot Citroen - Prototypage rapide
PFE PSA Peugeot Citroen - Prototypage rapide PFE PSA Peugeot Citroen - Prototypage rapide
PFE PSA Peugeot Citroen - Prototypage rapide Régis Castéran
 
Rich Desktop Applications
Rich Desktop ApplicationsRich Desktop Applications
Rich Desktop Applicationsgoldoraf
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsJulien Wittouck
 
DEVASC_Module_7 - Infrastructure & automatisation.pptx
DEVASC_Module_7 - Infrastructure & automatisation.pptxDEVASC_Module_7 - Infrastructure & automatisation.pptx
DEVASC_Module_7 - Infrastructure & automatisation.pptxTasnimBenAmmar
 
Symfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantSymfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantHugo Hamon
 
ACRA - Présentation PAUG Avril 2011
ACRA - Présentation PAUG Avril 2011ACRA - Présentation PAUG Avril 2011
ACRA - Présentation PAUG Avril 2011Kevin Gaudin
 
Java dans Windows Azure: l'exemple de Jonas
Java dans Windows Azure: l'exemple de JonasJava dans Windows Azure: l'exemple de Jonas
Java dans Windows Azure: l'exemple de JonasMicrosoft
 
Java dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASJava dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASGuillaume Sauthier
 
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !Paris Salesforce Developer Group
 
Comment réussir son projet en Angular 1.5 ?
Comment réussir son projet en Angular 1.5 ?Comment réussir son projet en Angular 1.5 ?
Comment réussir son projet en Angular 1.5 ?Maxime Bernard
 
Fichier_Compétences
Fichier_CompétencesFichier_Compétences
Fichier_CompétencesYang Fei
 
Firefox OS de la théorie à la pratique - OSDC
Firefox OS de la théorie à la pratique - OSDCFirefox OS de la théorie à la pratique - OSDC
Firefox OS de la théorie à la pratique - OSDCChristophe Villeneuve
 
Introduction à Symfony2
Introduction à Symfony2Introduction à Symfony2
Introduction à Symfony2Hugo Hamon
 

Similar a Aspect avec AspectJ (20)

20081113 - Nantes Jug - Apache Maven
20081113 - Nantes Jug - Apache Maven20081113 - Nantes Jug - Apache Maven
20081113 - Nantes Jug - Apache Maven
 
iTunes Stats
iTunes StatsiTunes Stats
iTunes Stats
 
Chaine de production pipeline
Chaine de production   pipelineChaine de production   pipeline
Chaine de production pipeline
 
Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013
 
PFE PSA Peugeot Citroen - Prototypage rapide
PFE PSA Peugeot Citroen - Prototypage rapide PFE PSA Peugeot Citroen - Prototypage rapide
PFE PSA Peugeot Citroen - Prototypage rapide
 
Aspectj
AspectjAspectj
Aspectj
 
Rich Desktop Applications
Rich Desktop ApplicationsRich Desktop Applications
Rich Desktop Applications
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'ts
 
DEVASC_Module_7 - Infrastructure & automatisation.pptx
DEVASC_Module_7 - Infrastructure & automatisation.pptxDEVASC_Module_7 - Infrastructure & automatisation.pptx
DEVASC_Module_7 - Infrastructure & automatisation.pptx
 
Symfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantSymfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 Performant
 
ACRA - Présentation PAUG Avril 2011
ACRA - Présentation PAUG Avril 2011ACRA - Présentation PAUG Avril 2011
ACRA - Présentation PAUG Avril 2011
 
Java dans Windows Azure: l'exemple de Jonas
Java dans Windows Azure: l'exemple de JonasJava dans Windows Azure: l'exemple de Jonas
Java dans Windows Azure: l'exemple de Jonas
 
Java dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASJava dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnAS
 
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !
La Tooling API, est-ce pour moi ? Bien sûr, viens voir pourquoi !
 
Comment réussir son projet en Angular 1.5 ?
Comment réussir son projet en Angular 1.5 ?Comment réussir son projet en Angular 1.5 ?
Comment réussir son projet en Angular 1.5 ?
 
Fichier_Compétences
Fichier_CompétencesFichier_Compétences
Fichier_Compétences
 
sfPot aop
sfPot aopsfPot aop
sfPot aop
 
Firefox OS de la théorie à la pratique - OSDC
Firefox OS de la théorie à la pratique - OSDCFirefox OS de la théorie à la pratique - OSDC
Firefox OS de la théorie à la pratique - OSDC
 
Stage GFC Atlantic
Stage GFC AtlanticStage GFC Atlantic
Stage GFC Atlantic
 
Introduction à Symfony2
Introduction à Symfony2Introduction à Symfony2
Introduction à Symfony2
 

Más de simeon

Gestion du contenu dans une entreprise
Gestion du contenu dans une entrepriseGestion du contenu dans une entreprise
Gestion du contenu dans une entreprisesimeon
 
Management Informatique
Management InformatiqueManagement Informatique
Management Informatiquesimeon
 
Gestion du contenu dans une entreprise (ECM)
Gestion du contenu dans une entreprise (ECM)Gestion du contenu dans une entreprise (ECM)
Gestion du contenu dans une entreprise (ECM)simeon
 
La Gouvernance des Services Informatiques
La Gouvernance des Services InformatiquesLa Gouvernance des Services Informatiques
La Gouvernance des Services Informatiquessimeon
 
Réseaux Sociaux et le WEB 2.0
Réseaux Sociaux et le WEB 2.0Réseaux Sociaux et le WEB 2.0
Réseaux Sociaux et le WEB 2.0simeon
 
Télécoms et innovations InterNet
Télécoms et innovations InterNetTélécoms et innovations InterNet
Télécoms et innovations InterNetsimeon
 
Persistance avec JPA
Persistance avec JPAPersistance avec JPA
Persistance avec JPAsimeon
 
Aspect avec Spring AOP
Aspect avec Spring AOPAspect avec Spring AOP
Aspect avec Spring AOPsimeon
 

Más de simeon (8)

Gestion du contenu dans une entreprise
Gestion du contenu dans une entrepriseGestion du contenu dans une entreprise
Gestion du contenu dans une entreprise
 
Management Informatique
Management InformatiqueManagement Informatique
Management Informatique
 
Gestion du contenu dans une entreprise (ECM)
Gestion du contenu dans une entreprise (ECM)Gestion du contenu dans une entreprise (ECM)
Gestion du contenu dans une entreprise (ECM)
 
La Gouvernance des Services Informatiques
La Gouvernance des Services InformatiquesLa Gouvernance des Services Informatiques
La Gouvernance des Services Informatiques
 
Réseaux Sociaux et le WEB 2.0
Réseaux Sociaux et le WEB 2.0Réseaux Sociaux et le WEB 2.0
Réseaux Sociaux et le WEB 2.0
 
Télécoms et innovations InterNet
Télécoms et innovations InterNetTélécoms et innovations InterNet
Télécoms et innovations InterNet
 
Persistance avec JPA
Persistance avec JPAPersistance avec JPA
Persistance avec JPA
 
Aspect avec Spring AOP
Aspect avec Spring AOPAspect avec Spring AOP
Aspect avec Spring AOP
 

Aspect avec AspectJ

  • 1. Architecture technique applicative Aspects Techniques Framework Java IBM « AspectJ 1.5 » Programmation Orientée Aspect ( Aspect Oriented Programming ) Ajout transparent de services techniques dans le code métier Outil de développement : Plug-in Elipse AJDT 1.2 / 1.3 « Découpler le code technique du code métier » Publication : juillet 2005 Catégorie : veille technologique Auteur : Jimmy Michel SIMEON Version éditoriale : 2.0.0.0, le 14 mars 2006 avancé simple expert Niveau : Public : Architecte Dévelopeur Manager
  • 2.
  • 3.
  • 4.
  • 5. Acteurs du marché AOP (bonne pratique AOP des experts en développements) Rod Johnson : Framework Spring AOP , AOP alliance auteur du livre «J2EE without EJB» Conteneurs léger (couplage lâche) vs conteneur lourd (couplage fort), Bill Burke : Leader JBoss AOP AOP alliance Jonas Bonér : framework AspectWerkz BEA Systems AspectWerkz fusionne avec AspectJ ! Aspect Oriented Programming (Frameworks AOP), Separation Of Concerns (SoC). Gregor Kiczales XEROX PARC : père de l’AOP et du framework AspectJ AspecJ appartient à la communauté Eclipse / IBM
  • 6.
  • 7.
  • 8.
  • 9. Visualisation des catégories d’aspects techniques dans un programme Identification des Aspects techniques !
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. Couplage fort du code technique et métier (l’évolution du code technique impacte le code métier) Design Pattern, Conteneur J2EE (Tx, sécurité, etc.) Etc. Besoins techniques Logique Domaine Données utilisateurs Couplage Couplage couplage couplage couplage Application Métier Processus et domaine métier Données Métier Accès aux données métier Interface Utilisateur Présentation (projet) Multi-médias Navigation Intégration ressources
  • 15. Couplage fort du code technique et métier (l’évolution du code technique impacte le code métier) Présentations Logiques Domaines Code métier ressources © Auteur : jimmy Siméon Framework, Design Pattern, Composant (utilise) utilisateurs Code technique Le code technique utilise les API techniques via un couplage par implémentation (utilise) Conception technique Couplage fort Couplage fort Sans AOP Code technique Aspects Sécurité Transaction ACID Communication Distante (RMI, etc.) Persistance Cache, pool, log, etc. Conteneur logiciel API technique
  • 16. Découpler les couches techniques et métiers (Programmation Orientée Aspects et Architecture Orientée Service) utilisateurs Présentations Logiques Domaines ressources Code des Aspects techniques (Préoccupations transverses) (Appels aux APIs Techniques, utilisation de Design Pattern) Code métier (instances de classes simples), (tissage) Conteneur logiciel (utilise) API techniques Couplage faible Couplage faible Avec AOP Aspects
  • 17. Aspect dans un page JSP (Java Server Pages) Code JSP Java Server Pages Page.jsp Compilateur JSP jspc Servlet Page_jsp.java Compilateur AspectJ ajc p-code tissé Page_jsp.class MyAspect.class Aspect MyAspect.aj (ou MyAspcet.java) Aspectjrt.jar Public pointcut pcd(HttpServvletRequest rq, HttpServletResponse rs): execution (* * MyServlet.doGet(HttpSerletRequest, HttpServletResponse)) && args (rq, rs); before (HttpServletRequest rq, HttpServletResponsse rs) throws IOException : pcd(rq, rs) { //Code de l’advice } %RACINE_PROJET% MyWebApp source jsp classes lib Aspectjrt.jar Page.jsp Page_jsp.java MyAspect.java Page_jsp.class MyAspect.class
  • 18.
  • 19.
  • 20.
  • 21. Syntaxe du descripteur de point de coupe AspectJ (PCD : PointCut Descriptor) PointCut Descriptor visibility-modifier publiic, private, Protected, package ParameterList
  • 22. Annotations dans AspectJ 5 (version 1.5) Descripteur de déploiement AspectJ (Schéma identique à AspectWerkz) Contexte exposé par les annotations
  • 23.
  • 24.
  • 25. Code métier épuré des aspects du code technique public class ATM { public void transfer (int fromAcctID,int toAcctId,double amount) throws InsufficientFundsException, FinderException { // find accounts ... fromAccount.withdraw(amount); toAccount.deposit(amount); } } Exemple d’utilisation des aspects
  • 26. Code AOP « AspectJ » dans Eclipse plug-in AJDT classe d’aspect, pointcut, types before() after() et around() Plusieurs PCD et Advice par Aspect Chaque Advise est associé à un PCD marqueur PCD : Descripteur de Point de Coupe
  • 27. Perspective du Plug-in AJDT dans Eclipse (Cross Reference et Outline)
  • 28. Visualiseur d’aspects (Pointcut « execution » et advise « before et after »)
  • 29. Annotations AspectJ 1.5 décrivant un aspect @Aspect, @Pointcut, @Before et introspection de type JoinPoint Annotations = Jdk 1.5 et AspectJ 1.5 (la classe métier)
  • 30. Configuration XML « META-INF/aop.xml » tissage LTW (Load-Time Weaving)
  • 31.
  • 32. AOP approche orthogonale à la POO Approche orthogonale Classe Aspect1 Classe Aspect2 Tissage du code Greffon (Advise) Méthode d’aspect (code à injecter) Point de jonction Point de coupe Descripteur de point de coupe (points de jonctions à atteindre) Ordonnancement de la projection des aspects Aspect abstrait © Auteur : jimmy Siméon
  • 33. Décompilation d’une classe tissée par un Aspect Après le Tissage d’un Aspect Classe métier décompilée
  • 34. Décompilation de la classe Java d’Aspect Classe d’Aspect décompilée
  • 35. Développement d’aspects en équipe Développeurs d’Aspects techniques Modules d’aspects Développeurs du code Métier Code métier Conteneur technique Tissage et déploiement Architecte d’Aspect Intégrateur Frameworks, design patterns,… Aspects techniques transverses,… Framework AOP, design Pattern AOP © Auteur : jimmy Siméon Extraction des aspects
  • 36. Benchmark AOP réalisé par Alexandre VASSEUR http://docs.codehaus.org/display/AW/AOP+Benchmark Valeurs des données en nano seconde
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42. Bibliographie D’autres livres disponibles en librairies (hors bibliographie) : Professional programming Software 2.0 « Introducing AspectJ », page 32 Russ Miles, author of the AspectJ Cookbook (O’Reilly) and Senior Technologist for General Dynamics United Kingdom Limited (russellmiles@mac.com)
  • 43.
  • 45. Le créateur du Framework AspectJ Undergraduate Study M.I.T. (1978-1983); Research Staff, MIT Lab for Computer Science (1980-1983); Member of Technical Staff, Symbolics Inc. (1983-1984); Member of Research Staff, Xerox PARC (1984-1999); Manager, Software Design Area, Xerox PARC (1992-1999); Principal Scientist, Xerox PARC (1996-1999); Professor, University of British Columbia (1999-); Xerox/Sierra Systems/NSERC Software Design Chair, UBC (1999-). The University of British Columbia 2329 West Mall Vancouver, BC Canada V6T 1Z4 Mr Grégor KICZALES MIT
  • 46. Outils AJDT « AspectJ Development Tools » plug-in Eclipse
  • 50. Framework AspectJ 1.5 dans AJDT 1.2
  • 52. Plug-in AJDT 1.3.0 et 1.2.1 Load-time Weaving (AJDT 1.2.1 and 1.3.0). Qu’est-ce qui a changé (refactoring) Crosscutting Comparison view
  • 53. « Design Patterns » applicables à l’AOP
  • 54. Outil AspectBrowser plug-in Eclipse ( University of California, San Diego) Department of Computer Science and Engineering University of California, San Diego Plug-in Eclipse Open Source Fonctions pour les Aspects : Création, Visualisation Graphique, Colorisation du code, Recherche Outils sous licence : « Common Public License »
  • 55.
  • 56. Analyse du modèle existant