/*
 * $Header: /home/cvspublic/jakarta-slide/src/stores/org/apache/slide/store/impl/rdbms/J2EEStore.java,v 1.14 2004/07/28 09:34:17 ib Exp $
 * $Revision: 1.14 $
 * $Date: 2004/07/28 09:34:17 $
 *
 * ====================================================================
 *
 * Copyright 1999-2003 The Apache Software Foundation 
 *
 * Licensed 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.
 *
 */

package org.apache.slide.store.impl.rdbms;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.common.ServiceInitializationFailedException;
import org.apache.slide.common.ServiceParameterErrorException;
import org.apache.slide.common.ServiceParameterMissingException;
import org.apache.slide.store.ContentStore;
import org.apache.slide.store.LockStore;
import org.apache.slide.store.NodeStore;
import org.apache.slide.store.RevisionDescriptorStore;
import org.apache.slide.store.RevisionDescriptorsStore;
import org.apache.slide.store.SecurityStore;
import org.apache.slide.util.logger.Logger;

/**
 * J2EE store implementation - implements the shared parts of
 * the two (content, descriptors) J2EE stores for the new Indexed DB Schema.
 *
 * @version $Revision: 1.14 $
 */
public class J2EEStore
    extends AbstractRDBMSStore
    implements LockStore, NodeStore, RevisionDescriptorsStore, RevisionDescriptorStore, SecurityStore, ContentStore {

    protected String LOG_CHANNEL = this.getClass().getName();

    // ----------------------------------------------------- Instance Variables

    /**
     * Database connection source.
     */
    protected DataSource ds = null;

    /**
     * Value of the datasource parameter.
     */
    protected String datasource;

    // -------------------------------------------------------- Service Methods

    /**
     * Initializes the data source with a set of parameters.
     *
     * @param parameters Hashtable containing the parameters' name 
     *                   and associated value
     * @exception ServiceParameterErrorException   Incorrect service parameter
     * @exception ServiceParameterMissingException Service parameter missing
     */
    public void setParameters(Hashtable parameters)
        throws ServiceParameterErrorException, ServiceParameterMissingException {

        String value = (String) parameters.get("datasource");
        if (value == null) {
            throw new ServiceParameterMissingException(this, "datasource");
        }
        datasource = value;

        value = (String) parameters.get("tm-commits");
        if (value != null) {
            tmCommits = "true".equals(value);
        }
        
        super.setParameters(parameters);
    }

    /**
     * Initializes data source.
     * <p/>
     * Occurs in two steps :
     * <li>Datasource is looked up from the pool</li>
     * <li>Creation of the basic tables, if they didn't exist before</li>
     * 
     * @exception ServiceInitializationFailedException thrown if the data source 
     *            has already been initialized before
     */
    public synchronized void initialize(NamespaceAccessToken token) throws ServiceInitializationFailedException {

        // XXX might be done already in setParameter
        if (!alreadyInitialized) {
            try {
                // Loading and registering driver
                getLogger().log("Retrieving datasource '" + datasource + "'", LOG_CHANNEL, Logger.INFO);

                //	Initialize database
                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");

                ds = (DataSource) envCtx.lookup(datasource);
            } catch (ClassCastException e) {
                getLogger().log(
                    "Loading and registering datasource " + datasource + " failed",
                    LOG_CHANNEL,
                    Logger.ERROR);
                getLogger().log(e.toString(), LOG_CHANNEL, Logger.ERROR);
                throw new ServiceInitializationFailedException(this, e.getMessage());
            } catch (NamingException e) {
                getLogger().log(
                    "Loading and registering datasource " + datasource + " failed",
                    LOG_CHANNEL,
                    Logger.ERROR);
                getLogger().log(e.toString(), LOG_CHANNEL, Logger.ERROR);
                throw new ServiceInitializationFailedException(this, e.getMessage());
            } catch (Exception e) {
                getLogger().log(
                    "Loading and registering datasource " + datasource + " failed",
                    LOG_CHANNEL,
                    Logger.ERROR);
                getLogger().log(e.toString(), LOG_CHANNEL, Logger.ERROR);
                throw new ServiceInitializationFailedException(this, e.getMessage());
            } finally {
                alreadyInitialized = true;
            }

            if (ds == null) {
                getLogger().log("Datasource is null, can't initialize store");
                throw new ServiceInitializationFailedException(this, "Null datasource from context");
            }
        }
    }

    protected Connection getNewConnection() throws SQLException {
        Connection con = ds.getConnection();
        boolean autoCommit = con.getAutoCommit();
        if (autoCommit)
            con.setAutoCommit(false);
        return con;
    }

    protected boolean includeBranchInXid() {
        return false;
    }
}
