/*
 * JBoss, the OpenSource EJB server
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.test.asynchronous;

import java.lang.reflect.InvocationTargetException;
import javax.annotation.EJB;
import javax.annotation.security.DenyAll;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.PermitAll;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.Local;
import javax.ejb.EJBAccessException;
import org.jboss.aspects.asynch.AsynchProvider;
import org.jboss.aspects.asynch.Future;
import org.jboss.ejb3.JBossProxy;
import org.jboss.annotation.security.SecurityDomain;

/**
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.4.2.4 $
 */
@Stateless
@SecurityDomain("other")
@Remote(SecuredStatelessRemote.class)
@Local(SecuredStatelessLocal.class)
public class SecuredStatelessBean implements SecuredStatelessRemote, SecuredStatelessLocal
{
   @EJB
   public SecuredStatelessLocal local;

   @PermitAll
   public int uncheckedMethod(int i)
   {
      return i;
   }

   @DenyAll
   public int excludedMethod(int i)
   {
      return i;
   }

   @RolesAllowed("allowed")
   public int method(int i)
   {
      SecuredStatelessLocal asynchLocal = (SecuredStatelessLocal)((JBossProxy)local).getAsynchronousProxy();
      AsynchProvider ap = (AsynchProvider)asynchLocal;

      asynchLocal.excludedMethod(i);
      Object ret = getReturnOrException(ap);
      if (!(ret instanceof EJBAccessException))
      {
         throw new RuntimeException("Local excluded method call did not cause a SecurityException");
      }

      asynchLocal.localSecured(i);
      ret = getReturnOrException(ap);
      return (Integer)ret;
   }

   @RolesAllowed("allowed")
   public int localSecured(int i)
   {
      return i;
   }

   private Object getReturnOrException(AsynchProvider provider)
   {
      try
      {
         Future future = provider.getFuture();

         while (!future.isDone())
         {
            Thread.sleep(100);
         }
         return future.get();
      }
      catch(InvocationTargetException e)
      {
         return e.getCause();
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("Bummer");
      }
   }

}
