package addressbook;

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id: DBConnection.java 581305 2007-10-02 16:55:49Z vgritsenko $
 */
 
import java.net.URLEncoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;

/**
Singleton class used to hold system wide instances of database connection
and Collection object
*/
public class DBConnection extends HttpServlet {
    // Collection manager path to instantiate
    private static final String PROTOCOL = "xmldb:xindice";
    private static final String HOST = "localhost";
    private static final String PATH = "/db/addressbook";

    protected static DBConnection connection = new DBConnection();
    protected static Database db = null;
    protected static Collection collection = null;

    public Collection getCollectionInstance(HttpServletRequest request, HttpServletResponse response ) throws javax.servlet.ServletException, java.io.IOException {
   
        try {
            if (db == null) {
            
                // Register the dbxml database handler
                db = (Database)Class.forName("org.apache.xindice.client.xmldb.DatabaseImpl").newInstance();
                DatabaseManager.registerDatabase(db);

                // Get a collection instance
                String col = PROTOCOL + "://" + HOST + ":" + request.getServerPort() + PATH;
                collection = DatabaseManager.getCollection(col);
            }
   
        } catch (Exception e) {
            e.printStackTrace();

            // there's not much else we can do if the response is committed
            if (response.isCommitted())
                return collection;

            // 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(), "UTF-8"));
            } else {
                response.sendRedirect("/addressbook/error.jsp");
            }
        }
      
        return collection;
    }
}
