Search in sources :

Example 1 with ConnectionPolicy

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

the class ClientServerTest method setup.

@Override
public void setup() {
    try {
        this.login = (DatabaseLogin) getSession().getLogin().clone();
        this.server = new ServerSession(this.login, 2, 5);
        this.server.setSessionLog(getSession().getSessionLog());
        copyDescriptors(getSession());
        this.server.login();
        ConnectionPolicy connectionPolicy = this.server.getDefaultConnectionPolicy();
        if (this.exclusiveConnectionMode.equals(ExclusiveConnectionMode.Isolated)) {
            connectionPolicy.setExclusiveMode(ConnectionPolicy.ExclusiveMode.Isolated);
        } else if (this.exclusiveConnectionMode.equals(ExclusiveConnectionMode.Always)) {
            connectionPolicy.setExclusiveMode(ConnectionPolicy.ExclusiveMode.Always);
        }
        String propertyName = exclusiveConnectionMode;
        if (isIsolated) {
            propertyName += "_Isolated";
        }
        connectionPolicy.setProperty(propertyName, "true");
        this.clients.add(this.server.acquireClientSession(connectionPolicy));
        this.clients.add(this.server.acquireClientSession(connectionPolicy));
        this.clients.add(this.server.acquireClientSession(connectionPolicy));
    } catch (ValidationException ex) {
        this.verify();
    }
}
Also used : ServerSession(org.eclipse.persistence.sessions.server.ServerSession) ValidationException(org.eclipse.persistence.exceptions.ValidationException) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy)

Example 2 with ConnectionPolicy

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

the class EntityManagerJUnitTestSuite method internalTestPostAcquirePreReleaseEvents.

public void internalTestPostAcquirePreReleaseEvents(boolean useExternalConnectionPool) {
    if (isOnServer()) {
        // Uses DefaultConnector.
        return;
    }
    SessionBroker broker = ((JpaEntityManagerFactory) getEntityManagerFactory()).getSessionBroker();
    // Testing ExclusiveConnectionMode.Isolated requires a session that has isolated descriptors.
    ServerSession ss = (ServerSession) broker.getSessionForClass(Address.class);
    if (ss.getPlatform().isSybase()) {
        warning("Warning Sybase Driver does not work with DriverWrapper, testPostAcquirePreReleaseEvents can't run on this platform.");
        return;
    }
    if (ss.getPlatform().isSymfoware()) {
        warning("Test testPostAcquirePreReleaseEvents skipped for this platform, " + "Symfoware platform doesn't support failover.");
        return;
    }
    // normally false; set to true for debug output for just this single test
    boolean shouldForceFinest = false;
    int originalLogLevel = -1;
    // cache the original driver name and connection string.
    String originalDriverName = ss.getLogin().getDriverClassName();
    String originalConnectionString = ss.getLogin().getConnectionString();
    // cache original connector for external connection pool case
    Connector originalConnector = ss.getLogin().getConnector();
    // the new driver name and connection string to be used by the test
    String newDriverName = DriverWrapper.class.getName();
    String newConnectionString = DriverWrapper.codeUrl(originalConnectionString);
    // setup the wrapper driver
    DriverWrapper.initialize(originalDriverName);
    // The test need to connect with the new driver and connection string.
    // That could be done in JPA:
    // // close the existing emf
    // closeEntityManagerFactory();
    // HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties());
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, newDriverName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, newConnectionString);
    // emf = getEntityManagerFactory(properties);
    // However this only works in case closeEntityManagerFactory disconnects the original ServerSession,
    // which requires the factory to be the only one using the persistence unit.
    // Alternative - and faster - approach is to disconnect the original session directly
    // and then reconnected it with the new driver and connection string.
    broker.logout();
    if (useExternalConnectionPool) {
        ss.getLogin().setConnector(new JNDIConnector(new DataSourceImpl(null, newConnectionString, null, null)));
        ss.getLogin().useExternalConnectionPooling();
    } else {
        ss.getLogin().setDriverClassName(newDriverName);
        ss.getLogin().setConnectionString(newConnectionString);
    }
    if (shouldForceFinest) {
        if (broker.getLogLevel() != SessionLog.FINEST) {
            originalLogLevel = broker.getLogLevel();
            broker.setLogLevel(SessionLog.FINEST);
        }
    }
    // switch off reconnection
    boolean originalIsConnectionHealthValidatedOnError = ss.getLogin().isConnectionHealthValidatedOnError();
    ss.getLogin().setConnectionHealthValidatedOnError(false);
    // Using DriverWrapper the listener will repair connection on postAcquireConnection and break it on preReleaseConnection event.
    // Also the listener will verify that neither postAcquireConnection nor preReleaseConnection events not called two in a row.
    AcquireRepair_ReleaseBreak_Listener listener = new AcquireRepair_ReleaseBreak_Listener();
    ss.getEventManager().addListener(listener);
    // Driver's connect method will still work, however any method called on any acquired connection will throw SQLException.
    // On postAcquireConnection connection will be repaired; on preReleaseConnection - broken again.
    broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: DriverWrapper.breakOldConnections(); DriverWrapper.breakNewConnections();", null, null, false);
    DriverWrapper.breakOldConnections();
    DriverWrapper.breakNewConnections();
    broker.login();
    // test several configurations:
    // all exclusive connection modes
    String[] exclusiveConnectionModeArray = new String[] { ExclusiveConnectionMode.Transactional, ExclusiveConnectionMode.Isolated, ExclusiveConnectionMode.Always };
    // 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);
    try {
        HashMap emProperties = new HashMap(1);
        HashMap mapOfProperties = new HashMap(1);
        emProperties.put(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
        HashMap memberProperties = new HashMap();
        mapOfProperties.put(ss.getName(), memberProperties);
        String mode, pooled = "", exclusiveConnectionMode;
        for (int k = 0; k < 2; k++) {
            if (k == 1) {
                // use non pooled connections
                pooled = "non pooled; ";
                memberProperties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
            }
            for (int i = 0; i < exclusiveConnectionModeArray.length; i++) {
                exclusiveConnectionMode = exclusiveConnectionModeArray[i];
                for (int j = 0; j < 3; j++) {
                    // either beginning early transaction or not
                    boolean shouldBeginEarlyTransaction = (j == 2);
                    boolean shouldReadBeforeTransaction = (j == 1);
                    mode = pooled + exclusiveConnectionMode + (shouldBeginEarlyTransaction ? "; beginEarlyTransaction" : "") + (shouldReadBeforeTransaction ? "; readBeforeTransaction" : "");
                    broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: " + mode, null, null, false);
                    memberProperties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, exclusiveConnectionMode);
                    EntityManager em = createEntityManager(emProperties);
                    if (shouldReadBeforeTransaction) {
                        em.find(Address.class, 1);
                    }
                    Address address = null;
                    try {
                        em.getTransaction().begin();
                        if (shouldBeginEarlyTransaction) {
                            em.unwrap(UnitOfWorkImpl.class).beginEarlyTransaction();
                        }
                        address = new Address();
                        address.setCountry("testPostAcquirePreReleaseEvents");
                        em.persist(address);
                        em.getTransaction().commit();
                    } finally {
                        // expected exception - connection is invalid and cannot be reconnected.
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        closeEntityManager(em);
                    }
                    if (listener.hasAcquiredConnections()) {
                        fail(mode + " connection was not passed to preReleaseConnection event");
                    }
                }
            }
        }
    } finally {
        // clear the driver wrapper
        DriverWrapper.clear();
        // reconnect the session using the original driver and connection string
        ss.getEventManager().removeListener(listener);
        // clean-up
        // remove the inserted object
        EntityManager em = createEntityManager();
        em.getTransaction().begin();
        try {
            em.createQuery("DELETE FROM Address a WHERE a.country = 'testPostAcquirePreReleaseEvents'");
            em.getTransaction().commit();
        } finally {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            closeEntityManager(em);
            broker.logout();
            if (originalLogLevel >= 0) {
                broker.setLogLevel(originalLogLevel);
            }
            if (useExternalConnectionPool) {
                ss.getLogin().setConnector(originalConnector);
                ss.getLogin().dontUseExternalConnectionPooling();
            } else {
                ss.getLogin().setDriverClassName(originalDriverName);
                ss.getLogin().setConnectionString(originalConnectionString);
            }
            ss.getLogin().setConnectionHealthValidatedOnError(originalIsConnectionHealthValidatedOnError);
            broker.login();
        }
    }
}
Also used : Connector(org.eclipse.persistence.sessions.Connector) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) Address(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_1.Address) HashMap(java.util.HashMap) DataSourceImpl(org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy)

Example 3 with ConnectionPolicy

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

the class EntityManagerJUnitTestSuite method internalTestPostAcquirePreReleaseEvents.

public void internalTestPostAcquirePreReleaseEvents(boolean useExternalConnectionPool) {
    if (isOnServer()) {
        // Uses DefaultConnector.
        return;
    }
    ServerSession ss = ((JpaEntityManagerFactory) getEntityManagerFactory()).getServerSession();
    // Assert.assertFalse("Warning Sybase Driver does not work with DriverWrapper, testPostAcquirePreReleaseEvents can't run on this platform.",  ss.getPlatform().isSybase());
    if (ss.getPlatform().isSymfoware()) {
        getServerSession().logMessage("Test testPostAcquirePreReleaseEvents skipped for this platform, " + "Symfoware platform doesn't support failover.");
        return;
    }
    // normally false; set to true for debug output for just this single test
    boolean shouldForceFinest = false;
    int originalLogLevel = -1;
    // cache the original driver name and connection string.
    String originalDriverName = ss.getLogin().getDriverClassName();
    String originalConnectionString = ss.getLogin().getConnectionString();
    // cache original connector for external connection pool case
    Connector originalConnector = ss.getLogin().getConnector();
    // the new driver name and connection string to be used by the test
    String newDriverName = DriverWrapper.class.getName();
    String newConnectionString = DriverWrapper.codeUrl(originalConnectionString);
    // setup the wrapper driver
    DriverWrapper.initialize(originalDriverName);
    // The test need to connect with the new driver and connection string.
    // That could be done in JPA:
    // // close the existing emf
    // closeEntityManagerFactory();
    // HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties());
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, newDriverName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, newConnectionString);
    // emf = getEntityManagerFactory(properties);
    // However this only works in case closeEntityManagerFactory disconnects the original ServerSession,
    // which requires the factory to be the only one using the persistence unit.
    // Alternative - and faster - approach is to disconnect the original session directly
    // and then reconnected it with the new driver and connection string.
    ss.logout();
    if (useExternalConnectionPool) {
        ss.getLogin().setConnector(new JNDIConnector(new DataSourceImpl(null, newConnectionString, null, null)));
        ss.getLogin().useExternalConnectionPooling();
    } else {
        ss.getLogin().setDriverClassName(newDriverName);
        ss.getLogin().setConnectionString(newConnectionString);
    }
    if (shouldForceFinest) {
        if (ss.getLogLevel() != SessionLog.FINEST) {
            originalLogLevel = ss.getLogLevel();
            ss.setLogLevel(SessionLog.FINEST);
        }
    }
    // switch off reconnection
    boolean originalIsConnectionHealthValidatedOnError = ss.getLogin().isConnectionHealthValidatedOnError();
    ss.getLogin().setConnectionHealthValidatedOnError(false);
    // Using DriverWrapper the listener will repair connection on postAcquireConnection and break it on preReleaseConnection event.
    // Also the listener will verify that neither postAcquireConnection nor preReleaseConnection events not called two in a row.
    AcquireRepair_ReleaseBreak_Listener listener = new AcquireRepair_ReleaseBreak_Listener();
    ss.getEventManager().addListener(listener);
    // Driver's connect method will still work, however any method called on any acquired connection will throw SQLException.
    // On postAcquireConnection connection will be repaired; on preReleaseConnection - broken again.
    ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: DriverWrapper.breakOldConnections(); DriverWrapper.breakNewConnections();", null, null, false);
    DriverWrapper.breakOldConnections();
    DriverWrapper.breakNewConnections();
    ss.login();
    // test several configurations:
    // all exclusive connection modes
    String[] exclusiveConnectionModeArray = new String[] { ExclusiveConnectionMode.Transactional, ExclusiveConnectionMode.Isolated, ExclusiveConnectionMode.Always };
    // 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);
    try {
        HashMap emProperties = new HashMap();
        String mode, pooled = "", exclusiveConnectionMode;
        for (int k = 0; k < 2; k++) {
            if (k == 1) {
                // use non pooled connections
                pooled = "non pooled; ";
                emProperties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
            }
            for (int i = 0; i < exclusiveConnectionModeArray.length; i++) {
                exclusiveConnectionMode = exclusiveConnectionModeArray[i];
                for (int j = 0; j < 3; j++) {
                    // either beginning early transaction or not
                    boolean shouldBeginEarlyTransaction = (j == 2);
                    boolean shouldReadBeforeTransaction = (j == 1);
                    mode = pooled + exclusiveConnectionMode + (shouldBeginEarlyTransaction ? "; beginEarlyTransaction" : "") + (shouldReadBeforeTransaction ? "; readBeforeTransaction" : "");
                    ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: " + mode, null, null, false);
                    emProperties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, exclusiveConnectionMode);
                    EntityManager em = createEntityManager(emProperties);
                    if (shouldReadBeforeTransaction) {
                        em.find(Employee.class, 1);
                    }
                    Employee emp = null;
                    try {
                        em.getTransaction().begin();
                        if (shouldBeginEarlyTransaction) {
                            em.unwrap(UnitOfWorkImpl.class).beginEarlyTransaction();
                        }
                        emp = new Employee();
                        emp.setFirstName("testPostAcquirePreReleaseEvents");
                        em.persist(emp);
                        em.getTransaction().commit();
                    } finally {
                        // expected exception - connection is invalid and cannot be reconnected.
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        closeEntityManager(em);
                    }
                    if (listener.hasAcquiredConnections()) {
                        fail(mode + " connection was not passed to preReleaseConnection event");
                    }
                }
            }
        }
    } finally {
        // clear the driver wrapper
        DriverWrapper.clear();
        // reconnect the session using the original driver and connection string
        ss.getEventManager().removeListener(listener);
        // clean-up
        // remove the inserted object
        EntityManager em = createEntityManager();
        em.getTransaction().begin();
        try {
            em.createQuery("DELETE FROM Employee e WHERE e.firstName = 'testPostAcquirePreReleaseEvents'");
            em.getTransaction().commit();
        } finally {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            closeEntityManager(em);
            ss.logout();
            if (originalLogLevel >= 0) {
                ss.setLogLevel(originalLogLevel);
            }
            if (useExternalConnectionPool) {
                ss.getLogin().setConnector(originalConnector);
                ss.getLogin().dontUseExternalConnectionPooling();
            } else {
                ss.getLogin().setDriverClassName(originalDriverName);
                ss.getLogin().setConnectionString(originalConnectionString);
            }
            ss.getLogin().setConnectionHealthValidatedOnError(originalIsConnectionHealthValidatedOnError);
            ss.login();
        }
    }
}
Also used : Connector(org.eclipse.persistence.sessions.Connector) DefaultConnector(org.eclipse.persistence.sessions.DefaultConnector) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) HashMap(java.util.HashMap) DataSourceImpl(org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy)

Example 4 with ConnectionPolicy

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

the class EntityManagerJUnitTestSuite method internalTestConnectionPolicy.

public void internalTestConnectionPolicy(boolean useSetProperty) {
    // setup
    String errorMsg = "";
    HashMap properties = null;
    if (!useSetProperty) {
        properties = new HashMap();
        properties.put(EntityManagerProperties.JDBC_USER, "em_user");
        properties.put(EntityManagerProperties.JDBC_PASSWORD, "em_password");
        properties.put(EntityManagerProperties.JTA_DATASOURCE, "em_jta_datasource");
        properties.put(EntityManagerProperties.NON_JTA_DATASOURCE, "em_nonjta_datasource");
        properties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
    }
    // test
    EntityManager em = null;
    boolean isInTransaction = false;
    try {
        // assume that if JTA is used on server then EntityManager is always injected.
        boolean isEmInjected = isOnServer() && getServerSession().getLogin().shouldUseExternalTransactionController();
        if (isEmInjected) {
            em = createEntityManager();
            // In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
            beginTransaction(em);
            isInTransaction = true;
            ((EntityManagerImpl) em.getDelegate()).setProperties(properties);
        } else {
            EntityManagerFactory emFactory = getEntityManagerFactory();
            em = emFactory.createEntityManager(properties);
        }
        if (useSetProperty) {
            em.setProperty(EntityManagerProperties.JDBC_USER, "em_user");
            em.setProperty(EntityManagerProperties.JDBC_PASSWORD, "em_password");
            em.setProperty(EntityManagerProperties.JTA_DATASOURCE, "em_jta_datasource");
            em.setProperty(EntityManagerProperties.NON_JTA_DATASOURCE, "em_nonjta_datasource");
            em.setProperty(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
        }
        // verify
        ClientSession clientSession;
        if (isOnServer()) {
            clientSession = (ClientSession) ((EntityManagerImpl) em.getDelegate()).getActivePersistenceContext(null).getParent();
        } else {
            clientSession = (ClientSession) ((EntityManagerImpl) em).getActivePersistenceContext(null).getParent();
        }
        if (!clientSession.isExclusiveIsolatedClientSession()) {
            errorMsg += "ExclusiveIsolatedClientSession was expected\n";
        }
        ConnectionPolicy policy = clientSession.getConnectionPolicy();
        if (policy.isPooled()) {
            errorMsg += "NOT pooled policy was expected\n";
        }
        String user = (String) policy.getLogin().getProperty("user");
        if (!user.equals("em_user")) {
            errorMsg += "em_user was expected\n";
        }
        String password = (String) policy.getLogin().getProperty("password");
        if (!password.equals("em_password")) {
            errorMsg += "em_password was expected\n";
        }
        if (!(((DatasourceLogin) policy.getLogin()).getConnector() instanceof JNDIConnector)) {
            errorMsg += "JNDIConnector was expected\n";
        } else {
            JNDIConnector jndiConnector = (JNDIConnector) ((DatasourceLogin) policy.getLogin()).getConnector();
            String dataSourceName = jndiConnector.getName();
            if (dataSourceName == null) {
                errorMsg += "NON null dataSourceName was expected\n";
            } else {
                if (clientSession.getParent().getLogin().shouldUseExternalTransactionController()) {
                    if (dataSourceName.equals("em_nonjta_datasource")) {
                        errorMsg += "em_jta_datasource was expected\n";
                    }
                } else {
                    if (dataSourceName.equals("em_jta_datasource")) {
                        errorMsg += "em_nonjta_datasource was expected\n";
                    }
                }
            }
        }
    } finally {
        // clean-up
        if (isInTransaction) {
            rollbackTransaction(em);
        }
        if (em != null) {
            closeEntityManager(em);
        }
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) ClientSession(org.eclipse.persistence.sessions.server.ClientSession) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy)

Example 5 with ConnectionPolicy

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

the class EntityManagerJUnitTestSuite method internalTestConnectionPolicy.

public void internalTestConnectionPolicy(boolean useSetProperty) {
    // setup
    String errorMsg = "";
    // number of composite members
    int n = 3;
    Map mapOfProperties = new HashMap();
    for (int i = 1; i <= n; i++) {
        String prefix = "em_" + i + "_";
        Map properties = new HashMap();
        properties.put(EntityManagerProperties.JDBC_USER, prefix + "user");
        properties.put(EntityManagerProperties.JDBC_PASSWORD, prefix + "password");
        properties.put(EntityManagerProperties.JTA_DATASOURCE, prefix + "jta_datasource");
        properties.put(EntityManagerProperties.NON_JTA_DATASOURCE, prefix + "nonjta_datasource");
        properties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
        mapOfProperties.put(getCompositeMemberPuName(i), properties);
    }
    HashMap properties = null;
    if (!useSetProperty) {
        properties = new HashMap(1);
        properties.put(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
    }
    // test
    EntityManager em = null;
    boolean isInTransaction = false;
    try {
        // assume that if JTA is used on server then EntityManager is always injected.
        boolean isEmInjected = isOnServer() && getDatabaseSession().hasExternalTransactionController();
        if (isEmInjected) {
            em = createEntityManager();
            // In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
            beginTransaction(em);
            isInTransaction = true;
            ((EntityManagerImpl) em.getDelegate()).setProperties(properties);
        } else {
            EntityManagerFactory emFactory = getEntityManagerFactory();
            em = emFactory.createEntityManager(properties);
        }
        if (useSetProperty) {
            em.setProperty(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
        }
        for (int i = 1; i <= n; i++) {
            // verify
            SessionBroker clientSessionBroker;
            if (isOnServer()) {
                clientSessionBroker = (SessionBroker) ((EntityManagerImpl) em.getDelegate()).getActivePersistenceContext(null).getParent();
            } else {
                clientSessionBroker = (SessionBroker) ((EntityManagerImpl) em).getActivePersistenceContext(null).getParent();
            }
            ClientSession clientSession = (ClientSession) clientSessionBroker.getSessionForName(getCompositeMemberPuName(i));
            if (!clientSession.isExclusiveIsolatedClientSession()) {
                errorMsg += "ExclusiveIsolatedClientSession was expected\n";
            }
            ConnectionPolicy policy = clientSession.getConnectionPolicy();
            if (policy.isPooled()) {
                errorMsg += "NOT pooled policy was expected\n";
            }
            String user = (String) policy.getLogin().getProperty("user");
            String prefix = "em_" + i + "_";
            if (!user.equals(prefix + "user")) {
                errorMsg += prefix + "user was expected\n";
            }
            String password = (String) policy.getLogin().getProperty("password");
            if (!password.equals(prefix + "password")) {
                errorMsg += prefix + "password was expected\n";
            }
            if (!(((DatasourceLogin) policy.getLogin()).getConnector() instanceof JNDIConnector)) {
                errorMsg += "JNDIConnector was expected\n";
            } else {
                JNDIConnector jndiConnector = (JNDIConnector) ((DatasourceLogin) policy.getLogin()).getConnector();
                String dataSourceName = jndiConnector.getName();
                if (dataSourceName == null) {
                    errorMsg += "NON null dataSourceName was expected\n";
                } else {
                    if (clientSession.getParent().getLogin().shouldUseExternalTransactionController()) {
                        if (dataSourceName.equals(prefix + "nonjta_datasource")) {
                            errorMsg += prefix + "jta_datasource was expected\n";
                        }
                    } else {
                        if (dataSourceName.equals(prefix + "jta_datasource")) {
                            errorMsg += prefix + "jta_datasource was expected\n";
                        }
                    }
                }
            }
        }
    } finally {
        // clean-up
        if (isInTransaction) {
            rollbackTransaction(em);
        }
        if (em != null) {
            closeEntityManager(em);
        }
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) ClientSession(org.eclipse.persistence.sessions.server.ClientSession) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Map(java.util.Map) HashMap(java.util.HashMap)

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