/*
 * 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.enterprise.resource;


import java.util.logging.Level;

import javax.transaction.xa.XAResource;
import javax.resource.spi.*;
import javax.resource.ResourceException;
import javax.security.auth.Subject;

import com.sun.enterprise.deployment.ConnectorDescriptor;
import com.sun.enterprise.PoolManager;


/**
 * @author Tony Ng
 */
public class ConnectorAllocator extends AbstractConnectorAllocator {

    private boolean shareable;
   

    class ConnectionListenerImpl implements ConnectionEventListener {
        private ResourceHandle resource;
        
        public ConnectionListenerImpl(ResourceHandle resource) {
            this.resource = resource;
        }

        public void connectionClosed(ConnectionEvent evt) {
            if (resource.hasConnectionErrorOccurred()) {
	        return;
	    }
	    
            resource.decrementCount();
            if (resource.getShareCount() == 0) {
                poolMgr.resourceClosed(resource);
            } 
            
        }
        
        public void connectionErrorOccurred(ConnectionEvent evt) {
            resource.setConnectionErrorOccurred();

            ManagedConnection mc = (ManagedConnection) evt.getSource();
            mc.removeConnectionEventListener(this);
            poolMgr.resourceErrorOccurred(resource);
            try {
                mc.destroy();
            } catch (Exception ex) {
                // ignore exception
            }
        }

        public void localTransactionStarted(ConnectionEvent evt) {
            // no-op
        }

        public void localTransactionCommitted(ConnectionEvent evt) {
            // no-op
        }

        public void localTransactionRolledback(ConnectionEvent evt) {
            // no-op
        }
    }

    public ConnectorAllocator(PoolManager poolMgr,
                              ManagedConnectionFactory mcf,
                              ResourceSpec spec,
                              Subject subject,
                              ConnectionRequestInfo reqInfo,
                              ClientSecurityInfo info,
                              ConnectorDescriptor desc,
                              boolean shareable) {
        super(poolMgr, mcf, spec, subject, reqInfo, info, desc);
        this.shareable = shareable;
    }

    
    public ResourceHandle createResource()
         throws PoolingException
    {
        try {
            ManagedConnection mc =
                mcf.createManagedConnection(subject, reqInfo);
            
            ResourceHandle resource =
                new ResourceHandle(mc, spec, this, info);
            ConnectionEventListener l = 
                new ConnectionListenerImpl(resource);
            mc.addConnectionEventListener(l);
            return resource;
        } catch (ResourceException ex) {
            throw new PoolingException(ex);
        }
    }

    public void fillInResourceObjects(ResourceHandle resource)
        throws PoolingException
    {
        try {
	    ManagedConnection mc = (ManagedConnection) resource.getResource();
	    Object con = mc.getConnection( subject, reqInfo );
	    resource.incrementCount();
            XAResource xares = mc.getXAResource();
            resource.fillInResourceObjects(con, xares);
        } catch( ResourceException ex ) {
	    throw new PoolingException( ex );
	}
    }

    public void destroyResource(ResourceHandle resource)
        throws PoolingException {

        try {
            closeUserConnection(resource);
        } catch (Exception ex) {
            // ignore error
        }
        
        try {
            ManagedConnection mc = (ManagedConnection) resource.getResource();
            mc.destroy();
        } catch (Exception ex) {
            _logger.log(Level.WARNING, ex.getMessage());
            throw new PoolingException(ex);
        }

    }

    public boolean shareableWithinComponent() {
        return shareable;
    }
}
