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

  $Archive: /njcl_v2rmi/src/com/novell/service/nds/naming/net/PartitionContextFactory.java $
  $Revision: 10 $
  $Modtime: 1/05/01 3:59p $
 
  Copyright (c) 1998 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.nds.naming.net;

import java.rmi.RemoteException;
import java.lang.reflect.*;

import java.util.Hashtable;
import java.util.Properties;

import javax.naming.*;
import javax.naming.directory.DirContext;

import com.novell.service.jncp.NDSErrors;
import com.novell.service.jncp.NSIException;
import com.novell.service.jncp.NSIExceptionBuilder;

import com.novell.service.nds.naming.NdsEnvironment;
import com.novell.service.nds.naming.*;

import com.novell.service.session.SessionException;
import com.novell.service.jncpv2r.net.NetService;
import com.novell.service.jncpv2r.net.NetJNI;
import com.novell.service.jncpv2r.net.NetBuffer;
import com.novell.service.jncpv2r.net.NetIterationHandle;

import com.novell.utility.naming.Environment;
import com.novell.utility.naming.ContextWrappable;
import com.novell.utility.naming.spi.ContextFactory;


/** @internal
 *
 */
public final class PartitionContextFactory implements ContextFactory
{
   private static NameParser parser;
   private static Properties netContexts;
   private static NdsNamingExceptionFactory exceptionFactory =
       new NdsNamingExceptionFactory ();

   static
   {
      parser = new NdsPartitionNameParser ();

      netContexts = new Properties ();

      netContexts.put (
         Schema.PARTITION_ROOT,
         "com.novell.service.nds.naming.net.NetPartitionRootContext");
      netContexts.put (
         Schema.PARTITION,
         "com.novell.service.nds.naming.net.NetPartitionDirContext");
      netContexts.put (
         Schema.REPLICA,
         "com.novell.service.nds.naming.net.NetReplicaDirContext");

   } /* static */

   /**
    *
    */
   public PartitionContextFactory ()
   {

   }

   /**
    *
    */
   public Object getObjectInstance (
         Object object,
         Name name,
         Context nameCtx,
         Hashtable environment)
      throws Exception
   {
      NetEnvironment netEnvironment = new NetEnvironment (environment);

      if (object instanceof String)
      {
         return (getContextInstance ((String) object, netEnvironment));
      }

      if (object instanceof CompoundName)
      {
         return (getContextInstance (object.toString (), netEnvironment));
      }

      return (null);

   } /* getObjectInstance */

   /**
    *
    */
   public Context getContextInstance (
         String contextName,
         Environment environment)
      throws NamingException
   {
      String baseClass;
      NetEnvironment netEnvironment = getEnvironmentInstance (environment);

//Note: check NDS version when non-global schema is implemented
      baseClass = getBaseClass (contextName, netEnvironment);

      return (getContextInstance (contextName, baseClass, netEnvironment));

   } /* getContextInstance () */

   /**
    *
    */
   public Context getContextInstance (
         String objectName,
         Object baseClass,
         Environment environment)
      throws NamingException
   {
      NetEnvironment netEnvironment = getEnvironmentInstance (environment);

      try
      {
         Class cls;
         Class[] argTypes = new Class [2];
         Constructor ctor;
         Object[] args = new Object [2];

         cls = Class.forName (getClassName ((String) baseClass));

         argTypes [0] = Class.forName ("javax.naming.Name");
         argTypes [1] = Class.forName (
               "com.novell.service.nds.naming.net.NetEnvironment");
         ctor = cls.getDeclaredConstructor (argTypes);

         args [0] = parser.parse (objectName);
         args [1] = netEnvironment;

         return ((Context) ctor.newInstance (args));
      }
      catch (ClassNotFoundException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw (ne);
      }
      catch (SecurityException e)
      {
         NamingException ne = new NamingException ();
         ne.setRootCause (e);
         throw (ne);
      }
      catch (NoSuchMethodException e)
      {
         NamingException ne = new NamingException ();
         ne.setRootCause (e);
         throw (ne);
      }
      catch (InstantiationException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw (ne);
      }
      catch (IllegalAccessException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw (ne);
      }
      catch (IllegalArgumentException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw (ne);
      }
      catch (InvocationTargetException e)
      {
         NamingException ne = new NamingException ();
         ne.setRootCause (e);
         throw (ne);
      }

   } /* getContextInstance () */

   /**
    *
    */
   public Context getContextInstance (
         Object context)
      throws NamingException
   {
      throw (new OperationNotSupportedException ());

   } /* getContextInstance () */

   /**
    *
    */
   public String getClassName (
      Object baseClass)
   {
      return (netContexts.getProperty ((String) baseClass));

   } /* getClassName () */

   /**
    *
    */
   private String getBaseClass (
         String objectName,
         NetEnvironment environment)
      throws NamingException
   {
      int index;
      Name target = parser.parse (objectName);

      switch (target.size ())
      {
         case 0:
         {
            return (Schema.PARTITION_ROOT);

         } /* case 0: */

         case 1:
         {
            if (partitionExists (objectName, environment.getService ()))
            {
               return (Schema.PARTITION);
            }
            throw (new NameNotFoundException ());

         } /* case 1: */

         case 2:
         {
            if (replicaExists (target.get (1), target.get (0), environment))
            {
               return (Schema.REPLICA);
            }
            throw (new NameNotFoundException ());

         } /* case 2: */

      } /* switch (target.size ()) */

      throw (new NameNotFoundException ());

   } /* getBaseClass () */

   /**
    *
    */
   private boolean partitionExists (
         String objectName,
         NetService service)
      throws NamingException
   {
      try
      {
         StringBuffer partitionRoot = new StringBuffer();

         service.getPartitionRoot (
                           objectName,
                           partitionRoot);
/*         if (0 != ccode)
         {
            NamingException e;

            switch (ccode)
            {
               case NDSErrors.ERR_NO_SUCH_ENTRY:
               case NDSErrors.ERR_ILLEGAL_DS_NAME:
               {
                  return (false);
               }
               case NDSErrors.ERR_FAILED_AUTHENTICATION:
               {
                  e = new AuthenticationException ();
                  break;
               }
               case NDSErrors.ERR_ALL_REFERRALS_FAILED:
               case NDSErrors.ERR_NO_REFERRALS:
               case NDSErrors.ERR_INVALID_TRANSPORT:
               case NDSErrors.ERR_TRANSPORT_FAILURE:
               {
                  e = new CommunicationException ();
                  break;
               }
               default:
               {
                  e = new NamingException ();
                  break;
               }
            }
            e.setRootCause (NSIExceptionBuilder.build (ccode));
            throw (e);
         }*/
         return (objectName.equalsIgnoreCase (new String (partitionRoot)));
      }
      catch (NSIException e)
      {
			NamingException ne = exceptionFactory.getNamingException (e);
         throw ne;
      }
      catch (SessionException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw ne;
      }
      catch (RemoteException e)
      {
         NamingException ne = new NamingException ();

         ne.setRootCause (e);
         throw ne;
      }

   } /* partitionExists ( () */

   /**
    *
    */
   private boolean replicaExists (
         String replicaName,
         String partitionName,
         NetEnvironment environment)
      throws NamingException
   {
      NetReplicaNameClassEnumerator re = null;
      NameClassPair np;

      re = new NetReplicaNameClassEnumerator (environment, partitionName);

      while (re.hasMore ())
      {
          np = (NameClassPair) re.next ();
          if (replicaName.equals (np.getName ()))
          {
              return (true);
         }
      }
      return (false);

   } /* replicaExists () */

   /**
    *
    */
   private NetEnvironment getEnvironmentInstance (
         Environment environment)
      throws NamingException
   {
      if (environment instanceof NetEnvironment)
      {
         return ((NetEnvironment) environment);
      }
      return (new NetEnvironment (environment));

   } /* getEnvironmentInstance () */

} /* PartitionContextFactory */


