diff --git a/backend/core/pom.xml b/backend/core/pom.xml index 5ffac96a2..b60cfe7c3 100644 --- a/backend/core/pom.xml +++ b/backend/core/pom.xml @@ -61,7 +61,7 @@ gr.cite data-tools - 2.1.3 + 2.1.4 org.opencdmp diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java index e67b45c49..659523270 100644 --- a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java @@ -14,7 +14,7 @@ public class FieldEntity { private int ordinal; @XmlElementWrapper(name = "schematics") @XmlElement(name = "schematic") - private List schematics; + private List semantics; @XmlElement(name="defaultValue") private DefaultValueEntity defaultValue; @XmlElementWrapper(name = "visibilityRules") @@ -50,11 +50,11 @@ public class FieldEntity { this.ordinal = ordinal; } - public List getSchematics() { - return this.schematics; + public List getSemantics() { + return this.semantics; } - public void setSchematics(List schematics) { - this.schematics = schematics; + public void setSemantics(List semantics) { + this.semantics = semantics; } public BaseFieldDataEntity getData() { diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateFieldImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateFieldImportExport.java index a47c436db..afd0a9dac 100644 --- a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateFieldImportExport.java +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateFieldImportExport.java @@ -42,7 +42,7 @@ public class DescriptionTemplateFieldImportExport { @XmlElementWrapper(name = "schematics") @XmlElement(name = "schematic") - private List schematics; + private List semantics; @XmlAttribute(name="includeInExport") private Boolean includeInExport; @@ -95,12 +95,12 @@ public class DescriptionTemplateFieldImportExport { this.validations = validations; } - public List getSchematics() { - return this.schematics; + public List getSemantics() { + return this.semantics; } - public void setSchematics(List schematics) { - this.schematics = schematics; + public void setSemantics(List semantics) { + this.semantics = semantics; } public List getVisibilityRules() { diff --git a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java index 64570e67f..5c8086146 100644 --- a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java +++ b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java @@ -1,19 +1,18 @@ package org.opencdmp.data.tenant; -import org.opencdmp.commons.scope.tenant.TenantScope; -import org.opencdmp.commons.scope.tenant.TenantScoped; -import org.opencdmp.errorcode.ErrorThesaurusProperties; import gr.cite.tools.exception.MyForbiddenException; import gr.cite.tools.logging.LoggerService; import jakarta.persistence.PrePersist; import jakarta.persistence.PreRemove; import jakarta.persistence.PreUpdate; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.tenant.TenantScoped; +import org.opencdmp.errorcode.ErrorThesaurusProperties; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import javax.management.InvalidApplicationException; - import java.util.UUID; public class TenantListener { @@ -33,13 +32,13 @@ public class TenantListener { @PrePersist public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (this.tenantScope.isMultitenant()) { + if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to set not login tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (!tenantScope.isDefaultTenant()) { - final UUID tenantId = tenantScope.getTenant(); + if (!this.tenantScope.isDefaultTenant()) { + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } } else { @@ -50,18 +49,18 @@ public class TenantListener { @PreUpdate @PreRemove public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (!tenantScope.isDefaultTenant()) { + if (this.tenantScope.isMultitenant()) { + if (!this.tenantScope.isDefaultTenant()) { if (entity.getTenantId() == null) { logger.error("somebody tried to set null tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { + if (entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - final UUID tenantId = tenantScope.getTenant(); + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } else { if (entity.getTenantId() != null) { @@ -70,7 +69,7 @@ public class TenantListener { } } } else { - if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java index 0ccf54333..3e9ecc3a2 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java @@ -1,31 +1,33 @@ package org.opencdmp.integrationevent; -import org.opencdmp.integrationevent.inbox.InboxProperties; -import org.opencdmp.integrationevent.inbox.InboxRepositoryImpl; import gr.cite.queueinbox.InboxConfigurer; import gr.cite.queueinbox.repository.InboxRepository; +import jakarta.persistence.EntityManagerFactory; +import org.opencdmp.integrationevent.inbox.InboxProperties; +import org.opencdmp.integrationevent.inbox.InboxRepositoryImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; @Configuration -@EnableConfigurationProperties({InboxProperties.class}) +@EnableConfigurationProperties(InboxProperties.class) @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) public class InboxIntegrationEventConfigurer extends InboxConfigurer { - private ApplicationContext applicationContext; - private InboxProperties inboxProperties; + private final ApplicationContext applicationContext; + private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; - public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { + public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.inboxProperties = inboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean public InboxRepository inboxRepositoryCreator() { - return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); + return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory); } } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java index 45b71f14a..3bc62d7b7 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java @@ -1,15 +1,16 @@ package org.opencdmp.integrationevent; -import org.opencdmp.data.QueueOutboxEntity; -import org.opencdmp.integrationevent.outbox.OutboxProperties; -import org.opencdmp.integrationevent.outbox.OutboxRepositoryImpl; import gr.cite.queueoutbox.IntegrationEventContextCreator; import gr.cite.queueoutbox.OutboxConfigurer; import gr.cite.queueoutbox.repository.OutboxRepository; import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.broker.MessageHydrator; +import jakarta.persistence.EntityManagerFactory; +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.integrationevent.outbox.OutboxProperties; +import org.opencdmp.integrationevent.outbox.OutboxRepositoryImpl; import org.springframework.amqp.core.MessageProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -23,15 +24,17 @@ import java.time.Instant; import java.util.UUID; @Configuration -@EnableConfigurationProperties({OutboxProperties.class}) +@EnableConfigurationProperties(OutboxProperties.class) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { - private ApplicationContext applicationContext; - private OutboxProperties outboxProperties; + private final ApplicationContext applicationContext; + private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { + public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.outboxProperties = outboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean @@ -67,7 +70,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { @Bean public OutboxRepository outboxRepositoryCreator() { - return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); + return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory); } } diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java index 2251896b7..567ea8219 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java @@ -1,12 +1,5 @@ package org.opencdmp.integrationevent.inbox; -import org.opencdmp.commons.JsonHandlingService; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.data.QueueInboxEntity; -import org.opencdmp.data.TenantEntityManager; -import org.opencdmp.integrationevent.TrackedEvent; -import org.opencdmp.query.QueueInboxQuery; import gr.cite.queueinbox.entity.QueueInbox; import gr.cite.queueinbox.entity.QueueInboxStatus; import gr.cite.queueinbox.repository.CandidateInfo; @@ -21,6 +14,13 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueInboxEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.integrationevent.TrackedEvent; +import org.opencdmp.query.QueueInboxQuery; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; @@ -36,13 +36,15 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin private final JsonHandlingService jsonHandlingService; private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; public InboxRepositoryImpl( - ApplicationContext applicationContext, - InboxProperties inboxProperties + ApplicationContext applicationContext, + InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.inboxProperties = inboxProperties; } @@ -54,8 +56,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -112,9 +113,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -158,9 +157,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -206,9 +203,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.createQueueInboxEntity(inboxCreatorParams); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -266,10 +261,7 @@ public class InboxRepositoryImpl implements InboxRepository { private static fin try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java index 85bdb12cb..0ba279b12 100644 --- a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java @@ -1,10 +1,5 @@ package org.opencdmp.integrationevent.outbox; -import org.opencdmp.commons.JsonHandlingService; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.data.QueueOutboxEntity; -import org.opencdmp.query.QueueOutboxQuery; import gr.cite.queueoutbox.entity.QueueOutbox; import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; import gr.cite.queueoutbox.repository.CandidateInfo; @@ -18,6 +13,11 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.query.QueueOutboxQuery; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; @@ -36,13 +36,15 @@ public class OutboxRepositoryImpl implements OutboxRepository { private final JsonHandlingService jsonHandlingService; private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; public OutboxRepositoryImpl( - ApplicationContext applicationContext, - OutboxProperties outboxProperties + ApplicationContext applicationContext, + OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.outboxProperties = outboxProperties; } @@ -54,8 +56,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -115,9 +116,8 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -161,9 +161,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -208,10 +206,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -264,10 +259,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -308,10 +300,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -353,9 +342,8 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.mapEvent((OutboxIntegrationEvent) item); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java index a871ab31a..1bd18a94b 100644 --- a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java @@ -53,7 +53,7 @@ public class FieldCommonModelBuilder extends BaseCommonModelBuilder { Field m = new Field(); if (fields.hasField(this.asIndexer(Field._id))) m.setId(d.getId()); if (fields.hasField(this.asIndexer(Field._ordinal))) m.setOrdinal(d.getOrdinal()); - if (fields.hasField(this.asIndexer(Field._schematics))) m.setSchematics(d.getSchematics()); + if (fields.hasField(this.asIndexer(Field._semantics))) m.setSemantics(d.getSemantics()); if (fields.hasField(this.asIndexer(Field._includeInExport))) m.setIncludeInExport(d.getIncludeInExport()); if (fields.hasField(this.asIndexer(Field._validations))) m.setValidations(d.getValidations()); if (!defaultValueFields.isEmpty() && d.getDefaultValue() != null) m.setDefaultValue(this.builderFactory.builder(DefaultValueBuilder.class).withFieldEntity(d).authorize(this.authorize).build(defaultValueFields, d.getDefaultValue())); diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplate/Field.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplate/Field.java index be357f406..39d13ef49 100644 --- a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplate/Field.java +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplate/Field.java @@ -13,8 +13,8 @@ public class Field { public final static String _ordinal = "ordinal"; private Integer ordinal; - public final static String _schematics = "schematics"; - private List schematics; + public final static String _semantics = "semantics"; + private List semantics; public final static String _defaultValue = "defaultValue"; private DefaultValue defaultValue; @@ -47,12 +47,12 @@ public class Field { this.ordinal = ordinal; } - public List getSchematics() { - return this.schematics; + public List getSemantics() { + return this.semantics; } - public void setSchematics(List schematics) { - this.schematics = schematics; + public void setSemantics(List semantics) { + this.semantics = semantics; } public DefaultValue getDefaultValue() { diff --git a/backend/core/src/main/java/org/opencdmp/model/mapper/publicapi/DescriptionFieldToDatasetFieldMapper.java b/backend/core/src/main/java/org/opencdmp/model/mapper/publicapi/DescriptionFieldToDatasetFieldMapper.java index 1b1c47a40..8f34a5345 100644 --- a/backend/core/src/main/java/org/opencdmp/model/mapper/publicapi/DescriptionFieldToDatasetFieldMapper.java +++ b/backend/core/src/main/java/org/opencdmp/model/mapper/publicapi/DescriptionFieldToDatasetFieldMapper.java @@ -21,7 +21,7 @@ public class DescriptionFieldToDatasetFieldMapper { defaultValueEntity.setValue(field.getDefaultValue() != null ? field.getDefaultValue().getTextValue(): null); //TODO model.setDefaultValue(defaultValueEntity); model.setExport(field.getIncludeInExport()); - model.setSchematics(field.getSchematics()); + model.setSemantics(field.getSemantics()); model.setValidations(field.getValidations().stream().map(x -> (int) x.getValue()).toList()); VisibilityEntity visibilityEntity = new VisibilityEntity(); visibilityEntity.setRules(field.getVisibilityRules().stream().map(x -> { diff --git a/backend/core/src/main/java/org/opencdmp/model/persist/descriptiontemplatedefinition/FieldPersist.java b/backend/core/src/main/java/org/opencdmp/model/persist/descriptiontemplatedefinition/FieldPersist.java index 96b815210..3c8d19791 100644 --- a/backend/core/src/main/java/org/opencdmp/model/persist/descriptiontemplatedefinition/FieldPersist.java +++ b/backend/core/src/main/java/org/opencdmp/model/persist/descriptiontemplatedefinition/FieldPersist.java @@ -27,7 +27,7 @@ public class FieldPersist { public static final String _ordinal = "ordinal"; - private List schematics; + private List semantics; private DefaultValuePersist defaultValue; public static final String _defaultValue = "defaultValue"; @@ -62,12 +62,12 @@ public class FieldPersist { this.ordinal = ordinal; } - public List getSchematics() { - return this.schematics; + public List getSemantics() { + return this.semantics; } - public void setSchematics(List schematics) { - this.schematics = schematics; + public void setSemantics(List semantics) { + this.semantics = semantics; } public DefaultValuePersist getDefaultValue() { diff --git a/backend/core/src/main/java/org/opencdmp/model/publicapi/datasetwizard/Field.java b/backend/core/src/main/java/org/opencdmp/model/publicapi/datasetwizard/Field.java index 1cbf97d19..a9eaa66f8 100644 --- a/backend/core/src/main/java/org/opencdmp/model/publicapi/datasetwizard/Field.java +++ b/backend/core/src/main/java/org/opencdmp/model/publicapi/datasetwizard/Field.java @@ -32,7 +32,7 @@ public class Field implements Comparable, PropertiesModelBuilder { private List multiplicityItems; private List validations; private VisibilityEntity visible; - private List schematics; + private List semantics; private Boolean export; @@ -147,12 +147,12 @@ public class Field implements Comparable, PropertiesModelBuilder { this.numbering = numbering; } - public List getSchematics() { - return this.schematics; + public List getSemantics() { + return this.semantics; } - public void setSchematics(List schematics) { - this.schematics = schematics; + public void setSemantics(List semantics) { + this.semantics = semantics; } public Boolean getExport() { @@ -174,7 +174,7 @@ public class Field implements Comparable, PropertiesModelBuilder { newField.defaultValue = this.defaultValue; newField.data = this.data; newField.validations = this.validations; - newField.schematics = this.schematics; + newField.semantics = this.semantics; newField.numbering = "mult" + index + "_" + this.numbering; newField.export = this.export; return newField; @@ -210,7 +210,7 @@ public class Field implements Comparable, PropertiesModelBuilder { visibilityEntity.setRules(item.getVisibilityRules()); this.visible = visibilityEntity; this.validations = item.getValidations(); - this.schematics = item.getSchematics(); + this.semantics = item.getSemantics(); this.export = item.getIncludeInExport(); } diff --git a/backend/core/src/main/java/org/opencdmp/service/descriptiontemplate/DescriptionTemplateServiceImpl.java b/backend/core/src/main/java/org/opencdmp/service/descriptiontemplate/DescriptionTemplateServiceImpl.java index 0ab3bcdbb..71aa3317d 100644 --- a/backend/core/src/main/java/org/opencdmp/service/descriptiontemplate/DescriptionTemplateServiceImpl.java +++ b/backend/core/src/main/java/org/opencdmp/service/descriptiontemplate/DescriptionTemplateServiceImpl.java @@ -363,7 +363,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic data.setId(persist.getId()); data.setOrdinal(persist.getOrdinal()); - data.setSchematics(persist.getSchematics()); + data.setSemantics(persist.getSemantics()); //data.setNumbering(persist.get()); //TODO data.setValidations(persist.getValidations()); data.setIncludeInExport(persist.getIncludeInExport()); @@ -863,7 +863,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic FieldDataHelperService fieldDataHelperService = this.fieldDataHelperServiceProvider.get(fieldType); fieldEntity.setData(fieldDataHelperService.importExportMapDataToPersist(importExport.getData())); } - fieldEntity.setSchematics(importExport.getSchematics()); + fieldEntity.setSemantics(importExport.getSemantics()); return fieldEntity; } @@ -1027,7 +1027,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic FieldDataHelperService fieldDataHelperService = this.fieldDataHelperServiceProvider.get(fieldType); xml.setData(fieldDataHelperService.dataToImportExportXml(entity.getData())); } - xml.setSchematics(entity.getSchematics()); + xml.setSemantics(entity.getSemantics()); return xml; } diff --git a/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java b/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java index 07d2b1813..3567b7427 100644 --- a/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java +++ b/backend/core/src/main/java/org/opencdmp/service/metrics/UpdateMetricsTask.java @@ -1,31 +1,11 @@ package org.opencdmp.service.metrics; -import org.opencdmp.commons.enums.IsActive; -import org.opencdmp.commons.fake.FakeRequestScope; -import org.opencdmp.commons.metrics.MetricNames; -import org.opencdmp.commons.scope.tenant.TenantScope; -import org.opencdmp.data.QueueInboxEntity; -import org.opencdmp.data.StorageFileEntity; -import org.opencdmp.data.TenantEntity; -import org.opencdmp.data.TenantEntityManager; -import org.opencdmp.integrationevent.inbox.EventProcessingStatus; -import org.opencdmp.model.StorageFile; -import org.opencdmp.model.Tenant; -import org.opencdmp.query.QueueInboxQuery; -import org.opencdmp.query.StorageFileQuery; -import org.opencdmp.query.TenantQuery; -import org.opencdmp.service.storage.StorageFileService; -import gr.cite.queueinbox.entity.QueueInboxStatus; -import gr.cite.queueinbox.repository.CandidateInfo; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.logging.LoggerService; -import io.micrometer.prometheus.PrometheusMeterRegistry; import io.prometheus.client.Gauge; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.OptimisticLockException; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.TenantEntityManager; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; @@ -36,30 +16,28 @@ import org.springframework.stereotype.Service; import java.io.Closeable; import java.io.IOException; -import java.time.Instant; import java.util.Map; -import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; @Service -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class UpdateMetricsTask implements Closeable, ApplicationListener { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UpdateMetricsTask.class)); private final UpdateMetricsTaskProperties _config; private final ApplicationContext applicationContext; + private final EntityManagerFactory entityManagerFactory; private ScheduledExecutorService scheduler; private Map gauges; public UpdateMetricsTask( UpdateMetricsTaskProperties config, - ApplicationContext applicationContext) { + ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) { this._config = config; this.applicationContext = applicationContext; + this.entityManagerFactory = entityManagerFactory; this.gauges = null; } @@ -69,16 +47,16 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener 0) { logger.info("File clean up run in {} seconds", intervalSeconds); - scheduler = Executors.newScheduledThreadPool(1); - scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS); + this.scheduler = Executors.newScheduledThreadPool(1); + this.scheduler.scheduleAtFixedRate(this::process, 10, intervalSeconds, TimeUnit.SECONDS); } else { - scheduler = null; + this.scheduler = null; } } @Override public void close() throws IOException { - if (scheduler != null) this.scheduler.close(); + if (this.scheduler != null) this.scheduler.close(); } protected void process() { @@ -106,15 +84,10 @@ public class UpdateMetricsTask implements Closeable, ApplicationListener issuedFieldEntities = definition.getAllField().stream().filter(x -> x.getSchematics() != null && x.getSchematics().contains("rda.dataset.issued")).toList(); + List issuedFieldEntities = definition.getAllField().stream().filter(x -> x.getSemantics() != null && x.getSemantics().contains("rda.dataset.issued")).toList(); if (!this.conventionService.isListNullOrEmpty(issuedFieldEntities)) { String issuedIdNode = issuedFieldEntities.getFirst().getId(); Instant issuedValue = this.conventionService.isNullOrEmpty(issuedIdNode) ? null : description.getProperties().getFieldSets().values().stream().map(PropertyDefinitionFieldSet::getItems).flatMap(List::stream) .filter(x -> x.getFields() != null && x.getFields().containsKey(issuedIdNode)).map(x -> x.getFields().get(issuedIdNode).getDateValue()).filter(Objects::nonNull).findFirst().orElse(null); if (issuedValue != null) { - List licStartFieldSetsEntities = definition.getAllFieldSets().stream().filter(x -> x.getAllField() != null && x.getAllField().stream().anyMatch(y -> y.getSchematics() != null && y.getSchematics().contains("rda.dataset.distribution.license.start_date"))).toList(); + List licStartFieldSetsEntities = definition.getAllFieldSets().stream().filter(x -> x.getAllField() != null && x.getAllField().stream().anyMatch(y -> y.getSemantics() != null && y.getSemantics().contains("rda.dataset.distribution.license.start_date"))).toList(); for (FieldSetEntity licStartFieldSetEntity : licStartFieldSetsEntities) { - List licStartEntities = licStartFieldSetEntity.getAllField().stream().filter(x -> x.getSchematics() != null && x.getSchematics().contains("rda.dataset.distribution.license.start_date")).toList(); + List licStartEntities = licStartFieldSetEntity.getAllField().stream().filter(x -> x.getSemantics() != null && x.getSemantics().contains("rda.dataset.distribution.license.start_date")).toList(); if (!this.conventionService.isListNullOrEmpty(licStartEntities)) { this.ensureFieldSetEntity(description, licStartFieldSetEntity); @@ -456,9 +456,9 @@ public class PrefillingSourceServiceImpl implements PrefillingSourceService { private void prefillSemanticValueToDescription(Description description, List descriptionReferences, String semanticTarget, String parsedValue, DefinitionEntity definition, String type) { if (this.conventionService.isNullOrEmpty(semanticTarget) || this.conventionService.isNullOrEmpty(parsedValue)) return; - List fieldSetsEntities = definition.getAllFieldSets().stream().filter(x-> x.getAllField() != null && x.getAllField().stream().anyMatch(y-> !this.conventionService.isListNullOrEmpty(y.getSchematics()) && y.getSchematics().contains(semanticTarget))).toList(); + List fieldSetsEntities = definition.getAllFieldSets().stream().filter(x-> x.getAllField() != null && x.getAllField().stream().anyMatch(y-> !this.conventionService.isListNullOrEmpty(y.getSemantics()) && y.getSemantics().contains(semanticTarget))).toList(); for (FieldSetEntity fieldSetEntity: fieldSetsEntities) { - List fieldEntities = fieldSetEntity.getAllField().stream().filter(x-> !this.conventionService.isListNullOrEmpty(x.getSchematics()) && x.getSchematics().contains(semanticTarget)).toList(); + List fieldEntities = fieldSetEntity.getAllField().stream().filter(x-> !this.conventionService.isListNullOrEmpty(x.getSemantics()) && x.getSemantics().contains(semanticTarget)).toList(); if (!this.conventionService.isListNullOrEmpty(fieldEntities)) { this.ensureFieldSetEntity(description, fieldSetEntity); for (FieldEntity fieldEntity : fieldEntities){ diff --git a/backend/core/src/main/java/org/opencdmp/service/storage/StorageFileCleanupTask.java b/backend/core/src/main/java/org/opencdmp/service/storage/StorageFileCleanupTask.java index 5dc76cde6..735af64f9 100644 --- a/backend/core/src/main/java/org/opencdmp/service/storage/StorageFileCleanupTask.java +++ b/backend/core/src/main/java/org/opencdmp/service/storage/StorageFileCleanupTask.java @@ -7,6 +7,7 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.OptimisticLockException; +import org.jetbrains.annotations.NotNull; import org.opencdmp.commons.fake.FakeRequestScope; import org.opencdmp.commons.scope.tenant.TenantScope; import org.opencdmp.data.StorageFileEntity; @@ -34,7 +35,7 @@ import java.util.concurrent.TimeUnit; @Service @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class StorageFileCleanupTask implements Closeable, ApplicationListener { - private class CandidateInfo + private static class CandidateInfo { private UUID id; private Instant createdAt; @@ -59,19 +60,21 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener 0) { logger.info("File clean up run in {} seconds", intervalSeconds); @@ -117,9 +120,8 @@ public class StorageFileCleanupTask implements Closeable, ApplicationListener fieldInfoList = new ArrayList<>(); @@ -530,13 +529,13 @@ public class UserServiceImpl implements UserService { String token = this.createRemoveConfirmation(data.getId()); - this.createRemoveCredentialNotificationEvent(token, data.getUserId(), NotificationContactType.EMAIL); + this.createRemoveCredentialNotificationEvent(token, data.getUserId()); } - private void createRemoveCredentialNotificationEvent(String token, UUID userId, NotificationContactType type) throws InvalidApplicationException { + private void createRemoveCredentialNotificationEvent(String token, UUID userId) throws InvalidApplicationException { NotifyIntegrationEvent event = new NotifyIntegrationEvent(); event.setUserId(userId); - event.setContactTypeHint(type); + event.setContactTypeHint(NotificationContactType.EMAIL); event.setNotificationType(this.notificationProperties.getRemoveCredentialConfirmationType()); NotificationFieldData data = new NotificationFieldData(); List fieldInfoList = new ArrayList<>(); @@ -647,12 +646,12 @@ public class UserServiceImpl implements UserService { this.entityManager.merge(userCredential); } - List userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect(); + List userContacts = this.queryFactory.query(UserContactInfoQuery.class).userIds(oldUser.getId()).collect(); UserContactInfoQuery newUserContactInfoQuery = this.queryFactory.query(UserContactInfoQuery.class).userIds(newUser.getId()); newUserContactInfoQuery.setOrder(new Ordering().addDescending(UserContactInfo._ordinal)); UserContactInfoEntity newUserContactInfo = newUserContactInfoQuery.first(); int ordinal = newUserContactInfo == null ? 0 : newUserContactInfo.getOrdinal() + 1; - for (UserContactInfoEntity userContactInfo : userContactInfos){ + for (UserContactInfoEntity userContactInfo : userContacts){ userContactInfo.setUserId(newUser.getId()); userContactInfo.setOrdinal(ordinal); this.entityManager.merge(userContactInfo); @@ -759,9 +758,9 @@ public class UserServiceImpl implements UserService { if (userCredentialEntity.getData() != null){ UserCredentialDataEntity userCredentialDataEntity = this.jsonHandlingService.fromJsonSafe(UserCredentialDataEntity.class, userCredentialEntity.getData()); if (userCredentialDataEntity != null && !this.conventionService.isNullOrEmpty(userCredentialDataEntity.getEmail())) { - List userContactInfos = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect(); - if (!this.conventionService.isListNullOrEmpty(userContactInfos)) - this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContactInfos); + List userContacts = this.queryFactory.query(UserContactInfoQuery.class).values(userCredentialDataEntity.getEmail()).userIds(userCredentialEntity.getUserId()).collect(); + if (!this.conventionService.isListNullOrEmpty(userContacts)) + this.deleterFactory.deleter(UserContactInfoDeleter.class).delete(userContacts); } } this.deleterFactory.deleter(UserCredentialDeleter.class).delete(List.of(userCredentialEntity)); @@ -772,10 +771,10 @@ public class UserServiceImpl implements UserService { this.entityManager.flush(); + this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId()); + this.keycloakService.removeFromAllGroups(userCredentialEntity.getExternalId()); this.addToDefaultUserGroups(userCredentialEntity.getExternalId()); - - this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId()); } private void addToDefaultUserGroups(String subjectId){ diff --git a/backend/pom.xml b/backend/pom.xml index 6eed694df..aa2a54174 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -215,7 +215,7 @@ gr.cite data-tools - 2.1.3 + 2.1.4 gr.cite diff --git a/backend/web/src/main/java/org/opencdmp/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java b/backend/web/src/main/java/org/opencdmp/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java index 42e638c32..394ac0cc9 100644 --- a/backend/web/src/main/java/org/opencdmp/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java +++ b/backend/web/src/main/java/org/opencdmp/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java @@ -186,7 +186,7 @@ public class PublicDatasetsDescriptionDocumentation { String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._ordinal), String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._data, BaseFieldData._label), String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._data, BaseFieldData._fieldType), - String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._schematics), + String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._semantics), String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._defaultValue, DefaultValue._dateValue), String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._defaultValue, DefaultValue._booleanValue), String.join(".", Description._descriptionTemplate, DescriptionTemplate._definition, Definition._pages, Page._sections, Section._fieldSets, FieldSet._fields, Field._defaultValue, DefaultValue._textValue), diff --git a/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts b/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts index c2693ea37..389240caf 100644 --- a/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts +++ b/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts @@ -71,7 +71,7 @@ export interface DescriptionTemplateFieldSetPersist { export interface DescriptionTemplateFieldPersist { id: string; ordinal: number; - schematics: string[]; + semantics: string[]; defaultValue: DescriptionTemplateDefaultValuePersist; visibilityRules: DescriptionTemplateRulePersist[]; validations: DescriptionTemplateFieldValidationType[]; diff --git a/dmp-frontend/src/app/core/model/description-template/description-template.ts b/dmp-frontend/src/app/core/model/description-template/description-template.ts index 6b597bca5..96dc842a9 100644 --- a/dmp-frontend/src/app/core/model/description-template/description-template.ts +++ b/dmp-frontend/src/app/core/model/description-template/description-template.ts @@ -68,7 +68,7 @@ export interface DescriptionTemplateFieldSet { export interface DescriptionTemplateField { id: string; ordinal: number; - schematics?: string[]; + semantics?: string[]; defaultValue?: DescriptionTemplateDefaultValue; visibilityRules?: DescriptionTemplateRule[]; validations?: DescriptionTemplateFieldValidationType[]; diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts index f4f777d95..48c9ca9bb 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts @@ -227,7 +227,7 @@ export class DescriptionTemplateEditorCompositeFieldComponent extends BaseCompon id: editorField.id, ordinal: editorField.ordinal, numbering: '', - schematics: editorField.schematics, + semantics: editorField.semantics, defaultValue: editorField.defaultValue, visibilityRules: editorField.visibilityRules, validations: editorField.validations, diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html index 07af14ebc..416806a2c 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html @@ -123,9 +123,9 @@ {{'DESCRIPTION-TEMPLATE-EDITOR.STEPS.FORM.COMPOSITE-FIELD.FIELDS.SEMANTICS' | translate}} - + - {{form.get('schematics').getError('backendError').message}} + {{form.get('semantics').getError('backendError').message}}
diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/final-preview/final-preview.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/final-preview/final-preview.component.ts index 0ab71cd58..f908c6d17 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/final-preview/final-preview.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/final-preview/final-preview.component.ts @@ -122,7 +122,7 @@ export class FinalPreviewComponent implements OnInit { let convertedField: DescriptionTemplateField ={ id: persist.id, ordinal: persist.ordinal, - schematics: persist.schematics, + semantics: persist.semantics, defaultValue: persist.defaultValue, visibilityRules: persist.visibilityRules, validations: persist.validations, diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts index 4e56fdbac..4d27509ce 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts @@ -692,7 +692,7 @@ export class DescriptionTemplateMultiplicityEditorModel implements DescriptionTe export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateFieldPersist { id: string; ordinal: number; - schematics: string[]; + semantics: string[]; defaultValue: DescriptionTemplateDefaultValueEditorModel = new DescriptionTemplateDefaultValueEditorModel(this.validationErrorModel); visibilityRules: DescriptionTemplateRuleEditorModel[] = []; validations: DescriptionTemplateFieldValidationType[] = []; @@ -710,7 +710,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF if (item) { this.id = item.id; this.ordinal = item.ordinal; - this.schematics = item.schematics; + this.semantics = item.semantics; this.defaultValue = new DescriptionTemplateDefaultValueEditorModel(this.validationErrorModel).fromModel(item.defaultValue); this.validations = item.validations; this.includeInExport = item.includeInExport; @@ -737,7 +737,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF return this.formBuilder.group({ id: [{ value: this.id, disabled: disabled }, context.getValidation('id').validators], ordinal: [{ value: this.ordinal, disabled: disabled }, context.getValidation('ordinal').validators], - schematics: [{ value: this.schematics, disabled: disabled }, context.getValidation('schematics').validators], + semantics: [{ value: this.semantics, disabled: disabled }, context.getValidation('semantics').validators], validations: [{ value: this.validations, disabled: disabled }, context.getValidation('validations').validators], includeInExport: [{ value: this.includeInExport, disabled: disabled }, context.getValidation('includeInExport').validators], data: this.data.buildForm({ @@ -766,7 +766,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF const baseValidationArray: Validation[] = new Array(); baseValidationArray.push({ key: 'id', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}id`)] }); baseValidationArray.push({ key: 'ordinal', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}ordinal`)] }); - baseValidationArray.push({ key: 'schematics', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}schematics`)] }); + baseValidationArray.push({ key: 'semantics', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}semantics`)] }); baseValidationArray.push({ key: 'defaultValue', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}defaultValue`)] }); baseValidationArray.push({ key: 'validations', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}validations`)] }); baseValidationArray.push({ key: 'includeInExport', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}includeInExport`)] }); @@ -814,7 +814,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF validationErrorModel }); - ['id', 'ordinal', 'schematics', 'defaultValue', 'validations', 'includeInExport'].forEach(keyField => { + ['id', 'ordinal', 'semantics', 'defaultValue', 'validations', 'includeInExport'].forEach(keyField => { const control = formGroup?.get(keyField); control?.clearValidators(); control?.addValidators(context.getValidation(keyField).validators); diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts index 3667b24d4..1fb4d9fb0 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts @@ -57,7 +57,7 @@ export class DescriptionTemplateEditorResolver extends BaseEditorResolver { [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.multiplicity), nameof(x => x.tableView)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.id)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.ordinal)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.schematics)].join('.'), + [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.semantics)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.defaultValue), nameof(x => x.textValue)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.defaultValue), nameof(x => x.dateValue)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.defaultValue), nameof(x => x.booleanValue)].join('.'), diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java index b8a3b685c..1adb80c48 100644 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java +++ b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java @@ -150,7 +150,7 @@ public class GlobalExceptionHandler { Map.entry("error", "System error") ); } - }; + } String serialization = this.jsonHandlingService.toJsonSafe(result); return new HandledException(statusCode, serialization, logLevel); } diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java index afac21279..ef5fc0e34 100644 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java +++ b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java @@ -9,6 +9,7 @@ import gr.cite.notification.authorization.Permission; import gr.cite.notification.common.enums.IsActive; import gr.cite.notification.common.scope.tenant.TenantScope; import gr.cite.notification.common.scope.user.UserScope; +import gr.cite.notification.data.TenantEntityManager; import gr.cite.notification.data.TenantUserEntity; import gr.cite.notification.data.UserEntity; import gr.cite.notification.data.tenant.TenantScopedBaseEntity; @@ -52,6 +53,7 @@ public class TenantInterceptor implements WebRequestInterceptor { private final UserAllowedTenantCacheService userAllowedTenantCacheService; private final ErrorThesaurusProperties errors; private final QueryUtilsService queryUtilsService; + public final TenantEntityManager tenantEntityManager; @PersistenceContext public EntityManager entityManager; @@ -64,7 +66,7 @@ public class TenantInterceptor implements WebRequestInterceptor { ApplicationContext applicationContext, TenantScopeProperties tenantScopeProperties, UserAllowedTenantCacheService userAllowedTenantCacheService, - ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService) { + ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService, TenantEntityManager tenantEntityManager) { this.tenantScope = tenantScope; this.userScope = userScope; this.currentPrincipalResolver = currentPrincipalResolver; @@ -74,6 +76,7 @@ public class TenantInterceptor implements WebRequestInterceptor { this.userAllowedTenantCacheService = userAllowedTenantCacheService; this.errors = errors; this.queryUtilsService = queryUtilsService; + this.tenantEntityManager = tenantEntityManager; } @Override @@ -103,16 +106,7 @@ public class TenantInterceptor implements WebRequestInterceptor { } if (isUserAllowedTenant) { - if(!tenantScope.isDefaultTenant()) { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); - } else { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } + this.tenantEntityManager.reloadTenantFilters(); } else { if (isAllowedNoTenant || this.isWhiteListedEndpoint(request)) { tenantScope.setTenant(null, null); @@ -181,6 +175,7 @@ public class TenantInterceptor implements WebRequestInterceptor { @Override public void postHandle(@NonNull WebRequest request, ModelMap model) { this.tenantScope.setTenant(null, null); + this.tenantEntityManager.disableTenantFilters(); } @Override diff --git a/notification-service/notification/pom.xml b/notification-service/notification/pom.xml index 76279f0b5..978ecf310 100644 --- a/notification-service/notification/pom.xml +++ b/notification-service/notification/pom.xml @@ -53,7 +53,7 @@ gr.cite data-tools - 2.1.2 + 2.1.4 gr.cite @@ -83,7 +83,7 @@ gr.cite validation - 3.0.2 + 3.0.3 diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java b/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java index cec063abf..1207e4580 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java @@ -70,7 +70,7 @@ public class XmlHandlingService { public T fromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { if (XmlSerializable.class.isAssignableFrom(type)){ XmlSerializable object = (XmlSerializable)type.newInstance(); - return (T) object.fromXml(this.getDocument(xmlString).getDocumentElement()); + return object.fromXml(this.getDocument(xmlString).getDocumentElement()); } else { JAXBContext jaxbContext = JAXBContext.newInstance(type); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java b/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java index 8c33cb9f7..59ffd49b4 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java @@ -25,7 +25,7 @@ public class LockByKeyManager { } - private static ConcurrentHashMap locks = new ConcurrentHashMap(); + private static final ConcurrentHashMap locks = new ConcurrentHashMap(); public void lock(String key) { LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java index f8f2df085..726be9a97 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java @@ -8,7 +8,7 @@ import java.util.LinkedHashMap; import java.util.Map; public class FakeRequestAttributes implements RequestAttributes { - private Map requestAttributeMap = new HashMap<>(); + private final Map requestAttributeMap = new HashMap<>(); private final Map requestDestructionCallbacks = new LinkedHashMap<>(8); private volatile boolean requestActive = true; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java index 349cf0707..c09af9a5e 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java @@ -1,8 +1,6 @@ package gr.cite.notification.common.scope.tenant; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.EntityManager; -import org.hibernate.Session; +import gr.cite.notification.data.TenantEntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.RequestScope; @@ -27,11 +25,11 @@ public class TenantScope { } public Boolean isMultitenant() { - return multitenancy.isMultitenant(); + return this.multitenancy.isMultitenant(); } public String getDefaultTenantCode() { - return multitenancy.getDefaultTenantCode(); + return this.multitenancy.getDefaultTenantCode(); } public Boolean isSet() { @@ -62,55 +60,18 @@ public class TenantScope { return this.tenantCode.get(); } - public void setTempTenant(EntityManager entityManager, UUID tenant, String tenantCode) { + public void setTempTenant(TenantEntityManager entityManager, UUID tenant, String tenantCode) throws InvalidApplicationException { this.tenant.set(tenant); this.tenantCode.set(tenantCode); - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - if (this.tenant.get() != null || this.isDefaultTenant()) { - if(!this.isDefaultTenant()) { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); - } else { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } + entityManager.reloadTenantFilters(); } - public void removeTempTenant(EntityManager entityManager) { + public void removeTempTenant(TenantEntityManager entityManager) throws InvalidApplicationException { this.tenant.set(this.initialTenant.get()); this.tenantCode.set(this.initialTenantCode.get()); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); - - entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - if (this.initialTenant.get() != null || this.isDefaultTenant()) { - if(!this.isDefaultTenant()) { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); - } else { - entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } + entityManager.reloadTenantFilters(); } public void setTenant(UUID tenant, String tenantCode) { diff --git a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java index 58d962160..38413fef9 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java @@ -6,6 +6,7 @@ import gr.cite.notification.service.message.common.MessageBuilderBase; import gr.cite.notification.service.notificationscheduling.NotificationSchedulingService; import gr.cite.notification.service.notificationscheduling.NotificationSchedulingServiceImpl; import gr.cite.queueinbox.task.rabbitmq.QueueListenerProperties; +import jakarta.persistence.EntityManagerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -33,11 +34,13 @@ public class NotificationConfig { } private final ApplicationContext applicationContext; private final NotificationProperties properties; + private final EntityManagerFactory entityManagerFactory; @Autowired - public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties) { + public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.properties = properties; + this.entityManagerFactory = entityManagerFactory; } @Bean(BeanQualifier.GLOBAL_POLICIES_MAP) @@ -71,7 +74,7 @@ public class NotificationConfig { @Bean public NotificationSchedulingService notificationSchedulingService() { - return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties); + return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties, this.entityManagerFactory); } @Bean diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java index fd7d63266..360e3031a 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java @@ -33,9 +33,9 @@ public class TenantEntityManager { } public T merge(T entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!this.tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } else if (tenantScopedEntity.getTenantId() != null) { throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } @@ -44,9 +44,9 @@ public class TenantEntityManager { } public void remove(Object entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!this.tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } else if (tenantScopedEntity.getTenantId() != null) { throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } @@ -57,12 +57,22 @@ public class TenantEntityManager { public T find(Class entityClass, Object primaryKey) throws InvalidApplicationException { T entity = this.entityManager.find(entityClass, primaryKey); - if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) return null; + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; } return entity; } + public T find(Class entityClass, Object primaryKey, boolean disableTracking) throws InvalidApplicationException { + T entity = this.entityManager.find(entityClass, primaryKey); + + if (this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; + } + if (disableTracking) this.entityManager.detach(entity); + return entity; + } + public void flush() { this.entityManager.flush(); } @@ -80,14 +90,34 @@ public class TenantEntityManager { public void clear() { this.entityManager.clear(); } - - public void enableTenantFilters() throws InvalidApplicationException { - if (!tenantScope.isSet()) return; - if(!tenantScope.isDefaultTenant()) { + + public void reloadTenantFilters() throws InvalidApplicationException { + this.disableTenantFilters(); + + if (!this.tenantScope.isSet()) return; + + if(!this.tenantScope.isDefaultTenant()) { this.entityManager .unwrap(Session.class) .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); + } else { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + + public void loadExplictTenantFilters() throws InvalidApplicationException { + this.disableTenantFilters(); + + if (!this.tenantScope.isSet()) return; + + if(!this.tenantScope.isDefaultTenant()) { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); } else { this.entityManager .unwrap(Session.class) @@ -103,14 +133,18 @@ public class TenantEntityManager { this.entityManager .unwrap(Session.class) .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + + this.entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT); } - + public EntityManager getEntityManager() { - return entityManager; + return this.entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } -} +} \ No newline at end of file diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java index 2ac3d8397..f0628ed9a 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java @@ -1,44 +1,44 @@ -package gr.cite.notification.data.tenant; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import jakarta.persistence.EntityManager; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.Aspect; -import org.hibernate.Session; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; - -@Aspect -@Component -public class TenantFilterAspect { - - private final TenantScope tenantScope; - - @Autowired - public TenantFilterAspect( - TenantScope tenantScope - ) { - this.tenantScope = tenantScope; - } - - @AfterReturning( - pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", - returning = "retVal") - public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { - if (retVal instanceof EntityManager && tenantScope.isSet()) { - Session session = ((EntityManager) retVal).unwrap(Session.class); - if(!tenantScope.isDefaultTenant()) { - session - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); - } else { - session - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - } - } - -} +//package gr.cite.notification.data.tenant; +// +//import gr.cite.notification.common.scope.tenant.TenantScope; +//import jakarta.persistence.EntityManager; +//import org.aspectj.lang.JoinPoint; +//import org.aspectj.lang.annotation.AfterReturning; +//import org.aspectj.lang.annotation.Aspect; +//import org.hibernate.Session; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.stereotype.Component; +// +//import javax.management.InvalidApplicationException; +// +//@Aspect +//@Component +//public class TenantFilterAspect { +// +// private final TenantScope tenantScope; +// +// @Autowired +// public TenantFilterAspect( +// TenantScope tenantScope +// ) { +// this.tenantScope = tenantScope; +// } +// +// @AfterReturning( +// pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", +// returning = "retVal") +// public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { +// if (retVal instanceof EntityManager && tenantScope.isSet()) { +// Session session = ((EntityManager) retVal).unwrap(Session.class); +// if(!tenantScope.isDefaultTenant()) { +// session +// .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) +// .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); +// } else { +// session +// .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); +// } +// } +// } +// +//} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java index 40ef56aee..4d376bdfa 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java @@ -32,13 +32,13 @@ public class TenantListener { @PrePersist public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (this.tenantScope.isMultitenant()) { + if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to set not login tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (!tenantScope.isDefaultTenant()) { - final UUID tenantId = tenantScope.getTenant(); + if (!this.tenantScope.isDefaultTenant()) { + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } } else { @@ -49,18 +49,18 @@ public class TenantListener { @PreUpdate @PreRemove public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { - if (tenantScope.isMultitenant()) { - if (!tenantScope.isDefaultTenant()) { + if (this.tenantScope.isMultitenant()) { + if (!this.tenantScope.isDefaultTenant()) { if (entity.getTenantId() == null) { logger.error("somebody tried to set null tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { + if (entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } - final UUID tenantId = tenantScope.getTenant(); + final UUID tenantId = this.tenantScope.getTenant(); entity.setTenantId(tenantId); } else { if (entity.getTenantId() != null) { @@ -69,7 +69,7 @@ public class TenantListener { } } } else { - if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(this.tenantScope.getTenant()) != 0)) { logger.error("somebody tried to change an entries tenant"); throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java index 57b499883..6f5d5c0fb 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java @@ -15,22 +15,25 @@ import java.util.UUID; //@Getter //@Setter //@NoArgsConstructor -@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = {@ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)}) +@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) +@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) @FilterDef(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER) -@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") @Filter(name = TenantScopedBaseEntity.TENANT_FILTER, condition = "(tenant = (cast(:tenantId as uuid)) or tenant is null)") +@Filter(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, condition = "(tenant = (cast(:tenantId as uuid)))") +@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") @EntityListeners(TenantListener.class) public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable { private static final long serialVersionUID = 1L; public static final String TENANT_FILTER = "tenantFilter"; public static final String DEFAULT_TENANT_FILTER = "defaultTenantFilter"; + public static final String TENANT_FILTER_EXPLICT = "tenantFilterExplict"; public static final String TENANT_FILTER_TENANT_PARAM = "tenantId"; @Column(name = "tenant", columnDefinition = "uuid", nullable = true) private UUID tenantId; public static final String _tenantId = "tenantId"; public UUID getTenantId() { - return tenantId; + return this.tenantId; } @Override diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java index 998ce70f3..053d3780d 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java @@ -4,6 +4,7 @@ import gr.cite.notification.integrationevent.inbox.InboxProperties; import gr.cite.notification.integrationevent.inbox.InboxRepositoryImpl; import gr.cite.queueinbox.InboxConfigurer; import gr.cite.queueinbox.repository.InboxRepository; +import jakarta.persistence.EntityManagerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; @@ -15,18 +16,20 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) public class InboxIntegrationEventConfigurer extends InboxConfigurer { - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; - private InboxProperties inboxProperties; + private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; - public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { + public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.inboxProperties = inboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean public InboxRepository inboxRepositoryCreator() { - return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); + return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties, this.entityManagerFactory); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java index efbaab157..f3a41cc91 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java @@ -9,6 +9,7 @@ import gr.cite.queueoutbox.repository.OutboxRepository; import gr.cite.rabbitmq.IntegrationEventMessageConstants; import gr.cite.rabbitmq.RabbitProperties; import gr.cite.rabbitmq.broker.MessageHydrator; +import jakarta.persistence.EntityManagerFactory; import org.springframework.amqp.core.MessageProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -25,12 +26,14 @@ import java.util.UUID; @EnableConfigurationProperties({OutboxProperties.class}) @ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { - private ApplicationContext applicationContext; - private OutboxProperties outboxProperties; + private final ApplicationContext applicationContext; + private final OutboxProperties outboxProperties; + private final EntityManagerFactory entityManagerFactory; - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { + public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.outboxProperties = outboxProperties; + this.entityManagerFactory = entityManagerFactory; } @Bean @@ -66,7 +69,7 @@ public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { @Bean public OutboxRepository outboxRepositoryCreator() { - return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); + return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties, this.entityManagerFactory); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java index a5c6d2553..42ea7b9de 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java @@ -41,17 +41,17 @@ public class InboxRepositoryImpl implements InboxRepository { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class)); protected final ApplicationContext applicationContext; - private final JsonHandlingService jsonHandlingService; - private final InboxProperties inboxProperties; + private final EntityManagerFactory entityManagerFactory; public InboxRepositoryImpl( - ApplicationContext applicationContext, - InboxProperties inboxProperties + ApplicationContext applicationContext, + InboxProperties inboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); this.inboxProperties = inboxProperties; } @@ -63,8 +63,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -121,9 +120,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -167,9 +164,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -215,9 +210,8 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.createQueueInboxEntity(inboxCreatorParams); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -276,9 +270,7 @@ public class InboxRepositoryImpl implements InboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java index bc8ae7b5f..7b2c19748 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java @@ -7,11 +7,9 @@ import gr.cite.notification.common.JsonHandlingService; import gr.cite.notification.common.enums.NotificationNotifyState; import gr.cite.notification.common.enums.NotificationTrackingProcess; import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.common.scope.fake.FakeRequestScope; import gr.cite.notification.common.scope.tenant.TenantScope; import gr.cite.notification.data.TenantEntity; import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; import gr.cite.notification.integrationevent.inbox.InboxPrincipal; import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; @@ -21,21 +19,14 @@ import gr.cite.notification.query.TenantQuery; import gr.cite.notification.service.notification.NotificationService; import gr.cite.tools.auditing.AuditService; import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyValidationException; import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.OptimisticLockException; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.MessageSource; import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.time.Instant; import java.util.AbstractMap; import java.util.Map; @@ -47,11 +38,6 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifyIntegrationEventHandlerImpl.class)); private final JsonHandlingService jsonHandlingService; - - - private final ErrorThesaurusProperties errors; - - private final MessageSource messageSource; private final QueryFactory queryFactory; private final TenantScope tenantScope; private final CurrentPrincipalResolver currentPrincipalResolver; @@ -60,10 +46,8 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent private final NotificationService notificationService; private final AuditService auditService; private final TenantEntityManager tenantEntityManager; - public NotifyIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, ErrorThesaurusProperties errors, MessageSource messageSource, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, NotifyConsistencyHandler notifyConsistencyHandler, NotificationService notificationService, AuditService auditService, TenantEntityManager tenantEntityManager) { + public NotifyIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, NotifyConsistencyHandler notifyConsistencyHandler, NotificationService notificationService, AuditService auditService, TenantEntityManager tenantEntityManager) { this.jsonHandlingService = jsonHandlingService; - this.errors = errors; - this.messageSource = messageSource; this.queryFactory = queryFactory; this.tenantScope = tenantScope; this.currentPrincipalResolver = currentPrincipalResolver; @@ -104,11 +88,11 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -116,7 +100,7 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent if (!(notifyConsistencyHandler.isConsistent(new NotifyConsistencyPredicates(event.getUserId(), event.getContactTypeHint(), event.getContactHint())))) { status = EventProcessingStatus.Postponed; currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + tenantScope.removeTempTenant(this.tenantEntityManager); return status; } notificationService.persist(model, new BaseFieldSet()); @@ -129,7 +113,11 @@ public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEvent logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java index 204570ed8..1afb3929e 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java @@ -73,11 +73,11 @@ public class TenantDefaultLocaleRemovalIntegrationEventHandlerImpl implements Te logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java index d516d3e87..05bc060b8 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java @@ -82,11 +82,11 @@ public class TenantDefaultLocaleTouchedIntegrationEventHandlerImpl implements Te logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java index 426c77352..13facd7c5 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java @@ -26,6 +26,7 @@ import org.springframework.context.annotation.Scope; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.util.AbstractMap; import java.util.Map; @@ -86,11 +87,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -98,7 +99,7 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr if (!(userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(event.getUserId())))) { status = EventProcessingStatus.Postponed; currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + tenantScope.removeTempTenant(this.tenantEntityManager); return status; } @@ -113,7 +114,11 @@ public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegr logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java index 02daacb66..18f90a147 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java @@ -14,6 +14,7 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -229,10 +230,10 @@ public class UserTouchedIntegrationEvent extends TrackedEvent { @Override protected List specifications(UserCredential item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getSubjectId())) - .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) + return Collections.singletonList( + this.spec() + .must(() -> !this.isEmpty(item.getSubjectId())) + .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) ); } } @@ -271,10 +272,10 @@ public class UserTouchedIntegrationEvent extends TrackedEvent { @Override protected List specifications(TenantUser item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isNull(item.getTenant())) - .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) + return Collections.singletonList( + this.spec() + .must(() -> !this.isNull(item.getTenant())) + .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) ); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java index 6f2ae39d5..dd2bf81e6 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; +import javax.management.InvalidApplicationException; import java.util.AbstractMap; import java.util.Map; @@ -76,11 +77,11 @@ public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegr logger.error("missing tenant from event message"); return EventProcessingStatus.Error; } - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), properties.getTenantId(), tenant.getCode()); + this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); } else if (this.tenantScope.isMultitenant()) { // logger.error("missing tenant from event message"); // return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); + this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); } currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); @@ -96,7 +97,11 @@ public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegr logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); } finally { currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager.getEntityManager()); + try { + tenantScope.removeTempTenant(this.tenantEntityManager); + } catch (InvalidApplicationException e) { + logger.error( e.getMessage(), e); + } } return status; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java index 2b4926dea..51c770647 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java @@ -33,16 +33,16 @@ public class OutboxRepositoryImpl implements OutboxRepository { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class)); - private final JsonHandlingService jsonHandlingService; + private final EntityManagerFactory entityManagerFactory; private final OutboxProperties outboxProperties; public OutboxRepositoryImpl( ApplicationContext applicationContext, - OutboxProperties outboxProperties + OutboxProperties outboxProperties, EntityManagerFactory entityManagerFactory ) { this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.entityManagerFactory = entityManagerFactory; this.outboxProperties = outboxProperties; } @@ -54,8 +54,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -115,9 +114,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -161,9 +158,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -208,10 +203,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -264,10 +256,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -308,10 +297,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { - - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -353,9 +339,7 @@ public class OutboxRepositoryImpl implements OutboxRepository { try (FakeRequestScope ignored = new FakeRequestScope()) { try { queueMessage = this.mapEvent((OutboxIntegrationEvent) item); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java index f062e44e6..ad1d29ada 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java @@ -34,7 +34,7 @@ public abstract class BaseBuilder implements Builder { M model = null; return null; //TODO } - List models = this.build(directives, Arrays.asList(data)); + List models = this.build(directives, List.of(data)); return models.stream().findFirst().orElse(null); //TODO } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java index 16c2d25d7..9355ccea0 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java @@ -69,12 +69,7 @@ public class UserDeleter implements Deleter { if (data == null || data.isEmpty()) return; List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); -// { -// logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName()); -// List items = this.queryFactory.query(UserRoleQuery.class).userIds(ids).collect(); -// UserRoleDeleter deleter = this.deleterFactory.deleter(UserRoleDeleter.class); -// deleter.delete(items); -// } + { logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName()); List items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); @@ -87,12 +82,7 @@ public class UserDeleter implements Deleter { UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.class); deleter.delete(items); } -// { -// logger.debug("checking related - {}", TenantUserEntity.class.getSimpleName()); -// List items = this.queryFactory.query(TenantUserQuery.class).userIds(ids).collect(); -// TenantUserDeleter deleter = this.deleterFactory.deleter(TenantUserDeleter.class); -// deleter.delete(items); -// } + Instant now = Instant.now(); for (UserEntity item : data) { diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java index be7525f1d..432cdc2a8 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java @@ -102,7 +102,7 @@ public class EmailContactExtractor implements ContactExtractor { return contacts; } default: - throw new MyApplicationException("Invalid type " + overrideMode.toString()); + throw new MyApplicationException("Invalid type " + overrideMode); } } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java index 037a81d36..05677604c 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java @@ -38,7 +38,6 @@ import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; -import jakarta.transaction.Transactional; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -102,7 +101,6 @@ public class NotificationServiceImpl implements NotificationService { } @Override - @Transactional public Notification persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { logger.debug(new MapLogEntry("persisting notification").And("model", model).And("fields", fields)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java index 53136d40c..86501d2e5 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java @@ -40,10 +40,12 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationSchedulingServiceImpl.class)); private final ApplicationContext applicationContext; private final NotificationProperties properties; + private final EntityManagerFactory entityManagerFactory; - public NotificationSchedulingServiceImpl(ApplicationContext applicationContext, NotificationProperties properties) { + public NotificationSchedulingServiceImpl(ApplicationContext applicationContext, NotificationProperties properties, EntityManagerFactory entityManagerFactory) { this.applicationContext = applicationContext; this.properties = properties; + this.entityManagerFactory = entityManagerFactory; } @Override @@ -53,9 +55,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling CandidateInfo candidateInfo = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); @@ -73,18 +74,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling candidates.setNotifyState(NotificationNotifyState.PROCESSING); //candidates.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); + try { if (candidates.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } candidates = entityManager.merge(candidates); entityManager.persist(candidates); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); @@ -108,9 +112,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldWait = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationEntity notification = entityManager.find(NotificationEntity.class, candidateInfo.getNotificationId()); @@ -122,7 +125,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling accumulatedRetry += (i * options.getRetryThreshold()); for (int i = 1; i <= notification.getRetryCount(); i += 1) pastAccumulateRetry += (i * options.getRetryThreshold()); - int randAccumulatedRetry = ThreadLocalRandom.current().nextInt((int) (accumulatedRetry / 2), accumulatedRetry + 1); + int randAccumulatedRetry = ThreadLocalRandom.current().nextInt(accumulatedRetry / 2, accumulatedRetry + 1); long additionalTime = randAccumulatedRetry > options.getMaxRetryDelaySeconds() ? options.getMaxRetryDelaySeconds() : randAccumulatedRetry; long retry = pastAccumulateRetry + additionalTime; @@ -133,19 +136,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setNotifyState(candidateInfo.getPreviousState()); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } // notification = entityManager.merge(notification); entityManager.merge(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } } @@ -170,9 +175,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldOmit = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -183,19 +187,21 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setNotifyState(NotificationNotifyState.OMITTED); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } notification = entityManager.merge(notification); entityManager.persist(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } shouldOmit = true; } @@ -219,9 +225,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean success = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -239,9 +244,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } result = notificationService.doNotify(notification); @@ -262,7 +267,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling entityManager.persist(notification1); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } @@ -290,9 +295,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling CandidateInfo candidateInfo = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); @@ -312,18 +316,20 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling candidates.setTrackingProcess(NotificationTrackingProcess.PROCESSING); //candidates.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (candidates.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(candidates.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } candidates = entityManager.merge(candidates); entityManager.persist(candidates); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); } @@ -346,9 +352,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling EntityTransaction transaction = null; Boolean shouldOmit = false; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -359,20 +364,22 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling notification.setTrackingProcess(NotificationTrackingProcess.OMITTED); //notification.setUpdatedAt(Instant.now()); TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); try { if (notification.getTenantId() != null) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } notification = entityManager.merge(notification); entityManager.persist(notification); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } shouldOmit = true; } @@ -397,9 +404,8 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling Boolean success = null; try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); @@ -417,9 +423,9 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling try { if (notification.getTenantId() != null) { TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(entityManager, tenant.getId(), tenant.getCode()); + tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); } else { - tenantScope.setTempTenant(entityManager, null, tenantScope.getDefaultTenantCode()); + tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); } try { TrackingFactory trackingFactory = applicationContext.getBean(TrackingFactory.class); @@ -445,7 +451,7 @@ public class NotificationSchedulingServiceImpl implements NotificationScheduling entityManager.persist(notification1); entityManager.flush(); } finally { - tenantScope.removeTempTenant(entityManager); + tenantScope.removeTempTenant(tenantEntityManager); } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java index 96fd88989..313c7f12b 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java @@ -29,11 +29,13 @@ public class InAppNotifier implements Notify{ private final JsonHandlingService jsonHandlingService; private final ApplicationContext applicationContext; + private final EntityManagerFactory entityManagerFactory; @Autowired - public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext) { + public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext, EntityManagerFactory entityManagerFactory) { this.jsonHandlingService = jsonHandlingService; this.applicationContext = applicationContext; + this.entityManagerFactory = entityManagerFactory; } @Override @@ -42,9 +44,7 @@ public class InAppNotifier implements Notify{ EntityManager entityManager = null; EntityTransaction transaction = null; try { - EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); - - entityManager = entityManagerFactory.createEntityManager(); + entityManager = this.entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); InAppContact inAppContact = (InAppContact) contact; diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java index 749524670..92a70d190 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java @@ -10,7 +10,7 @@ import java.util.stream.Collectors; @Component public class NotifierFactory { - private Map notifyMap; + private final Map notifyMap; public NotifierFactory(List notifies) { this.notifyMap = notifies.stream().collect(Collectors.toMap(Notify::supports, notify -> notify)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java index f7e43610a..4608c0092 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java @@ -18,7 +18,7 @@ public class EmailTracker implements Track { // if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING) if(1==1) { - this.logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); + logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); return null; } diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java index 6c1d56a17..13cfa4577 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java @@ -10,7 +10,7 @@ import java.util.stream.Collectors; @Component public class TrackingFactory { - private Map trackMap; + private final Map trackMap; public TrackingFactory(List notifies) { this.trackMap = notifies.stream().collect(Collectors.toMap(Track::supports, track -> track)); diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java index d8cbce40e..86008e739 100644 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java +++ b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java @@ -33,8 +33,6 @@ import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; -import jakarta.persistence.EntityManager; -import jakarta.transaction.Transactional; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; @@ -87,7 +85,6 @@ public class UserServiceImpl implements UserService { } @Override - @Transactional public User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { logger.debug(new MapLogEntry("persisting user").And("model", model).And("fields", fields)); @@ -229,7 +226,7 @@ public class UserServiceImpl implements UserService { try { TenantEntity tenant = tenantEntities.stream().filter(x -> x.getId().equals(model.getTenant())).findFirst().orElse(null); if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getTenant(), Tenant.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.tenantScope.setTempTenant(this.entityManager.getEntityManager(), tenant.getId(), tenant.getCode()); + this.tenantScope.setTempTenant(this.entityManager, tenant.getId(), tenant.getCode()); data = new TenantUserEntity(); data.setId(UUID.randomUUID()); data.setUserId(userId); @@ -239,7 +236,7 @@ public class UserServiceImpl implements UserService { data.setIsActive(IsActive.Active); entityManager.persist(data); } finally { - this.tenantScope.removeTempTenant(this.entityManager.getEntityManager()); + this.tenantScope.removeTempTenant(this.entityManager); } } updatedCreatedIds.add(data.getId());