All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.datanucleus.store.rdbms.ConnectionFactoryImpl Maven / Gradle / Ivy

There is a newer version: 6.0.8
Show newest version
/**********************************************************************
Copyright (c) 2007 Erik Bengtson and others. All rights reserved.
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.

Contributors:
    ...
**********************************************************************/
package org.datanucleus.store.rdbms;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

import org.datanucleus.ExecutionContext;
import org.datanucleus.PropertyNames;
import org.datanucleus.Transaction;
import org.datanucleus.exceptions.ConnectionFactoryNotFoundException;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.exceptions.NucleusException;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.exceptions.UnsupportedConnectionFactoryException;
import org.datanucleus.store.StoreManager;
import org.datanucleus.store.connection.AbstractConnectionFactory;
import org.datanucleus.store.connection.AbstractEmulatedXAResource;
import org.datanucleus.store.connection.AbstractManagedConnection;
import org.datanucleus.store.connection.ManagedConnection;
import org.datanucleus.store.rdbms.adapter.DatastoreAdapter;
import org.datanucleus.store.rdbms.connectionpool.ConnectionPool;
import org.datanucleus.store.rdbms.connectionpool.ConnectionPoolFactory;
import org.datanucleus.transaction.TransactionIsolation;
import org.datanucleus.transaction.TransactionUtils;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.StringUtils;

/**
 * ConnectionFactory for RDBMS datastores.
 * Each instance is a factory of transactional or non-transactional connections.
 */
public class ConnectionFactoryImpl extends AbstractConnectionFactory
{
    /** Datasources from which to get the connections. Will have a single DataSource unless using a priority list of DataSources. */
    DataSource[] dataSources;

    /** Optional locally-managed pool of connections from which we get our connections (when using URL). */
    ConnectionPool pool = null;

    /**
     * Constructor.
     * @param storeMgr Store Manager
     * @param resourceName either tx or nontx
     */
    public ConnectionFactoryImpl(StoreManager storeMgr, String resourceName)
    {
        super(storeMgr, resourceName);
        if (resourceName.equals(RESOURCE_NAME_TX))
        {
            // Primary DataSource to be present always
            initialiseDataSources();
        }
    }

    /* (non-Javadoc)
     * @see org.datanucleus.store.connection.AbstractConnectionFactory#close()
     */
    @Override
    public void close()
    {
        if (pool != null)
        {
            // Close any DataNucleus-created connection pool
            if (NucleusLogger.CONNECTION.isDebugEnabled())
            {
                NucleusLogger.CONNECTION.debug(Localiser.msg("047010", getResourceName()));
            }
            pool.close();
        }
        super.close();
    }

    /**
     * Method to initialise the DataSource(s) used by this ConnectionFactory.
     * Only invoked when the request for the first connection comes in.
     */
    protected synchronized void initialiseDataSources()
    {
        if (getResourceName().equals(RESOURCE_NAME_TX))
        {
            // Transactional
            String requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE);
            Object connDS = storeMgr.getConnectionFactory();
            String connJNDI = storeMgr.getConnectionFactoryName();
            String connURL = storeMgr.getConnectionURL();
            dataSources = generateDataSources(storeMgr, connDS, connJNDI, getResourceName(), requiredPoolingType, connURL);
            if (dataSources == null)
            {
                throw new NucleusUserException(Localiser.msg("047009", "transactional")).setFatal();
            }
        }
        else
        {
            // Non-transactional
            String requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE2);
            if (requiredPoolingType == null)
            {
                requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE);
            }
            Object connDS = storeMgr.getConnectionFactory2();
            String connJNDI = storeMgr.getConnectionFactory2Name();
            String connURL = storeMgr.getConnectionURL();
            dataSources = generateDataSources(storeMgr, connDS, connJNDI, getResourceName(), requiredPoolingType, connURL);
            if (dataSources == null)
            {
                // Fallback to transactional settings
                connDS = storeMgr.getConnectionFactory();
                connJNDI = storeMgr.getConnectionFactoryName();
                dataSources = generateDataSources(storeMgr, connDS, connJNDI, getResourceName(), requiredPoolingType, connURL);
            }
            if (dataSources == null)
            {
                throw new NucleusUserException(Localiser.msg("047009", "non-transactional")).setFatal();
            }
        }
    }

    /**
     * Method to generate the datasource(s) used by this connection factory.
     * Searches initially for a provided DataSource then, if not found, for JNDI DataSource(s), and finally for the DataSource at a connection URL.
     * @param storeMgr Store Manager
     * @param connDS Factory data source object
     * @param connJNDI DataSource JNDI name(s)
     * @param resourceType Type of resource
     * @param requiredPoolingType Type of connection pool
     * @param connURL URL for connections
     * @return The DataSource(s)
     */
    private DataSource[] generateDataSources(StoreManager storeMgr, Object connDS, String connJNDI, String resourceType, String requiredPoolingType, String connURL)
    {
        DataSource[] dataSources = null;
        if (connDS != null)
        {
            if (!(connDS instanceof DataSource) && !(connDS instanceof XADataSource))
            {
                throw new UnsupportedConnectionFactoryException(connDS);
            }
            dataSources = new DataSource[1];
            dataSources[0] = (DataSource) connDS;
        }
        else if (connJNDI != null)
        {
            String[] connectionFactoryNames = StringUtils.split(connJNDI, ",");
            dataSources = new DataSource[connectionFactoryNames.length];
            for (int i=0; i= 0)
                        {
                            // Override with the adapters required isolation level
                            reqdIsolationLevel = rdba.getRequiredTransactionIsolationLevel();
                        }

                        cnx = connProvider.getConnection(dataSources);
                        boolean succeeded = false;
                        try
                        {
                            if (cnx.isReadOnly() != readOnly)
                            {
                                NucleusLogger.CONNECTION.debug("Setting readonly=" + readOnly + " to connection: " + cnx.toString());
                                cnx.setReadOnly(readOnly);
                            }

                            if (reqdIsolationLevel == TransactionIsolation.NONE)
                            {
                                if (!cnx.getAutoCommit())
                                {
                                    cnx.setAutoCommit(true);
                                }
                            }
                            else
                            {
                                if (cnx.getAutoCommit())
                                {
                                    cnx.setAutoCommit(false);
                                }
                                if (rdba.supportsTransactionIsolation(reqdIsolationLevel))
                                {
                                    int currentIsolationLevel = cnx.getTransactionIsolation();
                                    if (currentIsolationLevel != reqdIsolationLevel)
                                    {
                                        cnx.setTransactionIsolation(reqdIsolationLevel);
                                    }
                                }
                                else
                                {
                                    NucleusLogger.CONNECTION.warn(Localiser.msg("051008", reqdIsolationLevel));
                                }
                            }

                            if (NucleusLogger.CONNECTION.isDebugEnabled())
                            {
                                NucleusLogger.CONNECTION.debug(Localiser.msg("009012", this.toString(),
                                    TransactionUtils.getNameForTransactionIsolationLevel(reqdIsolationLevel), cnx.getAutoCommit()));
                            }

                            if (reqdIsolationLevel != isolation && isolation == TransactionIsolation.NONE)
                            {
                                // User asked for a level that implies auto-commit so make sure it has that
                                if (!cnx.getAutoCommit())
                                {
                                    NucleusLogger.CONNECTION.debug("Setting autocommit=true for connection: "+StringUtils.toJVMIDString(cnx));
                                    cnx.setAutoCommit(true);
                                }
                            }

                            succeeded = true;
                        }
                        catch (SQLException e)
                        {
                            throw new NucleusDataStoreException(e.getMessage(),e);
                        }
                        finally
                        {
                            if (!succeeded)
                            {
                                try
                                {
                                    cnx.close();
                                }
                                catch (SQLException e)
                                {
                                }

                                if (NucleusLogger.CONNECTION.isDebugEnabled())
                                {
                                    NucleusLogger.CONNECTION.debug(Localiser.msg("009013", this.toString()));
                                }
                            }
                        }
                    }
                    else
                    {
                        // Create basic Connection since no DatastoreAdapter created yet
                        cnx = dataSources[0].getConnection();
                        if (cnx == null)
                        {
                            String msg = Localiser.msg("009010", dataSources[0]);
                            NucleusLogger.CONNECTION.error(msg);
                            throw new NucleusDataStoreException(msg);
                        }
                        if (NucleusLogger.CONNECTION.isDebugEnabled())
                        {
                            NucleusLogger.CONNECTION.debug(Localiser.msg("009011", this.toString()));
                        }
                    }
                }
                catch (SQLException e)
                {
                    throw new NucleusDataStoreException(e.getMessage(),e);
                }

                this.conn = cnx;
            }
            needsCommitting = true;
            return this.conn;
        }

        /**
         * Close the connection
         */
        public void close()
        {
            for (int i=0; i savepoints = null;

        /* (non-Javadoc)
         * @see org.datanucleus.store.connection.AbstractManagedConnection#setSavepoint(java.lang.String)
         */
        @Override
        public void setSavepoint(String name)
        {
            try
            {
                Savepoint sp = ((Connection)conn).setSavepoint(name);
                if (savepoints == null)
                {
                    savepoints = new HashMap<>();
                }
                savepoints.put(name, sp);
            }
            catch (SQLException sqle)
            {
                throw new NucleusDataStoreException("Exception setting savepoint " + name, sqle);
            }
        }

        /* (non-Javadoc)
         * @see org.datanucleus.store.connection.AbstractManagedConnection#releaseSavepoint(java.lang.String)
         */
        @Override
        public void releaseSavepoint(String name)
        {
            try
            {
                if (savepoints == null)
                {
                    return;
                }
                Savepoint sp = savepoints.remove(name);
                if (sp == null)
                {
                    throw new IllegalStateException("No savepoint with name " + name);
                }
                ((Connection)conn).releaseSavepoint(sp);
            }
            catch (SQLException sqle)
            {
                throw new NucleusDataStoreException("Exception releasing savepoint " + name, sqle);
            }
        }

        /* (non-Javadoc)
         * @see org.datanucleus.store.connection.AbstractManagedConnection#rollbackToSavepoint(java.lang.String)
         */
        @Override
        public void rollbackToSavepoint(String name)
        {
            try
            {
                if (savepoints == null)
                {
                    return;
                }
                Savepoint sp = savepoints.get(name);
                if (sp == null)
                {
                    throw new IllegalStateException("No savepoint with name " + name);
                }
                ((Connection)conn).rollback(sp);
            }
            catch (SQLException sqle)
            {
                throw new NucleusDataStoreException("Exception rolling back to savepoint " + name, sqle);
            }
        }

        /* (non-Javadoc)
         * @see org.datanucleus.store.connection.AbstractManagedConnection#closeAfterTransactionEnd()
         */
        @Override
        public boolean closeAfterTransactionEnd()
        {
            if (storeMgr.getBooleanProperty(PropertyNames.PROPERTY_CONNECTION_SINGLE_CONNECTION))
            {
                return false;
            }
            return super.closeAfterTransactionEnd();
        }
    }

    /**
     * Emulate the two phase protocol for non XA
     */
    static class EmulatedXAResource extends AbstractEmulatedXAResource
    {
        Connection conn;

        EmulatedXAResource(ManagedConnection mconn)
        {
            super(mconn);
            this.conn = (Connection) mconn.getConnection();
        }

        public void commit(Xid xid, boolean onePhase) throws XAException
        {
            super.commit(xid, onePhase);
            try
            {
                conn.commit();
                ((ManagedConnectionImpl)mconn).xaRes = null;
            }
            catch (SQLException e)
            {
                NucleusLogger.CONNECTION.debug(Localiser.msg("009020", mconn.toString(), xid.toString(), onePhase));
                XAException xe = new XAException(StringUtils.getStringFromStackTrace(e));
                xe.initCause(e);
                throw xe;
            }
        }

        public void rollback(Xid xid) throws XAException
        {
            super.rollback(xid);
            try
            {
                conn.rollback();
                ((ManagedConnectionImpl)mconn).xaRes = null;
            }
            catch (SQLException e)
            {
                NucleusLogger.CONNECTION.debug(Localiser.msg("009022", mconn.toString(), xid.toString()));
                XAException xe = new XAException(StringUtils.getStringFromStackTrace(e));
                xe.initCause(e);
                throw xe;
            }
        }

        public void end(Xid xid, int flags) throws XAException
        {
            super.end(xid, flags);
            ((ManagedConnectionImpl)mconn).xaRes = null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy