use of org.neo4j.ogm.domain.gh824.Address in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testEMCloseAndOpen.
public void testEMCloseAndOpen() {
if (isOnServer()) {
// Uses DefaultConnector.
return;
}
// Assert.assertFalse("Warning Sybase Driver does not work with DriverWrapper, testEMCloseAndOpen can't run on this platform.", getPlatform(Address.class).isSybase());
if (getPlatform(Address.class).isSymfoware()) {
getDatabaseSession().logMessage("Test testEMCloseAndOpen 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;
SessionBroker broker = ((JpaEntityManagerFactory) getEntityManagerFactory()).getSessionBroker();
// Testing ExclusiveConnectionMode.Isolated requires a session that has isolated descriptors.
ServerSession ss = (ServerSession) broker.getSessionForClass(Address.class);
// make sure the id hasn't been already used - it will be assigned to a new object (in case sequencing is not used).
int id = (ss.getNextSequenceNumberValue(Address.class)).intValue();
// cache the original driver name and connection string.
String originalDriverName = ss.getLogin().getDriverClassName();
String originalConnectionString = ss.getLogin().getConnectionString();
// 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 SessionBroker,
// 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();
ss.getLogin().setDriverClassName(newDriverName);
ss.getLogin().setConnectionString(newConnectionString);
AcquireReleaseListener listener = new AcquireReleaseListener();
ss.getEventManager().addListener(listener);
if (shouldForceFinest) {
if (broker.getLogLevel() != SessionLog.FINEST) {
originalLogLevel = broker.getLogLevel();
broker.setLogLevel(SessionLog.FINEST);
}
}
broker.login();
String errorMsg = "";
// test several configurations:
// all exclusive connection modes
String[] exclusiveConnectionModeArray = new String[] { ExclusiveConnectionMode.Transactional, ExclusiveConnectionMode.Isolated, ExclusiveConnectionMode.Always };
// Workaround for Bug 309881 - problems with CallQueryMechanism.prepareCall method
// Because of this bug em.find ignores QueryHints.JDBC_TIMEOUT,
// have to set it directly into the Descriptor's ReadObjectQuery.
// This should be removed from the test after the bug is fixed.
ReadObjectQuery addressFindQuery = broker.getDescriptor(Address.class).getQueryManager().getReadObjectQuery();
int originalQueryTimeout = addressFindQuery.getQueryTimeout();
if (originalQueryTimeout > 0) {
ss.setQueryTimeoutDefault(0);
addressFindQuery.setQueryTimeout(0);
// The same bug 309881 requires the query to be reprepaired for queryTimeOut to be set on its call
addressFindQuery.setIsPrepared(false);
addressFindQuery.checkPrepare(ss, null);
}
// currently reconnection is not attempted if query time out is not zero.
HashMap noTimeOutHint = new HashMap(1);
noTimeOutHint.put(QueryHints.JDBC_TIMEOUT, 0);
try {
for (int i = 0; i < 3; i++) {
String exclusiveConnectionMode = exclusiveConnectionModeArray[i];
for (int j = 0; j < 2; j++) {
// either using or not using sequencing
boolean useSequencing = (j == 0);
broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: " + (useSequencing ? "sequencing" : "no sequencing"), null, null, false);
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);
memberProperties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, exclusiveConnectionMode);
EntityManager em = createEntityManager(emProperties);
em.find(Address.class, 1, noTimeOutHint);
Address address = null;
boolean hasUnexpectedlyCommitted = false;
try {
em.getTransaction().begin();
// imitate disconnecting from network:
// driver's connect method and any method on any connection will throw SQLException
broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: DriverWrapper.breakDriver(); DriverWrapper.breakOldConnections();", null, null, false);
DriverWrapper.breakDriver();
DriverWrapper.breakOldConnections();
address = new Address();
if (!useSequencing) {
address.setID(id);
}
em.persist(address);
em.getTransaction().commit();
// should never get here - all connections should be broken.
hasUnexpectedlyCommitted = true;
errorMsg += "useSequencing = " + useSequencing + "; exclusiveConnectionMode = " + exclusiveConnectionMode + ": Commit has unexpectedly succeeded - should have failed because all connections broken. driver = " + ss.getLogin().getDriverClassName() + "; url = " + ss.getLogin().getConnectionString();
} catch (Exception e) {
// expected exception - connection is invalid and cannot be reconnected.
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
}
closeEntityManager(em);
// verify - all connections should be released
String localErrorMsg = "";
if (listener.nAcquredWriteConnections() > 0) {
localErrorMsg += "writeConnection not released; ";
}
if (listener.nAcquredReadConnections() > 0) {
localErrorMsg += "readConnection not released; ";
}
if (localErrorMsg.length() > 0) {
localErrorMsg = exclusiveConnectionMode + " useSequencing=" + useSequencing + ": " + localErrorMsg;
errorMsg += localErrorMsg;
listener.clear();
}
// imitate reconnecting to network:
// driver's connect method will now work, all newly acquired connections will work, too;
// however the old connections cached in the connection pools are still invalid.
DriverWrapper.repairDriver();
broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: DriverWrapper.repairDriver();", null, null, false);
boolean failed = true;
try {
em = createEntityManager();
em.find(Address.class, 1);
if (!hasUnexpectedlyCommitted) {
em.getTransaction().begin();
address = new Address();
if (!useSequencing) {
address.setID(id);
}
em.persist(address);
em.getTransaction().commit();
failed = false;
}
} finally {
if (failed) {
// This should not happen
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
closeEntityManager(em);
if (errorMsg.length() > 0) {
broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: errorMsg: " + "\n" + errorMsg, null, null, false);
}
}
}
// clean-up
// remove the inserted object
em.getTransaction().begin();
em.remove(address);
em.getTransaction().commit();
closeEntityManager(em);
}
}
} finally {
// This should be removed from the test after the bug is fixed.
if (originalQueryTimeout > 0) {
ss.setQueryTimeoutDefault(originalQueryTimeout);
addressFindQuery.setQueryTimeout(originalQueryTimeout);
// The same bug 309881 requires the query to be reprepaired for queryTimeOut to be set on its call
addressFindQuery.setIsPrepared(false);
addressFindQuery.checkPrepare(ss, null);
}
// clear the driver wrapper
DriverWrapper.clear();
// reconnect the session using the original driver and connection string
ss.getEventManager().removeListener(listener);
broker.logout();
if (originalLogLevel >= 0) {
broker.setLogLevel(originalLogLevel);
}
ss.getLogin().setDriverClassName(originalDriverName);
ss.getLogin().setConnectionString(originalConnectionString);
broker.login();
if (errorMsg.length() > 0) {
fail(errorMsg);
}
}
}
use of org.neo4j.ogm.domain.gh824.Address in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testIsLoadedWithoutReferenceAttribute.
public void testIsLoadedWithoutReferenceAttribute() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
Employee manager = new Employee();
manager.addManagedEmployee(emp);
emp.setManager(manager);
em.persist(emp);
em.flush();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
emp.getAddress().getCity();
emp.getPhoneNumbers().size();
ProviderUtil util = (new PersistenceProvider()).getProviderUtil();
if (emp instanceof PersistenceWeaved) {
assertTrue("ProviderUtil did not return LOADED for isLoaded for address when it should.", util.isLoadedWithReference(emp, "address").equals(LoadState.LOADED));
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.NOT_LOADED));
} else {
assertTrue("(Unweaved) ProviderUtil did not return LOADED for isLoaded for address when it should.", util.isLoadedWithReference(emp, "address").equals(LoadState.LOADED));
assertTrue("(Unweaved) ProviderUtil did not return LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.LOADED));
}
assertTrue("ProviderUtil did not return LOADED for isLoaded for phoneNumbers when it should.", util.isLoadedWithReference(emp, "phoneNumbers").equals(LoadState.LOADED));
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for projects when it should.", util.isLoadedWithReference(emp, "projects").equals(LoadState.NOT_LOADED));
assertTrue("ProviderUtil did not return UNKNOWN for isLoaded when it should.", util.isLoaded(new NonEntity()).equals(LoadState.UNKNOWN));
} finally {
rollbackTransaction(em);
}
}
use of org.neo4j.ogm.domain.gh824.Address in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testNoPersistOnCommit.
// Test Not using the persist operation on commit.
public void testNoPersistOnCommit() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setLastName("SomeName");
Address addr = new Address();
addr.setCity("Douglas");
try {
em.persist(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
((RepeatableWriteUnitOfWork) JpaHelper.getEntityManager(em).getUnitOfWork()).setDiscoverUnregisteredNewObjectsWithoutPersist(true);
employee = em.find(Employee.class, employee.getId());
employee.setAddress(addr);
addr.getEmployees().add(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager();
clearCache();
beginTransaction(em);
((RepeatableWriteUnitOfWork) JpaHelper.getEntityManager(em).getUnitOfWork()).setDiscoverUnregisteredNewObjectsWithoutPersist(true);
employee = em.find(Employee.class, employee.getId());
employee.getAddress().setCountry("country");
employee.getAddress().getEmployees().size();
employee.setAddress((Address) null);
em.remove(employee);
commitTransaction(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
assertNull("Employee Not Deleted", employee);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
} finally {
try {
em = createEntityManager();
clearCache();
beginTransaction(em);
em.remove(em.find(Address.class, addr.getID()));
commitTransaction(em);
} catch (RuntimeException ex) {
// ignore
}
}
}
use of org.neo4j.ogm.domain.gh824.Address in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testOverwrittingAndOverLoadingMethods.
// This test weaving works with over-writing methods in subclasses, and overloading methods.
public void testOverwrittingAndOverLoadingMethods() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Address address = new Address();
address.setCity("Ottawa");
Employee employee = new Employee();
employee.setAddress(address);
LargeProject project = new LargeProject();
project.setTeamLeader(employee);
em.persist(employee);
em.persist(project);
commitTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
project = em.find(LargeProject.class, project.getId());
if ((employee.getAddress("Home") == null) || (!employee.getAddress("Home").getCity().equals("Ottawa"))) {
fail("Get address did not work.");
}
employee.setAddress("Toronto");
if (!employee.getAddress().getCity().equals("Toronto")) {
fail("Set address did not work.");
}
if (project.getTeamLeader() != employee) {
fail("Get team leader did not work, team is: " + project.getTeamLeader() + " but should be:" + employee);
}
em.remove(employee.getAddress());
em.remove(employee);
em.remove(project);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
use of org.neo4j.ogm.domain.gh824.Address in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testSerializedLazy.
// test for GlassFish bug 711 - throw a descriptive exception when an uninstantiated valueholder is serialized and then accessed
public void testSerializedLazy() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Owen");
emp.setLastName("Hargreaves");
emp.setId(40);
Address address = new Address();
address.setCity("Munich");
emp.setAddress(address);
em.persist(emp);
em.flush();
commitTransaction(em);
closeEntityManager(em);
clearCache();
em = createEntityManager();
String ejbqlString = "SELECT e FROM Employee e WHERE e.firstName = 'Owen' and e.lastName = 'Hargreaves'";
List result = em.createQuery(ejbqlString).getResultList();
emp = (Employee) result.get(0);
Exception exception = null;
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(emp);
stream.flush();
byte[] arr = byteStream.toByteArray();
ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
emp = (Employee) inObjStream.readObject();
emp.getAddress();
} catch (ValidationException e) {
if (e.getErrorCode() == ValidationException.INSTANTIATING_VALUEHOLDER_WITH_NULL_SESSION) {
exception = e;
} else {
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
} catch (Exception e) {
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
// Only throw error if weaving was used.
if (isWeavingEnabled()) {
assertNotNull("The correct exception was not thrown while traversing an uninstantiated lazy relationship on a serialized object: " + exception, exception);
}
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
}
Aggregations