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

  $Archive: /njcl_v2rmi/src/com/novell/service/nds/naming/net/SchemaContextFactory.java $
  $Revision: 14 $
  $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.util.Hashtable;
import java.util.Properties;
import java.util.NoSuchElementException;

import java.lang.reflect.*;

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

import com.novell.service.session.Session;
import com.novell.service.session.SessionException;
import com.novell.service.jncpv2r.net.NetService;

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

import com.novell.service.jncp.NSIException;

import com.novell.service.jncpv2r.net.NetJNI;
import com.novell.service.jncpv2r.net.NetBuffer;
import com.novell.service.jncpv2r.net.NetReadClassDefBuffer;
import com.novell.service.jncpv2r.net.NetReadAttrDefBuffer;
import com.novell.service.jncpv2r.net.NetIterationHandle;
import com.novell.service.jncpv2r.net.NetClassInfo;
import com.novell.service.jncpv2r.net.NetAttrInfo;

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


/** @internal
 *
 */
public final class SchemaContextFactory implements ContextFactory
{
   private static NameParser parser;
   private static String defaultContext;
   private static Properties netContexts;
	private static NdsNamingExceptionFactory exceptionFactory;

   static
   {
      parser = new NdsNameParser ();
//      defaultContext = "com.novell.service.nds.naming.net.NetDirContext";
      netContexts = new Properties ();
		exceptionFactory = new NdsNamingExceptionFactory ();

      netContexts.put (
         Schema.SCHEMA_CONTAINER,
         "com.novell.service.nds.naming.net.NetSchemaRootDirContext");
      netContexts.put (
         Schema.ATTRIBUTE_CONTAINER,
         "com.novell.service.nds.naming.net.NetAttributeDefinitionsDirContext");
      netContexts.put (
         Schema.CLASS_CONTAINER,
         "com.novell.service.nds.naming.net.NetClassDefinitionsDirContext");
      netContexts.put (
         Schema.SYNTAX_CONTAINER,
         "com.novell.service.nds.naming.net.NetSyntaxDefinitionsDirContext");
      netContexts.put (
         Schema.SCHEMA_ATTRIBUTE,
         "com.novell.service.nds.naming.net.NetAttributeDefinitionDirContext");
      netContexts.put (
         Schema.SCHEMA_CLASS,
         "com.novell.service.nds.naming.net.NetClassDefinitionDirContext");
      netContexts.put (
         Schema.SCHEMA_SYNTAX,
         "com.novell.service.nds.naming.net.NetSyntaxDefinitionDirContext");

   } /* static */

   /**
    *
    */
   public SchemaContextFactory ()
   {

   }

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

      // object passed should be DN of root
      if (object instanceof String)
      {
         return (getContextInstance ((String) object, netEnvironment));
      }

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

   } /* getObjectInstance */

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

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

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

   } /* getContextInstance () */

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

      // Is info an attribute info?
      if (info instanceof NetAttrInfo)
      {
         return (new NetAttributeDefinitionDirContext (
                        objectName,
                        (NetAttrInfo) info,
                        netEnvironment));
      }


      // Is info an NetClassInfo?
      if (info instanceof NetClassInfo)
      {
         return (new NetClassDefinitionDirContext (
                        objectName,
                        (NetClassInfo) info,
                        netEnvironment));
      }


      // Is info a base class?
      if (info instanceof String)
      {
         try
         {
            Class cls;
            Class[] argTypes = new Class [3];
            Constructor ctor;
            Object[] args = new Object [3];

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

            argTypes [0] = Class.forName ("java.lang.String");
            argTypes [1] = Class.forName ("java.lang.String");
            argTypes [2] = Class.forName (
                  "com.novell.service.nds.naming.net.NetEnvironment");
            ctor = cls.getDeclaredConstructor (argTypes);

            args [0] = objectName;
            args [1] = info;
            args [2] = 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);
         }
      }

      throw new NamingException ();

   } /* getContextInstance () */

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

   } /* getContextInstance () */

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

   } /* getClassName () */

   /**
    *
    */
   private Object getSchemaInfo (
         String objectName,
         NetEnvironment netEnvironment)
      throws NamingException
   {
      int index;
      Name target;
      String component;

      NetService service = netEnvironment.getService ();

      target = parser.parse (objectName.toLowerCase ());

      switch (target.size ())
      {
         case 1:
         {
            component = target.get (0);

            if (-1 != (index = component.indexOf ("schema")))
            {
               if (3 >= index)
               {
                  // SC=Schema
                  return (Schema.SCHEMA_CONTAINER);
               }
            }
            break;

         } /* case 1: */

         case 2:
         {
            component = target.get (1);

            if (-1 != (index = component.indexOf ("classes")))
            {
               if (index <= 3)
               {
                  // SC=Classes.SC=Schema
                  return (Schema.CLASS_CONTAINER);
               }
            }
            else if (-1 != (index = component.indexOf ("attributes")))
            {
               if (index <= 3)
               {
                  // SC=Attributes.SC=Schema
                  return (Schema.ATTRIBUTE_CONTAINER);
               }
            }
            else if (-1 != (index = component.indexOf ("syntaxes")))
            {
               if (index <= 3)
               {
                  // SC=Syntaxes.SC=Schema
                  return (Schema.SYNTAX_CONTAINER);
               }
               return (Schema.SCHEMA_SYNTAX);
            }
            break;

         } /* case 2: */

         case 3:
         {
            component = target.get (1);

            if (-1 != (index = component.indexOf ("classes")))
            {
               if (3 >= index)
               {
                  // CL=*.SC=Classes.SC=Schema
                  return (getClassInfo (objectName, service, netEnvironment));
               }
            }
            else if (-1 != (index = component.indexOf ("attributes")))
            {
               if (3 >= index)
               {
                  // AT=*.SC=Attributes.SC=Schema
                  return (getAttrInfo (objectName, service, netEnvironment));
               }
            }
            else if (-1 != (index = component.indexOf ("syntaxes")))
            {
               if (3 >= index)
               {
                  // S=*.SC=Syntaxes.SC=Schema
                  if (schemaSyntaxExists (objectName, service))
                  {
                     return (Schema.SCHEMA_SYNTAX);
                  }
                  throw (new NameNotFoundException ());
               }
            }
            break;

         } /* case 3: */

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

      throw (new NameNotFoundException ());

   } /* getSchemaInfo () */

   /**
    *
    */
   protected Object getClassInfo (
         String objectName,
         NetService service,
         NetEnvironment environment)
      throws NamingException
   {
      try
      {
         Name dName = new NdsNameParser ().parse (objectName);
         String name = dName.get (dName.size () - 1);

         NetIterationHandle iterationHandle = new NetIterationHandle (
                                             service,
                                             NetJNI.DSV_READ_CLASS_DEF);

         NetBuffer classNames = new NetBuffer (service,
                                NetJNI.DSV_READ_CLASS_DEF,
                                NetJNI.DEFAULT_MESSAGE_LEN);

         NetReadClassDefBuffer classDefs = new NetReadClassDefBuffer (
                                       service,
                                       environment.getClassAttributesLevel (),
                                       environment.getBatchSize ());

         classNames.putClassName (name);

         service.readClassDef (
                        environment.getClassAttributesLevel (),
                        false,
                        classNames.getHandle (),
                        iterationHandle,
                        classDefs);

         return (classDefs.getEntries ().nextElement ());
      }
      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);
      }

   } /* getClassInfo () */

   /**
    *
    */
   protected Object getAttrInfo (
         String objectName,
         NetService service,
         NetEnvironment environment)
      throws NamingException
   {
      try
      {
         Name dName = parser.parse (objectName);
         String name = dName.get (dName.size () - 1);

         NetIterationHandle iterationHandle = new NetIterationHandle (
                                             service,
                                             NetJNI.DSV_READ_ATTR_DEF);

         NetBuffer attrNames = new NetBuffer (service,
                                NetJNI.DSV_READ_ATTR_DEF,
                                NetJNI.DEFAULT_MESSAGE_LEN);

         NetReadAttrDefBuffer attrDefs = new NetReadAttrDefBuffer (
                        service,
                        NetJNI.DS_ATTR_DEFS,
                        environment.getBatchSize ());

         attrNames.putAttributeName (name);

         service.readAttrDef (
                        NetJNI.DS_ATTR_DEFS,
                        false,
                        attrNames.getHandle (),
                        iterationHandle,
                        attrDefs);

         return (attrDefs.getEntries ().nextElement ());
      }
      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);
      }

   } /* schemaAttributeExists () */

   /**
    *
    */
   protected boolean schemaSyntaxExists (
         String objectName,
         NetService service)
      throws NamingException
   {
      try
      {
         Name name = parser.parse (objectName);

         objectName = name.get (name.size () - 1);

         NetIterationHandle iterationHandle = new NetIterationHandle (
                                             service,
                                             NetJNI.DSV_READ_SYNTAXES);
         NetBuffer syntaxNames = new NetBuffer (service,
                                          NetJNI.DSV_READ_SYNTAXES,
                                          NetJNI.DEFAULT_MESSAGE_LEN);
         NetBuffer syntaxDefs = new NetBuffer (service);

         // NWDSReadSyntaxes can't handle SN=, strip it
         int index;

         if ((index = objectName.indexOf ('=')) != -1)
         {
            objectName = objectName.substring (index + 1);
         }

         syntaxNames.putSyntaxName (objectName);

         service.readSyntaxes (
                           NetJNI.DS_SYNTAX_NAMES,
                           false,
                           syntaxNames.getHandle (),
                           iterationHandle,
                           syntaxDefs.getHandle ());

         return true;
      }
      catch (NSIException e)
      {
      }
      catch (SessionException e)
      {
         NamingException ne = new NamingException ();

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

         ne.setRootCause (e);
         throw (ne);
      }
      return (false);

   } /* schemaSyntaxExists () */

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

   } /* getEnvironmentInstance () */

} /* SchemaContextFactory */


