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

import java.security.Identity;
import java.security.Principal;
import java.util.HashSet;
import java.util.Properties;
import javax.ejb.EJBException;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBLocalObject;
import javax.ejb.EJBObject;
import javax.ejb.SessionContext;
import javax.ejb.TimerService;
import javax.ejb.TransactionManagementType;
import javax.naming.NamingException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import javax.xml.rpc.handler.MessageContext;
import org.jboss.aop.Advisor;
import org.jboss.ejb3.tx.TxUtil;
import org.jboss.ejb3.tx.UserTransactionImpl;
import org.jboss.logging.Logger;
import org.jboss.security.RunAsIdentity;
import org.jboss.security.SecurityAssociation;
import org.jboss.security.SimplePrincipal;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.1.2.5 $
 */
public abstract class BaseSessionContext extends BaseContext implements SessionContext
{
   private static final Logger log = Logger.getLogger(BaseSessionContext.class);
   
   protected BaseSessionContext()
   {
   }

   public Object lookup(String name)
   {
      try
      {
         return container.getInitialContext().lookup(name);
      }
      catch (NamingException ignored)
      {
      }
      return null;
   }

   public Identity getCallerIdentity()
   {
      throw new IllegalStateException("deprecated");
   }

   public Principal getCallerPrincipal()
   {
      Principal principal = SecurityAssociation.getCallerPrincipal();
      if (getRm() != null)
      {
         principal = getRm().getPrincipal(principal);
      }
      
      // This method never returns null. 
      if (principal == null)
         throw new java.lang.IllegalStateException();
      
      return principal;
   }

   public boolean isCallerInRole(Identity role)
   {
      throw new IllegalStateException("deprecated");
   }

   public boolean isCallerInRole(String roleName)
   {
      // TODO revert to aspects.security.SecurityContext impl when JBoss AOP 1.1 is out.
      Principal principal = getCallerPrincipal();
      // Check the caller of this beans run-as identity
      // todo use priveleged stuff in ejb class
      RunAsIdentity runAsIdentity = SecurityActions.peekRunAsIdentity(1);
      
      if (principal == null && runAsIdentity == null)
         return false;

      if (getRm() == null)
      {
         String msg = "isCallerInRole() called with no security context. "
                      + "Check that a security-domain has been set for the application.";
         throw new IllegalStateException(msg);
      }

      HashSet set = new HashSet();
      set.add(new SimplePrincipal(roleName));
        
      if (runAsIdentity == null)
         return getRm().doesUserHaveRole(principal, set);
      else
         return runAsIdentity.doesUserHaveRole(set);
   }

   public TimerService getTimerService() throws IllegalStateException
   {
      return getContainer().getTimerService();
   }

   public UserTransaction getUserTransaction() throws IllegalStateException
   {
      TransactionManagementType type = TxUtil.getTransactionManagementType(((Advisor) getContainer()));
      if (type != TransactionManagementType.BEAN) throw new IllegalStateException("Container " + getContainer().getEjbName() + ": it is illegal to inject UserTransaction into a CMT bean");

      return new UserTransactionImpl();
   }

   public EJBHome getEJBHome()
   {
      throw new EJBException("EJB 3.0 does not have a home type.");
   }

   public EJBLocalHome getEJBLocalHome()
   {
      throw new EJBException("EJB 3.0 does not have a home type.");
   }

   public Properties getEnvironment()
   {
      throw new EJBException("Deprecated");
   }

   public void setRollbackOnly() throws IllegalStateException
   {
      // EJB1.1 11.6.1: Must throw IllegalStateException if BMT
      TransactionManagementType type = TxUtil.getTransactionManagementType(((Advisor) getContainer()));
      if (type != TransactionManagementType.CONTAINER) throw new IllegalStateException("Container " + getContainer().getEjbName() + ": it is illegal to call setRollbackOnly from BMT: " + type);

      try
      {
         TransactionManager tm = TxUtil.getTransactionManager();

         // The getRollbackOnly and setRollBackOnly method of the SessionContext interface should be used
         // only in the session bean methods that execute in the context of a transaction.
         if (tm.getTransaction() == null)
            throw new IllegalStateException("setRollbackOnly() not allowed without a transaction.");

         tm.setRollbackOnly();
      }
      catch (SystemException e)
      {
         log.warn("failed to set rollback only; ignoring", e);
      }
   }

   public boolean getRollbackOnly() throws IllegalStateException
   {
      // EJB1.1 11.6.1: Must throw IllegalStateException if BMT
      TransactionManagementType type = TxUtil.getTransactionManagementType(((Advisor) getContainer()));
      if (type != TransactionManagementType.CONTAINER) throw new IllegalStateException("Container " + getContainer().getEjbName() + ": it is illegal to call getRollbackOnly from BMT: " + type);

      try
      {
         TransactionManager tm = TxUtil.getTransactionManager();

         // The getRollbackOnly and setRollBackOnly method of the SessionContext interface should be used
         // only in the session bean methods that execute in the context of a transaction.
         if (tm.getTransaction() == null)
            throw new IllegalStateException("setRollbackOnly() not allowed without a transaction.");

         return tm.getStatus() == Status.STATUS_MARKED_ROLLBACK;
      }
      catch (SystemException e)
      {
         log.warn("failed to set rollback only; ignoring", e);
         return true;
      }
   }

   public EJBLocalObject getEJBLocalObject() throws IllegalStateException
   {
      throw new RuntimeException("NOT IMPLEMENTED");
   }

   public EJBObject getEJBObject() throws IllegalStateException
   {
      throw new RuntimeException("NOT IMPLEMENTED");
   }
   
   public Object getBusinessObject(Class businessInterface) throws IllegalStateException
   {
      throw new RuntimeException("NOT IMPLEMENTED");
   }

   public MessageContext getMessageContext() throws IllegalStateException
   {
      throw new RuntimeException("NOT IMPLEMENTED");
   }

}
