AspectWerkz - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

AspectWerkz

Description:

AspectWerkz. Jonas Bon r. Senior Software Engineer. BEA Systems. dynamic AOP for Java ... Nanning and Spring (dynamic proxy based) ... – PowerPoint PPT presentation

Number of Views:109
Avg rating:3.0/5.0
Slides: 47
Provided by: jonas2
Category:

less

Transcript and Presenter's Notes

Title: AspectWerkz


1
JavaPolis 2003
AspectWerkz
dynamic AOP for Java
Jonas Bonér Senior Software Engineer BEA System
s
2
Overall Presentation Goal
  • Learn how to use the
  • AspectWerkz AOP framework
  • to enable AOP in real-world
  • enterprise applications

3
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

4
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

5
Limitations
  • AspectJ
  • too academic, steep learning curve
  • not dynamic
  • language extension
  • Nanning and Spring (dynamic proxy based)
  • join point model very limited (interception on
    callee side)
  • not high-performant (uses reflection)
  • BEAs AspectSystem
  • not vendor and/or platform independent
  • only a hooking mechanism
  • JBoss AOP
  • no JVM wide hook (uses custom class loader)

6
Requirements
  • Pure Java
  • XML and runtime attribute definition
  • Easy to learn and use

Usability
Dynamicity
  • Dynamic runtime model
  • Hot-deployment of aspects, advices and
    introductions

Ease of integration
  • Platform and vendor independent
  • Runtime bytecode weaving and static compilation

Production quality
  • Lightweight and high-performant
  • Tool support (debugging etc.)
  • AspectWerkz

7
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

8
Pointcut pattern language
  • Fine-grained pattern language for picking out
    join points
  • Pattern format
  • type package.class.method(types)
  • String foo.baz.Bar.method(int, Object)
  • Supports wildcards
  • foo.baz.Bar.(..)
  • foo...(..)
  • Subtype patterns
  • foo.baz.Bar
  • Can be composed
  • (pc1 pc2) pc3
  • pc1 !pc3

9
Pointcut types
  • Execution - picks out join points defining method
    execution (callee side)
  • Call - picks out join points defining method call
    (caller side)
  • Get/Set - picks out join points defining field
    access or modification
  • Cflow - picks out join points defining a control
    flow
  • Throws - picks out join points defining where an
    exception is thrown out of a method

10
Deployment models
  • Defines the scope or life-cycle of the advice
    or introduction
  • AspectWerkz supports four different deployment
    models
  • perJVM - one sole instance per JVM (singleton)
  • perClass - one instance per target class
  • perInstance - one instance per target class
    instance
  • perThread - one instance per thread

11
Advices
  • Allows you to add additional code at matching
  • pointcuts
  • Three types of advices
  • Around advice - is invoked around the join
    point
  • After advice - is invoked after the join point
  • Before advice - is invoked before the join point

12
Advices
  • Example around advice

public Object myAdvice(JoinPoint joinPoint) thro
ws Throwable // do stuff Object result
joinPoint.proceed() // do more stuff
return result
13
Join point introspection
  • Each advice is passed a JoinPoint instance
  • Allows introspection possibilities
  • RTTI about a specific join point
  • For example at a execution join point could we
    get
  • target instance and class
  • method instance
  • parameter values and types
  • return value and type
  • Possible to modify parameters and return value at
    runtime

14
Mixins
  • Introductions allows you to add code to existing
    classes
  • Implemented in AspectWerkz using mixins
  • Mixins are
  • a way of simulating multiple inheritance
  • common in dynamic languages like Ruby, CLOS and
    Groovy
  • The mixin must consist of
  • an interface
  • an implementation of that interface
  • The mixin implementation can be any regular Java
    class

15
Mixins
perJVM
perClass
perInstance
perThread
target instance
16
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

17
Definition models
  • Supports two different definition models
  • XML
  • Runtime attributes
  • XML definition model
  • Advantages
  • Widely used and intuitive format
  • Great tool support
  • Disadvantages
  • Separates the implementation from the definition
  • Overly complex, hard to read
  • No refactoring support

18
Runtime attribute definition model
  • Aspect components
  • aspects are self-defined and self-contained
  • implementation and definition in one single
    class
  • supports abstraction and inheritance
  • easy to build reusable aspect libraries
  • Custom runtime attributes implementation
  • JavaDoc tags (parsed using QDox)
  • attributes inserted in bytecode of compiled
    class/method/field
  • ready for JSR-175 (Metadata Facility for Java)

19
Runtime attribute definition model
  • Example
  • / _at_Aspect perInstance /
  • public class LoggingAspect extends Aspect

/ _at_Call foo.bar..(..) /
Pointcut logMethodCall / _at_Execution
foo.baz..(..) / Pointcut logMethodExecut
ion
/ _at_Before logMethodCall / public void logEntry
(JoinPoint joinPoint) ... / _at_After
logMethodCall / public void logExit(JoinPoint jo
inPoint) ... / _at_Around logMethodE
xecution / public Object logExecution(JoinPoint
joinPoint) ...
20
Runtime attribute definition model
  • Example mixin
  • /
  • _at_Aspect perInstance
  • /
  • public class PersistenceAspect extends Aspect
  • ... // advices and pointcuts
  • /
  • _at_Introduce ..domain.
  • /
  • public class PersistableMixin extends MyBase
  • implements Persistable, Traceable, Metered

  • ... // implementation of the mixin
  • ... // more mixins

21
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

22
Real-world examples
  • Good candidates for AOP
  • role based security
  • transaction demarcation
  • persistence
  • lazy loading
  • eager loading (loading policies)
  • asynchronous calls
  • synchronization
  • virtual mock objects for unit testing
  • performance optimization
  • design patterns
  • business rules
  • pure mixin based implementations (quantum AOP)

23
Role Based Security
24
Role Based Security
  • Abstract aspect with pointcuts
  • /
  • _at_Aspect perThread
  • /
  • public abstract class AbstractRoleBasedAccessProto
    col
  • extends Aspect
  • protected Subject m_subject null
  • protected final SecurityManager
    m_securityManager ...
  • / To be defined by the concrete aspect. /
  • Pointcut authenticationPoints
  • / To be defined by the concrete aspect. /
  • Pointcut authorizationPoints
  • ... // advices

25
Role Based Security
  • Authentication advice
  • /
  • _at_Around authenticationPoints
  • /
  • public Object authenticateUser(JoinPoint
    joinPoint)
  • throws Throwable
  • if (m_subject null)
  • // no subject authentication required
  • Context ctx ... // get the principals
    and credentials
  • m_subject m_securityManager.authenticate(
    ctx)
  • Object result Subject.doAsPrivileged(
  • m_subject, new PrivilegedExceptionAction()

  • public Object run() throws Exception
  • return joinPoint.proceed()
  • , null
  • )

26
Role Based Security
  • Authorization advice
  • /
  • _at_Around authorizationPoints
  • /
  • public Object authorizeUser(JoinPoint joinPoint)

  • throws Throwable
  • MethodJoinPoint jp (MethodJoinPoint)joinPoint

  • if (m_securityManager.checkPermission(
  • m_subject,
  • jp.getTargetClass(),
  • jp.getMethod()))
  • // user is authorized proceed
  • return joinPoint.proceed()
  • else
  • throw new SecurityException(...)

27
Role Based Security
  • Concrete aspect
  • /
  • _at_Aspect perThread
  • /
  • public class RoleBasedAccessProtocol
  • extends AbstractRoleBasedAccessProtocol
  • /
  • _at_Execution testapp.facade..(..)
  • /
  • Pointcut authenticationPoints
  • /
  • _at_Execution testapp.service..(..)
  • /
  • Pointcut authorizationPoints

28
Unit Of Work
  • Unit Of Work
  • Common pattern in enterprise application
    architectures
  • Implements a transaction
  • Keeps track of new, removed and dirty objects
  • Can be used to implement
  • Transaction demarcation for POJOs
  • Persistence handling for POJOs

29
Unit Of Work
  • UnitOfWork API

public class UnitOfWork public static UnitO
fWork begin() public void commit()
public void rollback() // registers th
e transactional objects public void registerN
ew(Object obj) public void registerRemove
d(Object obj) public void registerDirty(O
bject obj) // template methods publi
c void doBegin() public void doCommit()
public void doRollback()
public class JtaAwareUnitOfWork extends
UnitOfWork public void doBegin() p
ublic void doCommit() public void doRollb
ack()
30
Unit Of Work
  • Problems with regular non-AOP implementation
  • Is a cross-cutting concern
  • Introduces code scattering
  • Introduces code tangling

31
Unit Of Work
  • For example, this code

... Address address new Address(...) customer
.addAddress(address)
...
  • Will have to be replaced by
  • UnitOrWork unitOfWork UnitOfWork.begin()
  • try
  • Address address new Address(...)
  • unitOfWork.registerNew(address)
  • customer.addAddress(address)
  • unitOfWork.registerDirty(customer)
  • unitOfWork.commit()
  • catch(Exception e)
  • unitOfWork.rollback()

32
Unit Of Work
  • Enter Aspect-Oriented Programming
  • Can make the UnitOfWork completely transparent
  • Abstract Aspect
  • / _at_Aspect perJVM /
  • public abstract class AbstractUnitOfWorkProtocol

  • extends Aspect
  • / To be defined by the subclass. /
  • Pointcut transactionalObjectCreationPoints
  • / To be defined by the subclass. /
  • Pointcut transactionalObjectModificationPoin
    ts
  • / To be defined by the subclass. /
  • Pointcut transactionalMethods
  • ... // advices and introductions

33
Unit Of Work
  • Advice - registerNew
  • Registers the newly created object as new
  • /
  • _at_Around transactionalObjectCreationPoints
  • /
  • public Object registerNew(JoinPoint joinPoint)

  • throws Throwable
  • Object newInstance joinPoint.proceed()
  • if (UnitOfWork.isInUnitOfWork())
  • UnitOfWork unitOfWork
  • UnitOfWork.getCurrent()
  • unitOfWork.registerNew(newInstance)
  • return newInstance

34
Unit Of Work
  • Advice - registerDirty
  • Registers an object as dirty just before a field
    is modified
  • /
  • _at_Before transactionalObjectModificationPoints
  • /
  • public void registerDirty(JoinPoint joinPoint)

  • throws Throwable
  • if (UnitOfWork.isInUnitOfWork())
  • FieldJoinPoint jp (FieldJoinPoint)joinPo
    int
  • UnitOfWork unitOfWork
  • UnitOfWork.getCurrent()
  • unitOfWork.registerDirty(
  • jp.getTargetInstance(),
  • jp.getFieldName()
  • )

35
Unit Of Work
  • Advice proceedInTransaction
  • / _at_Around transactionalMethods /
  • public Object proceedInTransaction(JoinPoint
    joinPoint)
  • if (UnitOfWork.isInUnitOfWork())
  • return joinPoint.proceed()
  • UnitOfWork unitOfWork
    UnitOfWork.begin()
  • final Object result
  • try
  • result joinPoint.proceed()
  • if (unitOfWork.isRollbackOnly())
  • unitOfWork.rollback()
  • else
  • unitOfWork.commit()
  • catch (Throwable throwable)
  • throw handleException(throwable,
    unitOfWork)
  • finally
  • UnitOfWork.dispose()

36
Unit Of Work
  • Handle exception method
  • Uses the same approach as in EJB
  • private Throwable handleException(
  • Throwable throwable,
  • UnitOfWork unitOfWork)
  • if (throwable instanceof RuntimeException)

  • unitOfWork.rollback()
  • else
  • unitOfWork.commit()
  • return throwable

37
Unit Of Work
  • Mixin - Transactional
  • Mixin with life-cycle and utility methods
  • Applied to the transactional objects
  • Inner class in the abstract aspect
  • / _at_Introduce TO_BE_DEFINED /
  • public abstract class TransactionalImpl
  • implements Transactional, Serializable
  • public void setRollbackOnly()
  • public UnitOfWork getUnitOfWork()
  • public TransactionContext getTransaction()

  • public void create()
  • public void remove()
  • public void markDirty()
  • public boolean exists()

38
Unit Of Work
39
Test application
40
DEMO
41
Agenda
  • Background
  • Concepts and constructs
  • Definition models
  • Real-world examples
  • Dynamic runtime model
  • Questions

42
Dynamic runtime model
  • Allows you to redefine the system at runtime
  • Swap mixin implementation at runtime
  • SystemLoader.getSystem(systemId).
  • getMixin(oldMixinName).
  • swapImplementation(newMixinClassName)
  • Add new aspects and advices at runtime
  • SystemLoader.getSystem(systemId).createAspect(
  • aspectName,
  • className,
  • DeploymentModel.PER_INSTANCE,
  • classLoader
  • )

43
Dynamic runtime model
  • Reorder advices at runtime
  • Remove advices at runtime
  • List pointcuts SystemLoader.getSystem(systemId
    ).
  • getAspect(aspectName).
  • getPointcuts(className, method)
  • for (Iterator it pointcuts.iterator()
  • it.hasNext())
  • Pointcut pointcut (Pointcut)it.next()
  • if (pointcut.hasAdvice(adviceName))
  • pointcut.removeAdvice(adviceName)

44
Links
  • http//aspectwerkz.codehaus.org/
  • http//wiki.codehaus.org/aspectwerkz
  • http//blogs.codehaus.org/projects/aspectwerkz/
  • http//blogs.codehaus.org/people/jboner/
  • http//blogs.codehaus.org/people/avasseur/
  • http//www.aosd.net/

45
QA
46
JavaPolis 2003
Thanksfor listening
Write a Comment
User Comments (0)
About PowerShow.com