Presentation is loading. Please wait.

Presentation is loading. Please wait.

郝克刚 西北大学计算机科学系 (为研究生们作的报告)

Similar presentations


Presentation on theme: "郝克刚 西北大学计算机科学系 (为研究生们作的报告)"— Presentation transcript:

1 郝克刚 西北大学计算机科学系 (为研究生们作的报告) 2003.10
Aspect-Oriented Programming (AOP) and Aspect-oriented software development (AOSD) 面向方面的程序设计 (AOP) 和面向方面的软件开发方法 (AOSD) 郝克刚 西北大学计算机科学系 (为研究生们作的报告) 2018/9/17

2 软件技术新动向:面向方面方法的兴起 二十年的实践证明:面向对象的开发方法具有很强的生命力,已为广大的软件业界所普遍采用。
但是,对多数复杂的系统,在多种需求关注点和实现的模块(构件、类)之间的对应中,往往出现交叉分割(横切)的现象。即需求关注点在实现中的分散和实现构件内容的混杂。从而导致了软件开发和维护的一系列困难(Poor traceability, Lower productivity, Less code reuse, Poor code quality, More difficult evolution 。) 面向方面方法就是针对这些问题而产生的。它一出现就得到业界的广泛关注。很可能,它将成为软件开发方法发展的重要一步,引起新一轮软件开发方法和支持工具研究和开发的热潮。 2018/9/17

3 讲座大纲: AOP AOSD 的飞速发展 基本概念和内容 AspectJ 的基本思路 (-- 语言的概念和结构) 研究和开发的方向和课题
2018/9/17

4 international conferences on AOP
Workshop on Aspect Oriented Programming(ECOOP 1997) June 1997 Int’l Workshop on Aspect Oriented Programming(ICSE 1998) April 1998. Workshop on Aspect Oriented Programming(ECOOP 1998), Jan 1998. Int’l Workshop on Aspect Oriented Programming(ECOOP 1999), June 1999. Workshop on Advanced Separations of Concerns(OOPSLA 2000), Oct Workshop on Aspects and Dimensions of Concerns(ECOOP 2000), June 2000. Workshop on Multi-Dimentional Separation of Concerns in Software Engineering(ICSE 2000), June 2000. Workshop on Advanced Separations of Concerns(ECOOP 2001), June Workshop on Advanced Separations of Concerns in Object Orieted Systems (OOPSLA 2001), Oct Workshop on Advanced Separation of Concerns in Software Engineering(ICSE 2001), May 2001. 2018/9/17

5 international conferences on AOSD
the 1st international conference on Aspect-oriented software development . Enschede, The Netherlands, on April 22-26, 2nd international conference on Aspect-oriented software development . Boston, Massachusetts, USA, March , 2003. the 3rd International Conference on Aspect-Oriented Software Development . Lancaster UK, March 2018/9/17

6 Workshop on Aspect-Orientation (German)
AOP-GI 2001: Workshop on Aspect-Orientation, May 3-4, 2001, University of Paderborn. (German only) AOSD-GI 2002: Second Workshop on Aspect-Oriented Software Development of the GI, February 21-22, 2002, University of Bonn. AOSD-GI 2003: Third Workshop on Aspect-Oriented Software Development of the GI, March , University of Essen. 2018/9/17

7 Research Projects: Supported Systems:
AspectC++, AspectJ, AspectR, AspectS,… Research Prototypes: Applications: Methods & Foundations: 2018/9/17

8 Web sites: http://aosd.net http://www.aspectc.org/
Xerox PARC's research on AOP : …… 2018/9/17

9 A Bibliography of Aspect-Oriented Software Development
Version 1.0 (502) RIACS Technical Report August 2002 Version 1. 1 (694) RIACS Technical Report January 2003 Version 1.22 {Research Institute for Advanced Computer Science}, 2018/9/17

10 The fundamental goal of AOSD
The fundamental goal of AOSD -- effective separation of concerns-- was enunciated about 30 years ago, most notably by Dijkstra and Parnas. The first two decades or so of research on separation of concerns focused primarily on providing new kinds of modules, able to separate concerns in new ways. This led to some key advances, including abstract data types and object-oriented programming, which have had dramatic impact on software engineering research and practice. 2018/9/17

11 The time is right for practitioners to begin using AOSD technology
The approaches suffered from a limitation, however: they could encapsulate concerns that aligned with the dominant decomposition of the software into modules such as objects or classes, but not concerns that cut across multiple modules. The advent and promulgation of aspect-oriented programming awakened broader interest in the area, on the part of researchers and practitioners alike. The time is right for practitioners to begin using AOSD technology, for researchers to solve some of the challenging problems that remain, and for researchers and practitioners to work together to make AOSD a mainstream software development technology. 2018/9/17

12 Evolution of software programming methodology
machine-level coding higher-level languages structured languages Object-oriented programming (OOP) Each new methodology presents new ways to decompose problems: machine code, machine-independent code, procedures, classes, and so on. Each new methodology allowed a more natural mapping of system requirements to programming constructs. 2018/9/17

13 the next big step OOP has shown its strength when it comes to modeling common behavior. However, OOP does not adequately address behaviors that span over many -- often unrelated -- modules. In contrast, AOP methodology fills this void. AOP quite possibly represents the next big step in the evolution of programming methodologies. 2018/9/17

14 View the system as a set of concerns (关注点,考虑)
A typical system may consist of several kinds of concerns, including: business logic, performance, data persistence, logging and debugging, authentication, security, multithread safety, error checking, and so on. development-process concerns, such as: comprehensibility, maintainability, traceability, and evolution ease . 2018/9/17

15 Concern decomposition: The prism(棱镜) analogy
2018/9/17

16 Modularity problems Scatter (分散) tangle (混杂) crosscut(横切、交叉分割)
2018/9/17

17 bad modularity (分散) (混杂) scattering – spread around
tangling – code in one region addresses multiple concerns (混杂) scattering and tangling (S&T) tend to appear together; they describe different facets of the same problem /* * * ==================================================================== * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * reserved. * Copyright (c) 1999 The Apache Software Foundation. All rights * The Apache Software License, Version 1.1 * 1. Redistributions of source code must retain the above copyright * are met: * the documentation and/or other materials provided with the * distribution. * notice, this list of conditions and the following disclaimer in * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer. itself, * if and wherever such third-party acknowlegements normally appear. * Apache Software Foundation ( * Alternately, this acknowlegement may appear in the software * "This product includes software developed by the * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * Foundation" must not be used to endorse or promote products * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * 5. Products derived from this software may not be called "Apache" * permission, please contact derived * from this software without prior written permission. For written * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * This software consists of voluntary contributions made by many * SUCH DAMAGE. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * information on the Apache Software Foundation, please see * individuals on behalf of the Apache Software Foundation. For more * [Additional notices, if required by prior licensing conditions] */ * < package org.apache.tomcat.session; import java.net.*; import java.util.*; import java.io.*; import org.apache.tomcat.util.StringManager; import org.apache.tomcat.core.*; * Core implementation of an application level session James Duncan Davidson /** import javax.servlet.http.*; import javax.servlet.*; James Todd Jason Hunter private String id; private Hashtable values = new Hashtable(); private StringManager sm = public class ApplicationSession implements HttpSession { StringManager.getManager("org.apache.tomcat.session"); private ServerSession serverSession; private boolean valid = true; private int inactiveInterval = -1; private long lastAccessed = creationTime; private Context context; private long creationTime = System.currentTimeMillis();; private long thisAccessTime = creationTime; this.inactiveInterval = context.getSessionTimeOut(); this.context = context; this.id = id; Context context) { ApplicationSession(String id, ServerSession serverSession, this.serverSession = serverSession; } this.inactiveInterval *= 60; if (this.inactiveInterval != -1) { return serverSession; ServerSession getServerSession() { * inactivities can be dealt with accordingly. * Called by context when request comes in so that accesses and void accessed() { thisAccessTime = System.currentTimeMillis(); lastAccessed = thisAccessTime; // set last accessed to thisAccessTime as it will be left over // from the previous access int thisInterval = if (inactiveInterval != -1) { void validate() { validate(); invalidate(); if (thisInterval > inactiveInterval) { (int)(System.currentTimeMillis() - lastAccessed) / 1000; // if we have an inactive interval, check to see if we've exceeded it if (valid) { // HTTP SESSION IMPLEMENTATION METHODS String msg = sm.getString("applicationSession.session.ise"); public String getId() { throw new IllegalStateException(msg); } else { return id; return creationTime; public long getCreationTime() { public long getLastAccessedTime() { return new SessionContextImpl(); public HttpSessionContext getSessionContext() { return lastAccessed; public void invalidate() { // remove everything in the session serverSession.removeApplicationSession(context); removeValue(name); String name = (String)enum.nextElement(); Enumeration enum = values.keys(); while (enum.hasMoreElements()) { public boolean isNew() { valid = false; if (! valid) { return true; return false; if (thisAccessTime == creationTime) { public void setAttribute(String name, Object value) { setAttribute(name, value); public void putValue(String name, Object value) { removeValue(name); // remove any existing binding throw new IllegalArgumentException(msg); String msg = sm.getString("applicationSession.value.iae"); if (name == null) { new HttpSessionBindingEvent(this, name); ((HttpSessionBindingListener)value).valueBound(e); HttpSessionBindingEvent e = if (value != null && value instanceof HttpSessionBindingListener) { values.put(name, value); public Object getAttribute(String name) { return getAttribute(name); public Object getValue(String name) { return values.get(name); public String[] getValueNames() { names.addElement(e.nextElement()); while (e.hasMoreElements()) { Vector names = new Vector(); Enumeration e = getAttributeNames(); names.copyInto(valueNames); String[] valueNames = new String[names.size()]; public Enumeration getAttributeNames() { return valueNames; return (Enumeration)valuesClone.keys(); Hashtable valuesClone = (Hashtable)values.clone(); public void removeAttribute(String name) { removeAttribute(name); public void removeValue(String name) { Object o = values.get(name); ((HttpSessionBindingListener)o).valueUnbound(e); new HttpSessionBindingEvent(this,name); if (o instanceof HttpSessionBindingListener) { public void setMaxInactiveInterval(int interval) { values.remove(name); public int getMaxInactiveInterval() { inactiveInterval = interval; return inactiveInterval; // * Core implementation of a server session public class ServerSession { private Hashtable appSessions = new Hashtable(); ServerSession(String id) { (ApplicationSession)appSessions.get(context); ApplicationSession appSession = public ApplicationSession getApplicationSession(Context context, boolean create) { // sync to ensure valid? appSession = new ApplicationSession(id, this, context); // XXX if (appSession == null && create) { appSessions.put(context, appSession); return appSession; // a new appSession // inactive interval -- if so, invalidate and create // make sure that we haven't gone over the end of our appSessions.remove(context); void removeApplicationSession(Context context) { void validate() // if we have an inactive interval, check to see if // we've exceeded it ssm.removeSession(this); ServerSessionManager.getManager(); ServerSessionManager ssm = Enumeration enum = appSessions.keys(); synchronized void invalidate() { appSession.invalidate(); (ApplicationSession)appSessions.get(key); Object key = enum.nextElement(); String msg = sm.getString("serverSession.value.iae"); return values.keys(); public Enumeration getValueNames() { // solution for this, but we'll determine something else later. // sync'd for safty -- no other thread should be getting something // from this while we are reaping. This isn't the most optimal synchronized void reap() { appSession.validate(); ; * Standard implementation of the <b>Session</b> interface. This object is * <b>IMPLEMENTATION NOTE</b>: An instance of this class represents both the * <p> * to a different JVM for distributable session support. * serializable, so that it can be stored in persistent storage or transferred * internal (Session) and application level (HttpSession) view of the session. * HttpSession view of this instance back to a Session view. * of the <code>org.apache.tomcat.session</code> package cannot cast an * However, because the class itself is not declared public, Java logic outside $Revision: 1.2 $ $Date: 2000/05/15 17:54:10 $ Craig R. McClanahan // Constructors implements HttpSession, Session { final class StandardSession manager The manager with which this Session is associated * Construct a new Session associated with the specified Manager. super(); this.manager = manager; public StandardSession(Manager manager) { private long lastAccessedTime = creationTime; * The last accessed time for this Session. * The maximum time interval, in seconds, between client requests before private Manager manager = null; * The Manager with which this Session is associated. private int maxInactiveInterval = -1; * indicates that the session should never time out. * the servlet container may invalidate this session. A negative time private boolean isNew = true; * Flag indicating whether this session is new or not. * The string manager for this package. private boolean isValid = false; * Flag indicating whether this session is valid or not. private static HttpSessionContext sessionContext = null; * The HTTP session context associated with this session. private long thisAccessedTime = creationTime; * The current accessed time for this session. // Session Properties * Manager when an existing Session instance is reused. * Set the creation time for this session. This method is called by the time The new creation time this.thisAccessedTime = time; this.lastAccessedTime = time; public void setCreationTime(long time) { this.creationTime = time; * Return the session identifier for this session. return (this.id); public void setId(String id) { id The new session identifier * Set the session identifier for this session. ((ManagerBase) manager).remove(this); (manager instanceof ManagerBase)) if ((this.id != null) && (manager != null) && ((ManagerBase) manager).add(this); if ((manager != null) && (manager instanceof ManagerBase)) * Return descriptive information about this Session implementation and * the corresponding version number, in the format return (this.info); public String getInfo() { * <code><description>/<version></code>. * Return the last time the client sent a request associated with this * a value associated with the session, do not affect the access time. * GMT. Actions that your application takes, such as getting or setting * session, as the number of milliseconds since midnight, January 1, 1970 return (this.lastAccessedTime); * Return the Manager within which this Session is valid. return (this.manager); public Manager getManager() { public void setManager(Manager manager) { manager The new Manager * Set the Manager within which this Session is valid. * before the servlet container will invalidate the session. A negative * Return the maximum time interval, in seconds, between client requests * an invalidated session IllegalStateException if this method is called on * time indicates that the session should never time out. return (this.maxInactiveInterval); * Update the accessed time information for this session. This method * should be called by the context when a request comes in for a particular this.thisAccessedTime = System.currentTimeMillis(); this.lastAccessedTime = this.thisAccessedTime; public void access() { * session, even if the application does not reference it. this.isNew=false; * without triggering an exception if the session has already expired. * Perform the internal processing required to invalidate this session, // Remove this session from our manager's active sessions public void expire() { Vector results = new Vector(); // Unbind any objects associated with this session Enumeration names = results.elements(); String name = (String) names.nextElement(); while (names.hasMoreElements()) { results.addElement(attr); String attr = (String) attrs.nextElement(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { setValid(false); // Mark this session as invalid isNew The new value for the <code>isNew</code> flag * Set the <code>isNew</code> flag for this session. this.isNew = isNew; void setNew(boolean isNew) { isValid The new value for the <code>isValid</code> flag * Set the <code>isValid</code> flag for this session. // HttpSession Properties this.isValid = isValid; void setValid(boolean isValid) { * midnight, January 1, 1970 GMT. * Return the time when this session was created, in milliseconds since IllegalStateException if this method is called on an return (this.creationTime); * invalidated session * Return the session context with which this session is associated. * Java Servlet API. * replacement. It will be removed in a future version of the As of Version 2.1, this method is deprecated and has no return (sessionContext); if (sessionContext == null) sessionContext = new StandardSessionContext(); // HttpSession Public Methods * Return the object bound with the specified name in this session, or name Name of the attribute to be returned * <code>null</code> if no object is bound with that name. return (attributes.get(name)); * containing the names of the objects bound to this session. * Return an <code>Enumeration</code> of <code>String</code> objects return (attributes.keys()); name Name of the value to be returned * <code>getAttribute()</code> As of Version 2.2, this method is replaced by return (getAttribute(name)); * are no such objects, a zero-length array is returned. * Return the set of names of objects bound to this session. If there * <code>getAttributeNames()</code> return (names); names[i] = (String) results.elementAt(i); for (int i = 0; i < names.length; i++) String names[] = new String[results.size()]; * Invalidates this session and unbinds any objects bound to it. // Cause this session to expire expire(); * example, if the server used only cookie-based sessions, and the client * session, or if the client chooses not to join the session. For * Return <code>true</code> if the client does not yet know about the * request. * has disabled the use of cookies, then a session would be new on each return (this.isNew); * Remove the object bound with the specified name from this session. If * After this method executes, and if the object implements * does nothing. * the session does not have an object bound with this name, this method * <code>valueUnbound()</code> on the object. name Name of the object to remove from this session. * <code>HttpSessionBindingListener</code>, the container calls return; if (object == null) synchronized (attributes) { Object object = attributes.get(name); (new HttpSessionBindingEvent((HttpSession) this, name)); if (object instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) object).valueUnbound attributes.remove(name); // System.out.println( "Removing attribute " + name ); * replaced. * of the same name is already bound to this session, the object is * Bind an object to this session, using the specified name. If an object * non-serializable object in an environment marked distributable. IllegalArgumentException if an attempt is made to add a value Object to be bound, cannot be null * <code>valueBound()</code> on the object. name Name to which the object is bound, cannot be null throw new IllegalArgumentException !(value instanceof Serializable)) if ((manager != null) && manager.getDistributable() && ((HttpSessionBindingListener) value).valueBound if (value instanceof HttpSessionBindingListener) attributes.put(name, value); (sm.getString("standardSession.setAttribute.iae")); // HttpSession Private Methods * object input stream. * Read a serialized version of this session object from the specified IOException if an input/output error occurs ClassNotFoundException if an unknown class is specified stream The input stream to read from * is not restored by this method, and must be set explicitly. * <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager throws ClassNotFoundException, IOException { private void readObject(ObjectInputStream stream) maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); lastAccessedTime = ((Long) stream.readObject()).longValue(); id = (String) stream.readObject(); // Deserialize the scalar instance variables (except Manager) creationTime = ((Long) stream.readObject()).longValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); String name = (String) stream.readObject(); Object value = (Object) stream.readObject(); for (int i = 0; i < n; i++) { int n = ((Integer) stream.readObject()).intValue(); // Deserialize the attribute count and attribute values * object output stream. * Write a serialized version of this session object to the specified * <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable * will be silently ignored. If you do not want any such attributes, * explicitly. * <code>readObject()</code>, you must set the associated Manager * <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored * in the serialized representation of this Session. After calling * Manager is set to <code>true</code>. stream The output stream to write to * be sure the <code>distributable</code> property of our associated stream.writeObject(id); stream.writeObject(new Long(creationTime)); private void writeObject(ObjectOutputStream stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(new Boolean(isNew)); // Accumulate the names of serializable attributes stream.writeObject(new Boolean(isValid)); stream.writeObject(new Integer(maxInactiveInterval)); stream.writeObject(new Long(lastAccessedTime)); if (value instanceof Serializable) Object value = attributes.get(attr); stream.writeObject(new Integer(results.size())); // Serialize the attribute count and the attribute values stream.writeObject(attributes.get(name)); stream.writeObject(name); Enumeration getAttributeNames() | String[] getValueNames() | Object getAttribute(String) | long getCreationTime() | crosscut invalidate(StandardSession s): s & (int getMaxInactiveInterval() | static advice(StandardSession s): invalidate(s) { before { void setAttribute(String, Object)); void removeAttribute(String) | void invalidate() | boolean isNew() | + ".ise")); (s.sm.getString("standardSession." + thisJoinPoint.methodName throw new IllegalStateException if (!s.isValid()) // Private Class * when <code>HttpSession.getSessionContext()</code> is called. * This class is a dummy implementation of the <code>HttpSessionContext</code> * interface, to conform to the requirement that such an object be returned As of Java Servlet API 2.1 with no replacement. The private Vector dummy = new Vector(); final class StandardSessionContext implements HttpSessionContext { * interface will be removed in a future version of this API. * This method must return an empty <code>Enumeration</code> As of Java Servlet API 2.1 with no replacement. * within this context. * Return the session identifiers of all sessions defined * and will be removed in a future version of the API. return (dummy.elements()); public Enumeration getIds() { * This method must return null and will be removed in a id Session identifier for which to look up a session * specified session identifier. * Return the <code>HttpSession</code> associated with the public HttpSession getSession(String id) { * future version of the API. return (null); 2018/9/17

18 good modularity private long lastAccessed = creationTime; private int inactiveInterval = -1; validate(); thisAccessTime = System.currentTimeMillis(); lastAccessed = thisAccessTime; void accessed() { // set last accessed to thisAccessTime as it will be left over // from the previous access int thisInterval = (int)(System.currentTimeMillis() - lastAccessed) / 1000; if (inactiveInterval != -1) { // if we have an inactive interval, check to see if we've exceeded it void validate() { } invalidate(); if (thisInterval > inactiveInterval) { } else { return lastAccessed; public long getLastAccessedTime() { throw new IllegalStateException(msg); String msg = sm.getString("applicationSession.session.ise"); if (valid) { ServerSessionManager ssm = ssm.removeSession(this); ServerSessionManager.getManager(); private long lastAccessedTime = creationTime; * session, as the number of milliseconds since midnight, January 1, 1970 * Return the last time the client sent a request associated with this /** */ * a value associated with the session, do not affect the access time. * GMT. Actions that your application takes, such as getting or setting return (this.lastAccessedTime); this.lastAccessedTime = time; /* * ==================================================================== * reserved. * Redistribution and use in source and binary forms, with or without * Copyright (c) 1999 The Apache Software Foundation. All rights * The Apache Software License, Version 1.1 * * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * 1. Redistributions of source code must retain the above copyright * are met: * modification, are permitted provided that the following conditions * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * distribution. * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * "This product includes software developed by the * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products * if and wherever such third-party acknowlegements normally appear. itself, * Apache Software Foundation ( * Alternately, this acknowlegement may appear in the software * nor may "Apache" appear in their names without prior written * 5. Products derived from this software may not be called "Apache" * permission, please contact * from this software without prior written permission. For written derived * permission of the Apache Group. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * SUCH DAMAGE. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * < * [Additional notices, if required by prior licensing conditions] * information on the Apache Software Foundation, please see * individuals on behalf of the Apache Software Foundation. For more * This software consists of voluntary contributions made by many import java.io.*; import org.apache.tomcat.util.StringManager; import org.apache.tomcat.core.*; package org.apache.tomcat.session; * Core implementation of an application level session import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; Jason Hunter James Duncan Davidson StringManager.getManager("org.apache.tomcat.session"); private StringManager sm = public class ApplicationSession implements HttpSession { James Todd private long thisAccessTime = creationTime; private boolean valid = true; private Context context; private long creationTime = System.currentTimeMillis();; private ServerSession serverSession; private Hashtable values = new Hashtable(); private String id; this.id = id; this.inactiveInterval = context.getSessionTimeOut(); this.context = context; this.serverSession = serverSession; ApplicationSession(String id, ServerSession serverSession, Context context) { this.inactiveInterval *= 60; if (this.inactiveInterval != -1) { return serverSession; ServerSession getServerSession() { * Called by context when request comes in so that accesses and * inactivities can be dealt with accordingly. // HTTP SESSION IMPLEMENTATION METHODS return id; public String getId() { return creationTime; public long getCreationTime() { return new SessionContextImpl(); public HttpSessionContext getSessionContext() { public void invalidate() { // remove everything in the session serverSession.removeApplicationSession(context); removeValue(name); String name = (String)enum.nextElement(); Enumeration enum = values.keys(); while (enum.hasMoreElements()) { public boolean isNew() { valid = false; if (! valid) { return true; return false; if (thisAccessTime == creationTime) { public void setAttribute(String name, Object value) { setAttribute(name, value); public void putValue(String name, Object value) { removeValue(name); // remove any existing binding throw new IllegalArgumentException(msg); String msg = sm.getString("applicationSession.value.iae"); if (name == null) { new HttpSessionBindingEvent(this, name); ((HttpSessionBindingListener)value).valueBound(e); HttpSessionBindingEvent e = if (value != null && value instanceof HttpSessionBindingListener) { values.put(name, value); public Object getAttribute(String name) { return getAttribute(name); public Object getValue(String name) { return values.get(name); public String[] getValueNames() { names.addElement(e.nextElement()); while (e.hasMoreElements()) { Vector names = new Vector(); Enumeration e = getAttributeNames(); names.copyInto(valueNames); String[] valueNames = new String[names.size()]; public Enumeration getAttributeNames() { return valueNames; return (Enumeration)valuesClone.keys(); Hashtable valuesClone = (Hashtable)values.clone(); public void removeAttribute(String name) { removeAttribute(name); public void removeValue(String name) { Object o = values.get(name); ((HttpSessionBindingListener)o).valueUnbound(e); new HttpSessionBindingEvent(this,name); if (o instanceof HttpSessionBindingListener) { public void setMaxInactiveInterval(int interval) { values.remove(name); public int getMaxInactiveInterval() { inactiveInterval = interval; return inactiveInterval; // * Core implementation of a server session public class ServerSession { private Hashtable appSessions = new Hashtable(); ServerSession(String id) { (ApplicationSession)appSessions.get(context); ApplicationSession appSession = public ApplicationSession getApplicationSession(Context context, boolean create) { // sync to ensure valid? appSession = new ApplicationSession(id, this, context); // XXX if (appSession == null && create) { appSessions.put(context, appSession); return appSession; // a new appSession // inactive interval -- if so, invalidate and create // make sure that we haven't gone over the end of our appSessions.remove(context); void removeApplicationSession(Context context) { void validate() ynchronized void invalidate() { Enumeration enum = appSessions.keys(); appSession.invalidate(); (ApplicationSession)appSessions.get(key); Object key = enum.nextElement(); String msg = sm.getString("serverSession.value.iae"); return values.keys(); public Enumeration getValueNames() { synchronized void reap() { // sync'd for safty -- no other thread should be getting something // solution for this, but we'll determine something else later. // from this while we are reaping. This isn't the most optimal appSession.validate(); ; * Standard implementation of the <b>Session</b> interface. This object is * <b>IMPLEMENTATION NOTE</b>: An instance of this class represents both the * <p> * to a different JVM for distributable session support. * serializable, so that it can be stored in persistent storage or transferred * internal (Session) and application level (HttpSession) view of the session. * HttpSession view of this instance back to a Session view. * of the <code>org.apache.tomcat.session</code> package cannot cast an * However, because the class itself is not declared public, Java logic outside $Revision: 1.2 $ $Date: 2000/05/15 17:54:10 $ Craig R. McClanahan // Constructors implements HttpSession, Session { final class StandardSession * Construct a new Session associated with the specified Manager. this.manager = manager; super(); public StandardSession(Manager manager) { manager The manager with which this Session is associated * The last accessed time for this Session. private Manager manager = null; * The Manager with which this Session is associated. * the servlet container may invalidate this session. A negative time * The maximum time interval, in seconds, between client requests before private int maxInactiveInterval = -1; * indicates that the session should never time out. private boolean isNew = true; * Flag indicating whether this session is new or not. * The string manager for this package. private boolean isValid = false; * Flag indicating whether this session is valid or not. private static HttpSessionContext sessionContext = null; * The HTTP session context associated with this session. private long thisAccessedTime = creationTime; * The current accessed time for this session. // Session Properties * Set the creation time for this session. This method is called by the public void setCreationTime(long time) { time The new creation time * Manager when an existing Session instance is reused. this.thisAccessedTime = time; this.creationTime = time; * Return the session identifier for this session. return (this.id); * Set the session identifier for this session. (manager instanceof ManagerBase)) ((ManagerBase) manager).remove(this); public void setId(String id) { id The new session identifier if ((this.id != null) && (manager != null) && ((ManagerBase) manager).add(this); if ((manager != null) && (manager instanceof ManagerBase)) * Return descriptive information about this Session implementation and public String getInfo() { * <code><description>/<version></code>. * the corresponding version number, in the format return (this.info); * Return the Manager within which this Session is valid. return (this.manager); public Manager getManager() { public void setManager(Manager manager) { manager The new Manager * Set the Manager within which this Session is valid. * before the servlet container will invalidate the session. A negative * Return the maximum time interval, in seconds, between client requests * an invalidated session IllegalStateException if this method is called on * time indicates that the session should never time out. return (this.maxInactiveInterval); * Perform the internal processing required to invalidate this session, // Remove this session from our manager's active sessions public void expire() { * without triggering an exception if the session has already expired. results.addElement(attr); String attr = (String) attrs.nextElement(); while (attrs.hasMoreElements()) { // Unbind any objects associated with this session Vector results = new Vector(); Enumeration attrs = getAttributeNames(); String name = (String) names.nextElement(); while (names.hasMoreElements()) { Enumeration names = results.elements(); setValid(false); // Mark this session as invalid isNew The new value for the <code>isNew</code> flag * Set the <code>isNew</code> flag for this session. void setNew(boolean isNew) { this.isNew = isNew; isValid The new value for the <code>isValid</code> flag * Set the <code>isValid</code> flag for this session. void setValid(boolean isValid) { // HttpSession Properties this.isValid = isValid; * Return the time when this session was created, in milliseconds since * invalidated session IllegalStateException if this method is called on an * midnight, January 1, 1970 GMT. return (this.creationTime); * Return the session context with which this session is associated. * Java Servlet API. * replacement. It will be removed in a future version of the As of Version 2.1, this method is deprecated and has no return (sessionContext); sessionContext = new StandardSessionContext(); if (sessionContext == null) // HttpSession Public Methods name Name of the attribute to be returned * <code>null</code> if no object is bound with that name. * Return the object bound with the specified name in this session, or return (attributes.get(name)); * containing the names of the objects bound to this session. * Return an <code>Enumeration</code> of <code>String</code> objects return (attributes.keys()); name Name of the value to be returned As of Version 2.2, this method is replaced by return (getAttribute(name)); * <code>getAttribute()</code> * are no such objects, a zero-length array is returned. * Return the set of names of objects bound to this session. If there * <code>getAttributeNames()</code> return (names); names[i] = (String) results.elementAt(i); for (int i = 0; i < names.length; i++) String names[] = new String[results.size()]; * Invalidates this session and unbinds any objects bound to it. // Cause this session to expire expire(); * example, if the server used only cookie-based sessions, and the client * session, or if the client chooses not to join the session. For * Return <code>true</code> if the client does not yet know about the * request. * has disabled the use of cookies, then a session would be new on each return (this.isNew); * Remove the object bound with the specified name from this session. If * does nothing. * the session does not have an object bound with this name, this method name Name of the object to remove from this session. * <code>valueUnbound()</code> on the object. * <code>HttpSessionBindingListener</code>, the container calls * After this method executes, and if the object implements Object object = attributes.get(name); synchronized (attributes) { ((HttpSessionBindingListener) object).valueUnbound (new HttpSessionBindingEvent((HttpSession) this, name)); if (object instanceof HttpSessionBindingListener) { // System.out.println( "Removing attribute " + name ); if (object == null) return; attributes.remove(name); * replaced. * Bind an object to this session, using the specified name. If an object * of the same name is already bound to this session, the object is value Object to be bound, cannot be null * <code>valueBound()</code> on the object. name Name to which the object is bound, cannot be null * non-serializable object in an environment marked distributable. IllegalArgumentException if an attempt is made to add a throw new IllegalArgumentException attributes.put(name, value); (sm.getString("standardSession.setAttribute.iae")); if ((manager != null) && manager.getDistributable() && !(value instanceof Serializable)) ((HttpSessionBindingListener) value).valueBound if (value instanceof HttpSessionBindingListener) // HttpSession Private Methods * <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager * is not restored by this method, and must be set explicitly. * object input stream. * Read a serialized version of this session object from the specified IOException if an input/output error occurs ClassNotFoundException if an unknown class is specified stream The input stream to read from creationTime = ((Long) stream.readObject()). isValid = ((Boolean) stream.readObject()).booleanValue(); // Deserialize the scalar instance variables (except Manager) throws ClassNotFoundException, IOException { private void readObject(ObjectInputStream stream) String name = (String) stream.readObject(); for (int i = 0; i < n; i++) { Object value = (Object) stream.readObject(); int n = ((Integer) stream.readObject()).intValue(); // Deserialize the attribute count and attribute values * in the serialized representation of this Session. After calling * <code>readObject()</code>, you must set the associated Manager * <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored * object output stream. * Write a serialized version of this session object to the specified * be sure the <code>distributable</code> property of our associated * Manager is set to <code>true</code>. * will be silently ignored. If you do not want any such attributes, * explicitly. * <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable private void writeObject(ObjectOutputStream stream) throws IOException { stream The output stream to write to stream.writeObject(new Integer(maxInactiveInterval)); stream.writeObject(new Boolean(isNew)); stream.writeObject(new Long(lastAccessedTime)); stream.writeObject(id); // Write the scalar instance variables (except Manager) stream.writeObject(new Long(creationTime)); // Accumulate the names of serializable attributes stream.writeObject(new Boolean(isValid)); // Serialize the attribute count and the attribute values if (value instanceof Serializable) Object value = attributes.get(attr); stream.writeObject(new Integer(results.size())); stream.writeObject(attributes.get(name)); stream.writeObject(name); String[] getValueNames() | void invalidate() | Enumeration getAttributeNames() | Object getAttribute(String) | long getCreationTime() | crosscut invalidate(StandardSession s): s & (int getMaxInactiveInterval() | boolean isNew() | before { if (!s.isValid()) throw new IllegalStateException static advice(StandardSession s): invalidate(s) { void setAttribute(String, Object)); void removeAttribute(String) | + ".ise")); + thisJoinPoint.methodName (s.sm.getString("standardSession." // Private Class * when <code>HttpSession.getSessionContext()</code> is called. * This class is a dummy implementation of the <code>HttpSessionContext</code> * interface, to conform to the requirement that such an object be returned final class StandardSessionContext implements HttpSessionContext { * interface will be removed in a future version of this API. As of Java Servlet API 2.1 with no replacement. The * within this context. As of Java Servlet API 2.1 with no replacement. * Return the session identifiers of all sessions defined private Vector dummy = new Vector(); public Enumeration getIds() { * and will be removed in a future version of the API. * This method must return an empty <code>Enumeration</code> return (dummy.elements()); id Session identifier for which to look up a session * Return the <code>HttpSession</code> associated with the * specified session identifier. public HttpSession getSession(String id) { * future version of the API. * This method must return null and will be removed in a return (null); separated – implementation of a concern can be treated as relatively separate entity localized – implementation of a concern appears in one part of program modular – above + has a clear, well defined interface to rest of system 2018/9/17

19 Crosscutting concerns in a system (横切、交叉划分、跨断)
core module-level requirements and system-level requirements. Many system-level requirements tend to be orthogonal (mutually independent) to each other and to the module-level requirements. System-level requirements also tend to crosscut many core modules. For example, authentication, logging, resource pooling, administration, performance, and storage management. Each crosscuts several subsystems. For example, a storage-management concern affects every stateful business object. 2018/9/17

20 Crosscutting concern problems
the requirement space is an n-dimensional space, whereas the implementation space is one-dimensional. Such a mismatch results in an awkward requirements-to-implementation map. Symptoms(症状): Code tangling ; Code scattering. Implications(导致): Poor traceability, Lower productivity, Less code reuse, Poor code quality, More difficult evolution. The current response: mix-in classes, design patterns, and domain-specific solutions. 2018/9/17

21 The fundamentals of AOP
The modularization unit in AOP is called an aspect, just as a common concern's implementation in OOP is called a class. AOP involves three distinct development steps: Aspectual decomposition , Concern implementation, Aspectual recomposition. 2018/9/17

22 example public class CreditCardProcessor {     public void debit(CreditCard card, Currency amount)        throws InvalidCardException, NotEnoughAmountException,               CardExpiredException {         // Debiting logic(取款)     }     public void credit(CreditCard card, Currency amount)         throws InvalidCardException {         // Crediting logic (存款)     } } public interface Logger {     public void log(String message); } 2018/9/17

23 weaving rules Log each public operation's beginning
Log each public operation's completion Log any exception thrown by each public operation 2018/9/17

24 the weaver would produce composed code :
public class CreditCardProcessorWithLogging {     Logger _logger;     public void debit(CreditCard card, Money amount)          throws InvalidCardException, NotEnoughAmountException,                CardExpiredException {         _logger.log("Starting reditCardProcessor.credit(CreditCard, Money) "+ "Card: " + card + " Amount: " + amount);         // Debiting logic         _logger.log("Completing CreditCardProcessor.credit(CreditCard, Money) "+ "Card: " + card + " Amount: " + amount);      } 2018/9/17

25 public void credit(CreditCard card, Money amount)         throws InvalidCardException {         System.out.println("Debiting");         _logger.log("Starting CreditCardProcessor.debit (CreditCard,Money) “ + "Card: " + card + " Amount: " + amount);         // Crediting logic         _logger.log("Completing CreditCardProcessor.credit (CreditCard, Money) “ + "Card: " + card + " Amount: " + amount);      } } 2018/9/17

26 Anatomy(解剖)of AOP languages
The AOP language specification Implementation of concerns Weaving rules specificationn: a language for specifying rules for composing different implementation pieces to form the final system. AOP language implementation Combine the individual concerns Convert the resulting information into executable code 2018/9/17

27 implement the weaver in various ways
source-to-source translation preprocess source code for individual aspects to produce weaved source code feed this converted code to the base language compiler to produce final executable code. a Java-based AOP implementation convert individual aspects first into Java source code, then let the Java compiler convert it into byte code. The same approach can perform weaving at the byte code leve a VM implementation 2018/9/17

28 AOP benefits AOP helps overcome the problems caused by code tangling and code scattering. Here are other specific benefits AOP offers: Modularized implementation of crosscutting concerns Easier-to-evolve systems Late binding of design decisions More code reuse In general, a loosely coupled implementation represents the key to higher code reuse. AOP enables more loosely coupled implementations than OOP. 2018/9/17

29 Learn AspectJ to better understand aspect-oriented programming
2018/9/17

30 AspectJ: An AOP implementation for Java
AspectJ, from Xerox PARC, is a general-purpose aspect-oriented Java extension. AspectJ uses Java as the language for implementing individual concerns, and it specifies extensions to Java for weaving rules. These rules are specified in terms of : join points (联结点、交汇点 )define specific points in a program's execution, Pointcuts (切入点、指定切入点)is the language construct that specifies join points, Advice(告知) defines pieces of an aspect implementation to be executed at pointcuts, aspects (方面)combines these primitives. AspectJ's weaver -- an aspect compiler -- combines different aspects together. 2018/9/17

31 AspectJ overview AspectJ is a language specification as well as an AOP language implementation. The language specification defines various constructs and their semantics to support aspect-oriented concepts. AspectJ's language constructs extend the Java programming language. The language implementation offers tools for compiling, debugging, and documenting code. AspectJ provides an aspect weaver in the form of a compiler, an aspect-aware debugger and documentation generator, and a standalone aspect browser to visualize how an advice crosscuts a system's parts. 2018/9/17

32 AspectJ language overview
To support AOP, AspectJ adds to the Java language concepts: Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class Pointcuts: Program constructs to designate joinpoints and collect specific context at those points Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint 2018/9/17

33 a simple class containing methods to print a message: HelloWorld
// HelloWorld.java public class HelloWorld {     public static void say(String message) {         System.out.println(message);     }          public static void sayToPerson(String message, String name) {         System.out.println(name + ", " + message);     } } 2018/9/17

34 adding greeting and gratitude manners.
// MannersAspect.java public aspect MannersAspect {     pointcut callSayMessage() : call(public static void HelloWorld.say*(..));     before() : callSayMessage() {         System.out.println("Good day!");     }     after() : callSayMessage() {         System.out.println("Thank you!");     } } 2018/9/17

35 adding greeting and gratitude manners.
The MannersAspect.java file declares a MannersAspect aspect. The aspect defines a callSayMessage() pointcut that captures calls to all public static methods with names that start with say. It would capture say() and sayToPerson() in a HelloWorld class. Then you define two advices for before and after reaching the callSayMessage() pointcut: printing "Good day!" and "Thank you!" // MannersAspect.java public aspect MannersAspect {     pointcut callSayMessage() : call(public static void HelloWorld.say*(..));     before() : callSayMessage() {         System.out.println("Good day!");     }     after() : callSayMessage() {         System.out.println("Thank you!");     } } 2018/9/17

36 AspectJ language concepts and constructs --1
Joinpoints Joinpoints, a central concept in AspectJ, are well-defined points in a program's execution. Candidate joinpoints include calls to a method, a conditional check, a loop's beginning, or an assignment. Joinpoints also have a context associated with them. For example, a method-call joinpoint could have the target object and its argument as part of the context. 2018/9/17

37 AspectJ language concepts and constructs --2
Pointcuts, program constructs to designate joinpoints, let you specify a joinpoint collection. Pointcuts also let you expose context at the joinpoint to an advice implementation. AspectJ makes the following pointcuts available: Method call and execution Constructor call and execution Read/write access to a field Exception handler execution Object and class initialization execution HelloWorld example: pointcut callSayMessage() : call(public static void HelloWorld.say*(..)); 2018/9/17

38 Table 1. Call to methods and constructors pointcuts -- call pointcuts
call(public void MyClass.myMethod(String)) Call to myMethod() in MyClass taking a String argument, returning void, and with public access call(void MyClass.myMethod(..)) Call to myMethod() in MyClass taking any arguments, with void return type, and any access modifiers call(* MyClass.myMethod(..)) Call to myMethod() in MyClass taking any arguments returning any type call(* MyClass.myMethod*(..)) Call to any method with name starting in "myMethod" in MyClass call(* MyClass.myMethod*(String,..)) Call to any method with name starting in "myMethod" in MyClass and the first argument is of String type 2018/9/17

39 Call to myMethod() in any class in default package
call(* *.myMethod(..)) Call to myMethod() in any class in default package call(MyClass.new()) Call to any MyClass' constructor taking no arguments call(MyClass.new(..)) Call to any MyClass' constructor with any arguments call(MyClass+.new(..)) Call to any MyClass or its subclass's constructor. (Subclass indicated by use of '+' wildcard) call(public * com.mycompany..*.*(..)) All public methods in all classes in any package with com.mycompany the root package 2018/9/17

40 Table 2. Execution of methods and constructors pointcuts -- execution pointcuts
execution(public void MyClass.myMethod(String)) Execution of myMethod() in MyClass taking a String argument, returning void, and with public access execution(void MyClass.myMethod(..)) Execution of myMethod() in MyClass taking any arguments, with void return type, and any access modifiers execution(* MyClass.myMethod(..)) Execution of myMethod() in MyClass taking any arguments returning any type execution(* MyClass.myMethod*(..)) Execution of any method with name starting in "myMethod" in MyClass execution(* MyClass.myMethod*(String,..)) Execution of any method with name starting in "myMethod" in MyClass and the first argument is of String type 2018/9/17

41 execution(* *.myMethod(..))
Execution of myMethod() in any class in default package execution(MyClass.new()) Execution of any MyClass' constructor taking no arguments execution(MyClass.new(..)) Execution of any MyClass' constructor with any arguments execution(MyClass+.new(..)) Execution of any MyClass or its subclass's constructor. (Subclass indicated by use of '+' wildcard) execution(public * com.mycompany..*.*(..)) All public methods in all classes in any package with com.mycompany the root package 2018/9/17

42 Table 3. Field-access pointcuts
get(PrintStream System.out) Execution of read-access to field out of type PrintStream in System class set(int MyClass.x) Execution of write-access to field x of type int in MyClass Table 4. Exception-handler pointcuts handler(RemoteException) Execution of catch-block handling RemoteException type handler(IOException+) Execution of catch-block handling IOException or its subclasses handler(CreditCard*) Execution of catch-block handling exception types with names that start with CreditCard 2018/9/17

43 Table 5. Class-initialization pointcuts
staticinitialization(MyClass) Execution of static block of MyClass Staticinitialization(MyClass+) Execution of static block of MyClass or its subclasses Table 6. Lexical-structure-based pointcuts within(MyClass) Any pointcut inside MyClass's lexical scope within(MyClass*) Any pointcut inside lexical scope of classes with a name that starts with "MyClass" withincode(* MyClass.myMethod(..)) Any pointcut inside lexical scope of any myMethod() of MyClass 2018/9/17

44 Table 7. Control-flow-based pointcuts
cflow(call(* MyClass.myMethod(..)) All the joinpoints in control flow of call to any myMethod() in MyClass including call to the specified method itself cflowbelow(call(* MyClass.myMethod(..)) All the joinpoints in control flow of call to any myMethod() in MyClass excluding call to the specified method itself Table 8. Self-, target-, and arguments-type pointcuts this(JComponent+) All the joinpoints where this is instanceof JComponent target(MyClass) All the joinpoints where the object on which the method is called is of type MyClass args(String,..,int) All the joinpoints where the first argument is of String type and the last argument is of int type args(RemoteException) All the joinpoints where the type of argument or exception handler type is RemoteException 2018/9/17

45 Table 9. Conditional-test pointcuts
if(EventQueue.isDispatchThread()) All the joinpoints where EventQueue.isDispatchThread() evaluates to true Named and anonymous pointcuts Use ||, &&, and ! operators with pointcuts For example, call(* MyClass.m1()) || call(* MyClass.m2()) call(* MyClass.m1()) && cflow(call(* MyClass.m2()) !call(* MyClass.m1()) 2018/9/17

46 Exposing context AspectJ offers target(), this(), and args() pointcuts to collect the context. For example, pointcut publicOperationCardAmountArgs(CreditCard card, Money amount):         execution(public * CreditCardProcessor.*(..)) && args(card, amount); 2018/9/17

47 AspectJ language concepts and constructs --3
Advices specify the executable code when reaching certain pointcuts. AspectJ provides three ways to associate an advice with a joinpoint: A before advice runs just before the joinpoint, whereas an after advice runs just after. An around advice surrounds a joinpoint and has control if the joinpoint's execution should proceed. 2018/9/17

48 before() : call(public. MyClass. (. )) { System. out
before() : call(public * MyClass.*(..)) {         System.out.println("Before: " + thisJoinPoint + " " + System.currentTimeMillis()); } after() : call(public * MyClass.*(..)) {         System.out.println("After: " + thisJoinPoint + " " + System.currentTimeMillis()); } void around(Connection conn) : call(Connection.close()) && target(conn) {     if (enablePooling) {         connectionPool.put(conn);     } else {         proceed();     } } 2018/9/17

49 AspectJ language concepts and constructs --4
Aspects act as AspectJ's unit of modularization. It puts together pointcuts and advices. Aspects resemble classes: an aspect can contain methods and fields, extend other classes or aspects, and implement interfaces. However, you cannot create an object for an aspect using new. AspectJ does not allow classes to contain advices; only aspects can contain advices. A concrete aspect extending an abstract aspect can then provide concrete definitions of abstract pointcuts. 2018/9/17

50 AspectJ examples Example 1: Detect a Swing UI (user interface) update from a nonevent dispatch thread Example 2: Authentication Example 3: Add Japanese manners to HelloWorld 2018/9/17

51 Research Projects: Supported Systems:
AspectC++, AspectJ, AspectR, AspectS,… Research Prototypes: Applications: Methods & Foundations: 2018/9/17

52 Supported Systems: ANGIE Generation Now! provides a new frame processor language to implement generators, e.g., aspect weavers. AspectC++ is an aspect-oriented extension to the C++ programming language. AspectJ is a seamless aspect-oriented extension to Java that enables the modular implementation of a wide range of crosscutting concerns. AspectR is aspect-oriented programming for Ruby that allows you to wrap code around existing methods in your classes. AspectS is an early prototype that enables aspect-oriented programming in the Squeak/Smalltalk environment. 2018/9/17

53 JAC is a Java framework for aspect-oriented distributed programming.
AspectWerkz is a dynamic, lightweight and high-performant AOP/AOSD framework for Java. Caesar is an aspect-oriented programming language that focusses on multi-view decomposition and aspect reusability. DemeterJ and DJ facilitate the structure-shy encapsulation of traversal-related behavioral concerns. Hyper/J supports "multi-dimensional" separation and integration of concerns in standard Java software. JAC is a Java framework for aspect-oriented distributed programming. JAsCo is an aspect-oriented programming language tailored for component basedsoftware development. JMangler is a framework for load-time transformation of Java programs, whichsupports conflict-free composition of independently developed aspects(implemented as JMangler transformer components) and their joint application to existing base classes. 2018/9/17

54 MixJuice is an extension to Java, based on the difference-based module mechanism.
Mozart Programming System is an advanced development platform for intelligent, distributed applications. Object Everywhere - An article describing an AOP Framework based on COM with Delphi. PROSE is an AOP platform based on the Java Virtual Machine that allows dynamic weaving and un-weaving. SmartTools is an Aspect- and XML-oriented Semantic Framework Generator. UMLAUT is a framework that weaves multi-dimensional high level UML design models into detailed design models suitable for either implementation, simulation or validation. xlinkit checks the consistency of, and generates links between, distributed documents; it builds on a long line of research into the management of consistency across multiple views. 2018/9/17

55 Research Prototypes Apostle is an AspectJ-like aspect-oriented extension to Smalltalk. ArchJava extends Java with explicit software architecture constructs, separating out structural concerns that would otherwise crosscut the system. Aspect Browser is a graphical tool that uses the map metaphor to assist finding, exploring, and manipulating crosscutting concerns in software. Aspect Mining Tool (AMT) is a tool for identification and exploring latent concerns in software systems. AspectC is a simple AspectJ-like AOP extension to C. AspectC# explores adding AspectJ-style aspect support to C#. Aspect.pm is a set of Perl libraries for aspect-oriented programming. 2018/9/17

56 JADE is an extension to Java that allows for noninvasive composition.
ComposeJ is an extension of the java language that adds composition filters to Java classes through inlining. Concern Graphs are a manipulable representation of concerns that can be extracted from an existing code base. ConcernJ integrates the concepts of aspects, classes and Composition Filters into 'concerns'; this prototype demonstrates the transformation of (languageindependent) concern specifications and java classes into executable composition filters and java files. EAOP is an approach to AOP for Java with expressive crosscuts, explicit aspect composition, aspects of aspects, and dynamic aspect management. ISL is an aspect-oriented service which allows to ynamically express nonfunctional properties in terms of "interactions". JADE is an extension to Java that allows for noninvasive composition. 2018/9/17

57 JMunger is a tool to insert Java code into existing classes at load time.
MetaclassTalk is a reflective extension of Smalltalk that provides a MOP which can be used for AOP. Object Teams is a programming model that combines well explored concepts like role objects, collaborations, method interception, virtual types and dynamic aspect activation, introducing only a fairly small number of language constructs. The model is realized within the host languages Lua, Ruby and Java. Pythius is an open-source project to support aspect-oriented programming techniques in Python. QSOUL/Aop is an Aspect Oriented Logic Meta Programming tool in Squeak/Smalltalk. Weave.NET aims to provide a language independent mechanism for supporting the AspectJ notion of AOP that is also consistent with the component model of the .NET Framework. 2018/9/17

58 Applications a-kernel is an effort to apply AOP techniques to operating system kernel code. FACET is a framework for a customizable real-time event channel that uses aspects. Lasagne is an aspect-oriented architecture for context-sensitive and run-time weaving of aspects--prototypes have been developed in Java and Correlate. PacoSuite is a visual component composition environment which supports aspect oriented software development using the JAsCo programming language. 2018/9/17

59 QuO is a middleware framework and toolkit which includes aspect-oriented languages for developing quality of service enabled, adaptive distributed object applications. SoC+MAS is a research project whose main focus is the application of advanced separation of concerns techniques to handle the complexity of designing and implementing multi-agent OO software. SADES is a customizable and extensible object database evolution system implemented using AOP techniques. 2018/9/17

60 Methods & Foundations Afanti is a project aimed at developing techniques and tools to support testing and analysis of aspect-oriented software. AOPim is a method for the progressive implementation of persistent, distributed, and concurrent applications using aspect-oriented programming. Aspect-Oriented Component Engineering uses the concept of horizontal slices through vertically-decomposed components called aspects to characterize crosscutting properties of components. Aspect-Oriented Frameworks is research on frameworks for aspect-oriented software development. Aspect-Oriented Software Engineering aims to develop support for aspects throughout the development life cycle--specific application areas include middleware, component-based systems and databases. 2018/9/17

61 Assessment: Does AOP Work
Assessment: Does AOP Work? uses case study and experimental methods to evaluate AOP techniques and tools. Composition Filters model is a modular extension to the object-oriented model that allows the modular specification of aspects in a composable way. Cosmos is a concern-space modeling schema that supports the modeling of multidimensional concern spaces for purposes of software composition, decomposition, analysis, and understanding. D2AL provides a methodology, an aspect language and tools that support the development of robust and efficient distributed applications. Demeter Aspects points to Demeter subprojects about the foundations of the separation of crosscutting concerns. DisCo is a formal specification method that supports advanced separation of concerns for distributed reactive systems. 2018/9/17

62 Dynamic Aspect-Oriented Platform defines a distributed platform that provides dynamic composition between components and aspects as plug-ins. Event-based AOP is a formal framework for AOP featuring expressive crosscut definitions. Filter Objects Project is a project on first-class dynamically-pluggable filter objects and related modeling methods and notations. Implicit Context is an approach to improving the reusability and evolvability of systems through the reduction of extraneous embedded knowledge. Phoenix is an an Aspect-Oriented Approach for Software Reengineering using Transformations. Prospects is a project aimed at investigating how aspect oriented components can be used to derive useful models of specific concerns. 2018/9/17

63 Theme/UML is an aspect-oriented extension to the UML.
Quality Controlled Component-based Software Development (QCCS) is a project that is developing a methodology and supporting tools for the creation of components with contracts and based on AOSD. Semantics of Aspect-Oriented Programming (SAOP) is an effort to study constructs for AOP (e.g. method call interception), in particular their language design, their formal semantics, and their relation to program transformation. Synbad is an architecture design approach for identifying and composing architectural aspects. Theme/UML is an aspect-oriented extension to the UML. Vanderbilt/ISIS is working in the area of applying core AOP principles toward domain-specific visual modeling languages. XBel is a framework for reasoning about compositions of concerns on the requirements level. 2018/9/17

64 Early Aspects:  Aspect-Oriented Requirements Engineering and Architecture Design
In a fashion similar to object-orientation, aspect-orientation is following a cycle of natural progression from programming to other software development stages. Employing an aspect-oriented approach from the very early development stages can help capture crosscutting properties early on in the software life cycle; hence, improving the quality of the products and reducing adaptation, evolution and maintenance costs. 2018/9/17

65 concern validation at early software development stages;
processes and techniques for aspect-orientation at early software development stages; formalisms and notations for specifying aspects at early software development stages; aspect composition issues and mechanisms including those relating to composition with existing separation of concerns mechanisms such as viewpoints, architectural patterns and architecture trade-off analysis, and composition with life cycle concerns; role of aspects to improve requirements evolution and architecture adaptability; concern validation at early software development stages; mapping and influence of requirements and domain aspects to architecture design and later software development stages; 2018/9/17

66 integration of aspects with modeling mechanisms such as UML;
aspect dependencies and interactions at early software development stages; integration of aspects with modeling mechanisms such as UML; role of early aspects in the development of test cases to be used during verification and validation; tool support and automation for aspect-orientation at early software development stages 2018/9/17

67 well-planned usage While aspect oriented techniques can often produce better programs, sometimes aspect oriented mechanisms lead to unpredictable or incorrect results. Hence, a well-planned usage of such new mechanisms is a premise for the successful application of aspect-orientation. 2018/9/17

68 DisCo (Distributed Co-operation)
DisCo is a formal specification method for reactive systems. It incorporates a specification language, a methodology for developing specifications using the language, and tool support for the methodology. Currently the support tools include an animation facility for executing specifications, a tool for visualizing execution histories as scenarios, and a link to a mechanical theorem prover for verification. DisCo is currently funded by the Academy of Finland,Tise (Tampere graduate school in Information Science And Engineering) and Tekes(The Technology Development Center of Finland). 2018/9/17

69 DisCo Home Page http://disco.cs.tut.fi/
Mika Katara and Tommi Mikkonen. Aspect-Oriented Specification Architectures for Distributed Real-Time Systems. In Sten F. Andler, Michael G. Hinchey, and Jeff Offutt, editors, Proceedings of the Seventh IEEE International Conference on Engineering of Complex Computer Systems, ICECCS 2001, pages , Skövde, Sweden, June IEEE Computer Society Press. Pertti Kellomäki. Composing Distributed Systems from Reusable Aspects of Behavior. In Proceedings of ICDCS'02 Workshops. IEEE Press, 2002. 2018/9/17

70 AspectGAMMA GAMMA is an abstract language, based on multiset rewriting on a shared dataspace, designed to support parallel execution of a program on parallel and/or distributed architectures. AspectGAMMA is an extension to the GAMMA formalism. Aspects + GAMMA = AspectGAMMA A Formal Framework for Aspect-Oriented Specification. 2018/9/17

71 Object teams Split Object
Stephan Herrmann. Object teams: Improving modularity for crosscutting collaborations. In Proc. Net Object Days 2002. Split Object Daniel Bardou. Towards a Platform for Experimenting with Split Objects in Java and AspectJ Proceedings of the Third German AOSD-Workshopof the SIG Object-Oriented Software Development, March 4-5, Essen, Germany 2018/9/17

72 Semantics of aspect-oriented programming
R. L¨ammel. A Semantical Approach to Method-Call Interception. In Proc. of the 1st International Conference on Aspect-Oriented Software Development (AOSD 2002), pages 41–55, Twente, The Netherlands, Apr ACM Press. R. L¨ammel. Adding Superimposition To a Language Semantics (FOAL'03) 2018/9/17

73 FOAL: Foundations of Aspect-Oriented Languages
Proceedings mar, 2003, Boston, semantics of aspect-oriented languages, specification and verification or such languages, type systems, static analysis, theory of testing, theory of aspect composition, theory of aspect translation (compilation) and rewriting, and applications of such theories in practice (such as language design studies). The workshop aims to foster work in foundations, including formal studies, promote the exchange of ideas, and encourage workers in the semantics and formal methods communities to do research in the area of aspect-oriented programming languages. 2018/9/17

74 Aspect-Oriented Modeling with UML
Workshop on Aspect-Oriented Modeling with UML (AOSD-2002 , mar), { Second International Workshop on Aspect-Oriented Modeling with UML sep, 2002, { Third International Workshop on Aspect Oriented mar, 2003, Boston { This workshop is dedicated to the definition of aspect-oriented modeling techniques, methods and tools based on UML. Suggested issues are: 2018/9/17

75 How can we apply UML artifacts to AOSD?
Are the existing notations and modeling techniques of UML sufficient to model aspects, or do we need to extend UML to support AOSD? Is UML the appropriate modeling language on which to base modeling for AOSD? Is UML capable of expressing "Core" components and "Aspectual" components as well as associations linking them together? If we have to extend the UML, are the extension mechanisms provided by UML adequate? What could then be a UML profile for AOSD? Or would it be possible to rely only on a restricted subset of the UML for AOSD? What would this subset be? 2018/9/17

76 结束语 面向方面的软件开发方法,作为一种新的方法,新的动向,应当给予高度的关注和重视。
跟踪当代世界新技术潮流,学习,消化,研究,然后创新,应用,产业化,这是我们的技术路线和方针,也是我们的义不容辞的责任。 新技术是实践中产生的,但是需要进一步的深化、理论上的提高和研究。这为我们提供了广阔的空间。 目前这方面我们同国外的差距并不大,开展这方面的研究不失是一个好的方向。 2018/9/17

77 谢谢大家! 郝克刚 西北大学计算机科学系 软件工程研究所
本讲稿放在如下网站: 谢谢大家! 郝克刚 西北大学计算机科学系 软件工程研究所 2018/9/17


Download ppt "郝克刚 西北大学计算机科学系 (为研究生们作的报告)"

Similar presentations


Ads by Google