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

  $Archive: /njcl_v2rmi/src/com/novell/service/nds/naming/net/NetContextFactory.java $
  $Revision: 18 $
  $Modtime: 1/10/02 3:11p $

  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.lang.reflect.*;

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

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

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

import com.novell.service.nds.NdsObjectInfo;
import com.novell.service.nds.naming.NdsName;
import com.novell.service.nds.naming.NetSyntax;

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

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


/** @internal
 *
 */
public final class NetContextFactory implements ContextFactory
{
   private static NdsNamingExceptionFactory exceptionFactory =
       new NdsNamingExceptionFactory ();
   private static String defaultContext;
   private static Properties netContexts;

   static
   {
      defaultContext = "com.novell.service.nds.naming.net.NetDirContext";
      netContexts = new Properties ();

      netContexts.put (
         Schema.VOLUME,
         "com.novell.service.nds.naming.net.NetVolumeDirContext");
      netContexts.put (
         Schema.NCP_SERVER,
         "com.novell.service.nds.naming.net.NetServerDirContext");
      netContexts.put (
         Schema.TOP,
         "com.novell.service.nds.naming.net.NetTreeDirContext");
      netContexts.put (
         Schema.DIRECTORY_MAP,
         "com.novell.service.nds.naming.net.NetDirectoryMapDirContext");
      netContexts.put (
         Schema.QUEUE,
         "com.novell.service.nds.naming.net.NetQueueDirContext");
      netContexts.put (
         Schema.ALIAS,
         "com.novell.service.nds.naming.net.NetAliasDirContext");
      //netContexts.put (
      //   Schema.JAVA_CONTAINER,
      //   "com.novell.service.nds.naming.net.NetJavaContainerDirContext");

   } /* static */

   /**
    *
    */
   public NetContextFactory ()
   {

   }

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

      if (object instanceof Reference)
      {
         StringRefAddr address;
         URLParser urlParser;

         address = (StringRefAddr) ((Reference) object).get (0);
         urlParser = new URLParser ((String) address.getContent ());

         netEnvironment.addToEnvironment (
                           Context.PROVIDER_URL,
                           urlParser.getURL ());

         return (getContextInstance (
                     getCanonicalName (urlParser.getPath ()),
                     netEnvironment));
      }

      // 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
   {
      NetObjectInfo objectInfo; // for reading baseClass
		NetEntryInfo entryInfo;   // for reading federation_boundary
      StringBuffer distinguishedName = new StringBuffer ();
      NetEnvironment netEnvironment = getEnvironmentInstance (environment);

//Note: check NDS version when non-global schema is implemented
      objectInfo = getNetObjectInfo (
                        contextName,
								distinguishedName,
                        netEnvironment.getService ());

		/*  We need to find out if the distinguishedName returned by
		 *  getNetObjectInfo is actually the [Root] of a tree or not.
		 *  Historically (pre Tao), passing [Root] would return an object named
		 *  [Root] with a baseClass of "Top". With the advent of DNS names for
		 *  NDS trees, [Root] no longer exists and will be "spoofed" by NDS by
		 *  returning the "management root" object (acting as the "root" of this
		 *  federated tree) which may have a baseClass of OU, L, etc...
		 *
		 *  We use the baseClass (in objectInfo) to determine what type of
		 *  NetDirContext to create. It is now possible that an object of type
		 *  OU is the management root of the tree. We can determine if an object
		 *  is a management root by reading the FEDERATION_BOUNDARY attribute of
		 *  the object returned in the distinguishedName parameter of the
		 *  getNetObjectInfo call. If the FEDERATION_BOUNDARY value matches the
		 *  distinguishedName value, the object named by distinguishedName is a
		 *  management root. In this case, we would want to create a
		 *  NetTreeDirContext for an object with a baseClass having a value
		 *  other than "Top".
		 */
		String dn = distinguishedName.toString();

		entryInfo = getNetEntryInfo (
								dn,
								netEnvironment.getService (),
								netEnvironment.getBatchSize ());

		String fb = entryInfo.getFederationBoundary();
		if (fb != null) // in case Federation Boundary doesn't exist
		{
			if (fb.equalsIgnoreCase(dn))
			{
				// we will want NetTreeDirContext behaviour for this context
				objectInfo.setManagementRoot(true);
			}
		}

      return (getContextInstance (dn, objectInfo, netEnvironment));

   } /* getContextInstance () */

   /**
    *
    */
   public Context getContextInstance (
         String objectName,
         Object classInfo,
         Environment environment)
      throws NamingException
   {
      if (!(classInfo instanceof NdsObjectInfo))
      {
         throw (new NamingException ());
      }

      NdsObjectInfo objectInfo = (NdsObjectInfo) classInfo;
      NetEnvironment netEnvironment = getEnvironmentInstance (environment);

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

			if (objectInfo.isManagementRoot())
			{
				// we want NetTreeDirContext behavior if this context will
				// represent a management root object. (could be o,ou,l,s, etc)
				cls = Class.forName ("com.novell.service.nds.naming.net.NetTreeDirContext");
			}
			else
			{
				cls = Class.forName (getClassName (objectInfo.getBaseClass ()));
			}

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

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

   } /* 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 NetObjectInfo getNetObjectInfo (
         String objectName,
			StringBuffer distinguishedName,
         NetService service)
      throws NamingException
   {
      NetObjectInfo objectInfo = new NetObjectInfo ();

      try
      {
         service.readObjectInfo (
                           objectName,
                           distinguishedName,
                           objectInfo);
      }
      catch (SessionException e)
      {
         NamingException ne = new AuthenticationException ();

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

         ne.setRootCause (e);
         throw (ne);
      }
      catch (NSIException e)
      {
			NamingException ne = exceptionFactory.getNamingException (e);
         throw (ne);
      }
      return (objectInfo);

   } /* getNdsObjectInfo () */

   /**
    * Added this method so we can read the FEDERATION_BOUNDARY attribute.
    */
   private NetEntryInfo getNetEntryInfo (
         String objectName,
         NetService service,
		   int batchSize)
      throws NamingException
   {
      try
      {
         return service.readEntry (
                              objectName,
                              batchSize);
      }
      catch (SessionException e)
      {
         NamingException ne = new AuthenticationException ();

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

         ne.setRootCause (e);
         throw (ne);
      }
      catch (NSIException e)
      {
			NamingException ne = exceptionFactory.getNamingException (e);
         throw (ne);
      }

   } /* getNetEntryInfo () */

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

   } /* getEnvironmentInstance () */

   /**
    *
    */
   private String getCanonicalName (
         String path)
      throws NamingException
   {
      NdsName name;

      name = new NdsName ((path == null) ? "" : path, new NetSyntax ());

      return (name.getCanonicalString ());
   }

} /* NetContextFactory */



