How to enforce programming restrictions using Aspect Oriented Programming

Objectives

Using AOP (AspectJ), we will see how to enforce EJB programming restrictions as specified in section 25.1.2 "Programming Restrictions" of the EJB specification.
Please note that AOP can be also used, among many other things, to check authorization at runtime!
This is not a training course about AOP!

Writing an Aspect


public aspect EJBRestrictionsAspect { ...
  /**
   * The classes that are EnterpriseBeans
   */
   pointcut JyperionEJB() : within(javax.ejb.EnterpriseBean+);

All 'static' fields must be 'final'

The following code will tell the compiler not to compile if one of your EJBs as some 'static' or 'final' fields:

/**
 * 1) Static member access
 */
 pointcut staticMembers() : set(static * javax.ejb.EnterpriseBean+.*);
	
/**
 * Declare error if you set a static member
 */
 declare error : staticMembers() :
   "[AspectJ] You must only use 'static final' variables. See the EJB 2 specification - section 25.1.2";

No threads


/**
 * 2) No Thread use
 */
 pointcut threadUse() : call (* java.lang.Thread+.*(..)) ||
	                call (java.lang.Thread+.new(..));
	
/**
 * Declare error: No use of threads
 */
 declare error: threadUse() && JyperionEJB() :
   "[AspectJ] You must to use threads. See the EJB 2 specification - section 25.1.2";

No AWT


/**
 * 3) No AWT Calls
 */
 pointcut uiCalls() : call (* java.awt.*+.*(..));
	
/**
 * Declare error for direct AWT calls
 */
 declare error : uiCalls() && JyperionEJB() : 
   "[AspectJ] AWT calls are forbidden by the EJB 2 specification - section 25.1.2";
	
/**
 * Calls to libs that would call AWT calls from within the EJBs
 */
before() : uiCalls() && cflow(call(* javax.ejb.EnterpriseBean+.*(..))) {
   log("[AspectJ] AWT calls are forbidden by the EJB 2 specification - section 25.1.2");
   Thread.dumpStack();
}

No use of native libraries


/**
 * 10) No use of native libs
 */
 pointcut nativeCalls() : call(native * *.*(..));
	
/**
 * Declare error: No native calls
 */
 declare error : nativeCalls() && JyperionEJB() :
   "[AspectJ] Calls to native libraries strictly not allowed. See EJB 2 specification = section 25.1.2";