/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.gjc.spi;

import javax.resource.ResourceException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.security.PasswordCredential;

import com.sun.gjc.common.DataSourceObjectBuilder;
import com.sun.gjc.util.SecurityUtils;
import com.sun.logging.*;

import java.util.logging.Logger;
import java.util.logging.Level;

import com.sun.enterprise.util.i18n.StringManager;

import javax.resource.spi.ResourceAllocationException;

/**
 * Data Source <code>ManagedConnectionFactory</code> implementation for Generic JDBC Connector.
 *
 * @author Evani Sai Surya Kiran
 * @version 1.0, 02/07/30
 */

public class DSManagedConnectionFactory extends ManagedConnectionFactory {

    private transient javax.sql.DataSource dataSourceObj;

    private static Logger _logger;

    static {
        _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
    }

    /**
     * Creates a new physical connection to the underlying EIS resource
     * manager.
     *
     * @param subject       <code>Subject</code> instance passed by the application server
     * @param cxRequestInfo <code>ConnectionRequestInfo</code> which may be created
     *                      as a result of the invocation <code>getConnection(user, password)</code>
     *                      on the <code>DataSource</code> object
     * @return <code>ManagedConnection</code> object created
     * @throws ResourceException           if there is an error in instantiating the
     *                                     <code>DataSource</code> object used for the
     *                                     creation of the <code>ManagedConnection</code> object
     * @throws SecurityException           if there ino <code>PasswordCredential</code> object
     *                                     satisfying this request
     * @throws ResourceAllocationException if there is an error in allocating the
     *                                     physical connection
     */
    public javax.resource.spi.ManagedConnection createManagedConnection(javax.security.auth.Subject subject,
                                                                        ConnectionRequestInfo cxRequestInfo) throws ResourceException {
        if (logWriter != null) {
            logWriter.println("In createManagedConnection");
        }
        PasswordCredential pc = SecurityUtils.getPasswordCredential(this, subject, cxRequestInfo);

        javax.sql.DataSource dataSource = getDataSource();

        java.sql.Connection dsConn = null;

        try {
            /* For the case where the user/passwd of the connection pool is
            * equal to the PasswordCredential for the connection request
            * get a connection from this pool directly.
            * for all other conditions go create a new connection
            */

            if (isEqual(pc, getUser(), getPassword())) {
                dsConn = dataSource.getConnection();
            } else {
                dsConn = dataSource.getConnection(pc.getUserName(),
                        new String(pc.getPassword()));
            }
        } catch (java.sql.SQLException sqle) {
            //_logger.log(Level.WARNING, "jdbc.exc_create_conn", sqle.getMessage());
            _logger.log(Level.FINE, "jdbc.exc_create_conn", sqle.getMessage());
            StringManager localStrings =
                    StringManager.getManager(DataSourceObjectBuilder.class);
            String msg = localStrings.getString("jdbc.cannot_allocate_connection"
                    , sqle.getMessage());
            ResourceAllocationException rae = new ResourceAllocationException(msg);
            rae.initCause(sqle);
            throw rae;
        }

        com.sun.gjc.spi.ManagedConnection mc = constructManagedConnection(
                null, dsConn, pc, this);

        //GJCINT
        validateAndSetIsolation(mc);

        return mc;
    }

    /**
     * Returns the underlying datasource
     * @return DataSource of jdbc vendor
     * @throws ResourceException
     */
    public javax.sql.DataSource getDataSource() throws ResourceException {
        if (dataSourceObj == null) {
            try {
                dataSourceObj = (javax.sql.DataSource) super.getDataSource();
            } catch (ClassCastException cce) {
                _logger.log(Level.SEVERE, "jdbc.exc_cce", cce);
                throw new ResourceException(cce.getMessage());
            }
        }
        return dataSourceObj;
    }

    /**
     * Check if this <code>ManagedConnectionFactory</code> is equal to
     * another <code>ManagedConnectionFactory</code>.
     *
     * @param other <code>ManagedConnectionFactory</code> object for checking equality with
     * @return true    if the property sets of both the
     *         <code>ManagedConnectionFactory</code> objects are the same
     *         false	otherwise
     */
    public boolean equals(Object other) {
        if (logWriter != null) {
            logWriter.println("In equals");
        }
        /**
         * The check below means that two ManagedConnectionFactory objects are equal
         * if and only if their properties are the same.
         */
        if (other instanceof com.sun.gjc.spi.DSManagedConnectionFactory) {
            com.sun.gjc.spi.DSManagedConnectionFactory otherMCF =
                    (com.sun.gjc.spi.DSManagedConnectionFactory) other;
            return this.spec.equals(otherMCF.spec);
        }
        return false;
    }
}
