package org.dbxml.client.xmldb;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: DatabaseImpl.java,v 1.27 2001/09/09 18:07:49 kstaken Exp $
 */

import org.omg.CosNaming.*;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextPackage.*;

import java.util.*;
import java.io.*;
import java.net.*;

import org.xmldb.api.base.*;

import org.dbxml.core.FaultCodes;
import org.dbxml.core.corba.db.*;
import org.dbxml.core.corba.db.Database;

/**
 * DatabaseImpl is the XML:DB driver implementation for dbXML. It is the entry
 * point into the dbXML server but is not intended for direct use by users.
 * Users access it indirectly through the XML:DB DatabaseManager implementation.
 *
 *
 * This API is an implementation of the XML:DB API. More information on this API
 * can be found by looking at
 * <a href="http://www.xmldb.org/xapi/index.html">http://www.xmldb.org/xapi/index.html</a>
 * <p />
 *
 * The location to find the NamingService ior can be specified by setting the
 * property dbxml.naming.ior using setProperty. By default it will be set to
 * "http://localhost:8080/NamingService"
 *
 * The CORBA ORB implementation can be switched by setting the properties
 * org.omg.CORBA.ORBClass and org.omg.CORBA.ORBSingletonClass with the values
 * provided by your orb vendor. The values are set using setProperty().
 */
public class DatabaseImpl extends CommonConfigurable
   implements org.xmldb.api.base.Database {

   protected Hashtable dbs = null;

   /**
    * Name used in the uri for collections associated with this instance.
    */
   public static String INSTANCE_NAME = "dbxml";
   /**
    * The characters expected to separate the INSTANCE_NAME from the database
    * name.
    */
   public static String SEP = "://";
   /**
    * The XML:DB API Core Level Conformance of this implementation.
    */
   public static String CONFORMANCE_LEVEL = "0";
   /**
    * Default CORBA name service name for the Database instance.
    */
   public final static String DEFAULT_CORBA_NAME = "Database";
   /**
    * Default location where the Name service IOR can be located.
    */
   public final static String DEFAULT_NAMING_URI =
         "http://localhost:4080/NamingService";
   /**
    * Property name to set when needing to change the location of the naming
    * service URI.
    */
   public final static String NAMING_PROP = "dbxml.naming.ior";
   /**
    * Property name to use to set the name of the ORB property to use to
    * configure where to find the NameService ref.
    */
   public final static String ORB_NAMING_PROP = "dbxml.naming.orbproperty";
   /**
    * Property name to use to set the naming service up for resolve_initial_refs
    */
   public final static String DEFAULT_ORB_NAMING_PROP = "jacorb.NameServerURL";
   /**
    * Property name to use to set the name of the ORB Class. This is used to
    * override the JDKs built in CORBA ORB.
    */
   public final static String ORB_CLASS_PROP = "org.omg.CORBA.ORBClass";
   /**
    * Property name to use to set the name of the ORB singleton Class. This is
    * used to override the JDKs built in CORBA ORB.
    */
   public final static String ORB_SINGLETON_CLASS_PROP = "org.omg.CORBA.ORBSingletonClass";
   /**
    * Default ORB class. This is used to override the JDKs built in CORBA ORB.
    */
   public final static String DEFAULT_ORB_CLASS = "org.openorb.CORBA.ORB";
   /**
    * Default ORBSingleton class. This is used to override the JDKs built in
    * CORBA ORB.
    */
   public final static String DEFAULT_ORB_SINGLETON_CLASS = "org.openorb.CORBA.ORBSingleton";
   
   // CORBA naming context root element.
   protected static String ROOT_CONTEXT = INSTANCE_NAME;

   protected String orbNamingProp = DEFAULT_ORB_NAMING_PROP;
   
   /**
    * Constructor for the DatabaseImpl object
    */
   public DatabaseImpl() {
      super();
      dbs = new Hashtable();
   }

   /**
    * Gets the instance Name
    *
    * @return The Name value
    * @exception XMLDBException
    */
   public String getName() throws XMLDBException {
      return INSTANCE_NAME;
   }

   /**
    * Creates a Collection instance using the URI to locate the collection in
    * the dbXML instance. Applications should not call this method directly.
    * Instead they should call org.xmldb.api.base.DatabaseManager.getCollection().
    * <p />
    * The URI format accepted by this method:
    * dbxml:/[Nameservice host]//[Database Instance Name in the CORBA Name Service]/[collection path]
    * <p />
    * Nameservice host is optional.
    *
    * This usually looks something like this:
    * dbxml:///db/root/ocs. or
    * dbxml://some.host.com:8309/db/root/ocs
    * <p />
    * When you pass the URI to DatabaseManager.getCollection(uri) you must
    * prepend an xmldb: to the beginning to make it a valid XML:DB URI.
    * So to normal users of the API URIs will look like this:
    * xmldb:dbxml:///db/root/ocs. DatabaseManager will strip the
    * xmldb: before handing the URI to this getCollection implementation.
    * <p />
    * @param uri The URI specifing the location of the collection.
    * @return The Collection value
    * @exception XMLDBException
    */
   public org.xmldb.api.base.Collection getCollection(String uri, 
         String username, String password) throws XMLDBException {
             
      if (uri == null) {
         throw new XMLDBException(ErrorCodes.INVALID_URI);
      }

      // Get the name service URI to use to locate the server
      String corbaNameServiceURI = getNamingURI(uri);
      if (corbaNameServiceURI == null) {
         corbaNameServiceURI = DEFAULT_NAMING_URI;
      }
      
      // Get the name service name to use to locate the server
      String corbaName = getNamingNameFromURI(uri);
      if (corbaName == null) {
         corbaName = DEFAULT_CORBA_NAME;
      }

      // Create a Database instance for this name if it doesn't already
      // exist.
      String dbKey = corbaNameServiceURI + " " +  corbaName;      
      if (dbs.get(dbKey) == null) {
         init(corbaNameServiceURI, corbaName);
      }

      // dbxml:///db-instance/collection-path
      String collectionName = getCollectionFromURI(uri);
      org.xmldb.api.base.Collection collection = null;
      try {
         Database db = (Database) dbs.get(dbKey);

         collection =
            new CollectionImpl(db.getCollection(collectionName), db, this);
      }
      catch (APIException e) {
         if (e.faultCode == FaultCodes.COL_COLLECTION_NOT_FOUND) {
            return null;
         }
         else {
            throw FaultCodes.createXMLDBException(e);
         }
      }
      catch (Exception e) {
         throw FaultCodes.createXMLDBException(e);
      }

      return collection;
   }

   /**
    * Gets the ConformanceLevel attribute of the DatabaseImpl object
    *
    * @return The ConformanceLevel value
    * @exception XMLDBException Description of Exception
    */
   public String getConformanceLevel() throws XMLDBException {
      return CONFORMANCE_LEVEL;
   }

   /**
    * Used by org.xmldb.api.base.DatabaseManager to determine if this database
    * instance is the proper one to handle a request or not.
    *
    * @param uri The uri to test - see getCollection for a description of the
    *        format.
    * @return true if the URI can be handled, false otherwise.
    * @exception XMLDBException
    */
   public boolean acceptsURI(String uri) throws XMLDBException {
      if (uri.startsWith(INSTANCE_NAME)) {
         return true;
      }

      return false;
   }

   /**
    * Returns the Collection path portion of the URI.
    *
    * @param uri the URI to parse.
    * @return The collection path portion of the URI.
    * @exception XMLDBException
    */
   protected String getCollectionFromURI(String uri) throws XMLDBException {
      if ( ! uri.startsWith(INSTANCE_NAME) ) {
         throw new XMLDBException(ErrorCodes.INVALID_DATABASE);
      }

      // Find the start of the collection path skipping over the database name.
      int start = uri.indexOf('/', INSTANCE_NAME.length() + SEP.length());
      start = uri.indexOf('/', start + 1);
      
      // Remove the protocol and database instance name
      String result = "/";
      if ( start != -1 ) {
          result = uri.substring(start, uri.length());
      }

      return result;
   }

   /**
    * Returns the CORBA name service name portion of the URI.
    * This is dbxml:///[corba name]/
    *
    * @param uri the URI to parse.
    * @return The collection path portion of the URI.
    * @exception XMLDBException
    */
   protected String getNamingNameFromURI(String uri) throws XMLDBException {
      if ( ! uri.startsWith(INSTANCE_NAME) ) {
         throw new XMLDBException(ErrorCodes.INVALID_DATABASE);
      }

      // Find the start of the collection path.
      int start = uri.indexOf('/', INSTANCE_NAME.length() + SEP.length());
      int end = uri.indexOf('/', start + 1);
      
      // Remove the protocol and Database instance name
      String result = null;
      if ( end != -1 ) {
         result = uri.substring(start + 1, end);
      }
      else {
         result = uri.substring(start + 1, uri.length());
      }

      return result;
   }

   /**
    * Returns the CORBA name service host from the URI.
    * This is dbxml://[name service host]/
    *
    * @param uri the URI to parse.
    * @return The collection path portion of the URI.
    * @exception XMLDBException
    */
   protected String getNamingURI(String uri) throws XMLDBException {
      if ( ! uri.startsWith(INSTANCE_NAME) ) {
         throw new XMLDBException(ErrorCodes.INVALID_DATABASE);
      }

      String result = null;
      
      // Find the first double slashes.
      int first = uri.indexOf("//", INSTANCE_NAME.length());

      // Find the next slash.c
      int end = uri.indexOf('/', first + 2);
      
      // If we don't have 3 consecutive slashes then there should be a host
      if ( first != (end - 2) ) {
         result = uri.substring(first + 2, end);         
         result = "http://" + result + "/NamingService";
      }
          
      return result;
   }
   
   /**
    * Initializes the connection to dbXML via the CORBA API.
    */
   protected void init(String namingURI, String corbaName) throws XMLDBException {
      Properties orbConfig = getOrbConfig(namingURI);
      try {
         ORB orb = ORB.init(new String[0], orbConfig);

         NamingContextExt ncRef =
            NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));
         if (ncRef == null) {
            throw new XMLDBException(ErrorCodes.VENDOR_ERROR, 1,
               "A naming service could not be located at the uri "
               + orbConfig.get(orbNamingProp) +
               ". Make sure your dbXML instance is running");
         }

         // resolve the Object Reference in Naming
         NameComponent root = new NameComponent(ROOT_CONTEXT, "");
         NameComponent nc = new NameComponent(corbaName, "");
         NameComponent path[] = {root, nc};

         Database db = (org.dbxml.core.corba.db.Database)
            DatabaseHelper.narrow(ncRef.resolve(path));

         // Store the Database instance for this name.
         dbs.put(namingURI + " " + corbaName, db);
      }
      catch (NotFound e) {
         throw new XMLDBException(ErrorCodes.VENDOR_ERROR, 1,
            "A connection to the Database instance '" + corbaName +
               "' could not be created. ");
      }
      // TODO: More intelligent handling of CORBA exceptions
      catch (Exception e) {
         e.printStackTrace();
         throw FaultCodes.createXMLDBException(e);
      }
   }
   
   protected Properties getOrbConfig(String namingURI) {
      // Determine what property to set on the orb to get
      // resolve_initial_references to work.
      orbNamingProp = (String) config.get(ORB_NAMING_PROP);
      if (orbNamingProp == null) {
         orbNamingProp = DEFAULT_ORB_NAMING_PROP;
      }
      
      // Figure out what to hand to resolve_initial_references to locate the
      // naming service
      String propNamingURI = (String) config.get(NAMING_PROP);
      if (propNamingURI != null) {
         namingURI = propNamingURI;
      }
      
      // See if we're overriding the default ORB
      String orbClass = (String) config.get(ORB_CLASS_PROP);
      if (orbClass == null) {
         // test for default ORB if not found we'll try to use JacORB.
         orbClass = DEFAULT_ORB_CLASS;
         try {
            Class.forName(orbClass);
         }
         catch (ClassNotFoundException e) {
            orbClass = "org.jacorb.orb.ORB";
         }         
      }
            
      String orbSingletonClass = (String) config.get(ORB_SINGLETON_CLASS_PROP);
      if (orbSingletonClass == null) {
         // test for default ORB if not found we'll try to use JacORB.
         orbSingletonClass = DEFAULT_ORB_SINGLETON_CLASS;
         try {
            Class.forName(orbSingletonClass);
         }
         catch (ClassNotFoundException e) {
            orbSingletonClass = "org.jacorb.orb.ORBSingleton";
         }
      }
      
      Properties orbConf = new Properties();
      // Set the default naming location which is for JacORB 1.1 by default.
      orbConf.put(orbNamingProp, namingURI);

      // Also set it up for JacORB 1.3 to make switching easy.
      orbConf.put("ORBInitRef.NameService", namingURI);

      // Also set it up for OpenORB 1.1 to make switching easy.
      orbConf.put("InitRef.NameService", namingURI);

      orbConf.put("org.omg.CORBA.ORBClass", orbClass);
      orbConf.put("org.omg.CORBA.ORBSingletonClass", orbSingletonClass);
      
      return orbConf;
   }
}

