use of org.apereo.portal.jpa.EntityManagerCreatedEvent in project uPortal by Jasig.
the class EntityManagerCacheImpl method onApplicationEvent.
@Override
public void onApplicationEvent(AbstractEntityManagerEvent event) {
final String persistenceUnitName = event.getPersistenceUnitName();
final AtomicInteger counter = OPEN_EM_COUNTER.getUnchecked(persistenceUnitName);
final String entityManagerId = event.getEntityManagerId();
if (event instanceof EntityManagerCreatedEvent) {
final int count = counter.incrementAndGet();
if (logger.isTraceEnabled()) {
logger.trace("CREATE " + count + " - " + entityManagerId + " " + Thread.currentThread().getName());
}
// Get/Create the currentEntityManagers Map
Map<String, Deque<String>> currentEntityManagers = CURRENT_ENTITY_MANAGER_SESSIONS.get();
if (currentEntityManagers == null) {
currentEntityManagers = new HashMap<String, Deque<String>>();
CURRENT_ENTITY_MANAGER_SESSIONS.set(currentEntityManagers);
}
// Get/Create the Deque of current entityManagerIds
Deque<String> entityManagerIds = currentEntityManagers.get(persistenceUnitName);
if (entityManagerIds == null) {
entityManagerIds = new LinkedList<String>();
currentEntityManagers.put(persistenceUnitName, entityManagerIds);
}
// Set the current EMiD for this PU
entityManagerIds.offerFirst(entityManagerId);
} else if (event instanceof EntityManagerClosingEvent) {
final int count = counter.decrementAndGet();
if (logger.isTraceEnabled()) {
logger.trace("CLOSE " + count + " - " + entityManagerId + " " + Thread.currentThread().getName());
}
// Purge any cached data related to this entity manager
taggedCacheEntryPurger.purgeCacheEntries(new SimpleCacheEntryTag(CACHE_TAG, entityManagerId));
// Get the currentEntityManagers Map
final Map<String, Deque<String>> currentEntityManagers = CURRENT_ENTITY_MANAGER_SESSIONS.get();
if (currentEntityManagers == null || currentEntityManagers.isEmpty()) {
logger.error("Closing " + entityManagerId + " but there is no currentEntityManagers Map for this Thread", new Throwable());
}
// Get the Deque of current entityManagerIds
final Deque<String> entityManagerIds = currentEntityManagers.get(persistenceUnitName);
if (entityManagerIds == null || entityManagerIds.isEmpty()) {
logger.error("Closing " + entityManagerId + " but there is no entityManagerIds Deque for this Thread", new Throwable());
}
// Get the current EMiD for this PU
final String currentEntityManagerId = entityManagerIds.getFirst();
if (!currentEntityManagerId.equals(entityManagerId)) {
logger.error("Closing " + entityManagerId + " but the current EntityManagerId is " + currentEntityManagerId, new Throwable());
}
// Remove the current EMiD
entityManagerIds.removeFirst();
// If nothing else is tracked for this PU remove the deque
if (entityManagerIds.isEmpty()) {
currentEntityManagers.remove(persistenceUnitName);
}
// If nothing else is tracked for this thread remove the local
if (currentEntityManagers.isEmpty()) {
CURRENT_ENTITY_MANAGER_SESSIONS.remove();
}
}
}
Aggregations