Search in sources :

Example 11 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testNonPooledConnection.

// Bug 332683 - Problems with ClientSession connections
// This test verifies that non pooled connection case works.
public void testNonPooledConnection() {
    ServerSession ss = getServerSession();
    // Normally the user wishing to use not pooled connection would specify user and password properties (and possibly db url, too).
    // However if these properties have the same values that those in the logging then no non pooled connection is created and the pooled one used instead.
    // In the test we must use the same user as already in the session login (don't know any others) that forces usage of ConnectionPolicy property.
    ConnectionPolicy connectionPolicy = (ConnectionPolicy) ss.getDefaultConnectionPolicy().clone();
    connectionPolicy.setLogin(ss.getLogin());
    connectionPolicy.setPoolName(null);
    EntityManager em;
    boolean isEmInjected = isOnServer() && ss.getLogin().shouldUseExternalTransactionController();
    boolean isSpring = isOnServer() && getServerPlatform().isSpring();
    if (isEmInjected) {
        em = createEntityManager();
        // In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
        beginTransaction(em);
        em.setProperty(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
    } else {
        EntityManagerFactory emFactory = getEntityManagerFactory();
        Map properties = new HashMap(1);
        properties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
        em = emFactory.createEntityManager(properties);
        if (isSpring) {
            em.getTransaction().begin();
        } else {
            beginTransaction(em);
        }
    }
    try {
        // native query triggers early begin transaction
        em.createNativeQuery("SELECT F_NAME FROM CMP3_EMPLOYEE").getResultList();
        // verify that the connection is really not pooled.
        assertTrue("Test problem: connection should be not pooled", em.unwrap(UnitOfWork.class).getParent().getAccessor().getPool() == null);
    } finally {
        if (isSpring) {
            em.getTransaction().rollback();
        } else {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) HashMap(java.util.HashMap) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method createConnectionPolicies.

/**
 * Create connection policy using properties.
 * Default connection policy created if no connection properties specified.
 * Should be called only in case this.databaseSession is a SessionBroker.
 */
protected void createConnectionPolicies(Map mapOfProperties) {
    // Because the method called only in SessionBroker case this.connectionPolicies is guaranteed to be non null.
    Iterator<Map.Entry<String, ConnectionPolicy>> it = this.connectionPolicies.entrySet().iterator();
    while (it.hasNext()) {
        // key - sessionName, value - ConnectionPolicy
        Map.Entry<String, ConnectionPolicy> entry = it.next();
        if (entry.getValue() == null) {
            // ConnectionPolicy is null - should be recreated
            Map properties = null;
            if (mapOfProperties != null) {
                properties = (Map) mapOfProperties.get(entry.getKey());
            }
            ConnectionPolicy connectionPolicy = createConnectionPolicy((ServerSession) this.databaseSession.getSessionForName(entry.getKey()), properties);
            this.connectionPolicies.put(entry.getKey(), connectionPolicy);
        }
    }
}
Also used : ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Example 13 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method createConnectionPolicy.

/**
 * Create connection policy using properties.
 * Default connection policy created if no connection properties specified.
 */
protected static ConnectionPolicy createConnectionPolicy(ServerSession serverSession, Map properties) {
    ConnectionPolicy policy = serverSession.getDefaultConnectionPolicy();
    if (properties == null || properties.isEmpty()) {
        return policy;
    }
    // Search only the properties map - serverSession's properties have been
    // already processed.
    ConnectionPolicy policyFromProperties = (ConnectionPolicy) properties.get(EntityManagerProperties.CONNECTION_POLICY);
    if (policyFromProperties != null) {
        policy = policyFromProperties;
    }
    // Note that serverSession passed into the methods below only because it
    // carries the SessionLog into which the debug info should be written.
    // The property is search for in the passed properties map only (not in
    // serverSession, not in System.properties).
    ConnectionPolicy newPolicy = null;
    String isLazyString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(EntityManagerProperties.EXCLUSIVE_CONNECTION_IS_LAZY, properties, serverSession, false);
    if (isLazyString != null) {
        boolean isLazy = Boolean.parseBoolean(isLazyString);
        if (policy.isLazy() != isLazy) {
            if (newPolicy == null) {
                newPolicy = (ConnectionPolicy) policy.clone();
            }
            newPolicy.setIsLazy(isLazy);
        }
    }
    ConnectionPolicy.ExclusiveMode exclusiveMode = EntityManagerSetupImpl.getConnectionPolicyExclusiveModeFromProperties(properties, serverSession, false);
    if (exclusiveMode != null) {
        if (!exclusiveMode.equals(policy.getExclusiveMode())) {
            if (newPolicy == null) {
                newPolicy = (ConnectionPolicy) policy.clone();
            }
            newPolicy.setExclusiveMode(exclusiveMode);
        }
    }
    String user = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(EntityManagerProperties.JDBC_USER, properties, serverSession, false);
    String password = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(EntityManagerProperties.JDBC_PASSWORD, properties, serverSession, false);
    String driver = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(EntityManagerProperties.JDBC_DRIVER, properties, serverSession, false);
    String connectionString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(EntityManagerProperties.JDBC_URL, properties, serverSession, false);
    // find the jta datasource
    Object jtaDataSourceObj = EntityManagerFactoryProvider.getConfigPropertyLogDebug(EntityManagerProperties.JTA_DATASOURCE, properties, serverSession, false);
    DataSource jtaDataSource = null;
    String jtaDataSourceName = null;
    if (jtaDataSourceObj != null) {
        if (jtaDataSourceObj instanceof DataSource) {
            jtaDataSource = (DataSource) jtaDataSourceObj;
        } else if (jtaDataSourceObj instanceof String) {
            jtaDataSourceName = (String) jtaDataSourceObj;
        }
    }
    // find the non jta datasource
    Object nonjtaDataSourceObj = EntityManagerFactoryProvider.getConfigPropertyLogDebug(EntityManagerProperties.NON_JTA_DATASOURCE, properties, serverSession, false);
    DataSource nonjtaDataSource = null;
    String nonjtaDataSourceName = null;
    if (nonjtaDataSourceObj != null) {
        if (nonjtaDataSourceObj instanceof DataSource) {
            nonjtaDataSource = (DataSource) nonjtaDataSourceObj;
        } else if (nonjtaDataSourceObj instanceof String) {
            nonjtaDataSourceName = (String) nonjtaDataSourceObj;
        }
    }
    if (user != null || password != null || driver != null || connectionString != null || jtaDataSourceObj != null || nonjtaDataSourceObj != null) {
        // Validation: Can't specify jdbcDriver, connectionString with a
        // DataSource
        boolean isDefaultConnectorRequired = isPropertyToBeAdded(driver) || isPropertyToBeAdded(connectionString);
        boolean isJNDIConnectorRequired = isPropertyToBeAdded(jtaDataSource, jtaDataSourceName) || isPropertyToBeAdded(nonjtaDataSource, nonjtaDataSourceName);
        if (isDefaultConnectorRequired && isJNDIConnectorRequired) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("entity_manager_properties_conflict_default_connector_vs_jndi_connector", new Object[] {}));
        }
        DatasourceLogin login = (DatasourceLogin) policy.getLogin();
        if (login == null) {
            if (policy.getPoolName() != null) {
                login = (DatasourceLogin) serverSession.getConnectionPool(policy.getPoolName()).getLogin();
            } else {
                login = (DatasourceLogin) serverSession.getDatasourceLogin();
            }
        }
        // externalConnectionPooling
        if (login.shouldUseExternalTransactionController() && isDefaultConnectorRequired) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("entity_manager_properties_conflict_default_connector_vs_external_transaction_controller", new Object[] {}));
        }
        javax.sql.DataSource dataSource = null;
        String dataSourceName = null;
        if (isJNDIConnectorRequired) {
            if (login.shouldUseExternalTransactionController()) {
                if (isPropertyToBeAdded(jtaDataSource, jtaDataSourceName)) {
                    dataSource = jtaDataSource;
                    dataSourceName = jtaDataSourceName;
                }
                // flag.
                if (isPropertyToBeAdded(nonjtaDataSource, nonjtaDataSourceName)) {
                    serverSession.log(SessionLog.WARNING, SessionLog.PROPERTIES, "entity_manager_ignores_nonjta_data_source");
                }
            } else {
                if (isPropertyToBeAdded(nonjtaDataSource, nonjtaDataSourceName)) {
                    dataSource = nonjtaDataSource;
                    dataSourceName = nonjtaDataSourceName;
                }
                // flag.
                if (isPropertyToBeAdded(jtaDataSource, jtaDataSourceName)) {
                    serverSession.log(SessionLog.WARNING, SessionLog.PROPERTIES, "entity_manager_ignores_jta_data_source");
                }
            }
        }
        // isNew...Required == null means no change required; TRUE -
        // newValue substitute oldValue by newValue; FALSE - remove
        // oldValue.
        Boolean isNewUserRequired = isPropertyValueToBeUpdated(login.getUserName(), user);
        // if isNewUserRequired==null then isNewPasswordRequired==null, too:
        // don't create a new ConnectionPolicy if the same user/password passed to both createEMF and createEM
        Boolean isNewPasswordRequired = null;
        // should be removed, too.
        if (isNewUserRequired != null) {
            if (isNewUserRequired) {
                if (password != null) {
                    // can't compare the passed (un-encrypted) password with the existing encrypted one, therefore
                    // use the new password if it's not an empty string.
                    isNewPasswordRequired = password.length() > 0;
                }
            } else {
                // user should be removed -> remove password as well
                isNewPasswordRequired = Boolean.FALSE;
            }
        }
        DefaultConnector oldDefaultConnector = null;
        if (login.getConnector() instanceof DefaultConnector) {
            oldDefaultConnector = (DefaultConnector) login.getConnector();
        }
        boolean isNewDefaultConnectorRequired = oldDefaultConnector == null && isDefaultConnectorRequired;
        JNDIConnector oldJNDIConnector = null;
        if (login.getConnector() instanceof JNDIConnector) {
            oldJNDIConnector = (JNDIConnector) login.getConnector();
        }
        boolean isNewJNDIConnectorRequired = oldJNDIConnector == null && isJNDIConnectorRequired;
        Boolean isNewDriverRequired = null;
        Boolean isNewConnectionStringRequired = null;
        if (isNewDefaultConnectorRequired) {
            isNewDriverRequired = isPropertyValueToBeUpdated(null, driver);
            isNewConnectionStringRequired = isPropertyValueToBeUpdated(null, connectionString);
        } else {
            if (oldDefaultConnector != null) {
                isNewDriverRequired = isPropertyValueToBeUpdated(oldDefaultConnector.getDriverClassName(), driver);
                isNewConnectionStringRequired = isPropertyValueToBeUpdated(oldDefaultConnector.getConnectionString(), connectionString);
            }
        }
        Boolean isNewDataSourceRequired = null;
        if (isNewJNDIConnectorRequired) {
            isNewDataSourceRequired = Boolean.TRUE;
        } else {
            if (oldJNDIConnector != null) {
                if (dataSource != null) {
                    if (!dataSource.equals(oldJNDIConnector.getDataSource())) {
                        isNewDataSourceRequired = Boolean.TRUE;
                    }
                } else if (dataSourceName != null) {
                    if (!dataSourceName.equals(oldJNDIConnector.getName())) {
                        isNewDataSourceRequired = Boolean.TRUE;
                    }
                }
            }
        }
        if (isNewUserRequired != null || isNewPasswordRequired != null || isNewDriverRequired != null || isNewConnectionStringRequired != null || isNewDataSourceRequired != null) {
            // a new login required - so a new policy required, too.
            if (newPolicy == null) {
                newPolicy = (ConnectionPolicy) policy.clone();
            }
            // the new policy must have a new login - not to override the
            // existing one in the original ConnectionPolicy that is likely
            // shared.
            DatasourceLogin newLogin = (DatasourceLogin) newPolicy.getLogin();
            // sometimes it doesn't.
            if (newPolicy.getLogin() == null || newPolicy.getLogin() == policy.getLogin()) {
                newLogin = login.clone();
                newPolicy.setLogin(newLogin);
            }
            // because it uses a new login the connection policy should not
            // be pooled.
            newPolicy.setPoolName(null);
            if (isNewUserRequired != null) {
                if (isNewUserRequired) {
                    newLogin.setProperty("user", user);
                } else {
                    newLogin.getProperties().remove("user");
                }
            }
            if (isNewPasswordRequired != null) {
                if (isNewPasswordRequired) {
                    newLogin.setProperty("password", password);
                } else {
                    newLogin.getProperties().remove("password");
                }
            }
            if (isNewDefaultConnectorRequired) {
                newLogin.setConnector(new DefaultConnector());
                newLogin.setUsesExternalConnectionPooling(false);
            } else if (isNewJNDIConnectorRequired) {
                newLogin.setConnector(new JNDIConnector());
                newLogin.setUsesExternalConnectionPooling(true);
            }
            if (isDefaultConnectorRequired) {
                DefaultConnector defaultConnector = (DefaultConnector) newLogin.getConnector();
                if (isNewDriverRequired != null) {
                    if (isNewDriverRequired) {
                        defaultConnector.setDriverClassName(driver);
                    } else {
                        defaultConnector.setDriverClassName(null);
                    }
                }
                if (isNewConnectionStringRequired != null) {
                    if (isNewConnectionStringRequired) {
                        defaultConnector.setDatabaseURL(connectionString);
                    } else {
                        defaultConnector.setDatabaseURL(null);
                    }
                }
            } else if (isNewDataSourceRequired != null) {
                JNDIConnector jndiConnector = (JNDIConnector) newLogin.getConnector();
                if (isNewDataSourceRequired) {
                    if (dataSource != null) {
                        jndiConnector.setDataSource(dataSource);
                    } else {
                        // dataSourceName != null
                        jndiConnector.setDataSource(null);
                        jndiConnector.setName(dataSourceName);
                    }
                }
            }
        }
    }
    if (newPolicy != null) {
        return newPolicy;
    } else {
        return policy;
    }
}
Also used : DatasourceLogin(org.eclipse.persistence.sessions.DatasourceLogin) DataSource(javax.sql.DataSource) DataSource(javax.sql.DataSource) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) DefaultConnector(org.eclipse.persistence.sessions.DefaultConnector)

Aggregations

ConnectionPolicy (org.eclipse.persistence.sessions.server.ConnectionPolicy)13 HashMap (java.util.HashMap)10 EntityManager (jakarta.persistence.EntityManager)9 ServerSession (org.eclipse.persistence.sessions.server.ServerSession)8 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)6 JpaEntityManagerFactory (org.eclipse.persistence.jpa.JpaEntityManagerFactory)6 JNDIConnector (org.eclipse.persistence.sessions.JNDIConnector)5 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)4 Map (java.util.Map)4 EntityTransaction (jakarta.persistence.EntityTransaction)3 EntityManagerFactoryImpl (org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl)3 Dog (org.eclipse.persistence.jpa.test.basic.model.Dog)3 Person (org.eclipse.persistence.jpa.test.basic.model.Person)3 XmlFish (org.eclipse.persistence.jpa.test.basic.model.XmlFish)3 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)3 Test (org.junit.Test)3 EntityManagerImpl (org.eclipse.persistence.internal.jpa.EntityManagerImpl)2 DataSourceImpl (org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl)2 RepeatableWriteUnitOfWork (org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork)2 UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)2