LockCleanupSessionListener implements HttpSessionListener { @Override public void sessionDestroyed(HttpSessionEvent se) { final ConfigIOServiceProducer ioServiceProducer = ConfigIOServiceProducer.getInstance(); final IOService ioService = ioServiceProducer.configIOService(); final FileSystem fileSystem = ioServiceProducer.configFileSystem(); @SuppressWarnings("unchecked") final Set<LockInfo> locks = (Set<LockInfo>) se.getSession() .getAttribute(VFSLockServiceImpl.LOCK_SESSION_ATTRIBUTE_NAME); if (locks != null) { try { ioService.startBatch(fileSystem); for (LockInfo lock : locks) { try { final Path lockPath = Paths.convert(PathFactory.newLock(lock.getFile())); if (ioService.readAllString(lockPath).equals(lock.lockedBy())) { ioService.delete(lockPath); } } catch (NoSuchFileException e) { logger.debug("Problem when releasing lock on session end (lock no longer exists): " + lock, e); } catch (Throwable t) { logger.warn("Problem when releasing lock on session end: " + lock, t); } } } finally { ioService.endBatch(); } } }  @Override void sessionCreated(HttpSessionEvent se); @Override void sessionDestroyed(HttpSessionEvent se);  }
@Test public void throwExceptionWhenIOProducerNotInitialized() { final LockCleanupSessionListener listener = new LockCleanupSessionListener(); assertThatThrownBy(() -> listener.sessionDestroyed(evt)) .isInstanceOf(IllegalStateException.class) .hasMessage("org.uberfire.backend.server.io.ConfigIOServiceProducer not initialized on startup"); }
@Test public void initWithoutInjection() { final ConfigIOServiceProducer producer = spy(new ConfigIOServiceProducer()); final LockCleanupSessionListener listener = new LockCleanupSessionListener(); try { when(evt.getSession()).thenReturn(session); when(session.getAttribute(VFSLockServiceImpl.LOCK_SESSION_ATTRIBUTE_NAME)).thenReturn(Collections.emptySet()); when(producer.configIOService()).thenReturn(ioService); producer.setup(); listener.sessionDestroyed(evt); verify(producer).configIOService(); verify(producer).configFileSystem(); } finally { producer.destroy(); } }
@Test public void releaseLockAssociatedWithSession() { final ConfigIOServiceProducer producer = spy(new ConfigIOServiceProducer()); final LockCleanupSessionListener listener = spy(new LockCleanupSessionListener()); try { final String lockedBy = "christian"; final LockInfo lock = new LockInfo(true, lockedBy, PathFactory.newPath("file", "default: when(evt.getSession()).thenReturn(session); when(session.getAttribute(VFSLockServiceImpl.LOCK_SESSION_ATTRIBUTE_NAME)).thenReturn(Collections.singleton(lock)); when(producer.configIOService()).thenReturn(ioService); when(ioService.readAllString(any(Path.class))).thenReturn(lockedBy); producer.setup(); listener.sessionDestroyed(evt); verify(ioService, times(1)).delete(any(Path.class)); } finally { producer.destroy(); } }