use of javax.jdo.listener.DeleteLifecycleListener in project tests by datanucleus.
the class JDOPersistenceTestCase method cleanup.
protected void cleanup(Set<Object> toCleanup) throws Exception {
// Keep track of what is being deleted so we don't need to
// delete what has already been deleted by the cascade.
Set<Object> deleted = new HashSet<>();
DeleteLifecycleListener listener = new DeleteLifecycleListener() {
@Override
public void preDelete(InstanceLifecycleEvent event) {
// Nothing to do
}
@Override
public void postDelete(InstanceLifecycleEvent event) {
Object id = ((Persistable) event.getSource()).dnGetObjectId();
deleted.add(id);
}
};
try (PersistenceManager pm = pmf.getPersistenceManager()) {
pm.addInstanceLifecycleListener(listener, Object.class);
Set<Object> toDelete = toCleanup;
Set<Object> retry = new HashSet<>();
int attempts = 0;
do {
// Try to delete
for (Object id : toDelete) {
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Cleaning up: " + id);
}
if (deleted.contains(id)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Already deleted: " + id);
}
} else {
Object object = pm.getObjectById(id, false);
boolean cleanerRun = false;
for (Entry<String, Consumer<PersistenceManager>> entry : cleanersByPrefix.entrySet()) {
if (object.getClass().getName().startsWith(entry.getKey())) {
entry.getValue().accept(pm);
cleanerRun = true;
break;
}
}
if (!cleanerRun) {
LOG.debug(">> calling deletePersistent on " + StringUtils.toJVMIDString(object) + " state=" + JDOHelper.getObjectState(object));
pm.deletePersistent(object);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Cleaned " + id + " successfully");
}
}
} catch (Exception e) {
LOG.warn("Exception in delete process", e);
if (LOG.isDebugEnabled()) {
LOG.debug("Failed, retrying later: " + id);
}
retry.add(id);
}
}
attempts++;
if (!retry.isEmpty() && attempts > MAX_CLEANUP_ATTEMPTS) {
// Give up
retry.clear();
// throw new Exception("Fail to cleanup the following object(s) after " + attempts + " attempts: " + retry);
}
// Try again
toDelete.clear();
toDelete.addAll(retry);
retry.clear();
} while (!toDelete.isEmpty());
}
}
Aggregations