From bca8dfb088027585859ba20da021ceb99c94efe8 Mon Sep 17 00:00:00 2001 From: sgiannopoulos Date: Tue, 28 May 2024 14:57:40 +0300 Subject: [PATCH] fix notification event --- backend/core/pom.xml | 2 +- .../opencdmp/data/tenant/TenantListener.java | 25 +++--- .../InboxIntegrationEventConfigurer.java | 18 ++-- .../OutboxIntegrationEventConfigurer.java | 19 ++-- .../inbox/InboxRepositoryImpl.java | 42 ++++----- .../outbox/OutboxRepositoryImpl.java | 46 ++++------ .../service/metrics/UpdateMetricsTask.java | 49 +++-------- .../storage/StorageFileCleanupTask.java | 19 ++-- .../service/user/UserServiceImpl.java | 35 ++++---- backend/pom.xml | 2 +- .../GlobalExceptionHandler.java | 2 +- .../web/scope/tenant/TenantInterceptor.java | 17 ++-- notification-service/notification/pom.xml | 4 +- .../common/XmlHandlingService.java | 2 +- .../common/lock/LockByKeyManager.java | 2 +- .../scope/fake/FakeRequestAttributes.java | 2 +- .../common/scope/tenant/TenantScope.java | 53 ++--------- .../notification/NotificationConfig.java | 7 +- .../data/TenantEntityManager.java | 66 ++++++++++---- .../data/tenant/TenantFilterAspect.java | 88 +++++++++---------- .../data/tenant/TenantListener.java | 18 ++-- .../data/tenant/TenantScopedBaseEntity.java | 9 +- .../InboxIntegrationEventConfigurer.java | 11 ++- .../OutboxIntegrationEventConfigurer.java | 11 ++- .../inbox/InboxRepositoryImpl.java | 28 +++--- .../NotifyIntegrationEventHandlerImpl.java | 32 +++---- ...aleRemovalIntegrationEventHandlerImpl.java | 4 +- ...aleTouchedIntegrationEventHandlerImpl.java | 4 +- ...serRemovalIntegrationEventHandlerImpl.java | 13 ++- .../UserTouchedIntegrationEvent.java | 17 ++-- ...serTouchedIntegrationEventHandlerImpl.java | 11 ++- .../outbox/OutboxRepositoryImpl.java | 36 +++----- .../model/builder/BaseBuilder.java | 2 +- .../model/deleter/UserDeleter.java | 14 +-- .../extractor/EmailContactExtractor.java | 2 +- .../notification/NotificationServiceImpl.java | 2 - .../NotificationSchedulingServiceImpl.java | 80 +++++++++-------- .../service/notify/InAppNotifier.java | 8 +- .../service/notify/NotifierFactory.java | 2 +- .../service/track/EmailTracker.java | 2 +- .../service/track/TrackingFactory.java | 2 +- .../service/user/UserServiceImpl.java | 7 +- 42 files changed, 370 insertions(+), 445 deletions(-) diff --git a/backend/core/pom.xml b/backend/core/pom.xml index 5ffac96a2..b60cfe7c3 100644 --- a/backend/core/pom.xml +++ b/backend/core/pom.xml @@ -61,7 +61,7 @@ gr.cite data-tools - 2.1.3 + 2.1.4 org.opencdmp diff --git a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java index 64570e67f..5c8086146 100644 --- a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java +++ b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java @@ -1,19 +1,18 @@ package org.opencdmp.data.tenant; -import org.opencdmp.commons.scope.tenant.TenantScope; -import org.opencdmp.commons.scope.tenant.TenantScoped; -import org.opencdmp.errorcode.ErrorThesaurusProperties; import gr.cite.tools.exception.MyForbiddenException; import gr.cite.tools.logging.LoggerService; import jakarta.persistence.PrePersist; import jakarta.persistence.PreRemove; import jakarta.persistence.PreUpdate; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.tenant.TenantScoped; +import org.opencdmp.errorcode.ErrorThesaurusProperties; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import javax.management.InvalidApplicationException; - import java.util.UUID; public class TenantListener { @@ -33,13 +32,13 @@ public class TenantListener { @PrePersist public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (this.tenantScope.isMultitenant()) { + if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to set not login tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (!tenantScope.isDefaultTenant()) { - final UUID tenantId = tenantScope.getTenant(); + if (!this.tenantScope.isDefaultTenant()) { + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } } else { @@ -50,18 +49,18 @@ public class TenantListener { @PreUpdate @PreRemove public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (!tenantScope.isDefaultTenant()) { + if (this.tenantScope.isMultitenant()) { + if (!this.tenantScope.isDefaultTenant()) { if (entity.getTenantId() == null) { logger.error("somebody tried to set null tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { + if (entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - final UUID tenantId = tenantScope.getTenant(); + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } else { if (entity.getTenantId() != null) { @@ -70,7 +69,7 @@ public class TenantListener { } } } else { - if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java index 0ccf54333..3e9ecc3a2 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java @@ -1,31 +1,33 @@ package org.opencdmp.integrationevent; -import org.opencdmp.integrationevent.inbox.InboxProperties; -import org.opencdmp.integrationevent.inbox.InboxRepositoryImpl; import gr.cite.queueinbox.InboxConfigurer; import gr.cite.queueinbox.repository.InboxRepository; +import jakarta.persistence.EntityManagerFactory; +import org.opencdmp.integrationevent.inbox.InboxProperties; +import org.opencdmp.integrationevent.inbox.InboxRepositoryImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; @Configuration -@EnableConfigurationProperties({InboxProperties.class}) +@EnableConfigurationProperties(InboxProperties.class) @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) public class InboxIntegrationEventConfigurer extends InboxConfigurer { - private ApplicationContext applicationContext; - private InboxProperties inboxProperties; + private final ApplicationContext applicationContext; + private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; - public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { + public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.inboxProperties = inboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean public InboxRepository inboxRepositoryCreator() { - return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); + return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory); } } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java index 45b71f14a..3bc62d7b7 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java @@ -1,15 +1,16 @@ package org.opencdmp.integrationevent; -import org.opencdmp.data.QueueOutboxEntity; -import org.opencdmp.integrationevent.outbox.OutboxProperties; -import org.opencdmp.integrationevent.outbox.OutboxRepositoryImpl; import gr.cite.queueoutbox.IntegrationEventContextCreator; import gr.cite.queueoutbox.OutboxConfigurer; import gr.cite.queueoutbox.repository.OutboxRepository; import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.broker.MessageHydrator; +import jakarta.persistence.EntityManagerFactory; +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.integrationevent.outbox.OutboxProperties; +import org.opencdmp.integrationevent.outbox.OutboxRepositoryImpl; import org.springframework.amqp.core.MessageProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -23,15 +24,17 @@ import java.time.Instant; import java.util.UUID; @Configuration -@EnableConfigurationProperties({OutboxProperties.class}) +@EnableConfigurationProperties(OutboxProperties.class) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { - private ApplicationContext applicationContext; - private OutboxProperties outboxProperties; + private final ApplicationContext applicationContext; + private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { + public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.outboxProperties = outboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean @@ -67,7 +70,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { @Bean public OutboxRepository outboxRepositoryCreator() { - return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); + return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory); } } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java index 2251896b7..567ea8219 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java @@ -1,12 +1,5 @@ package org.opencdmp.integrationevent.inbox; -import org.opencdmp.commons.JsonHandlingService; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.data.QueueInboxEntity; -import org.opencdmp.data.TenantEntityManager; -import org.opencdmp.integrationevent.TrackedEvent; -import org.opencdmp.query.QueueInboxQuery; import gr.cite.queueinbox.entity.QueueInbox; import gr.cite.queueinbox.entity.QueueInboxStatus; import gr.cite.queueinbox.repository.CandidateInfo; @@ -21,6 +14,13 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueInboxEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.integrationevent.TrackedEvent; +import org.opencdmp.query.QueueInboxQuery; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; @@ -36,13 +36,15 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin private final JsonHandlingService jsonHandlingService; private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; public InboxRepositoryImpl( - ApplicationContext applicationContext, - InboxProperties inboxProperties + ApplicationContext applicationContext, + InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.inboxProperties = inboxProperties; } @@ -54,8 +56,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -112,9 +113,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -158,9 +157,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -206,9 +203,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.createQueueInboxEntity(inboxCreatorParams); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -266,10 +261,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java index 85bdb12cb..0ba279b12 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java @@ -1,10 +1,5 @@ package org.opencdmp.integrationevent.outbox; -import org.opencdmp.commons.JsonHandlingService; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.data.QueueOutboxEntity; -import org.opencdmp.query.QueueOutboxQuery; import gr.cite.queueoutbox.entity.QueueOutbox; import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; import gr.cite.queueoutbox.repository.CandidateInfo; @@ -18,6 +13,11 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.query.QueueOutboxQuery; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; @@ -36,13 +36,15 @@ public class OutboxRepositoryImpl implements OutboxRepository { private final JsonHandlingService jsonHandlingService; private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; public OutboxRepositoryImpl( - ApplicationContext applicationContext, - OutboxProperties outboxProperties + ApplicationContext applicationContext, + OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.outboxProperties = outboxProperties; } @@ -54,8 +56,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -115,9 +116,8 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -161,9 +161,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -208,10 +206,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -264,10 +259,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -308,10 +300,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -353,9 +342,8 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.mapEvent((OutboxIntegrationEvent) item); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); diff --git a/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java b/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java index 07d2b1813..3567b7427 100644 --- a/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java +++ b/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java @@ -1,31 +1,11 @@ package org.opencdmp.service.metrics; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.commons.metrics.MetricNames; -import org.opencdmp.commons.scope.tenant.TenantScope; -import org.opencdmp.data.QueueInboxEntity; -import org.opencdmp.data.StorageFileEntity; -import org.opencdmp.data.TenantEntity; -import org.opencdmp.data.TenantEntityManager; -import org.opencdmp.integrationevent.inbox.EventProcessingStatus; -import org.opencdmp.model.StorageFile; -import org.opencdmp.model.Tenant; -import org.opencdmp.query.QueueInboxQuery; -import org.opencdmp.query.StorageFileQuery; -import org.opencdmp.query.TenantQuery; -import org.opencdmp.service.storage.StorageFileService; -import gr.cite.queueinbox.entity.QueueInboxStatus; -import gr.cite.queueinbox.repository.CandidateInfo; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.logging.LoggerService; -import io.micrometer.prometheus.PrometheusMeterRegistry; import io.prometheus.client.Gauge; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.TenantEntityManager; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; @@ -36,30 +16,28 @@ import org.springframework.stereotype.Service; import java.io.Closeable; import java.io.IOException; -import java.time.Instant; import java.util.Map; -import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; @Service -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class UpdateMetricsTask implements Closeable, ApplicationListener { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UpdateMetricsTask.class)); private final UpdateMetricsTaskProperties _config; private final ApplicationContext applicationContext; + private final EntityManagerFactory entityManagerFactory; private ScheduledExecutorService scheduler; private Map gauges; public UpdateMetricsTask( UpdateMetricsTaskProperties config, - ApplicationContext applicationContext) { + ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) { this._config = config; this.applicationContext = applicationContext; + this.entityManagerFactory = entityManagerFactory; this.gauges = null; } @@ -69,16 +47,16 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener 0) { logger.info("File clean up run in {} seconds", intervalSeconds); - scheduler = Executors.newScheduledThreadPool(1); - scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS); + this.scheduler = Executors.newScheduledThreadPool(1); + this.scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS); } else { - scheduler = null; + this.scheduler = null; } } @Override public void close() throws IOException { - if (scheduler != null) this.scheduler.close(); + if (this.scheduler != null) this.scheduler.close(); } protected void process() { @@ -106,15 +84,10 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener { - private class CandidateInfo + private static class CandidateInfo { private UUID id; private Instant createdAt; @@ -59,19 +60,21 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener 0) { logger.info("File clean up run in {} seconds", intervalSeconds); @@ -117,9 +120,8 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener fieldInfoList = new ArrayList<>(); @@ -530,13 +529,13 @@ public class UserServiceImpl implements UserService { String token = this.createRemoveConfirmation(data.getId()); - this.createRemoveCredentialNotificationEvent(token, data.getUserId(), NotificationContactType.EMAIL); + this.createRemoveCredentialNotificationEvent(token, data.getUserId()); } - private void createRemoveCredentialNotificationEvent(String token, UUID userId, NotificationContactType type) throws InvalidApplicationException { + private void createRemoveCredentialNotificationEvent(String token, UUID userId) throws InvalidApplicationException { NotifyIntegrationEvent event = new NotifyIntegrationEvent(); event.setUserId(userId); - event.setContactTypeHint(type); + event.setContactTypeHint(NotificationContactType.EMAIL); event.setNotificationType(this.notificationProperties.getRemoveCredentialConfirmationType()); NotificationFieldData data = new NotificationFieldData(); List fieldInfoList = new ArrayList<>(); @@ -647,12 +646,12 @@ public class UserServiceImpl implements UserService { this.entityManager.merge(userCredential); } - List userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect(); + List userContacts = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect(); UserContactInfoQuery newUserContactInfoQuery = this.queryFactory.query(UserContactInfoQuery.class).userIds(newUser.getId()); newUserContactInfoQuery.setOrder(new Ordering().addDescending(UserContactInfo._ordinal)); UserContactInfoEntity newUserContactInfo = newUserContactInfoQuery.first(); int ordinal = newUserContactInfo == null ? 0 : newUserContactInfo.getOrdinal() + 1; - for (UserContactInfoEntity userContactInfo : userContactInfos){ + for (UserContactInfoEntity userContactInfo : userContacts){ userContactInfo.setUserId(newUser.getId()); userContactInfo.setOrdinal(ordinal); this.entityManager.merge(userContactInfo); @@ -759,9 +758,9 @@ public class UserServiceImpl implements UserService { if (userCredentialEntity.getData() != null){ UserCredentialDataEntity userCredentialDataEntity = this.jsonHandlingService.fromJsonSafe(UserCredentialDataEntity.class, userCredentialEntity.getData()); if (userCredentialDataEntity != null && !this.conventionService.isNullOrEmpty(userCredentialDataEntity.getEmail())) { - List userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect(); - if (!this.conventionService.isListNullOrEmpty(userContactInfos)) - this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContactInfos); + List userContacts = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect(); + if (!this.conventionService.isListNullOrEmpty(userContacts)) + this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContacts); } } this.deleterFactory.deleter(UserCredentialDeleter.class).delete(List.of(userCredentialEntity)); @@ -772,10 +771,10 @@ public class UserServiceImpl implements UserService { this.entityManager.flush(); + this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId()); + this.keycloakService.removeFromAllGroups(userCredentialEntity.getExternalId()); this.addToDefaultUserGroups(userCredentialEntity.getExternalId()); - - this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId()); } private void addToDefaultUserGroups(String subjectId){ diff --git a/backend/pom.xml b/backend/pom.xml index 6eed694df..aa2a54174 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -215,7 +215,7 @@ gr.cite data-tools - 2.1.3 + 2.1.4 gr.cite diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java index b8a3b685c..1adb80c48 100644 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java +++ b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java @@ -150,7 +150,7 @@ public class GlobalExceptionHandler { Map.entry("error", "System error") ); } - }; + } String serialization = this.jsonHandlingService.toJsonSafe(result); return new HandledException(statusCode, serialization, logLevel); } diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java index afac21279..ef5fc0e34 100644 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java +++ b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java @@ -9,6 +9,7 @@ import gr.cite.notification.authorization.Permission; import gr.cite.notification.common.enums.IsActive; import gr.cite.notification.common.scope.tenant.TenantScope; import gr.cite.notification.common.scope.user.UserScope; +import gr.cite.notification.data.TenantEntityManager; import gr.cite.notification.data.TenantUserEntity; import gr.cite.notification.data.UserEntity; import gr.cite.notification.data.tenant.TenantScopedBaseEntity; @@ -52,6 +53,7 @@ public class TenantInterceptor implements WebRequestInterceptor { private final UserAllowedTenantCacheService userAllowedTenantCacheService; private final ErrorThesaurusProperties errors; private final QueryUtilsService queryUtilsService; + public final TenantEntityManager tenantEntityManager; @PersistenceContext public EntityManager entityManager; @@ -64,7 +66,7 @@ public class TenantInterceptor implements WebRequestInterceptor { ApplicationContext applicationContext, TenantScopeProperties tenantScopeProperties, UserAllowedTenantCacheService userAllowedTenantCacheService, - ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService) { + ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService, TenantEntityManager tenantEntityManager) { this.tenantScope = tenantScope; this.userScope = userScope; this.currentPrincipalResolver = currentPrincipalResolver; @@ -74,6 +76,7 @@ public class TenantInterceptor implements WebRequestInterceptor { this.userAllowedTenantCacheService = userAllowedTenantCacheService; this.errors = errors; this.queryUtilsService = queryUtilsService; + this.tenantEntityManager = tenantEntityManager; } @Override @@ -103,16 +106,7 @@ public class TenantInterceptor implements WebRequestInterceptor { } if (isUserAllowedTenant) { - if(!tenantScope.isDefaultTenant()) { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); - } else { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } + this.tenantEntityManager.reloadTenantFilters(); } else { if (isAllowedNoTenant || this.isWhiteListedEndpoint(request)) { tenantScope.setTenant(null, null); @@ -181,6 +175,7 @@ public class TenantInterceptor implements WebRequestInterceptor { @Override public void postHandle(@NonNull WebRequest request, ModelMap model) { this.tenantScope.setTenant(null, null); + this.tenantEntityManager.disableTenantFilters(); } @Override diff --git a/notification-service/notification/pom.xml b/notification-service/notification/pom.xml index 76279f0b5..978ecf310 100644 --- a/notification-service/notification/pom.xml +++ b/notification-service/notification/pom.xml @@ -53,7 +53,7 @@ gr.cite data-tools - 2.1.2 + 2.1.4 gr.cite @@ -83,7 +83,7 @@ gr.cite validation - 3.0.2 + 3.0.3 diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java b/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java index cec063abf..1207e4580 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java @@ -70,7 +70,7 @@ public class XmlHandlingService { public T fromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { if (XmlSerializable.class.isAssignableFrom(type)){ XmlSerializable object = (XmlSerializable)type.newInstance(); - return (T) object.fromXml(this.getDocument(xmlString).getDocumentElement()); + return object.fromXml(this.getDocument(xmlString).getDocumentElement()); } else { JAXBContext jaxbContext = JAXBContext.newInstance(type); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java b/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java index 8c33cb9f7..59ffd49b4 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java @@ -25,7 +25,7 @@ public class LockByKeyManager { } - private static ConcurrentHashMap locks = new ConcurrentHashMap(); + private static final ConcurrentHashMap locks = new ConcurrentHashMap(); public void lock(String key) { LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java index f8f2df085..726be9a97 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java @@ -8,7 +8,7 @@ import java.util.LinkedHashMap; import java.util.Map; public class FakeRequestAttributes implements RequestAttributes { - private Map requestAttributeMap = new HashMap<>(); + private final Map requestAttributeMap = new HashMap<>(); private final Map requestDestructionCallbacks = new LinkedHashMap<>(8); private volatile boolean requestActive = true; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java index 349cf0707..c09af9a5e 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java @@ -1,8 +1,6 @@ package gr.cite.notification.common.scope.tenant; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.EntityManager; -import org.hibernate.Session; +import gr.cite.notification.data.TenantEntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.RequestScope; @@ -27,11 +25,11 @@ public class TenantScope { } public Boolean isMultitenant() { - return multitenancy.isMultitenant(); + return this.multitenancy.isMultitenant(); } public String getDefaultTenantCode() { - return multitenancy.getDefaultTenantCode(); + return this.multitenancy.getDefaultTenantCode(); } public Boolean isSet() { @@ -62,55 +60,18 @@ public class TenantScope { return this.tenantCode.get(); } - public void setTempTenant(EntityManager entityManager, UUID tenant, String tenantCode) { + public void setTempTenant(TenantEntityManager entityManager, UUID tenant, String tenantCode) throws InvalidApplicationException { this.tenant.set(tenant); this.tenantCode.set(tenantCode); - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - if (this.tenant.get() != null || this.isDefaultTenant()) { - if(!this.isDefaultTenant()) { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); - } else { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } + entityManager.reloadTenantFilters(); } - public void removeTempTenant(EntityManager entityManager) { + public void removeTempTenant(TenantEntityManager entityManager) throws InvalidApplicationException { this.tenant.set(this.initialTenant.get()); this.tenantCode.set(this.initialTenantCode.get()); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - if (this.initialTenant.get() != null || this.isDefaultTenant()) { - if(!this.isDefaultTenant()) { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); - } else { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } + entityManager.reloadTenantFilters(); } public void setTenant(UUID tenant, String tenantCode) { diff --git a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java index 58d962160..38413fef9 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java @@ -6,6 +6,7 @@ import gr.cite.notification.service.message.common.MessageBuilderBase; import gr.cite.notification.service.notificationscheduling.NotificationSchedulingService; import gr.cite.notification.service.notificationscheduling.NotificationSchedulingServiceImpl; import gr.cite.queueinbox.task.rabbitmq.QueueListenerProperties; +import jakarta.persistence.EntityManagerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -33,11 +34,13 @@ public class NotificationConfig { } private final ApplicationContext applicationContext; private final NotificationProperties properties; + private final EntityManagerFactory entityManagerFactory; @Autowired - public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties) { + public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.properties = properties; + this.entityManagerFactory = entityManagerFactory; } @Bean(BeanQualifier.GLOBAL_POLICIES_MAP) @@ -71,7 +74,7 @@ public class NotificationConfig { @Bean public NotificationSchedulingService notificationSchedulingService() { - return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties); + return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties, this.entityManagerFactory); } @Bean diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java index fd7d63266..360e3031a 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java @@ -33,9 +33,9 @@ public class TenantEntityManager { } public T merge(T entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!this.tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } else if (tenantScopedEntity.getTenantId() != null) { throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } @@ -44,9 +44,9 @@ public class TenantEntityManager { } public void remove(Object entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!this.tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } else if (tenantScopedEntity.getTenantId() != null) { throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } @@ -57,12 +57,22 @@ public class TenantEntityManager { public T find(Class entityClass, Object primaryKey) throws InvalidApplicationException { T entity = this.entityManager.find(entityClass, primaryKey); - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) return null; + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; } return entity; } + public T find(Class entityClass, Object primaryKey, boolean disableTracking) throws InvalidApplicationException { + T entity = this.entityManager.find(entityClass, primaryKey); + + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; + } + if (disableTracking) this.entityManager.detach(entity); + return entity; + } + public void flush() { this.entityManager.flush(); } @@ -80,14 +90,34 @@ public class TenantEntityManager { public void clear() { this.entityManager.clear(); } - - public void enableTenantFilters() throws InvalidApplicationException { - if (!tenantScope.isSet()) return; - if(!tenantScope.isDefaultTenant()) { + + public void reloadTenantFilters() throws InvalidApplicationException { + this.disableTenantFilters(); + + if (!this.tenantScope.isSet()) return; + + if(!this.tenantScope.isDefaultTenant()) { this.entityManager .unwrap(Session.class) .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); + } else { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + + public void loadExplictTenantFilters() throws InvalidApplicationException { + this.disableTenantFilters(); + + if (!this.tenantScope.isSet()) return; + + if(!this.tenantScope.isDefaultTenant()) { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); } else { this.entityManager .unwrap(Session.class) @@ -103,14 +133,18 @@ public class TenantEntityManager { this.entityManager .unwrap(Session.class) .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + + this.entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT); } - + public EntityManager getEntityManager() { - return entityManager; + return this.entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } -} +} \ No newline at end of file diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java index 2ac3d8397..f0628ed9a 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java @@ -1,44 +1,44 @@ -package gr.cite.notification.data.tenant; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import jakarta.persistence.EntityManager; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.Aspect; -import org.hibernate.Session; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; - -@Aspect -@Component -public class TenantFilterAspect { - - private final TenantScope tenantScope; - - @Autowired - public TenantFilterAspect( - TenantScope tenantScope - ) { - this.tenantScope = tenantScope; - } - - @AfterReturning( - pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", - returning = "retVal") - public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { - if (retVal instanceof EntityManager && tenantScope.isSet()) { - Session session = ((EntityManager) retVal).unwrap(Session.class); - if(!tenantScope.isDefaultTenant()) { - session - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); - } else { - session - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } - } - -} +//package gr.cite.notification.data.tenant; +// +//import gr.cite.notification.common.scope.tenant.TenantScope; +//import jakarta.persistence.EntityManager; +//import org.aspectj.lang.JoinPoint; +//import org.aspectj.lang.annotation.AfterReturning; +//import org.aspectj.lang.annotation.Aspect; +//import org.hibernate.Session; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.stereotype.Component; +// +//import javax.management.InvalidApplicationException; +// +//@Aspect +//@Component +//public class TenantFilterAspect { +// +// private final TenantScope tenantScope; +// +// @Autowired +// public TenantFilterAspect( +// TenantScope tenantScope +// ) { +// this.tenantScope = tenantScope; +// } +// +// @AfterReturning( +// pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", +// returning = "retVal") +// public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { +// if (retVal instanceof EntityManager && tenantScope.isSet()) { +// Session session = ((EntityManager) retVal).unwrap(Session.class); +// if(!tenantScope.isDefaultTenant()) { +// session +// .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) +// .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); +// } else { +// session +// .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); +// } +// } +// } +// +//} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java index 40ef56aee..4d376bdfa 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java @@ -32,13 +32,13 @@ public class TenantListener { @PrePersist public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (this.tenantScope.isMultitenant()) { + if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to set not login tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (!tenantScope.isDefaultTenant()) { - final UUID tenantId = tenantScope.getTenant(); + if (!this.tenantScope.isDefaultTenant()) { + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } } else { @@ -49,18 +49,18 @@ public class TenantListener { @PreUpdate @PreRemove public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (!tenantScope.isDefaultTenant()) { + if (this.tenantScope.isMultitenant()) { + if (!this.tenantScope.isDefaultTenant()) { if (entity.getTenantId() == null) { logger.error("somebody tried to set null tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { + if (entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - final UUID tenantId = tenantScope.getTenant(); + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } else { if (entity.getTenantId() != null) { @@ -69,7 +69,7 @@ public class TenantListener { } } } else { - if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java index 57b499883..6f5d5c0fb 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java @@ -15,22 +15,25 @@ import java.util.UUID; //@Getter //@Setter //@NoArgsConstructor -@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = {@ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)}) +@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) +@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) @FilterDef(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER) -@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") @Filter(name = TenantScopedBaseEntity.TENANT_FILTER, condition = "(tenant = (cast(:tenantId as uuid)) or tenant is null)") +@Filter(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, condition = "(tenant = (cast(:tenantId as uuid)))") +@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") @EntityListeners(TenantListener.class) public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable { private static final long serialVersionUID = 1L; public static final String TENANT_FILTER = "tenantFilter"; public static final String DEFAULT_TENANT_FILTER = "defaultTenantFilter"; + public static final String TENANT_FILTER_EXPLICT = "tenantFilterExplict"; public static final String TENANT_FILTER_TENANT_PARAM = "tenantId"; @Column(name = "tenant", columnDefinition = "uuid", nullable = true) private UUID tenantId; public static final String _tenantId = "tenantId"; public UUID getTenantId() { - return tenantId; + return this.tenantId; } @Override diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java index 998ce70f3..053d3780d 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java @@ -4,6 +4,7 @@ import gr.cite.notification.integrationevent.inbox.InboxProperties; import gr.cite.notification.integrationevent.inbox.InboxRepositoryImpl; import gr.cite.queueinbox.InboxConfigurer; import gr.cite.queueinbox.repository.InboxRepository; +import jakarta.persistence.EntityManagerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; @@ -15,18 +16,20 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) public class InboxIntegrationEventConfigurer extends InboxConfigurer { - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; - private InboxProperties inboxProperties; + private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; - public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { + public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.inboxProperties = inboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean public InboxRepository inboxRepositoryCreator() { - return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); + return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java index efbaab157..f3a41cc91 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java @@ -9,6 +9,7 @@ import gr.cite.queueoutbox.repository.OutboxRepository; import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.broker.MessageHydrator; +import jakarta.persistence.EntityManagerFactory; import org.springframework.amqp.core.MessageProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -25,12 +26,14 @@ import java.util.UUID; @EnableConfigurationProperties({OutboxProperties.class}) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { - private ApplicationContext applicationContext; - private OutboxProperties outboxProperties; + private final ApplicationContext applicationContext; + private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { + public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.outboxProperties = outboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean @@ -66,7 +69,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { @Bean public OutboxRepository outboxRepositoryCreator() { - return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); + return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java index a5c6d2553..42ea7b9de 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java @@ -41,17 +41,17 @@ public class InboxRepositoryImpl implements InboxRepository { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class)); protected final ApplicationContext applicationContext; - private final JsonHandlingService jsonHandlingService; - private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; public InboxRepositoryImpl( - ApplicationContext applicationContext, - InboxProperties inboxProperties + ApplicationContext applicationContext, + InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.inboxProperties = inboxProperties; } @@ -63,8 +63,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -121,9 +120,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -167,9 +164,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -215,9 +210,8 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.createQueueInboxEntity(inboxCreatorParams); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -276,9 +270,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java index bc8ae7b5f..7b2c19748 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java @@ -7,11 +7,9 @@ import gr.cite.notification.common.JsonHandlingService; import gr.cite.notification.common.enums.NotificationNotifyState; import gr.cite.notification.common.enums.NotificationTrackingProcess; import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.common.scope.fake.FakeRequestScope; import gr.cite.notification.common.scope.tenant.TenantScope; import gr.cite.notification.data.TenantEntity; import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; import gr.cite.notification.integrationevent.inbox.InboxPrincipal; import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; @@ -21,21 +19,14 @@ import gr.cite.notification.query.TenantQuery; import gr.cite.notification.service.notification.NotificationService; import gr.cite.tools.auditing.AuditService; import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyValidationException; import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.OptimisticLockException; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.MessageSource; import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.time.Instant; import java.util.AbstractMap; import java.util.Map; @@ -47,11 +38,6 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifyIntegrationEventHandlerImpl.class)); private final JsonHandlingService jsonHandlingService; - - - private final ErrorThesaurusProperties errors; - - private final MessageSource messageSource; private final QueryFactory queryFactory; private final TenantScope tenantScope; private final CurrentPrincipalResolver currentPrincipalResolver; @@ -60,10 +46,8 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent private final NotificationService notificationService; private final AuditService auditService; private final TenantEntityManager tenantEntityManager; - public NotifyIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, ErrorThesaurusProperties errors, MessageSource messageSource, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, NotifyConsistencyHandler notifyConsistencyHandler, NotificationService notificationService, AuditService auditService, TenantEntityManager tenantEntityManager) { + public NotifyIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, NotifyConsistencyHandler notifyConsistencyHandler, NotificationService notificationService, AuditService auditService, TenantEntityManager tenantEntityManager) { this.jsonHandlingService = jsonHandlingService; - this.errors = errors; - this.messageSource = messageSource; this.queryFactory = queryFactory; this.tenantScope = tenantScope; this.currentPrincipalResolver = currentPrincipalResolver; @@ -104,11 +88,11 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -116,7 +100,7 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent if (!(notifyConsistencyHandler.isConsistent(new NotifyConsistencyPredicates(event.getUserId(), event.getContactTypeHint(), event.getContactHint())))) { status = EventProcessingStatus.Postponed; currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + tenantScope.removeTempTenant(this.tenantEntityManager); return status; } notificationService.persist(model, new BaseFieldSet()); @@ -129,7 +113,11 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java index 204570ed8..1afb3929e 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java @@ -73,11 +73,11 @@ public class TenantDefaultLocaleRemovalIntegrationEventHandlerImpl implements Te logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java index d516d3e87..05bc060b8 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java @@ -82,11 +82,11 @@ public class TenantDefaultLocaleTouchedIntegrationEventHandlerImpl implements Te logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java index 426c77352..13facd7c5 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java @@ -26,6 +26,7 @@ import org.springframework.context.annotation.Scope; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.util.AbstractMap; import java.util.Map; @@ -86,11 +87,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -98,7 +99,7 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr if (!(userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(event.getUserId())))) { status = EventProcessingStatus.Postponed; currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + tenantScope.removeTempTenant(this.tenantEntityManager); return status; } @@ -113,7 +114,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java index 02daacb66..18f90a147 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java @@ -14,6 +14,7 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -229,10 +230,10 @@ public class UserTouchedIntegrationEvent extends TrackedEvent { @Override protected List specifications(UserCredential item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getSubjectId())) - .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) + return Collections.singletonList( + this.spec() + .must(() -> !this.isEmpty(item.getSubjectId())) + .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) ); } } @@ -271,10 +272,10 @@ public class UserTouchedIntegrationEvent extends TrackedEvent { @Override protected List specifications(TenantUser item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isNull(item.getTenant())) - .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) + return Collections.singletonList( + this.spec() + .must(() -> !this.isNull(item.getTenant())) + .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) ); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java index 6f2ae39d5..dd2bf81e6 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.util.AbstractMap; import java.util.Map; @@ -76,11 +77,11 @@ public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegr logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -96,7 +97,11 @@ public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegr logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java index 2b4926dea..51c770647 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java @@ -33,16 +33,16 @@ public class OutboxRepositoryImpl implements OutboxRepository { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class)); - private final JsonHandlingService jsonHandlingService; + private final EntityManagerFactory entityManagerFactory; private final OutboxProperties outboxProperties; public OutboxRepositoryImpl( ApplicationContext applicationContext, - OutboxProperties outboxProperties + OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; this.outboxProperties = outboxProperties; } @@ -54,8 +54,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -115,9 +114,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -161,9 +158,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -208,10 +203,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -264,10 +256,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -308,10 +297,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -353,9 +339,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.mapEvent((OutboxIntegrationEvent) item); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java index f062e44e6..ad1d29ada 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java @@ -34,7 +34,7 @@ public abstract class BaseBuilder implements Builder { M model = null; return null; //TODO } - List models = this.build(directives, Arrays.asList(data)); + List models = this.build(directives, List.of(data)); return models.stream().findFirst().orElse(null); //TODO } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java index 16c2d25d7..9355ccea0 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java @@ -69,12 +69,7 @@ public class UserDeleter implements Deleter { if (data == null || data.isEmpty()) return; List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); -// { -// logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName()); -// List items = this.queryFactory.query(UserRoleQuery.class).userIds(ids).collect(); -// UserRoleDeleter deleter = this.deleterFactory.deleter(UserRoleDeleter.class); -// deleter.delete(items); -// } + { logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName()); List items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); @@ -87,12 +82,7 @@ public class UserDeleter implements Deleter { UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.class); deleter.delete(items); } -// { -// logger.debug("checking related - {}", TenantUserEntity.class.getSimpleName()); -// List items = this.queryFactory.query(TenantUserQuery.class).userIds(ids).collect(); -// TenantUserDeleter deleter = this.deleterFactory.deleter(TenantUserDeleter.class); -// deleter.delete(items); -// } + Instant now = Instant.now(); for (UserEntity item : data) { diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java index be7525f1d..432cdc2a8 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java @@ -102,7 +102,7 @@ public class EmailContactExtractor implements ContactExtractor { return contacts; } default: - throw new MyApplicationException("Invalid type " + overrideMode.toString()); + throw new MyApplicationException("Invalid type " + overrideMode); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java index 037a81d36..05677604c 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java @@ -38,7 +38,6 @@ import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; -import jakarta.transaction.Transactional; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -102,7 +101,6 @@ public class NotificationServiceImpl implements NotificationService { } @Override - @Transactional public Notification persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { logger.debug(new MapLogEntry("persisting notification").And("model", model).And("fields", fields)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java index 53136d40c..86501d2e5 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java @@ -40,10 +40,12 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationSchedulingServiceImpl.class)); private final ApplicationContext applicationContext; private final NotificationProperties properties; + private final EntityManagerFactory entityManagerFactory; - public NotificationSchedulingServiceImpl(ApplicationContext applicationContext, NotificationProperties properties) { + public NotificationSchedulingServiceImpl(ApplicationContext applicationContext, NotificationProperties properties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.properties = properties; + this.entityManagerFactory = entityManagerFactory; } @Override @@ -53,9 +55,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling CandidateInfo candidateInfo = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); @@ -73,18 +74,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling candidates.setNotifyState(NotificationNotifyState.PROCESSING); //candidates.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); + try { if (candidates.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } candidates = entityManager.merge(candidates); entityManager.persist(candidates); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); @@ -108,9 +112,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldWait = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationEntity notification = entityManager.find(NotificationEntity.class, candidateInfo.getNotificationId()); @@ -122,7 +125,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling accumulatedRetry += (i * options.getRetryThreshold()); for (int i = 1; i <= notification.getRetryCount(); i += 1) pastAccumulateRetry += (i * options.getRetryThreshold()); - int randAccumulatedRetry = ThreadLocalRandom.current().nextInt((int) (accumulatedRetry / 2), accumulatedRetry + 1); + int randAccumulatedRetry = ThreadLocalRandom.current().nextInt(accumulatedRetry / 2, accumulatedRetry + 1); long additionalTime = randAccumulatedRetry > options.getMaxRetryDelaySeconds() ? options.getMaxRetryDelaySeconds() : randAccumulatedRetry; long retry = pastAccumulateRetry + additionalTime; @@ -133,19 +136,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setNotifyState(candidateInfo.getPreviousState()); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } // notification = entityManager.merge(notification); entityManager.merge(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } } @@ -170,9 +175,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldOmit = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -183,19 +187,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setNotifyState(NotificationNotifyState.OMITTED); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } notification = entityManager.merge(notification); entityManager.persist(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } shouldOmit = true; } @@ -219,9 +225,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean success = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -239,9 +244,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } result = notificationService.doNotify(notification); @@ -262,7 +267,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling entityManager.persist(notification1); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } @@ -290,9 +295,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling CandidateInfo candidateInfo = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); @@ -312,18 +316,20 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling candidates.setTrackingProcess(NotificationTrackingProcess.PROCESSING); //candidates.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (candidates.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } candidates = entityManager.merge(candidates); entityManager.persist(candidates); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); } @@ -346,9 +352,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldOmit = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -359,20 +364,22 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setTrackingProcess(NotificationTrackingProcess.OMITTED); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } notification = entityManager.merge(notification); entityManager.persist(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } shouldOmit = true; } @@ -397,9 +404,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling Boolean success = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -417,9 +423,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling try { if (notification.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } try { TrackingFactory trackingFactory = applicationContext.getBean(TrackingFactory.class); @@ -445,7 +451,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling entityManager.persist(notification1); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java index 96fd88989..313c7f12b 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java @@ -29,11 +29,13 @@ public class InAppNotifier implements Notify{ private final JsonHandlingService jsonHandlingService; private final ApplicationContext applicationContext; + private final EntityManagerFactory entityManagerFactory; @Autowired - public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext) { + public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) { this.jsonHandlingService = jsonHandlingService; this.applicationContext = applicationContext; + this.entityManagerFactory = entityManagerFactory; } @Override @@ -42,9 +44,7 @@ public class InAppNotifier implements Notify{ EntityManager entityManager = null; EntityTransaction transaction = null; try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); InAppContact inAppContact = (InAppContact) contact; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java index 749524670..92a70d190 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java @@ -10,7 +10,7 @@ import java.util.stream.Collectors; @Component public class NotifierFactory { - private Map notifyMap; + private final Map notifyMap; public NotifierFactory(List notifies) { this.notifyMap = notifies.stream().collect(Collectors.toMap(Notify::supports, notify -> notify)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java index f7e43610a..4608c0092 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java @@ -18,7 +18,7 @@ public class EmailTracker implements Track { // if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING) if(1==1) { - this.logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); + logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); return null; } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java index 6c1d56a17..13cfa4577 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java @@ -10,7 +10,7 @@ import java.util.stream.Collectors; @Component public class TrackingFactory { - private Map trackMap; + private final Map trackMap; public TrackingFactory(List notifies) { this.trackMap = notifies.stream().collect(Collectors.toMap(Track::supports, track -> track)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java index d8cbce40e..86008e739 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java @@ -33,8 +33,6 @@ import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; -import jakarta.persistence.EntityManager; -import jakarta.transaction.Transactional; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; @@ -87,7 +85,6 @@ public class UserServiceImpl implements UserService { } @Override - @Transactional public User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { logger.debug(new MapLogEntry("persisting user").And("model", model).And("fields", fields)); @@ -229,7 +226,7 @@ public class UserServiceImpl implements UserService { try { TenantEntity tenant = tenantEntities.stream().filter(x -> x.getId().equals(model.getTenant())).findFirst().orElse(null); if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getTenant(), Tenant.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.tenantScope.setTempTenant(this.entityManager.getEntityManager(), tenant.getId(), tenant.getCode()); + this.tenantScope.setTempTenant(this.entityManager, tenant.getId(), tenant.getCode()); data = new TenantUserEntity(); data.setId(UUID.randomUUID()); data.setUserId(userId); @@ -239,7 +236,7 @@ public class UserServiceImpl implements UserService { data.setIsActive(IsActive.Active); entityManager.persist(data); } finally { - this.tenantScope.removeTempTenant(this.entityManager.getEntityManager()); + this.tenantScope.removeTempTenant(this.entityManager); } } updatedCreatedIds.add(data.getId());