package org.dbxml.core;

/*
 * 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: Database.java,v 1.30 2001/07/13 01:56:50 tom Exp $
 */

import org.dbxml.server.*;
import org.dbxml.core.query.*;
import org.dbxml.core.security.*;
import org.dbxml.core.objects.*;
import org.dbxml.core.request.*;
import org.dbxml.server.util.*;

import org.w3c.dom.*;

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

/**
 * Database is the primary container for the dbXML Database Engine.
 */

public final class Database extends Collection implements Named, KernelAccess {
   private static final String DBROOT = "dbroot";
   private static final String SECURITY = "security";
   private static final String PACKAGE = "package";
   private static final String QUERYENGINE = "queryengine";
   private static final String NAME = "name";

   private static final Map databases = new HashMap(); // String to Database

   private DocumentCache docCache = new DocumentCache();
   private DBSecurityManager securityManager = null;

   private ObjectPool uriPool = new ObjectPool() {
      public Poolable createObject() {
         return new URIMapper();
      }
   };

   private SystemCollection sysCol = null;

   private boolean sysInit = false;
   private Kernel kernel = null;

   private QueryEngine engine = new QueryEngine(this);

   public Database() {
   }

   public static Database getDatabase(String name) {
      return (Database)databases.get(name);
   }

   public static String[] listDatabases() {
      return (String[]) databases.keySet().toArray(new String[0]);
   }

   public void setKernel(Kernel kernel) {
      this.kernel = kernel;
   }

   public Kernel getKernel() {
      return kernel;
   }

   public void setConfig(Configuration config) {
      this.config = config;

      name = config.getAttribute(NAME);
      setCanonicalName('/' + getName());
      setCollectionRoot(new File(config.getAttribute(DBROOT)));

      // Create the security manager so that it exists for loading the system
      // collections.
      // TODO: Finish security manager implementation
      if (securityManager == null) {
         boolean disableSecurity = false;
         if (config.getAttribute(SECURITY).equals("false")) {
            disableSecurity = true;
         }

         securityManager = new LocalSecurityManager(this, disableSecurity);
      }

      try {
         Configuration queryCfg = config.getChild(QUERYENGINE);
         if ( queryCfg != null )
            engine.setConfig(queryCfg);
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }

      if ( !sysInit ) {
         sysCol = new SystemCollection(this);

         try {
            sysCol.init();
         }
         catch ( dbXMLException e ) {
            org.dbxml.Debug.printStackTrace(e);
         }

         collections.put(sysCol.getName(), sysCol);
         sysInit = true;
      }

      // System collections are loaded so we need to load the security config
      // and setup the system for secure operation.
      // TODO: Finish security manager implementation
      /*if (securityManager != null) {
         securityManager.readConfig();
         // Default admin level for the primary thread for testing.
         try {
            securityManager.authenticate("scott", "tiger");
         }
         catch (Exception e) {
            org.dbxml.Debug.printStackTrace(e);
         }
         securityManager.setActive();
      }*/

      try {
         super.setConfig(config);
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }

      // Register the Database with the VM
      databases.put(getName(), this);
   }

   public SystemCollection getSystemCollection() {
      return sysCol;
   }

   public Database getDatabase() {
      return this;
   }

   /**
    * getURIMapper returns a pooled URIMapper instance.
    *
    * @return A Pooled URIMapper
    */
   public URIMapper getURIMapper() {
      return (URIMapper)uriPool.getObject();
   }

   /**
    * getURIMapper returns a pooled URIMapper instance.
    *
    * @param uri The URI to resolve
    * @return A Pooled (and resolved) URIMapper
    */
   public URIMapper getURIMapper(String uri) throws DBException {
      try {
         URIMapper map = (URIMapper)uriPool.getObject();
         map.setURI(uri);
         return map;
      }
      catch ( Exception e ) {
         throw new DBException(FaultCodes.URI_PARSE_ERROR, "Couldn't Parse URL: '"+uri+"'");
      }
   }

   /**
    * getDocumentCache returns the Database-level Document Cache.
    *
    * @return The DocumentCache
    */
   public DocumentCache getDocumentCache() {
      return docCache;
   }

   /**
    * getQueryEngine returns a reference to the Database's current
    * operating QueryEngine implementation.
    *
    * @return The QueryEngine instance
    */
   public QueryEngine getQueryEngine() {
      return engine;
   }

   /**
    * Returns the security manager instance for this Database.
    *
    * @return The security manager
    */
   public DBSecurityManager getSecurityManager() {
      return securityManager;
   }
}

