Search in sources :

Example 1 with JNDIConnector

use of org.eclipse.persistence.sessions.JNDIConnector 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 2 with JNDIConnector

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

the class EntityManagerSetupImpl method updatePools.

/**
 * Configure the internal connection pooling parameters.
 * By default if nothing is configured a default shared (exclusive) read/write pool is used with 32 min/max connections and 1 initial.
 */
@SuppressWarnings("deprecation")
protected void updatePools(ServerSession serverSession, Map m) {
    String value = null;
    String property = null;
    try {
        // Sizes are irrelevant for external connection pool
        if (!serverSession.getDefaultConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
            // CONNECTION and WRITE_CONNECTION properties both configure the default pool (mean the same thing, but WRITE normally used with READ).
            property = PersistenceUnitProperties.JDBC_CONNECTIONS_MIN;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setMinNumberOfConnections(Integer.parseInt(value));
            }
            property = PersistenceUnitProperties.JDBC_CONNECTIONS_MAX;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setMaxNumberOfConnections(Integer.parseInt(value));
            }
            property = PersistenceUnitProperties.JDBC_CONNECTIONS_INITIAL;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setInitialNumberOfConnections(Integer.parseInt(value));
            }
            property = PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setMinNumberOfConnections(Integer.parseInt(value));
            }
            property = PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setMaxNumberOfConnections(Integer.parseInt(value));
            }
            property = PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_INITIAL;
            value = getConfigPropertyAsStringLogDebug(property, m, serverSession);
            if (value != null) {
                serverSession.getDefaultConnectionPool().setInitialNumberOfConnections(Integer.parseInt(value));
            }
        }
        // Sizes and shared option are irrelevant for external connection pool
        if (!serverSession.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
            String shared = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED, m, serverSession);
            boolean isShared = false;
            if (shared != null) {
                isShared = Boolean.parseBoolean(shared);
            }
            ConnectionPool pool = null;
            if (isShared) {
                pool = new ReadConnectionPool("read", serverSession.getReadConnectionPool().getLogin(), serverSession);
            } else {
                pool = new ConnectionPool("read", serverSession.getReadConnectionPool().getLogin(), serverSession);
            }
            String min = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, m, serverSession);
            if (min != null) {
                value = min;
                property = PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN;
                pool.setMinNumberOfConnections(Integer.parseInt(min));
            }
            String max = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX, m, serverSession);
            if (max != null) {
                value = max;
                property = PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX;
                pool.setMaxNumberOfConnections(Integer.parseInt(max));
            }
            String initial = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_INITIAL, m, serverSession);
            if (initial != null) {
                value = initial;
                property = PersistenceUnitProperties.JDBC_READ_CONNECTIONS_INITIAL;
                pool.setInitialNumberOfConnections(Integer.parseInt(initial));
            }
            // Only set the read pool if they configured it, otherwise use default shared read/write.
            if (isShared || (min != null) || (max != null) || (initial != null)) {
                serverSession.setReadConnectionPool(pool);
            }
            String wait = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_CONNECTIONS_WAIT, m, serverSession);
            if (wait != null) {
                value = wait;
                property = PersistenceUnitProperties.JDBC_CONNECTIONS_WAIT;
                serverSession.getDefaultConnectionPool().setWaitTimeout(Integer.parseInt(wait));
                pool.setWaitTimeout(Integer.parseInt(wait));
            }
        }
        // Configure sequence connection pool if set.
        String sequence = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL, m, serverSession);
        if (sequence != null) {
            serverSession.getSequencingControl().setShouldUseSeparateConnection(Boolean.parseBoolean(sequence));
        }
        String sequenceDataSource = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_DATASOURCE, m, serverSession);
        if (sequenceDataSource != null) {
            DatasourceLogin login = this.session.getLogin().clone();
            login.dontUseExternalTransactionController();
            JNDIConnector jndiConnector = new JNDIConnector(sequenceDataSource);
            login.setConnector(jndiConnector);
            serverSession.getSequencingControl().setLogin(login);
        }
        // Sizes and shared option are irrelevant for external connection pool
        if (!serverSession.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
            value = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_MIN, m, serverSession);
            if (value != null) {
                property = PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_MIN;
                serverSession.getSequencingControl().setMinPoolSize(Integer.parseInt(value));
            }
            value = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_MAX, m, serverSession);
            if (value != null) {
                property = PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_MAX;
                serverSession.getSequencingControl().setMaxPoolSize(Integer.parseInt(value));
            }
            value = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_INITIAL, m, serverSession);
            if (value != null) {
                property = PersistenceUnitProperties.JDBC_SEQUENCE_CONNECTION_POOL_INITIAL;
                serverSession.getSequencingControl().setInitialPoolSize(Integer.parseInt(value));
            }
        }
    } catch (NumberFormatException exception) {
        serverSession.handleException(ValidationException.invalidValueForProperty(value, property, exception));
    }
}
Also used : ExternalConnectionPool(org.eclipse.persistence.sessions.server.ExternalConnectionPool) ReadConnectionPool(org.eclipse.persistence.sessions.server.ReadConnectionPool) ConnectionPool(org.eclipse.persistence.sessions.server.ConnectionPool) DatasourceLogin(org.eclipse.persistence.sessions.DatasourceLogin) ReadConnectionPool(org.eclipse.persistence.sessions.server.ReadConnectionPool) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) EntityManagerFactoryProvider.getConfigPropertyAsString(org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.getConfigPropertyAsString)

Example 3 with JNDIConnector

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

the class TestJNDIConnector method setup.

@Before
public void setup() {
    _handler = new MyInvocationHandler();
    _ctx = (Context) Proxy.newProxyInstance(null, new Class<?>[] { Context.class }, _handler);
    _dataSource = (DataSource) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { DataSource.class }, _handler);
    _connector = new JNDIConnector(_ctx, "test");
}
Also used : JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) Before(org.junit.Before)

Example 4 with JNDIConnector

use of org.eclipse.persistence.sessions.JNDIConnector 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 5 with JNDIConnector

use of org.eclipse.persistence.sessions.JNDIConnector 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)

Aggregations

JNDIConnector (org.eclipse.persistence.sessions.JNDIConnector)23 HashMap (java.util.HashMap)7 Connector (org.eclipse.persistence.sessions.Connector)7 DefaultConnector (org.eclipse.persistence.sessions.DefaultConnector)6 EntityManager (jakarta.persistence.EntityManager)5 DataSource (javax.sql.DataSource)5 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)5 JpaEntityManagerFactory (org.eclipse.persistence.jpa.JpaEntityManagerFactory)5 DatasourceLogin (org.eclipse.persistence.sessions.DatasourceLogin)5 ServerSession (org.eclipse.persistence.sessions.server.ServerSession)5 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)4 SQLException (java.sql.SQLException)4 Map (java.util.Map)4 DatabaseSession (org.eclipse.persistence.sessions.DatabaseSession)4 ConnectionPolicy (org.eclipse.persistence.sessions.server.ConnectionPolicy)4 PersistenceException (jakarta.persistence.PersistenceException)3 ValidationException (org.eclipse.persistence.exceptions.ValidationException)3 DatabaseLogin (org.eclipse.persistence.sessions.DatabaseLogin)3 Project (org.eclipse.persistence.sessions.Project)3 OptimisticLockException (jakarta.persistence.OptimisticLockException)2