use of org.eclipse.persistence.sessions.Connector 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();
}
}
}
use of org.eclipse.persistence.sessions.Connector 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();
}
}
}
use of org.eclipse.persistence.sessions.Connector in project eclipselink by eclipse-ee4j.
the class ExtensibilityTests method testMetadatasourceProperties.
public void testMetadatasourceProperties() {
EntityManagerFactory emf = getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
JpaEntityManagerFactory jpaEmf = JpaHelper.getEntityManagerFactory(em);
ServerSession originalSession = jpaEmf.getServerSession();
String sessionName = originalSession.getName();
// cleanUpProperties will be used to return the factory back to its original state
HashMap cleanUpProperties = new HashMap(4);
Object transactionType = originalSession.getProperty(PersistenceUnitProperties.TRANSACTION_TYPE);
if (transactionType != null) {
// that would remove the property
transactionType = "";
}
cleanUpProperties.put(PersistenceUnitProperties.TRANSACTION_TYPE, transactionType);
Object jtaDataSource = originalSession.getProperty(PersistenceUnitProperties.JTA_DATASOURCE);
if (jtaDataSource != null) {
Connector mainConnector = originalSession.getLogin().getConnector();
if (mainConnector instanceof JNDIConnector) {
jtaDataSource = ((JNDIConnector) mainConnector).getName();
} else {
// that would remove the property
jtaDataSource = "";
}
}
cleanUpProperties.put(PersistenceUnitProperties.JTA_DATASOURCE, jtaDataSource);
Object nonJtaDataSource = originalSession.getProperty(PersistenceUnitProperties.NON_JTA_DATASOURCE);
if (nonJtaDataSource != null) {
Connector readConnector = ((DatabaseLogin) originalSession.getReadConnectionPool().getLogin()).getConnector();
if (readConnector instanceof JNDIConnector) {
nonJtaDataSource = ((JNDIConnector) readConnector).getName();
} else {
// that would remove the property
nonJtaDataSource = "";
}
}
cleanUpProperties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, nonJtaDataSource);
// that would remove the property
cleanUpProperties.put(PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE, "");
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE, "extension.properties");
jpaEmf.refreshMetadata(properties);
try {
em = emf.createEntityManager();
fail("PersistenceException was expected");
} catch (PersistenceException ex) {
// exception expected because extension.properties contains bogus settings:
// jakarta.persistence.transactionType=JTA
// jakarta.persistence.jtaDataSource=MyJtaDataSource
// jakarta.persistence.nonJtaDataSource=MyNonJtaDataSource
// Examine the session to see whether these settings were applied
// Note that because session login has failed the session is not accessible from emf, only directly from emSetupImpls.
String errorMsg = "";
ServerSession serverSession = (ServerSession) EntityManagerFactoryProvider.emSetupImpls.get(sessionName).getSession();
if (!serverSession.getLogin().shouldUseExternalTransactionController()) {
errorMsg += "External tarnsaction controller was expected; ";
}
Connector mainConnector = serverSession.getLogin().getConnector();
if (!(mainConnector instanceof JNDIConnector)) {
errorMsg += "Main JNDIConnector was expected; ";
} else {
if (!((JNDIConnector) mainConnector).getName().equals("MyJtaDataSource")) {
errorMsg += "MyJtaDataSource was expected; ";
}
}
Connector readConnector = ((DatabaseLogin) serverSession.getReadConnectionPool().getLogin()).getConnector();
if (!(readConnector instanceof JNDIConnector)) {
errorMsg += "Read JNDIConnector was expected; ";
} else {
if (!((JNDIConnector) readConnector).getName().equals("MyNonJtaDataSource")) {
errorMsg += "MyNonJtaDataSource was expected; ";
}
}
} finally {
// clean-up: back to the original settings
jpaEmf.refreshMetadata(cleanUpProperties);
emf.createEntityManager();
}
}
use of org.eclipse.persistence.sessions.Connector in project eclipselink by eclipse-ee4j.
the class SimpleSpatialTestCase method getSession.
public static DatabaseSession getSession() throws Exception {
DatabaseSession spatialSession = null;
if (isJunit) {
// look up the session from sessions.xml
spatialSession = (DatabaseSession) SessionManager.getManager().getSession(SPATIAL_SESSION_NAME, SPATIAL_SESSIONS_XML_NAME);
} else {
// do not use sessions.xml to look up the session. Build it from the test browser's session
spatialSession = (DatabaseSession) SessionManager.getManager().getSessions().get(SPATIAL_SESSION_NAME);
if (spatialSession == null) {
Project project = new JGeometryProject();
Session configSession = SimpleJGeometryTestModel.getConfigSession();
project.setLogin((DatabaseLogin) configSession.getLogin().clone());
spatialSession = new org.eclipse.persistence.internal.sessions.DatabaseSessionImpl(project);
spatialSession.setServerPlatform(configSession.getServerPlatform());
spatialSession.getPlatform().addStructConverter(new JGeometryConverter());
// make the MyGeometryConverter type point at a user defined type for the current user
// Bug5837254, in case test running on the server, the user name should extract from the metadata
// of the datasource.
Connector connector = spatialSession.getLogin().getConnector();
String userName = "";
if (connector instanceof DefaultConnector) {
userName = spatialSession.getLogin().getUserName();
} else if (connector instanceof JNDIConnector) {
userName = ((JNDIConnector) spatialSession.getLogin().getConnector()).getDataSource().getConnection().getMetaData().getUserName();
}
MyGeometryConverter.MY_GEOMETRY_TYPE = userName + "." + MyGeometryConverter.MY_GEOMETRY_TYPE_NAME;
MyGeometryConverter.MY_GEOMETRY_TYPE = MyGeometryConverter.MY_GEOMETRY_TYPE.toUpperCase();
spatialSession.getPlatform().addStructConverter(new MyGeometryConverter());
(spatialSession).login();
SessionManager.getManager().addSession(SPATIAL_SESSION_NAME, spatialSession);
}
spatialSession.setSessionLog(SimpleJGeometryTestModel.getConfigSession().getSessionLog());
spatialSession.setLogLevel(SimpleJGeometryTestModel.getConfigSession().getLogLevel());
}
return spatialSession;
}
use of org.eclipse.persistence.sessions.Connector in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testGenerateSessionNameFromConnectionProperties.
public void testGenerateSessionNameFromConnectionProperties() {
// the test requires passing properties to createEMF or createContainerEMF method.
if (isOnServer()) {
return;
}
String errorMsg = "";
EntityManagerFactory emf;
Map properties;
String puName = "default";
String customizer = "org.eclipse.persistence.testing.tests.jpa.advanced.EntityManagerJUnitTestSuite$SessionNameCustomizer";
String myJtaDS = "myJtaDS";
String myNonJtaDS = "myNonJtaDS";
String myUrl = "myUrl";
String myUser = "myUser";
String myDriver = "myDriver";
String myPassword = "myPassword";
ServerSession originalSession = JUnitTestCase.getServerSession();
String loggingLevel = originalSession.getSessionLog().getLevelString();
SessionNameCustomizer.ss = null;
// 0: The session name specified in persistence.xml is NOT overridden -> the existing session is used by emf.
// If persistence.xml no longer specifies session name then comment out this part of the test.
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "RESOURCE_LOCAL");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, "");
properties.put(PersistenceUnitProperties.JDBC_URL, myUrl);
properties.put(PersistenceUnitProperties.JDBC_USER, myUser);
properties.put(PersistenceUnitProperties.JDBC_DRIVER, myDriver);
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, myPassword);
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if (SessionNameCustomizer.ss != null && SessionNameCustomizer.ss != originalSession) {
errorMsg += "0: Session name NOT overridden by an empty string - original session expected; ";
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
// 1: New session with DefaultConnector with myUrl, myDriver, myUser, myPassword
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
// to override SESSION_NAME if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.SESSION_NAME, "");
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "RESOURCE_LOCAL");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, "");
properties.put(PersistenceUnitProperties.JDBC_URL, myUrl);
properties.put(PersistenceUnitProperties.JDBC_USER, myUser);
properties.put(PersistenceUnitProperties.JDBC_DRIVER, myDriver);
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, myPassword);
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if (SessionNameCustomizer.ss == null && SessionNameCustomizer.ss == originalSession) {
errorMsg += "1: New session expected; ";
} else {
if (SessionNameCustomizer.ss.getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "1: internal connection pooling expected; ";
}
if (SessionNameCustomizer.ss.getLogin().shouldUseExternalTransactionController()) {
errorMsg += "1: no externalTransactionController expected; ";
}
if (!myUser.equals(SessionNameCustomizer.ss.getLogin().getUserName())) {
errorMsg += "1: myUser expected; ";
}
Connector connector = SessionNameCustomizer.ss.getLogin().getConnector();
if (connector instanceof DefaultConnector) {
if (!myUrl.equals(((DefaultConnector) connector).getDatabaseURL())) {
errorMsg += "1: myUrl expected; ";
}
if (!myDriver.equals(((DefaultConnector) connector).getDriverClassName())) {
errorMsg += "1: myDriver expected; ";
}
} else {
errorMsg += "1: DefaultConnector expected; ";
}
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
// 2: New session with JNDIConnector with myJtaDs, myNonJtaDs
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
// to override SESSION_NAME if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.SESSION_NAME, "");
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "JTA");
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, myJtaDS);
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, myNonJtaDS);
// to override user if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JDBC_USER, "");
// note that there is no need to override JDBC_URL, JDBC_DRIVER, JDBC_PASSWORD with an empty string, they will be ignored.
// JDBC_URL, JDBC_DRIVER - because data source(s) are specified; JDBC_PASSWORD - because JDBC_USER is not specified
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if (SessionNameCustomizer.ss == null && SessionNameCustomizer.ss == originalSession) {
errorMsg += "2: New session expected; ";
} else {
if (!SessionNameCustomizer.ss.getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "2: external connection pooling expected; ";
}
if (!SessionNameCustomizer.ss.getLogin().shouldUseExternalTransactionController()) {
errorMsg += "2: externalTransactionController expected; ";
}
if (SessionNameCustomizer.ss.getLogin().getUserName().length() > 0) {
errorMsg += "2: empty string user expected; ";
}
Connector connector = SessionNameCustomizer.ss.getLogin().getConnector();
if (connector instanceof JNDIConnector) {
if (!myJtaDS.equals(((JNDIConnector) connector).getName())) {
errorMsg += "2: myJtaDS expected; ";
}
} else {
errorMsg += "2: JNDIConnector expected; ";
}
if (!SessionNameCustomizer.ss.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "2: resding: external connection pooling expected; ";
}
if (SessionNameCustomizer.ss.getReadConnectionPool().getLogin().shouldUseExternalTransactionController()) {
errorMsg += "2: reading no externalTransactionController expected; ";
}
if (SessionNameCustomizer.ss.getReadConnectionPool().getLogin().getUserName().length() > 0) {
errorMsg += "2: reading: empty string user expected; ";
}
Connector readConnector = ((DatasourceLogin) SessionNameCustomizer.ss.getReadConnectionPool().getLogin()).getConnector();
if (readConnector instanceof JNDIConnector) {
if (!myNonJtaDS.equals(((JNDIConnector) readConnector).getName())) {
errorMsg += "2: reading: myNonJtaDS expected; ";
}
} else {
errorMsg += "2: reading: JNDIConnector expected; ";
}
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
if (errorMsg.length() > 0) {
fail(errorMsg);
}
}
Aggregations