fix notification event

This commit is contained in:
Efstratios Giannopoulos 2024-05-28 14:57:40 +03:00
parent 20a7936d93
commit bca8dfb088
42 changed files with 370 additions and 445 deletions

View File

@ -61,7 +61,7 @@
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>
<artifactId>data-tools</artifactId> <artifactId>data-tools</artifactId>
<version>2.1.3</version> <version>2.1.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.opencdmp</groupId> <groupId>org.opencdmp</groupId>

View File

@ -1,19 +1,18 @@
package org.opencdmp.data.tenant; 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.exception.MyForbiddenException;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import jakarta.persistence.PrePersist; import jakarta.persistence.PrePersist;
import jakarta.persistence.PreRemove; import jakarta.persistence.PreRemove;
import jakarta.persistence.PreUpdate; 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.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.management.InvalidApplicationException; import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
public class TenantListener { public class TenantListener {
@ -33,13 +32,13 @@ public class TenantListener {
@PrePersist @PrePersist
public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant()) { if (this.tenantScope.isMultitenant()) {
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 set not login tenant"); logger.error("somebody tried to set not login tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
} }
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
final UUID tenantId = tenantScope.getTenant(); final UUID tenantId = this.tenantScope.getTenant();
entity.setTenantId(tenantId); entity.setTenantId(tenantId);
} }
} else { } else {
@ -50,18 +49,18 @@ public class TenantListener {
@PreUpdate @PreUpdate
@PreRemove @PreRemove
public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant()) { if (this.tenantScope.isMultitenant()) {
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
if (entity.getTenantId() == null) { if (entity.getTenantId() == null) {
logger.error("somebody tried to set null tenant"); logger.error("somebody tried to set null tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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"); logger.error("somebody tried to change an entries tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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); entity.setTenantId(tenantId);
} else { } else {
if (entity.getTenantId() != null) { if (entity.getTenantId() != null) {
@ -70,7 +69,7 @@ public class TenantListener {
} }
} }
} else { } 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"); logger.error("somebody tried to change an entries tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
} }

View File

@ -1,31 +1,33 @@
package org.opencdmp.integrationevent; 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.InboxConfigurer;
import gr.cite.queueinbox.repository.InboxRepository; 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.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
@Configuration @Configuration
@EnableConfigurationProperties({InboxProperties.class}) @EnableConfigurationProperties(InboxProperties.class)
@ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false)
public class InboxIntegrationEventConfigurer extends InboxConfigurer { 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.applicationContext = applicationContext;
this.inboxProperties = inboxProperties; this.inboxProperties = inboxProperties;
this.entityManagerFactory = entityManagerFactory;
} }
@Bean @Bean
public InboxRepository inboxRepositoryCreator() { public InboxRepository inboxRepositoryCreator() {
return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory);
} }
} }

View File

@ -1,15 +1,16 @@
package org.opencdmp.integrationevent; 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.IntegrationEventContextCreator;
import gr.cite.queueoutbox.OutboxConfigurer; import gr.cite.queueoutbox.OutboxConfigurer;
import gr.cite.queueoutbox.repository.OutboxRepository; import gr.cite.queueoutbox.repository.OutboxRepository;
import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.IntegrationEventMessageConstants;
import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.RabbitProperties;
import gr.cite.rabbitmq.broker.MessageHydrator; 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.amqp.core.MessageProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@ -23,15 +24,17 @@ import java.time.Instant;
import java.util.UUID; import java.util.UUID;
@Configuration @Configuration
@EnableConfigurationProperties({OutboxProperties.class}) @EnableConfigurationProperties(OutboxProperties.class)
@ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false)
public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { public class OutboxIntegrationEventConfigurer extends OutboxConfigurer {
private ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private OutboxProperties outboxProperties; 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.applicationContext = applicationContext;
this.outboxProperties = outboxProperties; this.outboxProperties = outboxProperties;
this.entityManagerFactory = entityManagerFactory;
} }
@Bean @Bean
@ -67,7 +70,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer {
@Bean @Bean
public OutboxRepository outboxRepositoryCreator() { public OutboxRepository outboxRepositoryCreator() {
return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory);
} }
} }

View File

@ -1,12 +1,5 @@
package org.opencdmp.integrationevent.inbox; 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.QueueInbox;
import gr.cite.queueinbox.entity.QueueInboxStatus; import gr.cite.queueinbox.entity.QueueInboxStatus;
import gr.cite.queueinbox.repository.CandidateInfo; import gr.cite.queueinbox.repository.CandidateInfo;
@ -21,6 +14,13 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction; import jakarta.persistence.EntityTransaction;
import jakarta.persistence.OptimisticLockException; 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.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -36,12 +36,14 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
private final JsonHandlingService jsonHandlingService; private final JsonHandlingService jsonHandlingService;
private final InboxProperties inboxProperties; private final InboxProperties inboxProperties;
private final EntityManagerFactory entityManagerFactory;
public InboxRepositoryImpl( public InboxRepositoryImpl(
ApplicationContext applicationContext, ApplicationContext applicationContext,
InboxProperties inboxProperties InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory
) { ) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class);
this.inboxProperties = inboxProperties; this.inboxProperties = inboxProperties;
} }
@ -54,8 +56,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -112,9 +113,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -158,9 +157,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -206,9 +203,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
queueMessage = this.createQueueInboxEntity(inboxCreatorParams); queueMessage = this.createQueueInboxEntity(inboxCreatorParams);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -266,10 +261,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);

View File

@ -1,10 +1,5 @@
package org.opencdmp.integrationevent.outbox; 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.QueueOutbox;
import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus;
import gr.cite.queueoutbox.repository.CandidateInfo; import gr.cite.queueoutbox.repository.CandidateInfo;
@ -18,6 +13,11 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction; import jakarta.persistence.EntityTransaction;
import jakarta.persistence.OptimisticLockException; 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.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -36,12 +36,14 @@ public class OutboxRepositoryImpl implements OutboxRepository {
private final JsonHandlingService jsonHandlingService; private final JsonHandlingService jsonHandlingService;
private final OutboxProperties outboxProperties; private final OutboxProperties outboxProperties;
private final EntityManagerFactory entityManagerFactory;
public OutboxRepositoryImpl( public OutboxRepositoryImpl(
ApplicationContext applicationContext, ApplicationContext applicationContext,
OutboxProperties outboxProperties OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory
) { ) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class);
this.outboxProperties = outboxProperties; this.outboxProperties = outboxProperties;
} }
@ -54,8 +56,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -115,9 +116,8 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -161,9 +161,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -208,10 +206,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -264,10 +259,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -308,10 +300,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -353,9 +342,8 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
queueMessage = this.mapEvent((OutboxIntegrationEvent) item); queueMessage = this.mapEvent((OutboxIntegrationEvent) item);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();

View File

@ -1,31 +1,11 @@
package org.opencdmp.service.metrics; 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 gr.cite.tools.logging.LoggerService;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Gauge; import io.prometheus.client.Gauge;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction; import org.opencdmp.commons.fake.FakeRequestScope;
import jakarta.persistence.OptimisticLockException; import org.opencdmp.data.TenantEntityManager;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.event.ApplicationReadyEvent;
@ -36,30 +16,28 @@ import org.springframework.stereotype.Service;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.time.Instant;
import java.util.Map; import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service @Service
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class UpdateMetricsTask implements Closeable, ApplicationListener<ApplicationReadyEvent> { public class UpdateMetricsTask implements Closeable, ApplicationListener<ApplicationReadyEvent> {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UpdateMetricsTask.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UpdateMetricsTask.class));
private final UpdateMetricsTaskProperties _config; private final UpdateMetricsTaskProperties _config;
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final EntityManagerFactory entityManagerFactory;
private ScheduledExecutorService scheduler; private ScheduledExecutorService scheduler;
private Map<String, Gauge> gauges; private Map<String, Gauge> gauges;
public UpdateMetricsTask( public UpdateMetricsTask(
UpdateMetricsTaskProperties config, UpdateMetricsTaskProperties config,
ApplicationContext applicationContext) { ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) {
this._config = config; this._config = config;
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
this.gauges = null; this.gauges = null;
} }
@ -69,16 +47,16 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener<Applica
if (this._config .getEnable() && intervalSeconds > 0) { if (this._config .getEnable() && intervalSeconds > 0) {
logger.info("File clean up run in {} seconds", intervalSeconds); logger.info("File clean up run in {} seconds", intervalSeconds);
scheduler = Executors.newScheduledThreadPool(1); this.scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS); this.scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS);
} else { } else {
scheduler = null; this.scheduler = null;
} }
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
if (scheduler != null) this.scheduler.close(); if (this.scheduler != null) this.scheduler.close();
} }
protected void process() { protected void process() {
@ -106,15 +84,10 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener<Applica
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager); tenantEntityManager.setEntityManager(entityManager);
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
tenantScope.setTenant(null, tenantScope.getDefaultTenantCode());
MetricsService metricsService = this.applicationContext.getBean(MetricsService.class); MetricsService metricsService = this.applicationContext.getBean(MetricsService.class);

View File

@ -7,6 +7,7 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction; import jakarta.persistence.EntityTransaction;
import jakarta.persistence.OptimisticLockException; import jakarta.persistence.OptimisticLockException;
import org.jetbrains.annotations.NotNull;
import org.opencdmp.commons.fake.FakeRequestScope; import org.opencdmp.commons.fake.FakeRequestScope;
import org.opencdmp.commons.scope.tenant.TenantScope; import org.opencdmp.commons.scope.tenant.TenantScope;
import org.opencdmp.data.StorageFileEntity; import org.opencdmp.data.StorageFileEntity;
@ -34,7 +35,7 @@ import java.util.concurrent.TimeUnit;
@Service @Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class StorageFileCleanupTask implements Closeable, ApplicationListener<ApplicationReadyEvent> { public class StorageFileCleanupTask implements Closeable, ApplicationListener<ApplicationReadyEvent> {
private class CandidateInfo private static class CandidateInfo
{ {
private UUID id; private UUID id;
private Instant createdAt; private Instant createdAt;
@ -59,19 +60,21 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener<A
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(StorageFileCleanupTask.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(StorageFileCleanupTask.class));
private final StorageFileCleanupProperties _config; private final StorageFileCleanupProperties _config;
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final EntityManagerFactory entityManagerFactory;
private ScheduledExecutorService scheduler; private ScheduledExecutorService scheduler;
public StorageFileCleanupTask( public StorageFileCleanupTask(
StorageFileCleanupProperties config, StorageFileCleanupProperties config,
ApplicationContext applicationContext) { ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) {
this._config = config; this._config = config;
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
} }
@Override @Override
public void onApplicationEvent(ApplicationReadyEvent event) { public void onApplicationEvent(@NotNull ApplicationReadyEvent event) {
long intervalSeconds = this._config .getIntervalSeconds(); long intervalSeconds = this._config .getIntervalSeconds();
if (this._config .getEnable() && intervalSeconds > 0) { if (this._config .getEnable() && intervalSeconds > 0) {
logger.info("File clean up run in {} seconds", intervalSeconds); logger.info("File clean up run in {} seconds", intervalSeconds);
@ -117,9 +120,8 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener<A
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); 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 = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -173,8 +175,7 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener<A
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();

View File

@ -322,11 +322,10 @@ public class UserServiceImpl implements UserService {
throw new MyApplicationException("Currently cannot update roles for this user"); throw new MyApplicationException("Currently cannot update roles for this user");
if (userCredentials.getFirst().getExternalId() == null) if (userCredentials.getFirst().getExternalId() == null)
throw new MyApplicationException("Currently cannot update roles for this user"); throw new MyApplicationException("Currently cannot update roles for this user");
String subjectId = userCredentials.getFirst().getExternalId();
this.applyGlobalRoles(data.getId(), subjectId, model); this.applyGlobalRoles(data.getId(), model);
this.applyTenantRoles(data.getId(), subjectId, model); this.applyTenantRoles(data.getId(), model);
this.entityManager.flush(); this.entityManager.flush();
@ -338,7 +337,7 @@ public class UserServiceImpl implements UserService {
return this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(BaseFieldSet.build(fields, User._id), data); return this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(BaseFieldSet.build(fields, User._id), data);
} }
private void applyGlobalRoles(UUID userId, String subjectId, UserRolePatchPersist model) throws InvalidApplicationException { private void applyGlobalRoles(UUID userId, UserRolePatchPersist model) throws InvalidApplicationException {
try { try {
this.tenantScope.setTempTenant(this.entityManager, null, this.tenantScope.getDefaultTenantCode()); this.tenantScope.setTempTenant(this.entityManager, null, this.tenantScope.getDefaultTenantCode());
@ -368,7 +367,7 @@ public class UserServiceImpl implements UserService {
} }
} }
private void applyTenantRoles(UUID userId, String subjectId, UserRolePatchPersist model) throws InvalidApplicationException { private void applyTenantRoles(UUID userId, UserRolePatchPersist model) throws InvalidApplicationException {
if (!this.tenantScope.isSet()) throw new MyForbiddenException("tenant scope required"); if (!this.tenantScope.isSet()) throw new MyForbiddenException("tenant scope required");
UserRoleQuery userRoleQuery = this.queryFactory.query(UserRoleQuery.class).userIds(userId).roles(this.authorizationProperties.getAllowedTenantRoles()); UserRoleQuery userRoleQuery = this.queryFactory.query(UserRoleQuery.class).userIds(userId).roles(this.authorizationProperties.getAllowedTenantRoles());
@ -498,10 +497,10 @@ public class UserServiceImpl implements UserService {
if (this.userScope.getUserIdSafe() == null) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage()); if (this.userScope.getUserIdSafe() == null) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage());
String token = this.createMergeAccountConfirmation(model.getEmail()); String token = this.createMergeAccountConfirmation(model.getEmail());
this.createMergeNotificationEvent(token, user, model.getEmail(), NotificationContactType.EMAIL); this.createMergeNotificationEvent(token, user, model.getEmail());
} }
private void createMergeNotificationEvent(String token, UserEntity user, String email, NotificationContactType type) throws InvalidApplicationException { private void createMergeNotificationEvent(String token, UserEntity user, String email) throws InvalidApplicationException {
UserEntity currentUser = this.entityManager.find(UserEntity.class, this.userScope.getUserIdSafe()); UserEntity currentUser = this.entityManager.find(UserEntity.class, this.userScope.getUserIdSafe());
if (currentUser == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{ this.userScope.getUserIdSafe(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (currentUser == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{ this.userScope.getUserIdSafe(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -511,7 +510,7 @@ public class UserServiceImpl implements UserService {
contactPairs.add(new ContactPair(ContactInfoType.Email, email)); contactPairs.add(new ContactPair(ContactInfoType.Email, email));
NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); NotificationContactData contactData = new NotificationContactData(contactPairs, null, null);
event.setContactHint(this.jsonHandlingService.toJsonSafe(contactData)); event.setContactHint(this.jsonHandlingService.toJsonSafe(contactData));
event.setContactTypeHint(type); event.setContactTypeHint(NotificationContactType.EMAIL);
event.setNotificationType(this.notificationProperties.getMergeAccountConfirmationType()); event.setNotificationType(this.notificationProperties.getMergeAccountConfirmationType());
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
@ -530,13 +529,13 @@ public class UserServiceImpl implements UserService {
String token = this.createRemoveConfirmation(data.getId()); 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(); NotifyIntegrationEvent event = new NotifyIntegrationEvent();
event.setUserId(userId); event.setUserId(userId);
event.setContactTypeHint(type); event.setContactTypeHint(NotificationContactType.EMAIL);
event.setNotificationType(this.notificationProperties.getRemoveCredentialConfirmationType()); event.setNotificationType(this.notificationProperties.getRemoveCredentialConfirmationType());
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
@ -647,12 +646,12 @@ public class UserServiceImpl implements UserService {
this.entityManager.merge(userCredential); this.entityManager.merge(userCredential);
} }
List<UserContactInfoEntity> userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect(); List<UserContactInfoEntity> userContacts = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect();
UserContactInfoQuery newUserContactInfoQuery = this.queryFactory.query(UserContactInfoQuery.class).userIds(newUser.getId()); UserContactInfoQuery newUserContactInfoQuery = this.queryFactory.query(UserContactInfoQuery.class).userIds(newUser.getId());
newUserContactInfoQuery.setOrder(new Ordering().addDescending(UserContactInfo._ordinal)); newUserContactInfoQuery.setOrder(new Ordering().addDescending(UserContactInfo._ordinal));
UserContactInfoEntity newUserContactInfo = newUserContactInfoQuery.first(); UserContactInfoEntity newUserContactInfo = newUserContactInfoQuery.first();
int ordinal = newUserContactInfo == null ? 0 : newUserContactInfo.getOrdinal() + 1; int ordinal = newUserContactInfo == null ? 0 : newUserContactInfo.getOrdinal() + 1;
for (UserContactInfoEntity userContactInfo : userContactInfos){ for (UserContactInfoEntity userContactInfo : userContacts){
userContactInfo.setUserId(newUser.getId()); userContactInfo.setUserId(newUser.getId());
userContactInfo.setOrdinal(ordinal); userContactInfo.setOrdinal(ordinal);
this.entityManager.merge(userContactInfo); this.entityManager.merge(userContactInfo);
@ -759,9 +758,9 @@ public class UserServiceImpl implements UserService {
if (userCredentialEntity.getData() != null){ if (userCredentialEntity.getData() != null){
UserCredentialDataEntity userCredentialDataEntity = this.jsonHandlingService.fromJsonSafe(UserCredentialDataEntity.class, userCredentialEntity.getData()); UserCredentialDataEntity userCredentialDataEntity = this.jsonHandlingService.fromJsonSafe(UserCredentialDataEntity.class, userCredentialEntity.getData());
if (userCredentialDataEntity != null && !this.conventionService.isNullOrEmpty(userCredentialDataEntity.getEmail())) { if (userCredentialDataEntity != null && !this.conventionService.isNullOrEmpty(userCredentialDataEntity.getEmail())) {
List<UserContactInfoEntity> userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect(); List<UserContactInfoEntity> userContacts = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect();
if (!this.conventionService.isListNullOrEmpty(userContactInfos)) if (!this.conventionService.isListNullOrEmpty(userContacts))
this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContactInfos); this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContacts);
} }
} }
this.deleterFactory.deleter(UserCredentialDeleter.class).delete(List.of(userCredentialEntity)); this.deleterFactory.deleter(UserCredentialDeleter.class).delete(List.of(userCredentialEntity));
@ -772,10 +771,10 @@ public class UserServiceImpl implements UserService {
this.entityManager.flush(); this.entityManager.flush();
this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId());
this.keycloakService.removeFromAllGroups(userCredentialEntity.getExternalId()); this.keycloakService.removeFromAllGroups(userCredentialEntity.getExternalId());
this.addToDefaultUserGroups(userCredentialEntity.getExternalId()); this.addToDefaultUserGroups(userCredentialEntity.getExternalId());
this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId());
} }
private void addToDefaultUserGroups(String subjectId){ private void addToDefaultUserGroups(String subjectId){

View File

@ -215,7 +215,7 @@
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>
<artifactId>data-tools</artifactId> <artifactId>data-tools</artifactId>
<version>2.1.3</version> <version>2.1.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>

View File

@ -150,7 +150,7 @@ public class GlobalExceptionHandler {
Map.entry("error", "System error") Map.entry("error", "System error")
); );
} }
}; }
String serialization = this.jsonHandlingService.toJsonSafe(result); String serialization = this.jsonHandlingService.toJsonSafe(result);
return new HandledException(statusCode, serialization, logLevel); return new HandledException(statusCode, serialization, logLevel);
} }

View File

@ -9,6 +9,7 @@ import gr.cite.notification.authorization.Permission;
import gr.cite.notification.common.enums.IsActive; import gr.cite.notification.common.enums.IsActive;
import gr.cite.notification.common.scope.tenant.TenantScope; import gr.cite.notification.common.scope.tenant.TenantScope;
import gr.cite.notification.common.scope.user.UserScope; 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.TenantUserEntity;
import gr.cite.notification.data.UserEntity; import gr.cite.notification.data.UserEntity;
import gr.cite.notification.data.tenant.TenantScopedBaseEntity; import gr.cite.notification.data.tenant.TenantScopedBaseEntity;
@ -52,6 +53,7 @@ public class TenantInterceptor implements WebRequestInterceptor {
private final UserAllowedTenantCacheService userAllowedTenantCacheService; private final UserAllowedTenantCacheService userAllowedTenantCacheService;
private final ErrorThesaurusProperties errors; private final ErrorThesaurusProperties errors;
private final QueryUtilsService queryUtilsService; private final QueryUtilsService queryUtilsService;
public final TenantEntityManager tenantEntityManager;
@PersistenceContext @PersistenceContext
public EntityManager entityManager; public EntityManager entityManager;
@ -64,7 +66,7 @@ public class TenantInterceptor implements WebRequestInterceptor {
ApplicationContext applicationContext, ApplicationContext applicationContext,
TenantScopeProperties tenantScopeProperties, TenantScopeProperties tenantScopeProperties,
UserAllowedTenantCacheService userAllowedTenantCacheService, UserAllowedTenantCacheService userAllowedTenantCacheService,
ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService) { ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService, TenantEntityManager tenantEntityManager) {
this.tenantScope = tenantScope; this.tenantScope = tenantScope;
this.userScope = userScope; this.userScope = userScope;
this.currentPrincipalResolver = currentPrincipalResolver; this.currentPrincipalResolver = currentPrincipalResolver;
@ -74,6 +76,7 @@ public class TenantInterceptor implements WebRequestInterceptor {
this.userAllowedTenantCacheService = userAllowedTenantCacheService; this.userAllowedTenantCacheService = userAllowedTenantCacheService;
this.errors = errors; this.errors = errors;
this.queryUtilsService = queryUtilsService; this.queryUtilsService = queryUtilsService;
this.tenantEntityManager = tenantEntityManager;
} }
@Override @Override
@ -103,16 +106,7 @@ public class TenantInterceptor implements WebRequestInterceptor {
} }
if (isUserAllowedTenant) { if (isUserAllowedTenant) {
if(!tenantScope.isDefaultTenant()) { this.tenantEntityManager.reloadTenantFilters();
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);
}
} else { } else {
if (isAllowedNoTenant || this.isWhiteListedEndpoint(request)) { if (isAllowedNoTenant || this.isWhiteListedEndpoint(request)) {
tenantScope.setTenant(null, null); tenantScope.setTenant(null, null);
@ -181,6 +175,7 @@ public class TenantInterceptor implements WebRequestInterceptor {
@Override @Override
public void postHandle(@NonNull WebRequest request, ModelMap model) { public void postHandle(@NonNull WebRequest request, ModelMap model) {
this.tenantScope.setTenant(null, null); this.tenantScope.setTenant(null, null);
this.tenantEntityManager.disableTenantFilters();
} }
@Override @Override

View File

@ -53,7 +53,7 @@
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>
<artifactId>data-tools</artifactId> <artifactId>data-tools</artifactId>
<version>2.1.2</version> <version>2.1.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>
@ -83,7 +83,7 @@
<dependency> <dependency>
<groupId>gr.cite</groupId> <groupId>gr.cite</groupId>
<artifactId>validation</artifactId> <artifactId>validation</artifactId>
<version>3.0.2</version> <version>3.0.3</version>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -70,7 +70,7 @@ public class XmlHandlingService {
public <T> T fromXml(Class<T> type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { public <T> T fromXml(Class<T> type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException {
if (XmlSerializable.class.isAssignableFrom(type)){ if (XmlSerializable.class.isAssignableFrom(type)){
XmlSerializable<T> object = (XmlSerializable<T>)type.newInstance(); XmlSerializable<T> object = (XmlSerializable<T>)type.newInstance();
return (T) object.fromXml(this.getDocument(xmlString).getDocumentElement()); return object.fromXml(this.getDocument(xmlString).getDocumentElement());
} else { } else {
JAXBContext jaxbContext = JAXBContext.newInstance(type); JAXBContext jaxbContext = JAXBContext.newInstance(type);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

View File

@ -25,7 +25,7 @@ public class LockByKeyManager {
} }
private static ConcurrentHashMap<String, LockWrapper> locks = new ConcurrentHashMap<String, LockWrapper>(); private static final ConcurrentHashMap<String, LockWrapper> locks = new ConcurrentHashMap<String, LockWrapper>();
public void lock(String key) { public void lock(String key) {
LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue());

View File

@ -8,7 +8,7 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
public class FakeRequestAttributes implements RequestAttributes { public class FakeRequestAttributes implements RequestAttributes {
private Map<String, Object> requestAttributeMap = new HashMap<>(); private final Map<String, Object> requestAttributeMap = new HashMap<>();
private final Map<String, Runnable> requestDestructionCallbacks = new LinkedHashMap<>(8); private final Map<String, Runnable> requestDestructionCallbacks = new LinkedHashMap<>(8);
private volatile boolean requestActive = true; private volatile boolean requestActive = true;

View File

@ -1,8 +1,6 @@
package gr.cite.notification.common.scope.tenant; package gr.cite.notification.common.scope.tenant;
import gr.cite.notification.data.tenant.TenantScopedBaseEntity; import gr.cite.notification.data.TenantEntityManager;
import jakarta.persistence.EntityManager;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope; import org.springframework.web.context.annotation.RequestScope;
@ -27,11 +25,11 @@ public class TenantScope {
} }
public Boolean isMultitenant() { public Boolean isMultitenant() {
return multitenancy.isMultitenant(); return this.multitenancy.isMultitenant();
} }
public String getDefaultTenantCode() { public String getDefaultTenantCode() {
return multitenancy.getDefaultTenantCode(); return this.multitenancy.getDefaultTenantCode();
} }
public Boolean isSet() { public Boolean isSet() {
@ -62,55 +60,18 @@ public class TenantScope {
return this.tenantCode.get(); 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.tenant.set(tenant);
this.tenantCode.set(tenantCode); this.tenantCode.set(tenantCode);
entityManager entityManager.reloadTenantFilters();
.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);
}
}
} }
public void removeTempTenant(EntityManager entityManager) { public void removeTempTenant(TenantEntityManager entityManager) throws InvalidApplicationException {
this.tenant.set(this.initialTenant.get()); this.tenant.set(this.initialTenant.get());
this.tenantCode.set(this.initialTenantCode.get()); this.tenantCode.set(this.initialTenantCode.get());
entityManager.reloadTenantFilters();
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);
}
}
} }
public void setTenant(UUID tenant, String tenantCode) { public void setTenant(UUID tenant, String tenantCode) {

View File

@ -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.NotificationSchedulingService;
import gr.cite.notification.service.notificationscheduling.NotificationSchedulingServiceImpl; import gr.cite.notification.service.notificationscheduling.NotificationSchedulingServiceImpl;
import gr.cite.queueinbox.task.rabbitmq.QueueListenerProperties; import gr.cite.queueinbox.task.rabbitmq.QueueListenerProperties;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@ -33,11 +34,13 @@ public class NotificationConfig {
} }
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final NotificationProperties properties; private final NotificationProperties properties;
private final EntityManagerFactory entityManagerFactory;
@Autowired @Autowired
public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties) { public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties, EntityManagerFactory entityManagerFactory) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.properties = properties; this.properties = properties;
this.entityManagerFactory = entityManagerFactory;
} }
@Bean(BeanQualifier.GLOBAL_POLICIES_MAP) @Bean(BeanQualifier.GLOBAL_POLICIES_MAP)
@ -71,7 +74,7 @@ public class NotificationConfig {
@Bean @Bean
public NotificationSchedulingService notificationSchedulingService() { public NotificationSchedulingService notificationSchedulingService() {
return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties); return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties, this.entityManagerFactory);
} }
@Bean @Bean

View File

@ -33,9 +33,9 @@ public class TenantEntityManager {
} }
public <T> T merge(T entity) throws InvalidApplicationException { public <T> T merge(T entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) {
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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) { } else if (tenantScopedEntity.getTenantId() != null) {
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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 { public void remove(Object entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) {
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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) { } else if (tenantScopedEntity.getTenantId() != null) {
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
} }
@ -57,12 +57,22 @@ public class TenantEntityManager {
public <T> T find(Class<T> entityClass, Object primaryKey) throws InvalidApplicationException { public <T> T find(Class<T> entityClass, Object primaryKey) throws InvalidApplicationException {
T entity = this.entityManager.find(entityClass, primaryKey); T entity = this.entityManager.find(entityClass, primaryKey);
if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) {
if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) return null; if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null;
} }
return entity; return entity;
} }
public <T> T find(Class<T> 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() { public void flush() {
this.entityManager.flush(); this.entityManager.flush();
} }
@ -81,13 +91,33 @@ public class TenantEntityManager {
this.entityManager.clear(); this.entityManager.clear();
} }
public void enableTenantFilters() throws InvalidApplicationException { public void reloadTenantFilters() throws InvalidApplicationException {
if (!tenantScope.isSet()) return; this.disableTenantFilters();
if(!tenantScope.isDefaultTenant()) {
if (!this.tenantScope.isSet()) return;
if(!this.tenantScope.isDefaultTenant()) {
this.entityManager this.entityManager
.unwrap(Session.class) .unwrap(Session.class)
.enableFilter(TenantScopedBaseEntity.TENANT_FILTER) .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 { } else {
this.entityManager this.entityManager
.unwrap(Session.class) .unwrap(Session.class)
@ -103,10 +133,14 @@ public class TenantEntityManager {
this.entityManager this.entityManager
.unwrap(Session.class) .unwrap(Session.class)
.disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER);
this.entityManager
.unwrap(Session.class)
.disableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT);
} }
public EntityManager getEntityManager() { public EntityManager getEntityManager() {
return entityManager; return this.entityManager;
} }
public void setEntityManager(EntityManager entityManager) { public void setEntityManager(EntityManager entityManager) {

View File

@ -1,44 +1,44 @@
package gr.cite.notification.data.tenant; //package gr.cite.notification.data.tenant;
//
import gr.cite.notification.common.scope.tenant.TenantScope; //import gr.cite.notification.common.scope.tenant.TenantScope;
import jakarta.persistence.EntityManager; //import jakarta.persistence.EntityManager;
import org.aspectj.lang.JoinPoint; //import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; //import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; //import org.aspectj.lang.annotation.Aspect;
import org.hibernate.Session; //import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
//
import javax.management.InvalidApplicationException; //import javax.management.InvalidApplicationException;
//
@Aspect //@Aspect
@Component //@Component
public class TenantFilterAspect { //public class TenantFilterAspect {
//
private final TenantScope tenantScope; // private final TenantScope tenantScope;
//
@Autowired // @Autowired
public TenantFilterAspect( // public TenantFilterAspect(
TenantScope tenantScope // TenantScope tenantScope
) { // ) {
this.tenantScope = tenantScope; // this.tenantScope = tenantScope;
} // }
//
@AfterReturning( // @AfterReturning(
pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", // pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))",
returning = "retVal") // returning = "retVal")
public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { // public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException {
if (retVal instanceof EntityManager && tenantScope.isSet()) { // if (retVal instanceof EntityManager && tenantScope.isSet()) {
Session session = ((EntityManager) retVal).unwrap(Session.class); // Session session = ((EntityManager) retVal).unwrap(Session.class);
if(!tenantScope.isDefaultTenant()) { // if(!tenantScope.isDefaultTenant()) {
session // session
.enableFilter(TenantScopedBaseEntity.TENANT_FILTER) // .enableFilter(TenantScopedBaseEntity.TENANT_FILTER)
.setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); // .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString());
} else { // } else {
session // session
.enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); // .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER);
} // }
} // }
} // }
//
} //}

View File

@ -32,13 +32,13 @@ public class TenantListener {
@PrePersist @PrePersist
public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant()) { if (this.tenantScope.isMultitenant()) {
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 set not login tenant"); logger.error("somebody tried to set not login tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
} }
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
final UUID tenantId = tenantScope.getTenant(); final UUID tenantId = this.tenantScope.getTenant();
entity.setTenantId(tenantId); entity.setTenantId(tenantId);
} }
} else { } else {
@ -49,18 +49,18 @@ public class TenantListener {
@PreUpdate @PreUpdate
@PreRemove @PreRemove
public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException {
if (tenantScope.isMultitenant()) { if (this.tenantScope.isMultitenant()) {
if (!tenantScope.isDefaultTenant()) { if (!this.tenantScope.isDefaultTenant()) {
if (entity.getTenantId() == null) { if (entity.getTenantId() == null) {
logger.error("somebody tried to set null tenant"); logger.error("somebody tried to set null tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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"); logger.error("somebody tried to change an entries tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); 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); entity.setTenantId(tenantId);
} else { } else {
if (entity.getTenantId() != null) { if (entity.getTenantId() != null) {
@ -69,7 +69,7 @@ public class TenantListener {
} }
} }
} else { } 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"); logger.error("somebody tried to change an entries tenant");
throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
} }

View File

@ -15,22 +15,25 @@ import java.util.UUID;
//@Getter //@Getter
//@Setter //@Setter
//@NoArgsConstructor //@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) @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, 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) @EntityListeners(TenantListener.class)
public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable { public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String TENANT_FILTER = "tenantFilter"; public static final String TENANT_FILTER = "tenantFilter";
public static final String DEFAULT_TENANT_FILTER = "defaultTenantFilter"; 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"; public static final String TENANT_FILTER_TENANT_PARAM = "tenantId";
@Column(name = "tenant", columnDefinition = "uuid", nullable = true) @Column(name = "tenant", columnDefinition = "uuid", nullable = true)
private UUID tenantId; private UUID tenantId;
public static final String _tenantId = "tenantId"; public static final String _tenantId = "tenantId";
public UUID getTenantId() { public UUID getTenantId() {
return tenantId; return this.tenantId;
} }
@Override @Override

View File

@ -4,6 +4,7 @@ import gr.cite.notification.integrationevent.inbox.InboxProperties;
import gr.cite.notification.integrationevent.inbox.InboxRepositoryImpl; import gr.cite.notification.integrationevent.inbox.InboxRepositoryImpl;
import gr.cite.queueinbox.InboxConfigurer; import gr.cite.queueinbox.InboxConfigurer;
import gr.cite.queueinbox.repository.InboxRepository; import gr.cite.queueinbox.repository.InboxRepository;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -15,18 +16,20 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false)
public class InboxIntegrationEventConfigurer extends InboxConfigurer { 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.applicationContext = applicationContext;
this.inboxProperties = inboxProperties; this.inboxProperties = inboxProperties;
this.entityManagerFactory = entityManagerFactory;
} }
@Bean @Bean
public InboxRepository inboxRepositoryCreator() { public InboxRepository inboxRepositoryCreator() {
return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory);
} }
} }

View File

@ -9,6 +9,7 @@ import gr.cite.queueoutbox.repository.OutboxRepository;
import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.IntegrationEventMessageConstants;
import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.RabbitProperties;
import gr.cite.rabbitmq.broker.MessageHydrator; import gr.cite.rabbitmq.broker.MessageHydrator;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.core.MessageProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@ -25,12 +26,14 @@ import java.util.UUID;
@EnableConfigurationProperties({OutboxProperties.class}) @EnableConfigurationProperties({OutboxProperties.class})
@ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false)
public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { public class OutboxIntegrationEventConfigurer extends OutboxConfigurer {
private ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private OutboxProperties outboxProperties; 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.applicationContext = applicationContext;
this.outboxProperties = outboxProperties; this.outboxProperties = outboxProperties;
this.entityManagerFactory = entityManagerFactory;
} }
@Bean @Bean
@ -66,7 +69,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer {
@Bean @Bean
public OutboxRepository outboxRepositoryCreator() { public OutboxRepository outboxRepositoryCreator() {
return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory);
} }
} }

View File

@ -41,16 +41,16 @@ public class InboxRepositoryImpl implements InboxRepository {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class));
protected final ApplicationContext applicationContext; protected final ApplicationContext applicationContext;
private final JsonHandlingService jsonHandlingService; private final JsonHandlingService jsonHandlingService;
private final InboxProperties inboxProperties; private final InboxProperties inboxProperties;
private final EntityManagerFactory entityManagerFactory;
public InboxRepositoryImpl( public InboxRepositoryImpl(
ApplicationContext applicationContext, ApplicationContext applicationContext,
InboxProperties inboxProperties InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory
) { ) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class);
this.inboxProperties = inboxProperties; this.inboxProperties = inboxProperties;
} }
@ -63,8 +63,7 @@ public class InboxRepositoryImpl implements InboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -121,9 +120,7 @@ public class InboxRepositoryImpl implements InboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -167,9 +164,7 @@ public class InboxRepositoryImpl implements InboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -215,9 +210,8 @@ public class InboxRepositoryImpl implements InboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
queueMessage = this.createQueueInboxEntity(inboxCreatorParams); queueMessage = this.createQueueInboxEntity(inboxCreatorParams);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -276,9 +270,7 @@ public class InboxRepositoryImpl implements InboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);

View File

@ -7,11 +7,9 @@ import gr.cite.notification.common.JsonHandlingService;
import gr.cite.notification.common.enums.NotificationNotifyState; import gr.cite.notification.common.enums.NotificationNotifyState;
import gr.cite.notification.common.enums.NotificationTrackingProcess; import gr.cite.notification.common.enums.NotificationTrackingProcess;
import gr.cite.notification.common.enums.NotificationTrackingState; 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.common.scope.tenant.TenantScope;
import gr.cite.notification.data.TenantEntity; import gr.cite.notification.data.TenantEntity;
import gr.cite.notification.data.TenantEntityManager; 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.EventProcessingStatus;
import gr.cite.notification.integrationevent.inbox.InboxPrincipal; import gr.cite.notification.integrationevent.inbox.InboxPrincipal;
import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; 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.notification.service.notification.NotificationService;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyValidationException;
import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.logging.LoggerService; 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.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; 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.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.time.Instant; import java.time.Instant;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.Map; 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 static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifyIntegrationEventHandlerImpl.class));
private final JsonHandlingService jsonHandlingService; private final JsonHandlingService jsonHandlingService;
private final ErrorThesaurusProperties errors;
private final MessageSource messageSource;
private final QueryFactory queryFactory; private final QueryFactory queryFactory;
private final TenantScope tenantScope; private final TenantScope tenantScope;
private final CurrentPrincipalResolver currentPrincipalResolver; private final CurrentPrincipalResolver currentPrincipalResolver;
@ -60,10 +46,8 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent
private final NotificationService notificationService; private final NotificationService notificationService;
private final AuditService auditService; private final AuditService auditService;
private final TenantEntityManager tenantEntityManager; 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.jsonHandlingService = jsonHandlingService;
this.errors = errors;
this.messageSource = messageSource;
this.queryFactory = queryFactory; this.queryFactory = queryFactory;
this.tenantScope = tenantScope; this.tenantScope = tenantScope;
this.currentPrincipalResolver = currentPrincipalResolver; this.currentPrincipalResolver = currentPrincipalResolver;
@ -104,11 +88,11 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent
logger.error("missing tenant from event message"); logger.error("missing tenant from event message");
return EventProcessingStatus.Error; 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()) { } else if (this.tenantScope.isMultitenant()) {
// logger.error("missing tenant from event message"); // logger.error("missing tenant from event message");
// return EventProcessingStatus.Error; // 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)); 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())))) { if (!(notifyConsistencyHandler.isConsistent(new NotifyConsistencyPredicates(event.getUserId(), event.getContactTypeHint(), event.getContactHint())))) {
status = EventProcessingStatus.Postponed; status = EventProcessingStatus.Postponed;
currentPrincipalResolver.pop(); currentPrincipalResolver.pop();
tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); tenantScope.removeTempTenant(this.tenantEntityManager);
return status; return status;
} }
notificationService.persist(model, new BaseFieldSet()); 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); logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex);
} finally { } finally {
currentPrincipalResolver.pop(); currentPrincipalResolver.pop();
tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); try {
tenantScope.removeTempTenant(this.tenantEntityManager);
} catch (InvalidApplicationException e) {
logger.error( e.getMessage(), e);
}
} }
return status; return status;
} }

View File

@ -73,11 +73,11 @@ public class TenantDefaultLocaleRemovalIntegrationEventHandlerImpl implements Te
logger.error("missing tenant from event message"); logger.error("missing tenant from event message");
return EventProcessingStatus.Error; 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()) { } else if (this.tenantScope.isMultitenant()) {
// logger.error("missing tenant from event message"); // logger.error("missing tenant from event message");
// return EventProcessingStatus.Error; // 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)); currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties));

View File

@ -82,11 +82,11 @@ public class TenantDefaultLocaleTouchedIntegrationEventHandlerImpl implements Te
logger.error("missing tenant from event message"); logger.error("missing tenant from event message");
return EventProcessingStatus.Error; 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()) { } else if (this.tenantScope.isMultitenant()) {
// logger.error("missing tenant from event message"); // logger.error("missing tenant from event message");
// return EventProcessingStatus.Error; // 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)); currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties));

View File

@ -26,6 +26,7 @@ import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.Map; import java.util.Map;
@ -86,11 +87,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr
logger.error("missing tenant from event message"); logger.error("missing tenant from event message");
return EventProcessingStatus.Error; 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()) { } else if (this.tenantScope.isMultitenant()) {
// logger.error("missing tenant from event message"); // logger.error("missing tenant from event message");
// return EventProcessingStatus.Error; // 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)); currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties));
@ -98,7 +99,7 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr
if (!(userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(event.getUserId())))) { if (!(userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(event.getUserId())))) {
status = EventProcessingStatus.Postponed; status = EventProcessingStatus.Postponed;
currentPrincipalResolver.pop(); currentPrincipalResolver.pop();
tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); tenantScope.removeTempTenant(this.tenantEntityManager);
return status; return status;
} }
@ -113,7 +114,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr
logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex);
} finally { } finally {
currentPrincipalResolver.pop(); currentPrincipalResolver.pop();
tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); try {
tenantScope.removeTempTenant(this.tenantEntityManager);
} catch (InvalidApplicationException e) {
logger.error( e.getMessage(), e);
}
} }
return status; return status;

View File

@ -14,6 +14,7 @@ import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -229,7 +230,7 @@ public class UserTouchedIntegrationEvent extends TrackedEvent {
@Override @Override
protected List<Specification> specifications(UserCredential item) { protected List<Specification> specifications(UserCredential item) {
return Arrays.asList( return Collections.singletonList(
this.spec() this.spec()
.must(() -> !this.isEmpty(item.getSubjectId())) .must(() -> !this.isEmpty(item.getSubjectId()))
.failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale()))
@ -271,7 +272,7 @@ public class UserTouchedIntegrationEvent extends TrackedEvent {
@Override @Override
protected List<Specification> specifications(TenantUser item) { protected List<Specification> specifications(TenantUser item) {
return Arrays.asList( return Collections.singletonList(
this.spec() this.spec()
.must(() -> !this.isNull(item.getTenant())) .must(() -> !this.isNull(item.getTenant()))
.failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale()))

View File

@ -23,6 +23,7 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.Map; import java.util.Map;
@ -76,11 +77,11 @@ public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegr
logger.error("missing tenant from event message"); logger.error("missing tenant from event message");
return EventProcessingStatus.Error; 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()) { } else if (this.tenantScope.isMultitenant()) {
// logger.error("missing tenant from event message"); // logger.error("missing tenant from event message");
// return EventProcessingStatus.Error; // 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)); 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); logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex);
} finally { } finally {
currentPrincipalResolver.pop(); currentPrincipalResolver.pop();
tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); try {
tenantScope.removeTempTenant(this.tenantEntityManager);
} catch (InvalidApplicationException e) {
logger.error( e.getMessage(), e);
}
} }
return status; return status;

View File

@ -33,16 +33,16 @@ public class OutboxRepositoryImpl implements OutboxRepository {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class));
private final JsonHandlingService jsonHandlingService; private final EntityManagerFactory entityManagerFactory;
private final OutboxProperties outboxProperties; private final OutboxProperties outboxProperties;
public OutboxRepositoryImpl( public OutboxRepositoryImpl(
ApplicationContext applicationContext, ApplicationContext applicationContext,
OutboxProperties outboxProperties OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory
) { ) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.entityManagerFactory = entityManagerFactory;
this.outboxProperties = outboxProperties; this.outboxProperties = outboxProperties;
} }
@ -54,8 +54,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -115,9 +114,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -161,9 +158,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -208,10 +203,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -264,10 +256,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -308,10 +297,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
entityManager = this.entityManagerFactory.createEntityManager();
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -353,9 +339,7 @@ public class OutboxRepositoryImpl implements OutboxRepository {
try (FakeRequestScope ignored = new FakeRequestScope()) { try (FakeRequestScope ignored = new FakeRequestScope()) {
try { try {
queueMessage = this.mapEvent((OutboxIntegrationEvent) item); queueMessage = this.mapEvent((OutboxIntegrationEvent) item);
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();

View File

@ -34,7 +34,7 @@ public abstract class BaseBuilder<M, D> implements Builder {
M model = null; M model = null;
return null; //TODO return null; //TODO
} }
List<M> models = this.build(directives, Arrays.asList(data)); List<M> models = this.build(directives, List.of(data));
return models.stream().findFirst().orElse(null); //TODO return models.stream().findFirst().orElse(null); //TODO
} }

View File

@ -69,12 +69,7 @@ public class UserDeleter implements Deleter {
if (data == null || data.isEmpty()) if (data == null || data.isEmpty())
return; return;
List<UUID> ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); List<UUID> ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList());
// {
// logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName());
// List<UserRoleEntity> 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()); logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName());
List<UserCredentialEntity> items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); List<UserCredentialEntity> 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); UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.class);
deleter.delete(items); deleter.delete(items);
} }
// {
// logger.debug("checking related - {}", TenantUserEntity.class.getSimpleName());
// List<TenantUserEntity> items = this.queryFactory.query(TenantUserQuery.class).userIds(ids).collect();
// TenantUserDeleter deleter = this.deleterFactory.deleter(TenantUserDeleter.class);
// deleter.delete(items);
// }
Instant now = Instant.now(); Instant now = Instant.now();
for (UserEntity item : data) { for (UserEntity item : data) {

View File

@ -102,7 +102,7 @@ public class EmailContactExtractor implements ContactExtractor {
return contacts; return contacts;
} }
default: default:
throw new MyApplicationException("Invalid type " + overrideMode.toString()); throw new MyApplicationException("Invalid type " + overrideMode);
} }
} }

View File

@ -38,7 +38,6 @@ import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.logging.MapLogEntry;
import jakarta.transaction.Transactional;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -102,7 +101,6 @@ public class NotificationServiceImpl implements NotificationService {
} }
@Override @Override
@Transactional
public Notification persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { 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)); logger.debug(new MapLogEntry("persisting notification").And("model", model).And("fields", fields));

View File

@ -40,10 +40,12 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationSchedulingServiceImpl.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationSchedulingServiceImpl.class));
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final NotificationProperties properties; 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.applicationContext = applicationContext;
this.properties = properties; this.properties = properties;
this.entityManagerFactory = entityManagerFactory;
} }
@Override @Override
@ -53,9 +55,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
CandidateInfo candidateInfo = null; CandidateInfo candidateInfo = null;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); 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 = entityManager.getTransaction();
transaction.begin(); transaction.begin();
NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class);
@ -73,18 +74,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
candidates.setNotifyState(NotificationNotifyState.PROCESSING); candidates.setNotifyState(NotificationNotifyState.PROCESSING);
//candidates.setUpdatedAt(Instant.now()); //candidates.setUpdatedAt(Instant.now());
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager);
try { try {
if (candidates.getTenantId() != null) { if (candidates.getTenantId() != null) {
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
candidates = entityManager.merge(candidates); candidates = entityManager.merge(candidates);
entityManager.persist(candidates); entityManager.persist(candidates);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt());
@ -108,9 +112,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
EntityTransaction transaction = null; EntityTransaction transaction = null;
Boolean shouldWait = false; Boolean shouldWait = false;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
NotificationEntity notification = entityManager.find(NotificationEntity.class, candidateInfo.getNotificationId()); NotificationEntity notification = entityManager.find(NotificationEntity.class, candidateInfo.getNotificationId());
@ -122,7 +125,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
accumulatedRetry += (i * options.getRetryThreshold()); accumulatedRetry += (i * options.getRetryThreshold());
for (int i = 1; i <= notification.getRetryCount(); i += 1) for (int i = 1; i <= notification.getRetryCount(); i += 1)
pastAccumulateRetry += (i * options.getRetryThreshold()); 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 additionalTime = randAccumulatedRetry > options.getMaxRetryDelaySeconds() ? options.getMaxRetryDelaySeconds() : randAccumulatedRetry;
long retry = pastAccumulateRetry + additionalTime; long retry = pastAccumulateRetry + additionalTime;
@ -133,19 +136,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
notification.setNotifyState(candidateInfo.getPreviousState()); notification.setNotifyState(candidateInfo.getPreviousState());
//notification.setUpdatedAt(Instant.now()); //notification.setUpdatedAt(Instant.now());
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager);
try { try {
if (notification.getTenantId() != null) { if (notification.getTenantId() != null) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
// notification = entityManager.merge(notification); // notification = entityManager.merge(notification);
entityManager.merge(notification); entityManager.merge(notification);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
} }
@ -170,9 +175,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
EntityTransaction transaction = null; EntityTransaction transaction = null;
Boolean shouldOmit = false; Boolean shouldOmit = false;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -183,19 +187,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
notification.setNotifyState(NotificationNotifyState.OMITTED); notification.setNotifyState(NotificationNotifyState.OMITTED);
//notification.setUpdatedAt(Instant.now()); //notification.setUpdatedAt(Instant.now());
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager);
try { try {
if (notification.getTenantId() != null) { if (notification.getTenantId() != null) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
notification = entityManager.merge(notification); notification = entityManager.merge(notification);
entityManager.persist(notification); entityManager.persist(notification);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
shouldOmit = true; shouldOmit = true;
} }
@ -219,9 +225,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
EntityTransaction transaction = null; EntityTransaction transaction = null;
Boolean success = null; Boolean success = null;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -239,9 +244,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
if (notification.getTenantId() != null) { if (notification.getTenantId() != null) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
result = notificationService.doNotify(notification); result = notificationService.doNotify(notification);
@ -262,7 +267,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
entityManager.persist(notification1); entityManager.persist(notification1);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
@ -290,9 +295,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
CandidateInfo candidateInfo = null; CandidateInfo candidateInfo = null;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); 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 = entityManager.getTransaction();
transaction.begin(); transaction.begin();
NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class);
@ -312,18 +316,20 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
candidates.setTrackingProcess(NotificationTrackingProcess.PROCESSING); candidates.setTrackingProcess(NotificationTrackingProcess.PROCESSING);
//candidates.setUpdatedAt(Instant.now()); //candidates.setUpdatedAt(Instant.now());
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager);
try { try {
if (candidates.getTenantId() != null) { if (candidates.getTenantId() != null) {
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
candidates = entityManager.merge(candidates); candidates = entityManager.merge(candidates);
entityManager.persist(candidates); entityManager.persist(candidates);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt());
} }
@ -346,9 +352,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
EntityTransaction transaction = null; EntityTransaction transaction = null;
Boolean shouldOmit = false; Boolean shouldOmit = false;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager(); entityManager = this.entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -359,20 +364,22 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
notification.setTrackingProcess(NotificationTrackingProcess.OMITTED); notification.setTrackingProcess(NotificationTrackingProcess.OMITTED);
//notification.setUpdatedAt(Instant.now()); //notification.setUpdatedAt(Instant.now());
TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class);
TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class);
tenantEntityManager.setEntityManager(entityManager);
try { try {
if (notification.getTenantId() != null) { if (notification.getTenantId() != null) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class);
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
notification = entityManager.merge(notification); notification = entityManager.merge(notification);
entityManager.persist(notification); entityManager.persist(notification);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }
shouldOmit = true; shouldOmit = true;
} }
@ -397,9 +404,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
Boolean success = null; Boolean success = null;
try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) {
QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); 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 = entityManager.getTransaction();
transaction.begin(); transaction.begin();
@ -417,9 +423,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
try { try {
if (notification.getTenantId() != null) { if (notification.getTenantId() != null) {
TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); 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 { } else {
tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode());
} }
try { try {
TrackingFactory trackingFactory = applicationContext.getBean(TrackingFactory.class); TrackingFactory trackingFactory = applicationContext.getBean(TrackingFactory.class);
@ -445,7 +451,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling
entityManager.persist(notification1); entityManager.persist(notification1);
entityManager.flush(); entityManager.flush();
} finally { } finally {
tenantScope.removeTempTenant(entityManager); tenantScope.removeTempTenant(tenantEntityManager);
} }

View File

@ -29,11 +29,13 @@ public class InAppNotifier implements Notify{
private final JsonHandlingService jsonHandlingService; private final JsonHandlingService jsonHandlingService;
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final EntityManagerFactory entityManagerFactory;
@Autowired @Autowired
public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext) { public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) {
this.jsonHandlingService = jsonHandlingService; this.jsonHandlingService = jsonHandlingService;
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.entityManagerFactory = entityManagerFactory;
} }
@Override @Override
@ -42,9 +44,7 @@ public class InAppNotifier implements Notify{
EntityManager entityManager = null; EntityManager entityManager = null;
EntityTransaction transaction = null; EntityTransaction transaction = null;
try { try {
EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); entityManager = this.entityManagerFactory.createEntityManager();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.begin(); transaction.begin();
InAppContact inAppContact = (InAppContact) contact; InAppContact inAppContact = (InAppContact) contact;

View File

@ -10,7 +10,7 @@ import java.util.stream.Collectors;
@Component @Component
public class NotifierFactory { public class NotifierFactory {
private Map<NotificationContactType, Notify> notifyMap; private final Map<NotificationContactType, Notify> notifyMap;
public NotifierFactory(List<Notify> notifies) { public NotifierFactory(List<Notify> notifies) {
this.notifyMap = notifies.stream().collect(Collectors.toMap(Notify::supports, notify -> notify)); this.notifyMap = notifies.stream().collect(Collectors.toMap(Notify::supports, notify -> notify));

View File

@ -18,7 +18,7 @@ public class EmailTracker implements Track {
// if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING) // if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING)
if(1==1) 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; return null;
} }

View File

@ -10,7 +10,7 @@ import java.util.stream.Collectors;
@Component @Component
public class TrackingFactory { public class TrackingFactory {
private Map<NotificationContactType, Track> trackMap; private final Map<NotificationContactType, Track> trackMap;
public TrackingFactory(List<Track> notifies) { public TrackingFactory(List<Track> notifies) {
this.trackMap = notifies.stream().collect(Collectors.toMap(Track::supports, track -> track)); this.trackMap = notifies.stream().collect(Collectors.toMap(Track::supports, track -> track));

View File

@ -33,8 +33,6 @@ import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.logging.MapLogEntry;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -87,7 +85,6 @@ public class UserServiceImpl implements UserService {
} }
@Override @Override
@Transactional
public User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { 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)); logger.debug(new MapLogEntry("persisting user").And("model", model).And("fields", fields));
@ -229,7 +226,7 @@ public class UserServiceImpl implements UserService {
try { try {
TenantEntity tenant = tenantEntities.stream().filter(x -> x.getId().equals(model.getTenant())).findFirst().orElse(null); 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())); 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 = new TenantUserEntity();
data.setId(UUID.randomUUID()); data.setId(UUID.randomUUID());
data.setUserId(userId); data.setUserId(userId);
@ -239,7 +236,7 @@ public class UserServiceImpl implements UserService {
data.setIsActive(IsActive.Active); data.setIsActive(IsActive.Active);
entityManager.persist(data); entityManager.persist(data);
} finally { } finally {
this.tenantScope.removeTempTenant(this.entityManager.getEntityManager()); this.tenantScope.removeTempTenant(this.entityManager);
} }
} }
updatedCreatedIds.add(data.getId()); updatedCreatedIds.add(data.getId());