public void testAutoNaming() throws Exception
{
String jcdAlias = "testAutoNaming";
PBKey tempKey = new PBKey(jcdAlias, TestHelper.DEF_KEY.getUser(), TestHelper.DEF_KEY.getPassword());
MetadataManager mm = MetadataManager.getInstance();
PersistenceBroker broker = null;
try
{
JdbcConnectionDescriptor jcd = mm.connectionRepository().getDescriptor(TestHelper.DEF_KEY);
jcd = (JdbcConnectionDescriptor) SerializationUtils.clone(jcd);
// modify jcd copy
jcd.setJcdAlias(jcdAlias);
SequenceDescriptor sd = jcd.getSequenceDescriptor();
assertNotNull("Can not find sequence-descriptor - check test", sd);
// don't use autoNaming
sd.addAttribute("autoNaming", "false");
// add new connection descriptor to global base
mm.connectionRepository().addDescriptor(jcd);
// allow per thread changes of persistent object data
mm.setEnablePerThreadChanges(true);
DescriptorRepository dr = mm.copyOfGlobalRepository();
ClassDescriptor cld = dr.getDescriptorFor(SMAutoNaming.class);
FieldDescriptor field = cld.getAutoIncrementFields()[0];
// set sequence name for persistent object to null
field.setSequenceName(null);
mm.setDescriptor(dr);
broker = PersistenceBrokerFactory.createPersistenceBroker(tempKey);
try
{
/*
persistent object descriptor doesn't has a sequence name
and autoNaming is false --> expect an exception
*/
SMAutoNaming obj = new SMAutoNaming("testAutoNaming_1");
sd = broker.serviceConnectionManager().getConnectionDescriptor().getSequenceDescriptor();
assertTrue("false".equals(sd.getAttribute("autoNaming")));
broker.beginTransaction();
broker.store(obj);
broker.commitTransaction();
fail("If sequence manager implementation supports 'autoNaming' feature,"
+" this test should cause an exception (else ignore this failure).");
}
catch (PersistenceBrokerException e)
{
assertTrue(true);
broker.abortTransaction();
}
try
{
/* attribute 'auto-naming' is still false,
but now we set a sequence name for autoincrement field
--> should pass
*/
field.setSequenceName("AA_testAutoNaming_user_set");
SMAutoNaming obj = new SMAutoNaming("testAutoNaming_2");
broker.beginTransaction();
broker.store(obj);
broker.commitTransaction();
}
catch (PersistenceBrokerException e)
{
e.printStackTrace();
broker.close();
throw e;
}
try
{
// let OJB re-initialize sequence-manager
broker.close();
PersistenceBrokerFactory.releaseAllInstances();
/*
remove sequence name of autoincrement field
but enable automatic sequence name generation
--> should pass
*/
field.setSequenceName(null);
sd.addAttribute("autoNaming", "true");
broker = PersistenceBrokerFactory.createPersistenceBroker(tempKey);
SMAutoNaming obj = new SMAutoNaming("testAutoNaming_3");
broker.beginTransaction();
broker.store(obj);
broker.commitTransaction();
}
catch (PersistenceBrokerException e)
{
e.printStackTrace();
fail("Sequence key generation failed");
}
}
finally
{
// cleanup
if (broker != null) broker.close();
mm.setEnablePerThreadChanges(false);
}
}