@Transactional public AccessKey authenticate(@NotNull String key) { Optional<AccessKey> accessKeyOpt = genericDAO .createNamedQuery(AccessKey.class, "AccessKey.getByKey", Optional.of(CacheConfig.get())) .setParameter("someKey", key) .getResultList() .stream() .findFirst(); if (!accessKeyOpt.isPresent()) { return null; } AccessKey accessKey = accessKeyOpt.get(); final Long expirationPeriod = configurationService.getLong(Constants.SESSION_TIMEOUT, Constants.DEFAULT_SESSION_TIMEOUT); if (accessKey.getExpirationDate() != null) { final Long expiresIn = accessKey.getExpirationDate().getTime() - timestampService.getTimestamp().getTime(); if (AccessKeyType.SESSION == accessKey.getType() && expiresIn > 0 && expiresIn < expirationPeriod / 2) { em.refresh(accessKey, LockModeType.PESSIMISTIC_WRITE); accessKey.setExpirationDate( new Date(timestampService.getTimestamp().getTime() + expirationPeriod)); return genericDAO.merge(accessKey); } } return accessKey; }
@Scheduled(cron = "0 0 0 * * SUN") @Transactional(propagation = Propagation.NOT_SUPPORTED) public void removeExpiredKeys() { logger.debug("Removing expired access keys"); int removed = genericDAO .createNamedQuery("AccessKey.deleteOlderThan", Optional.<CacheConfig>empty()) .setParameter("expirationDate", timestampService.getTimestamp()) .executeUpdate(); logger.info("Removed {} expired access keys", removed); }