/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.aspects.patterns.observable;

import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.FieldInvocation;
import org.jboss.aop.joinpoint.Invocation;

/**
 * A Subject Interceptor. Traps changes to the object
 * and fires change notifications.
 * 
 * @author <a href="adrian@jboss.com">Adrian Brock</a>
 * @version $Revision: 1.1.4.3 $
 */
public class SubjectInterceptor implements Interceptor
{
   public String getName()
   {
      return "Observerable";
   }

   public Object invoke(Invocation invocation) throws Throwable
   {
      FieldInvocation fi = (FieldInvocation) invocation;
      Object before = fi.getField().get(fi.getTargetObject());
      Object result = invocation.invokeNext();
      Object after = fi.getField().get(fi.getTargetObject());
      if ((before == null && after != null) || (before != null && before.equals(after) == false))
      {
         Subject observable = (Subject) fi.getTargetObject();
         observable.notifyObservers();
      }
      return result;
   }
}
