package Addressbook;

/*
 * dbXML Core - Example Code
 *
 * Copyright (c) 1999-2001 The dbXML Group
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *       in all copies of substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * $Id: DBConnection.java,v 1.1 2001/08/08 04:56:14 kstaken Exp $
 */
 
import org.xmldb.api.base.*;
import org.dbxml.client.xmldb.*;
import org.xmldb.api.DatabaseManager;

import javax.servlet.*;
import javax.servlet.http.*;

import java.net.*;

/**
Singleton class used to hold system wide instances of database connection
and Collection object
*/
public class DBConnection extends HttpServlet {

   // Collection manager path to instantiate
   public static final String DBXMLURI="dbxml:///db/";
   public static final String COLLECTIONURI="xmldb:" + DBXMLURI;
   String colstring = COLLECTIONURI + "addressbook";
   
   protected static DBConnection connection = new DBConnection();
   protected static Database dbxml = null;
   protected static Collection collection = null;

   public Collection getCollectionInstance(HttpServletRequest request, HttpServletResponse response ) throws javax.servlet.ServletException, java.io.IOException {
   
      try {
         if ( dbxml == null ) {
            
            // Register the dbxml database handler
            dbxml = (Database)Class.forName("org.dbxml.client.xmldb.DatabaseImpl").newInstance();
            DatabaseManager.registerDatabase(dbxml);
            // Get a collection instance
            collection = DatabaseManager.getCollection( colstring );
         }
   
      } catch ( Exception e) {
      
         // Catch the exception and send the user to the error page
         if (e.getMessage() != null ) {
            response.sendRedirect("/Addressbook/error.jsp?error=" + URLEncoder.encode(e.getMessage()) );
         }
         else {
            response.sendRedirect("/Addressbook/error.jsp" );
         }
         e.printStackTrace();
      }
      
      return collection;
      
   }
}
