/* **************************************************************************

  $Archive: /njcl_v2rmi/src/com/novell/service/session/nds/NDSContextSessionState.java $
  $Revision: 17 $
  $Modtime: 11/17/00 10:50a $

  Copyright (c) 1997 Novell, Inc.  All Rights Reserved.

  THIS WORK IS  SUBJECT  TO  U.S.  AND  INTERNATIONAL  COPYRIGHT  LAWS  AND
  TREATIES.   NO  PART  OF  THIS  WORK MAY BE  USED,  PRACTICED,  PERFORMED
  COPIED, DISTRIBUTED, REVISED, MODIFIED, TRANSLATED,  ABRIDGED, CONDENSED,
  EXPANDED,  COLLECTED,  COMPILED,  LINKED,  RECAST, TRANSFORMED OR ADAPTED
  WITHOUT THE PRIOR WRITTEN CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION
  OF THIS WORK WITHOUT AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO
  CRIMINAL AND CIVIL LIABILITY.

****************************************************************************/
package com.novell.service.session.nds;

import java.rmi.RemoteException;
import com.novell.service.session.*;
import com.novell.service.session.util.Debug;
import com.novell.service.session.xplat.*;
import com.novell.service.session.spi.*;
import com.novell.service.jncp.NSIException;
import com.novell.service.jncp.ClientException;
import com.novell.service.jncp.ServerException;
import com.novell.service.jncp.ClientErrors;
import com.novell.service.jncp.ServerErrors;
import com.novell.java.security.*;
import com.novell.service.security.NdsIdentity;
import com.novell.service.security.NdsIdentityScope;

/** @internal
 */
public abstract class NDSContextSessionState extends NDSSessionState
{
   // Always access debug via final static...hopefully a final static of
   // false will be optimized out by the compiler
   final static private boolean  DEBUG = false;
	final static private boolean  FINALIZER_DEBUG = false;
   final static private boolean  I_DEBUG = false; // Ignore exception
   final static private boolean  S_DEBUG = false; // May have side effects
   final static private boolean  PASSWORD_DEBUG = false;

   // Print message if deprecated API is used
   final static private boolean ERROR_ON_DEPRECATED = false;

   protected NDSContext context;

   public NDSContextSessionState
   (
      SessionImpl attachedSession,
      NDSContext context
   )
   throws SessionException, RemoteException
   {
      super(attachedSession);

      if (null == context)
      {
         context = xplatUtil.createContext(
            getEffectiveEnvironment(),
            getDomainName());
      }

      setContext(context);

      if (DEBUG)
      {
         Debug.println("NCSS.<init>(): " + getContext());
      }
   }

   /*
    * Inherited from SessionState
    */
   protected void releaseResources()
   throws SessionException, RemoteException  //this method is not a remote method, but calls one, so must throw RemoteException
   {
      NDSContext context = getContext();
      try
      {
         context.close();
      }
      catch (NSIException e)
      {
         throw InvalidSessionState.makeInvalid(this.attachedSession, e);
      }
      super.releaseResources();
   }

   /**
    * Inherited from Session
    *
    * @see Session#getAttributes()
    */
   public SessionAttrs getAttributes
   (
   )
   throws SessionException, RemoteException
   {
      try
      {
         // Get inherited attributes
         SessionAttrs attributes = super.getAttributes();

         // Override with this session's
         if (forceOperationalAttributes(getEffectiveEnvironment()))
            attributes.modify(
               getContext().getAttributes());

         String attrIds[] =
         {
            NDS.TREE_NAME_ATTR_ID,
            Session.SESSION_TYPE_ATTR_ID
         };
         attributes.modify(
            getStateAttrs(attrIds));

         return attributes;
      }
      catch (NSIException e)
      {
         throw InvalidSessionState.makeInvalid(this.attachedSession, e);
      }
   }

   /**
    * Inherited from Session
    *
    * @see Session#getAttributes(String[])
    */
   public SessionAttrs getAttributes
   (
      String attrIds[]
   )
   throws SessionException, RemoteException
   {
      try
      {
         SessionAttrs attributes = new SessionAttrs();

         // Get this session's attributes
         attributes = getContext().getAttributes(attrIds);

         if (attributes.count() != attrIds.length)
         {
            // Get this state's attributes
            attributes.merge(getStateAttrs(attrIds));

            if (attributes.count() != attrIds.length)
            {
               // Get inherited attributes
               attributes.merge(
                  super.getAttributes(attrIds));
            }
         }

         return attributes;
      }
      catch (NSIException e)
      {
         throw InvalidSessionState.makeInvalid(this.attachedSession, e);
      }
   }

   private SessionAttrs getStateAttrs
   (
      String attrIds[]
   )
   throws SessionException
   {
      // Get inherited attributes
      SessionAttrs attributes = new SessionAttrs();

      // Override with this session's
      for (int i = 0; i < attrIds.length; i++)
      {
         if (NDS.TREE_NAME_ATTR_ID.equals(attrIds[i]))
         {
            attributes.modify(
               NDS.TREE_NAME_ATTR_ID,
               getContext().
                  getTreeName());
         }
      }
      return attributes;
   }

   /**
    * @deprecated Use com.novell.service.security and related packages.
    *
    * Inherited from Authenticatable.
    *
    */
   public String getName
   (
   )
   throws SessionException, RemoteException
   {
      if (ERROR_ON_DEPRECATED)
      {
         System.out.println("This API has been deprecated..." +
            "see documentation for more details. Stack trace follows:");
         Thread.dumpStack();
      }

      return context.getName();
   }

   /**
    * Inherited from Authenticatable.
    *
    */
   public Identity createIdentity
   (
      String userName
   )
   throws SessionException, RemoteException
   {
      try
      {
         NdsIdentity id = new NdsIdentity(userName,
            new NdsIdentityScope("", new NdsIdentityScope(getContext().getTreeName())));

         Session sm = this;
         while (sm.hasParent())
            sm = sm.getParent();
         id.setSessionManager((SessionManager)sm);
         id.setSession((Session)attachedSession);

         if (DEBUG || PASSWORD_DEBUG)
         {
            Debug.println("Identity: " + id.toString());
         }
         return id;
      }
      catch (KeyManagementException e)
      {
         throw new SessionException("Unable to instantiate Identity.", e);
      }
   }

   public String toString()
   {
      String s = "";
      try
      {
         if (null != context)
            s = context.toString();
      }
      catch (Exception e)
      {
         if (I_DEBUG)
         {
            Debug.ignoreException("unexpected", e);
         }
      }
      return (super.toString() + ":" + s);
   }

   /**
    * Make sure get/set synchronized...avoid read/write synch problems.
    */
//   synchronized protected void setContext(NDSContext context)
   protected void setContext(NDSContext context)
   {
      this.context = context;
   }

   /**
    * Make sure get/set synchronized...avoid read/write synch problems.
    */
//   synchronized protected NDSContext getContext()
   protected NDSContext getContext()
   {
      return this.context;
   }
}

