Merge branch 'dmp-refactoring' of https://code-repo.d4science.org/MaDgiK-CITE/argos into dmp-refactoring

This commit is contained in:
Sofia Papacharalampous 2024-05-08 11:42:55 +03:00
commit a88001bc72
26 changed files with 479 additions and 472 deletions

View File

@ -1,14 +1,14 @@
package org.opencdmp.integrationevent.outbox.tenantremoval; package org.opencdmp.integrationevent.outbox.tenantremoval;
import gr.cite.tools.data.query.QueryFactory;
import org.opencdmp.integrationevent.inbox.ConsistencyHandler; import org.opencdmp.integrationevent.inbox.ConsistencyHandler;
import org.opencdmp.query.TenantQuery; import org.opencdmp.query.TenantQuery;
import gr.cite.tools.data.query.QueryFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TenantRemovalConsistencyHandler implements ConsistencyHandler<TenantRemovalConsistencyPredicates> { public class TenantRemovalConsistencyHandler implements ConsistencyHandler<TenantRemovalConsistencyPredicates> {
private final QueryFactory queryFactory; private final QueryFactory queryFactory;
@ -19,7 +19,7 @@ public class TenantRemovalConsistencyHandler implements ConsistencyHandler<Tenan
@Override @Override
public Boolean isConsistent(TenantRemovalConsistencyPredicates consistencyPredicates) { public Boolean isConsistent(TenantRemovalConsistencyPredicates consistencyPredicates) {
long count = this.queryFactory.query(TenantQuery.class).ids(consistencyPredicates.getTenantId()).count(); long count = this.queryFactory.query(TenantQuery.class).disableTracking().ids(consistencyPredicates.getTenantId()).count();
return count > 0; return count > 0;
} }

View File

@ -1,14 +1,14 @@
package org.opencdmp.integrationevent.outbox.userremoval; package org.opencdmp.integrationevent.outbox.userremoval;
import gr.cite.tools.data.query.QueryFactory;
import org.opencdmp.integrationevent.inbox.ConsistencyHandler; import org.opencdmp.integrationevent.inbox.ConsistencyHandler;
import org.opencdmp.query.UserQuery; import org.opencdmp.query.UserQuery;
import gr.cite.tools.data.query.QueryFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component("outboxuserremovalconsistencyhandler") @Component("outboxuserremovalconsistencyhandler")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserRemovalConsistencyHandler implements ConsistencyHandler<UserRemovalConsistencyPredicates> { public class UserRemovalConsistencyHandler implements ConsistencyHandler<UserRemovalConsistencyPredicates> {
private final QueryFactory queryFactory; private final QueryFactory queryFactory;
@ -19,7 +19,7 @@ public class UserRemovalConsistencyHandler implements ConsistencyHandler<UserRem
@Override @Override
public Boolean isConsistent(UserRemovalConsistencyPredicates consistencyPredicates) { public Boolean isConsistent(UserRemovalConsistencyPredicates consistencyPredicates) {
long count = this.queryFactory.query(UserQuery.class).ids(consistencyPredicates.getUserId()).count(); long count = this.queryFactory.query(UserQuery.class).disableTracking().ids(consistencyPredicates.getUserId()).count();
return count != 0; return count != 0;
} }
} }

View File

@ -180,9 +180,9 @@ public class DescriptionPersist {
DmpEntity dmpEntity = null; DmpEntity dmpEntity = null;
DmpBlueprintEntity dmpBlueprintEntity = null; DmpBlueprintEntity dmpBlueprintEntity = null;
try { try {
descriptionTemplate = this.isValidGuid(item.getDescriptionTemplateId()) ? this.entityManager.find(DescriptionTemplateEntity.class, item.getDescriptionTemplateId()) : null; descriptionTemplate = this.isValidGuid(item.getDescriptionTemplateId()) ? this.entityManager.find(DescriptionTemplateEntity.class, item.getDescriptionTemplateId(), true) : null;
dmpEntity = this.isValidGuid(item.getDmpId()) ? this.entityManager.find(DmpEntity.class, item.getDmpId()) : null; dmpEntity = this.isValidGuid(item.getDmpId()) ? this.entityManager.find(DmpEntity.class, item.getDmpId(), true) : null;
dmpBlueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, dmpEntity.getBlueprintId()); dmpBlueprintEntity = dmpEntity == null ? null : this.entityManager.find(DmpBlueprintEntity.class, dmpEntity.getBlueprintId());
} catch (InvalidApplicationException e) { } catch (InvalidApplicationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -192,7 +192,7 @@ public class DmpPersist {
protected List<Specification> specifications(DmpPersist item) { protected List<Specification> specifications(DmpPersist item) {
DmpBlueprintEntity dmpBlueprintEntity = null; DmpBlueprintEntity dmpBlueprintEntity = null;
try { try {
dmpBlueprintEntity = this.isValidGuid(item.getBlueprint()) ? this.entityManager.find(DmpBlueprintEntity.class, item.getBlueprint()) : null; dmpBlueprintEntity = this.isValidGuid(item.getBlueprint()) ? this.entityManager.find(DmpBlueprintEntity.class, item.getBlueprint(), true) : null;
} catch (InvalidApplicationException e) { } catch (InvalidApplicationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -1,26 +1,5 @@
package org.opencdmp.service.actionconfirmation; package org.opencdmp.service.actionconfirmation;
import org.opencdmp.authorization.OwnedResource;
import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.XmlHandlingService;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.actionconfirmation.DmpInvitationEntity;
import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity;
import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.ActionConfirmationEntity;
import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.model.actionconfirmation.ActionConfirmation;
import org.opencdmp.model.referencetype.ReferenceType;
import org.opencdmp.model.builder.actionconfirmation.ActionConfirmationBuilder;
import org.opencdmp.model.deleter.ActionConfirmationDeleter;
import org.opencdmp.model.persist.ActionConfirmationPersist;
import org.opencdmp.model.persist.actionconfirmation.RemoveCredentialRequestPersist;
import org.opencdmp.model.persist.actionconfirmation.DmpInvitationPersist;
import org.opencdmp.model.persist.actionconfirmation.MergeAccountConfirmationPersist;
import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory; import gr.cite.tools.data.deleter.DeleterFactory;
@ -34,6 +13,27 @@ import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.logging.MapLogEntry;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.opencdmp.authorization.OwnedResource;
import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.XmlHandlingService;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.actionconfirmation.DmpInvitationEntity;
import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity;
import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.ActionConfirmationEntity;
import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.model.actionconfirmation.ActionConfirmation;
import org.opencdmp.model.builder.actionconfirmation.ActionConfirmationBuilder;
import org.opencdmp.model.deleter.ActionConfirmationDeleter;
import org.opencdmp.model.persist.ActionConfirmationPersist;
import org.opencdmp.model.persist.actionconfirmation.DmpInvitationPersist;
import org.opencdmp.model.persist.actionconfirmation.MergeAccountConfirmationPersist;
import org.opencdmp.model.persist.actionconfirmation.RemoveCredentialRequestPersist;
import org.opencdmp.model.referencetype.ReferenceType;
import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
@ -84,7 +84,7 @@ public class ActionConfirmationServiceImpl implements ActionConfirmationService
ActionConfirmationEntity data; ActionConfirmationEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(ActionConfirmationEntity.class, model.getId()); data = this.entityManager.find(ActionConfirmationEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {
@ -92,7 +92,7 @@ public class ActionConfirmationServiceImpl implements ActionConfirmationService
data.setId(UUID.randomUUID()); data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active); data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now()); data.setCreatedAt(Instant.now());
data.setCreatedById(userScope.getUserId()); data.setCreatedById(this.userScope.getUserId());
} }
this.authorizationService.authorizeAtLeastOneForce(List.of(new OwnedResource(data.getCreatedById())), Permission.EditActionConfirmation); this.authorizationService.authorizeAtLeastOneForce(List.of(new OwnedResource(data.getCreatedById())), Permission.EditActionConfirmation);

View File

@ -41,7 +41,10 @@ import org.opencdmp.integrationevent.outbox.annotationentityremoval.AnnotationEn
import org.opencdmp.integrationevent.outbox.annotationentitytouch.AnnotationEntityTouchedIntegrationEventHandler; import org.opencdmp.integrationevent.outbox.annotationentitytouch.AnnotationEntityTouchedIntegrationEventHandler;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent; import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler; import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler;
import org.opencdmp.model.*; import org.opencdmp.model.DescriptionValidationResult;
import org.opencdmp.model.DmpDescriptionTemplate;
import org.opencdmp.model.StorageFile;
import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.builder.descriptionproperties.DescriptionBuilder; import org.opencdmp.model.builder.descriptionproperties.DescriptionBuilder;
import org.opencdmp.model.deleter.DescriptionDeleter; import org.opencdmp.model.deleter.DescriptionDeleter;
import org.opencdmp.model.deleter.DescriptionReferenceDeleter; import org.opencdmp.model.deleter.DescriptionReferenceDeleter;
@ -212,12 +215,12 @@ public class DescriptionServiceImpl implements DescriptionService {
data.setDmpDescriptionTemplateId(model.getDmpDescriptionTemplateId()); data.setDmpDescriptionTemplateId(model.getDmpDescriptionTemplateId());
} }
DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getDescriptionTemplateId()); DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getDescriptionTemplateId(), true);
if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!dmpDescriptionTemplate.getDescriptionTemplateGroupId().equals(descriptionTemplateEntity.getGroupId())) throw new MyValidationException(this.errors.getInvalidDescriptionTemplate().getCode(), this.errors.getInvalidDescriptionTemplate().getMessage()); if (!dmpDescriptionTemplate.getDescriptionTemplateGroupId().equals(descriptionTemplateEntity.getGroupId())) throw new MyValidationException(this.errors.getInvalidDescriptionTemplate().getCode(), this.errors.getInvalidDescriptionTemplate().getMessage());
DmpEntity dmp = this.entityManager.find(DmpEntity.class, data.getDmpId()); DmpEntity dmp = this.entityManager.find(DmpEntity.class, data.getDmpId(), true);
if (dmp == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmp == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (dmp.getStatus().equals(DmpStatus.Finalized) && isUpdate) throw new MyValidationException(this.errors.getDmpIsFinalized().getCode(), this.errors.getDmpIsFinalized().getMessage()); if (dmp.getStatus().equals(DmpStatus.Finalized) && isUpdate) throw new MyValidationException(this.errors.getDmpIsFinalized().getCode(), this.errors.getDmpIsFinalized().getMessage());
@ -268,14 +271,14 @@ public class DescriptionServiceImpl implements DescriptionService {
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, data.getDescriptionTemplateId()); DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, data.getDescriptionTemplateId(), true);
if (oldDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (oldDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = this.entityManager.find(DmpDescriptionTemplateEntity.class, data.getDmpDescriptionTemplateId()); DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = this.entityManager.find(DmpDescriptionTemplateEntity.class, data.getDmpDescriptionTemplateId(), true);
if (dmpDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpDescriptionTemplateId(), DmpDescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpDescriptionTemplateId(), DmpDescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class) List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking()
.versionStatuses(DescriptionTemplateVersionStatus.Current) .versionStatuses(DescriptionTemplateVersionStatus.Current)
.isActive(IsActive.Active) .isActive(IsActive.Active)
.groupIds(oldDescriptionTemplateEntity.getGroupId()) .groupIds(oldDescriptionTemplateEntity.getGroupId())
@ -309,7 +312,7 @@ public class DescriptionServiceImpl implements DescriptionService {
} }
private void sendNotification(DescriptionEntity description) throws InvalidApplicationException { private void sendNotification(DescriptionEntity description) throws InvalidApplicationException {
List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking()
.dmpIds(description.getDmpId()) .dmpIds(description.getDmpId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
@ -319,7 +322,7 @@ public class DescriptionServiceImpl implements DescriptionService {
} }
for (DmpUserEntity dmpUser : existingUsers) { for (DmpUserEntity dmpUser : existingUsers) {
if (!dmpUser.getUserId().equals(this.userScope.getUserIdSafe())){ if (!dmpUser.getUserId().equals(this.userScope.getUserIdSafe())){
UserEntity user = this.queryFactory.query(UserQuery.class).ids(dmpUser.getUserId()).first(); UserEntity user = this.queryFactory.query(UserQuery.class).disableTracking().ids(dmpUser.getUserId()).first();
if (user != null){ if (user != null){
this.createDescriptionNotificationEvent(description, user); this.createDescriptionNotificationEvent(description, user);
} }
@ -375,7 +378,7 @@ public class DescriptionServiceImpl implements DescriptionService {
NotifyIntegrationEvent event = new NotifyIntegrationEvent(); NotifyIntegrationEvent event = new NotifyIntegrationEvent();
event.setUserId(user.getId()); event.setUserId(user.getId());
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
List<ContactPair> contactPairs = new ArrayList<>(); List<ContactPair> contactPairs = new ArrayList<>();
@ -387,7 +390,7 @@ public class DescriptionServiceImpl implements DescriptionService {
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName())); fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName()));
fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first().getName())); fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).disableTracking().ids(this.userScope.getUserId()).first().getName()));
fieldInfoList.add(new FieldInfo("{name}", DataType.String, description.getLabel())); fieldInfoList.add(new FieldInfo("{name}", DataType.String, description.getLabel()));
fieldInfoList.add(new FieldInfo("{id}", DataType.String, description.getId().toString())); fieldInfoList.add(new FieldInfo("{id}", DataType.String, description.getId().toString()));
data.setFields(fieldInfoList); data.setFields(fieldInfoList);
@ -422,7 +425,7 @@ public class DescriptionServiceImpl implements DescriptionService {
if (!data.getStatus().equals(model.getStatus())){ if (!data.getStatus().equals(model.getStatus())){
if (data.getStatus().equals(DescriptionStatus.Finalized)){ if (data.getStatus().equals(DescriptionStatus.Finalized)){
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(model.getId())), Permission.FinalizeDescription); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(model.getId())), Permission.FinalizeDescription);
DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, data.getDmpId()); DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, data.getDmpId(), true);
if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpId(), DmpEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpId(), DmpEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if(!dmpEntity.getStatus().equals(DmpStatus.Draft)) throw new MyValidationException(this.errors.getDmpIsFinalized().getCode(), this.errors.getDmpIsFinalized().getMessage()); if(!dmpEntity.getStatus().equals(DmpStatus.Draft)) throw new MyValidationException(this.errors.getDmpIsFinalized().getCode(), this.errors.getDmpIsFinalized().getMessage());
} }
@ -446,7 +449,7 @@ public class DescriptionServiceImpl implements DescriptionService {
public List<DescriptionValidationResult> validate(List<UUID> descriptionIds) throws InvalidApplicationException { public List<DescriptionValidationResult> validate(List<UUID> descriptionIds) throws InvalidApplicationException {
List<DescriptionValidationResult> descriptionValidationResults = new ArrayList<>(); List<DescriptionValidationResult> descriptionValidationResults = new ArrayList<>();
List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(descriptionIds).isActive(IsActive.Active).collect(); List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(descriptionIds).isActive(IsActive.Active).collect();
if (descriptions == null){ if (descriptions == null){
return null; return null;
} }
@ -512,7 +515,7 @@ public class DescriptionServiceImpl implements DescriptionService {
if (FieldType.UPLOAD.equals(fieldType)){ if (FieldType.UPLOAD.equals(fieldType)){
UUID newFileId = this.conventionService.isValidUUID(persist.getTextValue()) ? UUID.fromString(persist.getTextValue()) : null; UUID newFileId = this.conventionService.isValidUUID(persist.getTextValue()) ? UUID.fromString(persist.getTextValue()) : null;
if (newFileId != null){ if (newFileId != null){
StorageFileEntity storageFileEntity = this.queryFactory.query(StorageFileQuery.class).ids(newFileId).firstAs(new BaseFieldSet().ensure(StorageFile._id).ensure(StorageFile._storageType)); StorageFileEntity storageFileEntity = this.queryFactory.query(StorageFileQuery.class).disableTracking().ids(newFileId).firstAs(new BaseFieldSet().ensure(StorageFile._id).ensure(StorageFile._storageType));
if (storageFileEntity == null || storageFileEntity.getStorageType().equals(StorageType.Temp)){ if (storageFileEntity == null || storageFileEntity.getStorageType().equals(StorageType.Temp)){
StorageFile storageFile = this.storageFileService.copyToStorage(newFileId, StorageType.Main, true, new BaseFieldSet().ensure(StorageFile._id)); StorageFile storageFile = this.storageFileService.copyToStorage(newFileId, StorageType.Main, true, new BaseFieldSet().ensure(StorageFile._id));
this.storageFileService.updatePurgeAt(storageFile.getId(), null); this.storageFileService.updatePurgeAt(storageFile.getId(), null);
@ -538,7 +541,7 @@ public class DescriptionServiceImpl implements DescriptionService {
else if (!this.conventionService.isNullOrEmpty(persist.getTextValue())) ids.add(UUID.fromString(persist.getTextValue())); else if (!this.conventionService.isNullOrEmpty(persist.getTextValue())) ids.add(UUID.fromString(persist.getTextValue()));
if (!ids.isEmpty()){ if (!ids.isEmpty()){
Set<UUID> existingIds = this.queryFactory.query(DmpQuery.class).ids(ids).collectAs(new BaseFieldSet().ensure(Dmp._id)).stream().map(DmpEntity::getId).collect(Collectors.toSet()); Set<UUID> existingIds = this.queryFactory.query(DmpQuery.class).disableTracking().ids(ids).collectAs(new BaseFieldSet().ensure(Dmp._id)).stream().map(DmpEntity::getId).collect(Collectors.toSet());
for (UUID id : ids){ for (UUID id : ids){
if (!existingIds.contains(id)) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (!existingIds.contains(id)) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} }
@ -549,7 +552,7 @@ public class DescriptionServiceImpl implements DescriptionService {
else if (!this.conventionService.isNullOrEmpty(persist.getTextValue())) ids.add(UUID.fromString(persist.getTextValue())); else if (!this.conventionService.isNullOrEmpty(persist.getTextValue())) ids.add(UUID.fromString(persist.getTextValue()));
if (!ids.isEmpty()) { if (!ids.isEmpty()) {
Set<UUID> existingIds = this.queryFactory.query(DescriptionQuery.class).ids(ids).collectAs(new BaseFieldSet().ensure(Description._id)).stream().map(DescriptionEntity::getId).collect(Collectors.toSet()); Set<UUID> existingIds = this.queryFactory.query(DescriptionQuery.class).disableTracking().ids(ids).collectAs(new BaseFieldSet().ensure(Description._id)).stream().map(DescriptionEntity::getId).collect(Collectors.toSet());
for (UUID id : ids){ for (UUID id : ids){
if (!existingIds.contains(id)) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (!existingIds.contains(id)) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} }
@ -820,7 +823,7 @@ public class DescriptionServiceImpl implements DescriptionService {
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.CloneDescription); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.CloneDescription);
DescriptionEntity existing = this.queryFactory.query(DescriptionQuery.class).ids(descriptionId).isActive(IsActive.Active).first(); DescriptionEntity existing = this.queryFactory.query(DescriptionQuery.class).disableTracking().ids(descriptionId).isActive(IsActive.Active).first();
DescriptionEntity newDescription = new DescriptionEntity(); DescriptionEntity newDescription = new DescriptionEntity();
newDescription.setId(UUID.randomUUID()); newDescription.setId(UUID.randomUUID());
@ -838,12 +841,12 @@ public class DescriptionServiceImpl implements DescriptionService {
this.entityManager.persist(newDescription); this.entityManager.persist(newDescription);
List<DescriptionReferenceEntity> descriptionReferences = this.queryFactory.query(DescriptionReferenceQuery.class) List<DescriptionReferenceEntity> descriptionReferences = this.queryFactory.query(DescriptionReferenceQuery.class).disableTracking()
.descriptionIds(existing.getId()) .descriptionIds(existing.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
.collect(); .collect();
List<DescriptionTagEntity> descriptionTags = this.queryFactory.query(DescriptionTagQuery.class) List<DescriptionTagEntity> descriptionTags = this.queryFactory.query(DescriptionTagQuery.class).disableTracking()
.descriptionIds(existing.getId()) .descriptionIds(existing.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
.collect(); .collect();
@ -904,7 +907,7 @@ public class DescriptionServiceImpl implements DescriptionService {
//this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.CloneDescription); //this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.CloneDescription);
this.authorizationService.authorizeForce(Permission.EditDescription);//TODO: Missing Description or dmp for authz this.authorizationService.authorizeForce(Permission.EditDescription);//TODO: Missing Description or dmp for authz
DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).ids(model.getDescriptionTemplateId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).first(); DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().ids(model.getDescriptionTemplateId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).first();
if (descriptionTemplate == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionTemplate == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplate.getDefinition()); org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplate.getDefinition());
@ -944,22 +947,22 @@ public class DescriptionServiceImpl implements DescriptionService {
public StorageFileEntity getFieldFile(UUID descriptionId, UUID storageFileId) { public StorageFileEntity getFieldFile(UUID descriptionId, UUID storageFileId) {
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.BrowseDescription); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.descriptionAffiliation(descriptionId)), Permission.BrowseDescription);
DescriptionEntity descriptionEntity = this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).ids(descriptionId).first(); DescriptionEntity descriptionEntity = this.queryFactory.query(DescriptionQuery.class).disableTracking().isActive(IsActive.Active).ids(descriptionId).first();
if (descriptionEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionId, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionId, Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first(); DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().ids(descriptionEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first();
if (dmpDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionEntity.getDmpDescriptionTemplateId(), DmpDescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpDescriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionEntity.getDmpDescriptionTemplateId(), DmpDescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DmpEntity dmpEntity = this.queryFactory.query(DmpQuery.class).ids(dmpDescriptionTemplateEntity.getDmpId()).isActive(IsActive.Active).first(); DmpEntity dmpEntity = this.queryFactory.query(DmpQuery.class).ids(dmpDescriptionTemplateEntity.getDmpId()).disableTracking().isActive(IsActive.Active).first();
if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpDescriptionTemplateEntity.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpDescriptionTemplateEntity.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!dmpEntity.getAccessType().equals(DmpAccessType.Public)) if (!dmpEntity.getAccessType().equals(DmpAccessType.Public))
{ {
boolean isDmpUser = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmpEntity.getId()).userIds(this.userScope.getUserIdSafe()).isActives(IsActive.Active).count() > 0; boolean isDmpUser = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmpEntity.getId()).disableTracking().userIds(this.userScope.getUserIdSafe()).isActives(IsActive.Active).count() > 0;
if (!isDmpUser) throw new MyUnauthorizedException(); if (!isDmpUser) throw new MyUnauthorizedException();
} }
StorageFileEntity storageFile = this.queryFactory.query(StorageFileQuery.class).ids(storageFileId).first(); StorageFileEntity storageFile = this.queryFactory.query(StorageFileQuery.class).disableTracking().ids(storageFileId).first();
if (storageFile == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{storageFileId, StorageFile.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (storageFile == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{storageFileId, StorageFile.class.getSimpleName()}, LocaleContextHolder.getLocale()));
return storageFile; return storageFile;
@ -972,7 +975,7 @@ public class DescriptionServiceImpl implements DescriptionService {
DescriptionPersist persist = new DescriptionPersist(); DescriptionPersist persist = new DescriptionPersist();
if (data == null) return persist; if (data == null) return persist;
DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, data.getDescriptionTemplateId()); DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, data.getDescriptionTemplateId(), true);
if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
persist.setLabel(data.getLabel()); persist.setLabel(data.getLabel());
@ -996,7 +999,7 @@ public class DescriptionServiceImpl implements DescriptionService {
List<UUID> referenceIds = this.calculateAllReferenceIdsFromData(data, definition); List<UUID> referenceIds = this.calculateAllReferenceIdsFromData(data, definition);
List<ReferenceEntity> references = null; List<ReferenceEntity> references = null;
if (!this.conventionService.isListNullOrEmpty(referenceIds)){ if (!this.conventionService.isListNullOrEmpty(referenceIds)){
references = this.queryFactory.query(ReferenceQuery.class).ids(referenceIds).collect(); references = this.queryFactory.query(ReferenceQuery.class).disableTracking().ids(referenceIds).collect();
} }
if (data.getFieldSets() != null && !data.getFieldSets().isEmpty()){ if (data.getFieldSets() != null && !data.getFieldSets().isEmpty()){
persist.setFieldSets(new HashMap<>()); persist.setFieldSets(new HashMap<>());
@ -1128,7 +1131,7 @@ public class DescriptionServiceImpl implements DescriptionService {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDescription); if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDescription);
DescriptionEntity data = this.queryFactory.query(DescriptionQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DescriptionEntity data = this.queryFactory.query(DescriptionQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));
PropertyDefinitionEntity definition = this.jsonHandlingService.fromJson(PropertyDefinitionEntity.class, data.getProperties()); PropertyDefinitionEntity definition = this.jsonHandlingService.fromJson(PropertyDefinitionEntity.class, data.getProperties());
@ -1140,7 +1143,7 @@ public class DescriptionServiceImpl implements DescriptionService {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
this.authorizationService.authorizeForce(Permission.ExportDescription); this.authorizationService.authorizeForce(Permission.ExportDescription);
DescriptionEntity data = this.queryFactory.query(DescriptionQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DescriptionEntity data = this.queryFactory.query(DescriptionQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(data.getId(), false)); String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(data.getId(), false));
@ -1154,7 +1157,7 @@ public class DescriptionServiceImpl implements DescriptionService {
xml.setLabel(data.getLabel()); xml.setLabel(data.getLabel());
xml.setFinalizedAt(data.getFinalizedAt()); xml.setFinalizedAt(data.getFinalizedAt());
DescriptionTemplateEntity blueprintEntity = this.queryFactory.query(DescriptionTemplateQuery.class).ids(data.getDescriptionTemplateId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DescriptionTemplateEntity blueprintEntity = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().ids(data.getDescriptionTemplateId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (blueprintEntity != null) { if (blueprintEntity != null) {
xml.setDescriptionTemplate(this.descriptionTemplateService.exportXmlEntity(blueprintEntity.getId(), true)); xml.setDescriptionTemplate(this.descriptionTemplateService.exportXmlEntity(blueprintEntity.getId(), true));
} }
@ -1163,11 +1166,11 @@ public class DescriptionServiceImpl implements DescriptionService {
xml.setProperties(this.descriptionPropertyDefinitionToExport(propertiesEntity)); xml.setProperties(this.descriptionPropertyDefinitionToExport(propertiesEntity));
} }
List<DescriptionReferenceEntity> dmpReferences = this.queryFactory.query(DescriptionReferenceQuery.class).descriptionIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<DescriptionReferenceEntity> dmpReferences = this.queryFactory.query(DescriptionReferenceQuery.class).disableTracking().descriptionIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpReferences)) { if (!this.conventionService.isListNullOrEmpty(dmpReferences)) {
List<ReferenceEntity> references = this.queryFactory.query(ReferenceQuery.class).ids(dmpReferences.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<ReferenceEntity> references = this.queryFactory.query(ReferenceQuery.class).disableTracking().ids(dmpReferences.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
Map<UUID, ReferenceEntity> referenceEntityMap = references == null ? new HashMap<>() : references.stream().collect(Collectors.toMap(ReferenceEntity::getId, x-> x)); Map<UUID, ReferenceEntity> referenceEntityMap = references == null ? new HashMap<>() : references.stream().collect(Collectors.toMap(ReferenceEntity::getId, x-> x));
List<ReferenceTypeEntity> referenceTypes = references == null ? new ArrayList<>() : this.queryFactory.query(ReferenceTypeQuery.class).ids(references.stream().map(ReferenceEntity::getTypeId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<ReferenceTypeEntity> referenceTypes = references == null ? new ArrayList<>() : this.queryFactory.query(ReferenceTypeQuery.class).disableTracking().ids(references.stream().map(ReferenceEntity::getTypeId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
Map<UUID, ReferenceTypeEntity> referenceTypeEntityMap = referenceTypes == null ? new HashMap<>() : referenceTypes.stream().collect(Collectors.toMap(ReferenceTypeEntity::getId, x-> x)); Map<UUID, ReferenceTypeEntity> referenceTypeEntityMap = referenceTypes == null ? new HashMap<>() : referenceTypes.stream().collect(Collectors.toMap(ReferenceTypeEntity::getId, x-> x));
List<DescriptionReferenceImportExport> dmpReferenceImportExports = new LinkedList<>(); List<DescriptionReferenceImportExport> dmpReferenceImportExports = new LinkedList<>();
for (DescriptionReferenceEntity descriptionTemplateEntity : dmpReferences) { for (DescriptionReferenceEntity descriptionTemplateEntity : dmpReferences) {

View File

@ -36,7 +36,7 @@ import org.opencdmp.data.*;
import org.opencdmp.errorcode.ErrorThesaurusProperties; import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent; import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler; import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler;
import org.opencdmp.model.*; import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.builder.descriptiontemplate.DescriptionTemplateBuilder; import org.opencdmp.model.builder.descriptiontemplate.DescriptionTemplateBuilder;
import org.opencdmp.model.deleter.DescriptionTemplateDeleter; import org.opencdmp.model.deleter.DescriptionTemplateDeleter;
import org.opencdmp.model.deleter.UserDescriptionTemplateDeleter; import org.opencdmp.model.deleter.UserDescriptionTemplateDeleter;
@ -208,7 +208,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
throw new MyForbiddenException("Can not update finalized template"); throw new MyForbiddenException("Can not update finalized template");
if (newStatus.equals(DescriptionTemplateStatus.Finalized)) { if (newStatus.equals(DescriptionTemplateStatus.Finalized)) {
List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class).versionStatuses(DescriptionTemplateVersionStatus.Current).isActive(IsActive.Active).groupIds(data.getGroupId()).collect(); List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().versionStatuses(DescriptionTemplateVersionStatus.Current).isActive(IsActive.Active).groupIds(data.getGroupId()).collect();
if (latestVersionDescriptionTemplates.size() > 1) if (latestVersionDescriptionTemplates.size() > 1)
throw new MyValidationException("Multiple previous template found"); throw new MyValidationException("Multiple previous template found");
DescriptionTemplateEntity oldDescriptionTemplateEntity = latestVersionDescriptionTemplates.stream().findFirst().orElse(null); DescriptionTemplateEntity oldDescriptionTemplateEntity = latestVersionDescriptionTemplates.stream().findFirst().orElse(null);
@ -230,7 +230,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
private void persistUsers(UUID id, List<UserDescriptionTemplatePersist> users) throws InvalidApplicationException { private void persistUsers(UUID id, List<UserDescriptionTemplatePersist> users) throws InvalidApplicationException {
if (users == null) if (users == null)
users = new ArrayList<>(); users = new ArrayList<>();
List<UserDescriptionTemplateEntity> items = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(id).collect(); List<UserDescriptionTemplateEntity> items = this.queryFactory.query(UserDescriptionTemplateQuery.class).disableTracking().isActive(IsActive.Active).descriptionTemplateIds(id).collect();
List<UUID> updatedCreatedIds = new ArrayList<>(); List<UUID> updatedCreatedIds = new ArrayList<>();
for (UserDescriptionTemplatePersist user : users) { for (UserDescriptionTemplatePersist user : users) {
UserDescriptionTemplateEntity data = items.stream().filter(x -> x.getUserId().equals(user.getUserId()) && x.getRole().equals(user.getRole())).findFirst().orElse(null); UserDescriptionTemplateEntity data = items.stream().filter(x -> x.getUserId().equals(user.getUserId()) && x.getRole().equals(user.getRole())).findFirst().orElse(null);
@ -258,16 +258,16 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
private void sendDescriptionTemplateInvitationEvent(UserDescriptionTemplateEntity userDescriptionTemplate) throws InvalidApplicationException { private void sendDescriptionTemplateInvitationEvent(UserDescriptionTemplateEntity userDescriptionTemplate) throws InvalidApplicationException {
NotifyIntegrationEvent event = new NotifyIntegrationEvent(); NotifyIntegrationEvent event = new NotifyIntegrationEvent();
UserEntity user = this.entityManager.find(UserEntity.class, userDescriptionTemplate.getUserId()); UserEntity user = this.entityManager.find(UserEntity.class, userDescriptionTemplate.getUserId(), true);
if (user == null){ if (user == null){
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userDescriptionTemplate.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userDescriptionTemplate.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} }
DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(userDescriptionTemplate.getDescriptionTemplateId()).first(); DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().isActive(IsActive.Active).ids(userDescriptionTemplate.getDescriptionTemplateId()).first();
if (descriptionTemplate == null){ if (descriptionTemplate == null){
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userDescriptionTemplate.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userDescriptionTemplate.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} }
event.setUserId(user.getId()); event.setUserId(user.getId());
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
List<ContactPair> contactPairs = new ArrayList<>(); List<ContactPair> contactPairs = new ArrayList<>();
@ -447,7 +447,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Reference.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Reference.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} else { } else {
ReferenceTypeDataEntity referenceTypeDataEntity = ((ReferenceTypeDataEntity)fieldEntity.getData()); ReferenceTypeDataEntity referenceTypeDataEntity = ((ReferenceTypeDataEntity)fieldEntity.getData());
data = this.queryFactory.query(ReferenceQuery.class).sourceTypes(model.getSourceType()).typeIds(referenceTypeDataEntity.getReferenceTypeId()).sources(model.getSource()).isActive(IsActive.Active).references(model.getReference()).first(); data = this.queryFactory.query(ReferenceQuery.class).disableTracking().sourceTypes(model.getSourceType()).typeIds(referenceTypeDataEntity.getReferenceTypeId()).sources(model.getSource()).isActive(IsActive.Active).references(model.getReference()).first();
if (data == null){ if (data == null){
data = new ReferenceEntity(); data = new ReferenceEntity();
data.setId(UUID.randomUUID()); data.setId(UUID.randomUUID());
@ -463,7 +463,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setSourceType(model.getSourceType()); data.setSourceType(model.getSourceType());
try { try {
ReferenceTypeEntity referenceType = this.queryFactory.query(ReferenceTypeQuery.class).ids(referenceTypeDataEntity.getReferenceTypeId()).firstAs(new BaseFieldSet().ensure(ReferenceType._id).ensure(ReferenceTypeEntity._tenantId)); ReferenceTypeEntity referenceType = this.queryFactory.query(ReferenceTypeQuery.class).disableTracking().ids(referenceTypeDataEntity.getReferenceTypeId()).firstAs(new BaseFieldSet().ensure(ReferenceType._id).ensure(ReferenceTypeEntity._tenantId));
if (referenceType == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{referenceTypeDataEntity.getReferenceTypeId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (referenceType == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{referenceTypeDataEntity.getReferenceTypeId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data.getSourceType().equals(ReferenceSourceType.External) && !this.tenantScope.isDefaultTenant() && referenceType.getTenantId() == null){ if (data.getSourceType().equals(ReferenceSourceType.External) && !this.tenantScope.isDefaultTenant() && referenceType.getTenantId() == null){
@ -553,7 +553,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data.getVersionStatus().equals(DescriptionTemplateVersionStatus.Current)){ if (data.getVersionStatus().equals(DescriptionTemplateVersionStatus.Current)){
DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class) DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking()
.statuses(DescriptionTemplateStatus.Finalized) .statuses(DescriptionTemplateStatus.Finalized)
.excludedIds(data.getId()) .excludedIds(data.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
@ -582,7 +582,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.authorizationService.authorizeForce(Permission.CloneDescriptionTemplate); this.authorizationService.authorizeForce(Permission.CloneDescriptionTemplate);
DescriptionTemplateQuery query = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id); DescriptionTemplateQuery query = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id);
DescriptionTemplate model = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(fields, query.firstAs(fields)); DescriptionTemplate model = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(fields, query.firstAs(fields));
if (model == null) if (model == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -664,7 +664,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.authorizationService.authorizeForce(Permission.CreateNewVersionDescriptionTemplate); this.authorizationService.authorizeForce(Permission.CreateNewVersionDescriptionTemplate);
DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getId()); DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getId(), true);
if (oldDescriptionTemplateEntity == null) if (oldDescriptionTemplateEntity == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()).equals(model.getHash())) if (!this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()).equals(model.getHash()))
@ -672,7 +672,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
if (!this.tenantScope.isSet() || !Objects.equals(oldDescriptionTemplateEntity.getTenantId(), this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); if (!this.tenantScope.isSet() || !Objects.equals(oldDescriptionTemplateEntity.getTenantId(), this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class) List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking()
.versionStatuses(DescriptionTemplateVersionStatus.Current) .versionStatuses(DescriptionTemplateVersionStatus.Current)
.isActive(IsActive.Active) .isActive(IsActive.Active)
.groupIds(oldDescriptionTemplateEntity.getGroupId()) .groupIds(oldDescriptionTemplateEntity.getGroupId())
@ -683,7 +683,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
throw new MyValidationException("Multiple previous template found"); throw new MyValidationException("Multiple previous template found");
if (!latestVersionDescriptionTemplates.getFirst().getVersion().equals(oldDescriptionTemplateEntity.getVersion())) if (!latestVersionDescriptionTemplates.getFirst().getVersion().equals(oldDescriptionTemplateEntity.getVersion()))
throw new MyValidationException(this.errors.getDescriptionTemplateNewVersionConflict().getCode(), this.errors.getDescriptionTemplateNewVersionConflict().getMessage()); throw new MyValidationException(this.errors.getDescriptionTemplateNewVersionConflict().getCode(), this.errors.getDescriptionTemplateNewVersionConflict().getMessage());
Long notFinalizedCount = this.queryFactory.query(DescriptionTemplateQuery.class) Long notFinalizedCount = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking()
.versionStatuses(DescriptionTemplateVersionStatus.NotFinalized) .versionStatuses(DescriptionTemplateVersionStatus.NotFinalized)
.groupIds(oldDescriptionTemplateEntity.getGroupId()) .groupIds(oldDescriptionTemplateEntity.getGroupId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
@ -751,7 +751,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
persist.setDefinition(this.xmlDefinitionToPersist(importXml)); persist.setDefinition(this.xmlDefinitionToPersist(importXml));
persist.setType(importXml.getType()); persist.setType(importXml.getType());
DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, id); DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, id, true);
if (oldDescriptionTemplateEntity == null) if (oldDescriptionTemplateEntity == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
persist.setHash(this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt())); persist.setHash(this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()));
@ -899,7 +899,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
logger.debug(new MapLogEntry("exportXml").And("id", id)); logger.debug(new MapLogEntry("exportXml").And("id", id));
if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDescriptionTemplate); if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDescriptionTemplate);
DescriptionTemplateEntity data = this.queryFactory.query(DescriptionTemplateQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first(); DescriptionTemplateEntity data = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DefinitionEntity definition = this.xmlHandlingService.fromXml(DefinitionEntity.class, data.getDefinition()); DefinitionEntity definition = this.xmlHandlingService.fromXml(DefinitionEntity.class, data.getDefinition());
@ -912,7 +912,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
logger.debug(new MapLogEntry("exportXml").And("id", id)); logger.debug(new MapLogEntry("exportXml").And("id", id));
this.authorizationService.authorizeForce(Permission.ExportDescriptionTemplate); this.authorizationService.authorizeForce(Permission.ExportDescriptionTemplate);
DescriptionTemplateEntity data = this.queryFactory.query(DescriptionTemplateQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first(); DescriptionTemplateEntity data = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(id, false)); String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(id, false));

View File

@ -1,5 +1,16 @@
package org.opencdmp.service.descriptiontemplatetype; package org.opencdmp.service.descriptiontemplatetype;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.IsActive; import org.opencdmp.commons.enums.IsActive;
@ -13,17 +24,6 @@ import org.opencdmp.model.DescriptionTemplateType;
import org.opencdmp.model.builder.DescriptionTemplateTypeBuilder; import org.opencdmp.model.builder.DescriptionTemplateTypeBuilder;
import org.opencdmp.model.deleter.DescriptionTemplateTypeDeleter; import org.opencdmp.model.deleter.DescriptionTemplateTypeDeleter;
import org.opencdmp.model.persist.DescriptionTemplateTypePersist; import org.opencdmp.model.persist.DescriptionTemplateTypePersist;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -86,7 +86,7 @@ public class DescriptionTemplateTypeServiceImpl implements DescriptionTemplateTy
DescriptionTemplateTypeEntity data; DescriptionTemplateTypeEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(DescriptionTemplateTypeEntity.class, model.getId()); data = this.entityManager.find(DescriptionTemplateTypeEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplateType.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplateType.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {
data = new DescriptionTemplateTypeEntity(); data = new DescriptionTemplateTypeEntity();

View File

@ -207,7 +207,7 @@ public class DmpServiceImpl implements DmpService {
DmpEntity data = this.patchAndSave(model); DmpEntity data = this.patchAndSave(model);
DmpBlueprintEntity blueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, data.getBlueprintId()); DmpBlueprintEntity blueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, data.getBlueprintId(), true);
if (blueprintEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (blueprintEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
org.opencdmp.commons.types.dmpblueprint.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class, blueprintEntity.getDefinition()); org.opencdmp.commons.types.dmpblueprint.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class, blueprintEntity.getDefinition());
if (definition == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (definition == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -237,11 +237,11 @@ public class DmpServiceImpl implements DmpService {
} }
private void checkIfDescriptionTemplateIsUse (List<DmpDescriptionTemplatePersist> descriptionTemplates, UUID id){ private void checkIfDescriptionTemplateIsUse (List<DmpDescriptionTemplatePersist> descriptionTemplates, UUID id){
List<DmpDescriptionTemplateEntity> existingDmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(id).isActive(IsActive.Active).collect(); List<DmpDescriptionTemplateEntity> existingDmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(id).isActive(IsActive.Active).collect();
List<DmpDescriptionTemplateEntity> removedDescriptionTemplates = existingDmpDescriptionTemplates.stream().filter(x -> descriptionTemplates.stream().noneMatch(y -> y.getDescriptionTemplateGroupId().equals(x.getDescriptionTemplateGroupId()))).toList(); List<DmpDescriptionTemplateEntity> removedDescriptionTemplates = existingDmpDescriptionTemplates.stream().filter(x -> descriptionTemplates.stream().noneMatch(y -> y.getDescriptionTemplateGroupId().equals(x.getDescriptionTemplateGroupId()))).toList();
DmpDescriptionTemplateQuery dmpDescriptionTemplateQuery = this.queryFactory.query(DmpDescriptionTemplateQuery.class).isActive(IsActive.Active).dmpIds(id).descriptionTemplateGroupIds(removedDescriptionTemplates.stream().map(DmpDescriptionTemplateEntity::getDescriptionTemplateGroupId).collect(Collectors.toList())); DmpDescriptionTemplateQuery dmpDescriptionTemplateQuery = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().isActive(IsActive.Active).dmpIds(id).descriptionTemplateGroupIds(removedDescriptionTemplates.stream().map(DmpDescriptionTemplateEntity::getDescriptionTemplateGroupId).collect(Collectors.toList()));
DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpDescriptionTemplateSubQuery(dmpDescriptionTemplateQuery).isActive(IsActive.Active); DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpDescriptionTemplateSubQuery(dmpDescriptionTemplateQuery).isActive(IsActive.Active);
if (query != null && query.count() > 0) throw new MyValidationException(this.errors.getDmpDescriptionTemplateCanNotRemove().getCode(), this.errors.getDmpDescriptionTemplateCanNotRemove().getMessage()); if (query != null && query.count() > 0) throw new MyValidationException(this.errors.getDmpDescriptionTemplateCanNotRemove().getCode(), this.errors.getDmpDescriptionTemplateCanNotRemove().getMessage());
@ -268,7 +268,7 @@ public class DmpServiceImpl implements DmpService {
} }
private void sendNotification(DmpEntity dmp) throws InvalidApplicationException { private void sendNotification(DmpEntity dmp) throws InvalidApplicationException {
List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking()
.dmpIds(dmp.getId()) .dmpIds(dmp.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
@ -279,7 +279,7 @@ public class DmpServiceImpl implements DmpService {
for (DmpUserEntity dmpUser : existingUsers) { for (DmpUserEntity dmpUser : existingUsers) {
if (!dmpUser.getUserId().equals(this.userScope.getUserIdSafe())){ if (!dmpUser.getUserId().equals(this.userScope.getUserIdSafe())){
UserEntity user = this.queryFactory.query(UserQuery.class).ids(dmpUser.getUserId()).first(); UserEntity user = this.queryFactory.query(UserQuery.class).disableTracking().ids(dmpUser.getUserId()).first();
if (user != null){ if (user != null){
this.createDmpNotificationEvent(dmp, user); this.createDmpNotificationEvent(dmp, user);
} }
@ -290,7 +290,7 @@ public class DmpServiceImpl implements DmpService {
private void createDmpNotificationEvent(DmpEntity dmp, UserEntity user) throws InvalidApplicationException { private void createDmpNotificationEvent(DmpEntity dmp, UserEntity user) throws InvalidApplicationException {
NotifyIntegrationEvent event = new NotifyIntegrationEvent(); NotifyIntegrationEvent event = new NotifyIntegrationEvent();
event.setUserId(user.getId()); event.setUserId(user.getId());
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
List<ContactPair> contactPairs = new ArrayList<>(); List<ContactPair> contactPairs = new ArrayList<>();
@ -302,7 +302,7 @@ public class DmpServiceImpl implements DmpService {
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName())); fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName()));
fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first().getName())); fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).disableTracking().ids(this.userScope.getUserId()).first().getName()));
fieldInfoList.add(new FieldInfo("{name}", DataType.String, dmp.getLabel())); fieldInfoList.add(new FieldInfo("{name}", DataType.String, dmp.getLabel()));
fieldInfoList.add(new FieldInfo("{id}", DataType.String, dmp.getId().toString())); fieldInfoList.add(new FieldInfo("{id}", DataType.String, dmp.getId().toString()));
data.setFields(fieldInfoList); data.setFields(fieldInfoList);
@ -332,7 +332,7 @@ public class DmpServiceImpl implements DmpService {
DmpEntity data = this.entityManager.find(DmpEntity.class, id); DmpEntity data = this.entityManager.find(DmpEntity.class, id);
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).types(EntityType.DMP).entityIds(data.getId()); EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).types(EntityType.DMP).entityIds(data.getId());
if (entityDoiQuery.count() > 0) throw new MyApplicationException("DMP is deposited can not deleted"); if (entityDoiQuery.count() > 0) throw new MyApplicationException("DMP is deposited can not deleted");
DmpEntity previousFinalized = null; DmpEntity previousFinalized = null;
@ -365,11 +365,11 @@ public class DmpServiceImpl implements DmpService {
logger.debug(new MapLogEntry("persisting data bew version").And("model", model).And("fields", fields)); logger.debug(new MapLogEntry("persisting data bew version").And("model", model).And("fields", fields));
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation( model.getId())), Permission.CreateNewVersionDmp); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation( model.getId())), Permission.CreateNewVersionDmp);
DmpEntity oldDmpEntity = this.entityManager.find(DmpEntity.class, model.getId()); DmpEntity oldDmpEntity = this.entityManager.find(DmpEntity.class, model.getId(), true);
if (oldDmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (oldDmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(oldDmpEntity.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(oldDmpEntity.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
List<DmpEntity> latestVersionDmps = this.queryFactory.query(DmpQuery.class) List<DmpEntity> latestVersionDmps = this.queryFactory.query(DmpQuery.class).disableTracking()
.groupIds(oldDmpEntity.getGroupId()) .groupIds(oldDmpEntity.getGroupId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
.versionStatuses(DmpVersionStatus.Current) .versionStatuses(DmpVersionStatus.Current)
@ -379,7 +379,7 @@ public class DmpServiceImpl implements DmpService {
if (!latestVersionDmps.getFirst().getVersion().equals(oldDmpEntity.getVersion())){ if (!latestVersionDmps.getFirst().getVersion().equals(oldDmpEntity.getVersion())){
throw new MyValidationException(this.errors.getDmpNewVersionConflict().getCode(), this.errors.getDmpNewVersionConflict().getMessage()); throw new MyValidationException(this.errors.getDmpNewVersionConflict().getCode(), this.errors.getDmpNewVersionConflict().getMessage());
} }
Long notFinalizedCount = this.queryFactory.query(DmpQuery.class) Long notFinalizedCount = this.queryFactory.query(DmpQuery.class).disableTracking()
.versionStatuses(DmpVersionStatus.NotFinalized) .versionStatuses(DmpVersionStatus.NotFinalized)
.groupIds(oldDmpEntity.getGroupId()) .groupIds(oldDmpEntity.getGroupId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
@ -405,15 +405,15 @@ public class DmpServiceImpl implements DmpService {
this.entityManager.persist(newDmp); this.entityManager.persist(newDmp);
List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class) List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
List<DmpDescriptionTemplateEntity> dmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class) List<DmpDescriptionTemplateEntity> dmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
.collect(); .collect();
@ -480,7 +480,7 @@ public class DmpServiceImpl implements DmpService {
if (previousStatus.equals(newStatus)) if (previousStatus.equals(newStatus))
return; return;
if (previousStatus.equals(DmpStatus.Finalized) && newStatus.equals(DmpStatus.Draft)){ if (previousStatus.equals(DmpStatus.Finalized) && newStatus.equals(DmpStatus.Draft)){
boolean alreadyCreatedNewVersion = this.queryFactory.query(DmpQuery.class) boolean alreadyCreatedNewVersion = this.queryFactory.query(DmpQuery.class).disableTracking()
.versionStatuses(DmpVersionStatus.NotFinalized, DmpVersionStatus.Current) .versionStatuses(DmpVersionStatus.NotFinalized, DmpVersionStatus.Current)
.excludedIds(data.getId()) .excludedIds(data.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
@ -516,7 +516,7 @@ public class DmpServiceImpl implements DmpService {
public Dmp buildClone(CloneDmpPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, IOException, InvalidApplicationException { public Dmp buildClone(CloneDmpPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, IOException, InvalidApplicationException {
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation( model.getId())), Permission.CloneDmp); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation( model.getId())), Permission.CloneDmp);
DmpEntity existingDmpEntity = this.queryFactory.query(DmpQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(model.getId()).firstAs(fields); DmpEntity existingDmpEntity = this.queryFactory.query(DmpQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(model.getId()).firstAs(fields);
if (!this.conventionService.isValidGuid(model.getId()) || existingDmpEntity == null) if (!this.conventionService.isValidGuid(model.getId()) || existingDmpEntity == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -539,15 +539,15 @@ public class DmpServiceImpl implements DmpService {
this.entityManager.persist(newDmp); this.entityManager.persist(newDmp);
List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class) List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
List<DmpDescriptionTemplateEntity> dmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class) List<DmpDescriptionTemplateEntity> dmpDescriptionTemplates = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking()
.dmpIds(model.getId()) .dmpIds(model.getId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
.collect(); .collect();
@ -597,7 +597,7 @@ public class DmpServiceImpl implements DmpService {
this.annotationEntityTouchedIntegrationEventHandler.handleDmp(newDmp.getId()); this.annotationEntityTouchedIntegrationEventHandler.handleDmp(newDmp.getId());
DmpEntity resultingDmpEntity = this.queryFactory.query(DmpQuery.class).ids(newDmp.getId()).firstAs(fields); DmpEntity resultingDmpEntity = this.queryFactory.query(DmpQuery.class).disableTracking().ids(newDmp.getId()).firstAs(fields);
if (!this.conventionService.isListNullOrEmpty(model.getDescriptions())){ if (!this.conventionService.isListNullOrEmpty(model.getDescriptions())){
for (UUID description: model.getDescriptions()) { for (UUID description: model.getDescriptions()) {
this.descriptionService.clone(newDmp.getId(), description); this.descriptionService.clone(newDmp.getId(), description);
@ -612,7 +612,7 @@ public class DmpServiceImpl implements DmpService {
if (!disableDelete && (model == null || model.stream().noneMatch(x-> x.getUser() != null && DmpUserRole.Owner.equals(x.getRole())))) throw new MyApplicationException("At least one owner required"); if (!disableDelete && (model == null || model.stream().noneMatch(x-> x.getUser() != null && DmpUserRole.Owner.equals(x.getRole())))) throw new MyApplicationException("At least one owner required");
DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, dmpId); DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, dmpId, true);
if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpId, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpId, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class)
@ -658,7 +658,7 @@ public class DmpServiceImpl implements DmpService {
@Override @Override
public Dmp removeUser(DmpUserRemovePersist model, FieldSet fields) throws InvalidApplicationException, IOException { public Dmp removeUser(DmpUserRemovePersist model, FieldSet fields) throws InvalidApplicationException, IOException {
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation(model.getDmpId())), Permission.AssignDmpUsers); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation(model.getDmpId())), Permission.AssignDmpUsers);
DmpEntity data = this.entityManager.find(DmpEntity.class, model.getDmpId()); DmpEntity data = this.entityManager.find(DmpEntity.class, model.getDmpId(), true);
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class)
@ -1025,7 +1025,7 @@ public class DmpServiceImpl implements DmpService {
public DmpValidationResult validate(UUID id) throws InvalidApplicationException { public DmpValidationResult validate(UUID id) throws InvalidApplicationException {
DmpEntity dmp = this.queryFactory.query(DmpQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id).isActive(IsActive.Active).first(); DmpEntity dmp = this.queryFactory.query(DmpQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id).isActive(IsActive.Active).first();
if (dmp == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmp == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -1045,7 +1045,7 @@ public class DmpServiceImpl implements DmpService {
DmpPersist persist = new DmpPersist(); DmpPersist persist = new DmpPersist();
if (data == null) return persist; if (data == null) return persist;
DmpBlueprintEntity dmpBlueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, data.getBlueprintId()); DmpBlueprintEntity dmpBlueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, data.getBlueprintId(), true);
if (dmpBlueprintEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpBlueprintEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
persist.setId(data.getId()); persist.setId(data.getId());
@ -1057,7 +1057,7 @@ public class DmpServiceImpl implements DmpService {
persist.setAccessType(data.getAccessType()); persist.setAccessType(data.getAccessType());
persist.setLanguage(data.getLanguage()); persist.setLanguage(data.getLanguage());
List<DmpUserEntity> dmpUserEntities = this.queryFactory.query(DmpUserQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActives(IsActive.Active).collect(); List<DmpUserEntity> dmpUserEntities = this.queryFactory.query(DmpUserQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActives(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpUserEntities)){ if (!this.conventionService.isListNullOrEmpty(dmpUserEntities)){
persist.setUsers(new ArrayList<>()); persist.setUsers(new ArrayList<>());
@ -1066,11 +1066,11 @@ public class DmpServiceImpl implements DmpService {
} }
} }
List<DmpReferenceEntity> dmpReferenceEntities = this.queryFactory.query(DmpReferenceQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActives(IsActive.Active).collect(); List<DmpReferenceEntity> dmpReferenceEntities = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActives(IsActive.Active).collect();
org.opencdmp.commons.types.dmpblueprint.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class, dmpBlueprintEntity.getDefinition()); org.opencdmp.commons.types.dmpblueprint.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(org.opencdmp.commons.types.dmpblueprint.DefinitionEntity.class, dmpBlueprintEntity.getDefinition());
List<DmpDescriptionTemplateEntity> dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActive(IsActive.Active).collect(); List<DmpDescriptionTemplateEntity> dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).dmpIds(data.getId()).isActive(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpDescriptionTemplateEntities)){ if (!this.conventionService.isListNullOrEmpty(dmpDescriptionTemplateEntities)){
persist.setDescriptionTemplates(new ArrayList<>()); persist.setDescriptionTemplates(new ArrayList<>());
for (DmpDescriptionTemplateEntity descriptionTemplateEntity: dmpDescriptionTemplateEntities) { for (DmpDescriptionTemplateEntity descriptionTemplateEntity: dmpDescriptionTemplateEntities) {
@ -1094,7 +1094,7 @@ public class DmpServiceImpl implements DmpService {
List<ReferenceEntity> referencesFromAllFields = new ArrayList<>(); List<ReferenceEntity> referencesFromAllFields = new ArrayList<>();
if (!this.conventionService.isListNullOrEmpty(dmpReferenceEntities)) { if (!this.conventionService.isListNullOrEmpty(dmpReferenceEntities)) {
referencesFromAllFields = this.queryFactory.query(ReferenceQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(dmpReferenceEntities.stream().map(DmpReferenceEntity::getReferenceId).collect(Collectors.toList())).isActive(IsActive.Active).collect(); referencesFromAllFields = this.queryFactory.query(ReferenceQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(dmpReferenceEntities.stream().map(DmpReferenceEntity::getReferenceId).collect(Collectors.toList())).isActive(IsActive.Active).collect();
} }
Map<UUID, DmpBlueprintValuePersist> dmpBlueprintValues = new HashMap<>(); Map<UUID, DmpBlueprintValuePersist> dmpBlueprintValues = new HashMap<>();
@ -1214,12 +1214,12 @@ public class DmpServiceImpl implements DmpService {
private List<DmpUserPersist> inviteUserOrAssignUsers(UUID id, List<DmpUserPersist> users, boolean persistUsers) throws InvalidApplicationException, JAXBException, IOException { private List<DmpUserPersist> inviteUserOrAssignUsers(UUID id, List<DmpUserPersist> users, boolean persistUsers) throws InvalidApplicationException, JAXBException, IOException {
this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation(id)), Permission.InviteDmpUsers); this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.dmpAffiliation(id)), Permission.InviteDmpUsers);
DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(id).first(); DmpEntity dmp = this.queryFactory.query(DmpQuery.class).disableTracking().ids(id).first();
if (dmp == null){ if (dmp == null){
throw new InvalidApplicationException("Dmp does not exist!"); throw new InvalidApplicationException("Dmp does not exist!");
} }
List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class) List<DmpUserEntity> existingUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking()
.dmpIds(dmp.getId()) .dmpIds(dmp.getId())
.isActives(IsActive.Active) .isActives(IsActive.Active)
.collect(); .collect();
@ -1234,7 +1234,7 @@ public class DmpServiceImpl implements DmpService {
if (user.getUser() != null){ if (user.getUser() != null){
userId = user.getUser(); userId = user.getUser();
} else if (user.getEmail() != null) { } else if (user.getEmail() != null) {
UserContactInfoEntity contactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).values(user.getEmail()).types(ContactInfoType.Email).first(); UserContactInfoEntity contactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().values(user.getEmail()).types(ContactInfoType.Email).first();
if (contactInfoEntity != null){ if (contactInfoEntity != null){
userId = contactInfoEntity.getUserId(); userId = contactInfoEntity.getUserId();
} }
@ -1255,8 +1255,8 @@ public class DmpServiceImpl implements DmpService {
} }
private void sendDmpInvitationExistingUser(UUID userId, DmpEntity dmp, DmpUserRole role) throws InvalidApplicationException { private void sendDmpInvitationExistingUser(UUID userId, DmpEntity dmp, DmpUserRole role) throws InvalidApplicationException {
UserEntity recipient = this.queryFactory.query(UserQuery.class).ids(userId).isActive(IsActive.Active).first(); UserEntity recipient = this.queryFactory.query(UserQuery.class).disableTracking().ids(userId).isActive(IsActive.Active).first();
String email = this.queryFactory.query(UserContactInfoQuery.class).userIds(recipient.getId()).first().getValue(); String email = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().userIds(recipient.getId()).first().getValue();
this.createDmpInvitationExistingUserEvent(recipient, dmp, role, email); this.createDmpInvitationExistingUserEvent(recipient, dmp, role, email);
} }
@ -1273,7 +1273,7 @@ public class DmpServiceImpl implements DmpService {
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, recipient.getName())); fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, recipient.getName()));
fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserIdSafe()).first().getName())); fieldInfoList.add(new FieldInfo("{reasonName}", DataType.String, this.queryFactory.query(UserQuery.class).disableTracking().ids(this.userScope.getUserIdSafe()).first().getName()));
fieldInfoList.add(new FieldInfo("{dmpname}", DataType.String, dmp.getLabel())); fieldInfoList.add(new FieldInfo("{dmpname}", DataType.String, dmp.getLabel()));
fieldInfoList.add(new FieldInfo("{dmprole}", DataType.String, role.toString())); fieldInfoList.add(new FieldInfo("{dmprole}", DataType.String, role.toString()));
fieldInfoList.add(new FieldInfo("{id}", DataType.String, dmp.getId().toString())); fieldInfoList.add(new FieldInfo("{id}", DataType.String, dmp.getId().toString()));
@ -1355,7 +1355,7 @@ public class DmpServiceImpl implements DmpService {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDmp); if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDmp);
DmpEntity data = this.queryFactory.query(DmpQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DmpEntity data = this.queryFactory.query(DmpQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DmpPropertiesEntity definition = this.jsonHandlingService.fromJson(DmpPropertiesEntity.class, data.getProperties()); DmpPropertiesEntity definition = this.jsonHandlingService.fromJson(DmpPropertiesEntity.class, data.getProperties());
@ -1367,7 +1367,7 @@ public class DmpServiceImpl implements DmpService {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
this.authorizationService.authorizeForce(Permission.ExportDmp); this.authorizationService.authorizeForce(Permission.ExportDmp);
DmpEntity data = this.queryFactory.query(DmpQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DmpEntity data = this.queryFactory.query(DmpQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(data.getId(), false)); String xml = this.xmlHandlingService.toXml(this.exportXmlEntity(data.getId(), false));
@ -1386,7 +1386,7 @@ public class DmpServiceImpl implements DmpService {
if (propertiesEntity != null && !this.conventionService.isListNullOrEmpty(propertiesEntity.getContacts())) { if (propertiesEntity != null && !this.conventionService.isListNullOrEmpty(propertiesEntity.getContacts())) {
List<DmpContactImportExport> dmpContactImportExports = new LinkedList<>(); List<DmpContactImportExport> dmpContactImportExports = new LinkedList<>();
List<UserEntity> users = this.queryFactory.query(UserQuery.class).ids(propertiesEntity.getContacts().stream().map(DmpContactEntity::getUserId).filter(Objects::nonNull).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<UserEntity> users = this.queryFactory.query(UserQuery.class).disableTracking().ids(propertiesEntity.getContacts().stream().map(DmpContactEntity::getUserId).filter(Objects::nonNull).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
Map<UUID, UserEntity> usersMap = users == null ? new HashMap<>() : users.stream().collect(Collectors.toMap(UserEntity::getId, x-> x)); Map<UUID, UserEntity> usersMap = users == null ? new HashMap<>() : users.stream().collect(Collectors.toMap(UserEntity::getId, x-> x));
for (DmpContactEntity contactEntity : propertiesEntity.getContacts()) { for (DmpContactEntity contactEntity : propertiesEntity.getContacts()) {
dmpContactImportExports.add(this.dmpContactToExport(contactEntity, usersMap)); dmpContactImportExports.add(this.dmpContactToExport(contactEntity, usersMap));
@ -1394,9 +1394,9 @@ public class DmpServiceImpl implements DmpService {
xml.setContacts(dmpContactImportExports); xml.setContacts(dmpContactImportExports);
} }
List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class).dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActives(IsActive.Active).collect(); List<DmpUserEntity> dmpUsers = this.queryFactory.query(DmpUserQuery.class).disableTracking().dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActives(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpUsers)) { if (!this.conventionService.isListNullOrEmpty(dmpUsers)) {
List<UserEntity> users = this.queryFactory.query(UserQuery.class).ids(dmpUsers.stream().map(DmpUserEntity::getUserId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<UserEntity> users = this.queryFactory.query(UserQuery.class).disableTracking().ids(dmpUsers.stream().map(DmpUserEntity::getUserId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
Map<UUID, UserEntity> usersMap = users == null ? new HashMap<>() : users.stream().collect(Collectors.toMap(UserEntity::getId, x-> x)); Map<UUID, UserEntity> usersMap = users == null ? new HashMap<>() : users.stream().collect(Collectors.toMap(UserEntity::getId, x-> x));
List<DmpUserImportExport> dmpUserImportExports = new LinkedList<>(); List<DmpUserImportExport> dmpUserImportExports = new LinkedList<>();
for (DmpUserEntity dmpUserEntity : dmpUsers) { for (DmpUserEntity dmpUserEntity : dmpUsers) {
@ -1404,12 +1404,12 @@ public class DmpServiceImpl implements DmpService {
} }
xml.setUsers(dmpUserImportExports); xml.setUsers(dmpUserImportExports);
} }
DmpBlueprintEntity blueprintEntity = this.queryFactory.query(DmpBlueprintQuery.class).ids(data.getBlueprintId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first(); DmpBlueprintEntity blueprintEntity = this.queryFactory.query(DmpBlueprintQuery.class).disableTracking().ids(data.getBlueprintId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).first();
if (blueprintEntity != null) { if (blueprintEntity != null) {
xml.setBlueprint(this.dmpBlueprintService.getExportXmlEntity(blueprintEntity.getId(), true)); xml.setBlueprint(this.dmpBlueprintService.getExportXmlEntity(blueprintEntity.getId(), true));
} }
List<DmpDescriptionTemplateEntity> dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).dmpIds(data.getId()).isActive(IsActive.Active).collect(); List<DmpDescriptionTemplateEntity> dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).dmpIds(data.getId()).isActive(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpDescriptionTemplateEntities)) { if (!this.conventionService.isListNullOrEmpty(dmpDescriptionTemplateEntities)) {
List<DmpDescriptionTemplateImportExport> dmpDescriptionTemplateImportExports = new LinkedList<>(); List<DmpDescriptionTemplateImportExport> dmpDescriptionTemplateImportExports = new LinkedList<>();
for (DmpDescriptionTemplateEntity descriptionTemplateEntity : dmpDescriptionTemplateEntities) { for (DmpDescriptionTemplateEntity descriptionTemplateEntity : dmpDescriptionTemplateEntities) {
@ -1426,11 +1426,11 @@ public class DmpServiceImpl implements DmpService {
xml.setBlueprintValues(dmpDescriptionTemplateImportExports); xml.setBlueprintValues(dmpDescriptionTemplateImportExports);
} }
List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class).dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActives(IsActive.Active).collect(); List<DmpReferenceEntity> dmpReferences = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActives(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(dmpReferences)) { if (!this.conventionService.isListNullOrEmpty(dmpReferences)) {
List<ReferenceEntity> references = this.queryFactory.query(ReferenceQuery.class).ids(dmpReferences.stream().map(DmpReferenceEntity::getReferenceId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect(); List<ReferenceEntity> references = this.queryFactory.query(ReferenceQuery.class).disableTracking().ids(dmpReferences.stream().map(DmpReferenceEntity::getReferenceId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).isActive(IsActive.Active).collect();
Map<UUID, ReferenceEntity> referenceEntityMap = references == null ? new HashMap<>() : references.stream().collect(Collectors.toMap(ReferenceEntity::getId, x-> x)); Map<UUID, ReferenceEntity> referenceEntityMap = references == null ? new HashMap<>() : references.stream().collect(Collectors.toMap(ReferenceEntity::getId, x-> x));
List<ReferenceTypeEntity> referenceTypes = references == null ? new ArrayList<>() : this.queryFactory.query(ReferenceTypeQuery.class).ids(references.stream().map(ReferenceEntity::getTypeId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).collect(); List<ReferenceTypeEntity> referenceTypes = references == null ? new ArrayList<>() : this.queryFactory.query(ReferenceTypeQuery.class).disableTracking().ids(references.stream().map(ReferenceEntity::getTypeId).distinct().toList()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).collect();
Map<UUID, ReferenceTypeEntity> referenceTypeEntityMap = referenceTypes == null ? new HashMap<>() : referenceTypes.stream().collect(Collectors.toMap(ReferenceTypeEntity::getId, x-> x)); Map<UUID, ReferenceTypeEntity> referenceTypeEntityMap = referenceTypes == null ? new HashMap<>() : referenceTypes.stream().collect(Collectors.toMap(ReferenceTypeEntity::getId, x-> x));
List<DmpReferenceImportExport> dmpReferenceImportExports = new LinkedList<>(); List<DmpReferenceImportExport> dmpReferenceImportExports = new LinkedList<>();
for (DmpReferenceEntity descriptionTemplateEntity : dmpReferences) { for (DmpReferenceEntity descriptionTemplateEntity : dmpReferences) {
@ -1438,7 +1438,7 @@ public class DmpServiceImpl implements DmpService {
} }
xml.setReferences(dmpReferenceImportExports); xml.setReferences(dmpReferenceImportExports);
} }
List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).dmpIds(data.getId()).isActive(IsActive.Active).collect(); List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).disableTracking().dmpIds(data.getId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).dmpIds(data.getId()).isActive(IsActive.Active).collect();
if (!this.conventionService.isListNullOrEmpty(descriptions)) { if (!this.conventionService.isListNullOrEmpty(descriptions)) {
List<DescriptionImportExport> descriptionImportExports = new LinkedList<>(); List<DescriptionImportExport> descriptionImportExports = new LinkedList<>();
for (DescriptionEntity description : descriptions) { for (DescriptionEntity description : descriptions) {

View File

@ -27,10 +27,10 @@ import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.DmpBlueprintEntity; import org.opencdmp.data.DmpBlueprintEntity;
import org.opencdmp.data.TenantEntityManager; import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.errorcode.ErrorThesaurusProperties; import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.model.dmpblueprint.DmpBlueprint;
import org.opencdmp.model.builder.dmpblueprint.DmpBlueprintBuilder; import org.opencdmp.model.builder.dmpblueprint.DmpBlueprintBuilder;
import org.opencdmp.model.deleter.DmpBlueprintDeleter; import org.opencdmp.model.deleter.DmpBlueprintDeleter;
import org.opencdmp.model.dmpblueprint.Definition; import org.opencdmp.model.dmpblueprint.Definition;
import org.opencdmp.model.dmpblueprint.DmpBlueprint;
import org.opencdmp.model.dmpblueprint.Field; import org.opencdmp.model.dmpblueprint.Field;
import org.opencdmp.model.dmpblueprint.Section; import org.opencdmp.model.dmpblueprint.Section;
import org.opencdmp.model.persist.DmpBlueprintPersist; import org.opencdmp.model.persist.DmpBlueprintPersist;
@ -169,6 +169,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
if (newStatus.equals(DmpBlueprintStatus.Finalized)) { if (newStatus.equals(DmpBlueprintStatus.Finalized)) {
List<DmpBlueprintEntity> latestVersionDmpBlueprints = this.queryFactory.query(DmpBlueprintQuery.class) List<DmpBlueprintEntity> latestVersionDmpBlueprints = this.queryFactory.query(DmpBlueprintQuery.class)
.disableTracking()
.versionStatuses(DmpBlueprintVersionStatus.Current) .versionStatuses(DmpBlueprintVersionStatus.Current)
.isActive(IsActive.Active) .isActive(IsActive.Active)
.groupIds(data.getGroupId()) .groupIds(data.getGroupId())
@ -321,7 +322,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
} }
public boolean fieldInBlueprint(UUID id, DmpBlueprintSystemFieldType type) throws InvalidApplicationException { public boolean fieldInBlueprint(UUID id, DmpBlueprintSystemFieldType type) throws InvalidApplicationException {
DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, id); DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, id, true);
if (data == null) if (data == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
return this.fieldInBlueprint(data, type); return this.fieldInBlueprint(data, type);
@ -336,7 +337,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
this.authorizationService.authorizeForce(Permission.CloneDmpBlueprint); this.authorizationService.authorizeForce(Permission.CloneDmpBlueprint);
DmpBlueprintQuery query = this.queryFactory.query(DmpBlueprintQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id); DmpBlueprintQuery query = this.queryFactory.query(DmpBlueprintQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(id);
DmpBlueprint model = this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(fields, query.firstAs(fields)); DmpBlueprint model = this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(fields, query.firstAs(fields));
if (model == null) if (model == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -389,7 +390,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
this.authorizationService.authorizeForce(Permission.CreateNewVersionDmpBlueprint); this.authorizationService.authorizeForce(Permission.CreateNewVersionDmpBlueprint);
DmpBlueprintEntity oldDmpBlueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, model.getId()); DmpBlueprintEntity oldDmpBlueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, model.getId(), true);
if (oldDmpBlueprintEntity == null) if (oldDmpBlueprintEntity == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(oldDmpBlueprintEntity.getUpdatedAt()).equals(model.getHash())) if (!this.conventionService.hashValue(oldDmpBlueprintEntity.getUpdatedAt()).equals(model.getHash()))
@ -397,6 +398,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
if (!this.tenantScope.isSet() || !Objects.equals(oldDmpBlueprintEntity.getTenantId(), this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); if (!this.tenantScope.isSet() || !Objects.equals(oldDmpBlueprintEntity.getTenantId(), this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage());
List<DmpBlueprintEntity> latestVersionDmpBlueprints = this.queryFactory.query(DmpBlueprintQuery.class) List<DmpBlueprintEntity> latestVersionDmpBlueprints = this.queryFactory.query(DmpBlueprintQuery.class)
.disableTracking()
.versionStatuses(DmpBlueprintVersionStatus.Current) .versionStatuses(DmpBlueprintVersionStatus.Current)
.isActive(IsActive.Active) .isActive(IsActive.Active)
.statuses(DmpBlueprintStatus.Finalized) .statuses(DmpBlueprintStatus.Finalized)
@ -409,6 +411,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
if (!latestVersionDmpBlueprints.getFirst().getVersion().equals(oldDmpBlueprintEntity.getVersion())) if (!latestVersionDmpBlueprints.getFirst().getVersion().equals(oldDmpBlueprintEntity.getVersion()))
throw new MyValidationException(this.errors.getDmpBlueprintNewVersionConflict().getCode(), this.errors.getDmpBlueprintNewVersionConflict().getMessage()); throw new MyValidationException(this.errors.getDmpBlueprintNewVersionConflict().getCode(), this.errors.getDmpBlueprintNewVersionConflict().getMessage());
Long notFinalizedCount = this.queryFactory.query(DmpBlueprintQuery.class) Long notFinalizedCount = this.queryFactory.query(DmpBlueprintQuery.class)
.disableTracking()
.versionStatuses(DmpBlueprintVersionStatus.NotFinalized) .versionStatuses(DmpBlueprintVersionStatus.NotFinalized)
.groupIds(oldDmpBlueprintEntity.getGroupId()) .groupIds(oldDmpBlueprintEntity.getGroupId())
.isActive(IsActive.Active) .isActive(IsActive.Active)
@ -449,7 +452,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDmpBlueprint); if (!ignoreAuthorize) this.authorizationService.authorizeForce(Permission.ExportDmpBlueprint);
DmpBlueprintEntity data = this.queryFactory.query(DmpBlueprintQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first(); DmpBlueprintEntity data = this.queryFactory.query(DmpBlueprintQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
return this.definitionXmlToExport(data); return this.definitionXmlToExport(data);
@ -459,7 +462,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
@Override @Override
public ResponseEntity<byte[]> exportXml(UUID id) throws MyForbiddenException, MyNotFoundException, JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, TransformerException, InvalidApplicationException { public ResponseEntity<byte[]> exportXml(UUID id) throws MyForbiddenException, MyNotFoundException, JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, TransformerException, InvalidApplicationException {
logger.debug(new MapLogEntry("export xml").And("id", id)); logger.debug(new MapLogEntry("export xml").And("id", id));
DmpBlueprintEntity data = this.queryFactory.query(DmpBlueprintQuery.class).ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first(); DmpBlueprintEntity data = this.queryFactory.query(DmpBlueprintQuery.class).disableTracking().ids(id).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).isActive(IsActive.Active).first();
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String xml = this.xmlHandlingService.toXml(this.getExportXmlEntity(id, false)); String xml = this.xmlHandlingService.toXml(this.getExportXmlEntity(id, false));
@ -599,7 +602,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
persist.setDefinition(this.xmlDefinitionToPersist(dmpDefinition.getDmpBlueprintDefinition())); persist.setDefinition(this.xmlDefinitionToPersist(dmpDefinition.getDmpBlueprintDefinition()));
if (dmpDefinition.getId() != null) { if (dmpDefinition.getId() != null) {
persist.setId(dmpDefinition.getId()); persist.setId(dmpDefinition.getId());
DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, dmpDefinition.getId()); DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, dmpDefinition.getId(), true);
if (data == null) { if (data == null) {
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpDefinition.getId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpDefinition.getId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} }

View File

@ -61,7 +61,7 @@ public class ElasticQueryHelperServiceImpl implements ElasticQueryHelperService
query.setOrder(lookup.enrich(this.queryFactory).getOrder()); query.setOrder(lookup.enrich(this.queryFactory).getOrder());
if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(lookup.enrichElastic(this.queryFactory).authorize(flags).count()); if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(lookup.enrichElastic(this.queryFactory).authorize(flags).count());
} else { } else {
query = lookup.enrich(this.queryFactory).authorize(flags); query = lookup.enrich(this.queryFactory).disableTracking().authorize(flags);
if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(query.count()); if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(query.count());
} }
result.setItems(buildFunc.apply(query.collect())); result.setItems(buildFunc.apply(query.collect()));
@ -102,7 +102,7 @@ public class ElasticQueryHelperServiceImpl implements ElasticQueryHelperService
query.setOrder(lookup.enrich(this.queryFactory).getOrder()); query.setOrder(lookup.enrich(this.queryFactory).getOrder());
if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(lookup.enrichElastic(this.queryFactory).authorize(flags).count()); if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(lookup.enrichElastic(this.queryFactory).authorize(flags).count());
} else { } else {
query = lookup.enrich(this.queryFactory).authorize(flags); query = lookup.enrich(this.queryFactory).disableTracking().authorize(flags);
if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(query.count()); if (lookup.getMetadata() != null && lookup.getMetadata().countAll) result.setCount(query.count());
} }
result.setItems(buildFunc.apply(query.collect())); result.setItems(buildFunc.apply(query.collect()));

View File

@ -280,7 +280,7 @@ public class ElasticServiceImpl implements ElasticService {
DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmp); DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmp);
this.elasticsearchTemplate.save(dmpElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName())); this.elasticsearchTemplate.save(dmpElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName()));
List<DescriptionElasticEntity> descriptions = this.builderFactory.builder(DescriptionElasticBuilder.class).build(this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).dmpSubQuery(this.queryFactory.query(DmpQuery.class).ids(dmp.getId())).collect()); List<DescriptionElasticEntity> descriptions = this.builderFactory.builder(DescriptionElasticBuilder.class).build(this.queryFactory.query(DescriptionQuery.class).disableTracking().isActive(IsActive.Active).dmpSubQuery(this.queryFactory.query(DmpQuery.class).ids(dmp.getId())).collect());
this.elasticsearchTemplate.save(descriptions, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName())); this.elasticsearchTemplate.save(descriptions, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName()));
} }
@ -291,7 +291,7 @@ public class ElasticServiceImpl implements ElasticService {
DmpElasticEntity dmpElasticEntity = this.elasticsearchTemplate.get(dmp.getId().toString(),DmpElasticEntity.class, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName())); DmpElasticEntity dmpElasticEntity = this.elasticsearchTemplate.get(dmp.getId().toString(),DmpElasticEntity.class, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName()));
if (dmpElasticEntity == null) return; if (dmpElasticEntity == null) return;
this.elasticsearchTemplate.delete(dmpElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName())); this.elasticsearchTemplate.delete(dmpElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDmpIndexName()));
List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).dmpSubQuery(this.queryFactory.query(DmpQuery.class).ids(dmp.getId())).collectAs(new BaseFieldSet().ensure(Description._id)); List<DescriptionEntity> descriptions = this.queryFactory.query(DescriptionQuery.class).dmpSubQuery(this.queryFactory.query(DmpQuery.class).disableTracking().ids(dmp.getId())).collectAs(new BaseFieldSet().ensure(Description._id));
for (DescriptionEntity description: descriptions) { for (DescriptionEntity description: descriptions) {
DescriptionElasticEntity descriptionElasticEntity = this.elasticsearchTemplate.get(description.getId().toString(), DescriptionElasticEntity.class, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName())); DescriptionElasticEntity descriptionElasticEntity = this.elasticsearchTemplate.get(description.getId().toString(), DescriptionElasticEntity.class, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName()));
if (descriptionElasticEntity == null) continue; if (descriptionElasticEntity == null) continue;
@ -306,7 +306,7 @@ public class ElasticServiceImpl implements ElasticService {
DescriptionElasticEntity descriptionElasticEntity = this.builderFactory.builder(DescriptionElasticBuilder.class).build(description); DescriptionElasticEntity descriptionElasticEntity = this.builderFactory.builder(DescriptionElasticBuilder.class).build(description);
this.elasticsearchTemplate.save(descriptionElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName())); this.elasticsearchTemplate.save(descriptionElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName()));
DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, description.getDmpId()); DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, description.getDmpId(), true);
if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{description.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{description.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (dmpEntity.getIsActive().equals(IsActive.Active)) { if (dmpEntity.getIsActive().equals(IsActive.Active)) {
DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmpEntity); DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmpEntity);
@ -323,7 +323,7 @@ public class ElasticServiceImpl implements ElasticService {
if (descriptionElasticEntity == null) return; if (descriptionElasticEntity == null) return;
this.elasticsearchTemplate.delete(descriptionElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName())); this.elasticsearchTemplate.delete(descriptionElasticEntity, IndexCoordinates.of(this.appElasticProperties.getDescriptionIndexName()));
DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, description.getDmpId()); DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, description.getDmpId(), true);
if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{description.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{description.getDmpId(), Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (dmpEntity.getIsActive().equals(IsActive.Active)) { if (dmpEntity.getIsActive().equals(IsActive.Active)) {
DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmpEntity); DmpElasticEntity dmpElasticEntity = this.builderFactory.builder(DmpElasticBuilder.class).build(dmpEntity);
@ -373,7 +373,7 @@ public class ElasticServiceImpl implements ElasticService {
int pageSize = this.appElasticProperties.getResetBatchSize(); int pageSize = this.appElasticProperties.getResetBatchSize();
List<DmpEntity> items; List<DmpEntity> items;
do { do {
DmpQuery query = this.queryFactory.query(DmpQuery.class); DmpQuery query = this.queryFactory.query(DmpQuery.class).disableTracking();
query.setOrder(new Ordering().addAscending(Dmp._createdAt)); query.setOrder(new Ordering().addAscending(Dmp._createdAt));
query.setPage(new Paging(page * pageSize, pageSize)); query.setPage(new Paging(page * pageSize, pageSize));
@ -405,7 +405,7 @@ public class ElasticServiceImpl implements ElasticService {
int pageSize = this.appElasticProperties.getResetBatchSize(); int pageSize = this.appElasticProperties.getResetBatchSize();
List<DescriptionEntity> items; List<DescriptionEntity> items;
do { do {
DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class); DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).disableTracking();
query.setOrder(new Ordering().addAscending(Description._createdAt)); query.setOrder(new Ordering().addAscending(Description._createdAt));
query.setPage(new Paging(page * pageSize, pageSize)); query.setPage(new Paging(page * pageSize, pageSize));

View File

@ -1,5 +1,13 @@
package org.opencdmp.service.filetransformer; package org.opencdmp.service.filetransformer;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeCacheService;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeFilterFunction;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeModel;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.fieldset.BaseFieldSet;
import org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commonmodels.models.FileEnvelopeModel; import org.opencdmp.commonmodels.models.FileEnvelopeModel;
@ -16,10 +24,10 @@ import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.TenantConfigurationEntity; import org.opencdmp.data.TenantConfigurationEntity;
import org.opencdmp.event.TenantConfigurationTouchedEvent; import org.opencdmp.event.TenantConfigurationTouchedEvent;
import org.opencdmp.filetransformerbase.interfaces.FileTransformerConfiguration; import org.opencdmp.filetransformerbase.interfaces.FileTransformerConfiguration;
import org.opencdmp.model.description.Description;
import org.opencdmp.model.dmp.Dmp;
import org.opencdmp.model.builder.commonmodels.description.DescriptionCommonModelBuilder; import org.opencdmp.model.builder.commonmodels.description.DescriptionCommonModelBuilder;
import org.opencdmp.model.builder.commonmodels.dmp.DmpCommonModelBuilder; import org.opencdmp.model.builder.commonmodels.dmp.DmpCommonModelBuilder;
import org.opencdmp.model.description.Description;
import org.opencdmp.model.dmp.Dmp;
import org.opencdmp.model.file.RepositoryFileFormat; import org.opencdmp.model.file.RepositoryFileFormat;
import org.opencdmp.model.tenantconfiguration.TenantConfiguration; import org.opencdmp.model.tenantconfiguration.TenantConfiguration;
import org.opencdmp.query.DescriptionQuery; import org.opencdmp.query.DescriptionQuery;
@ -28,14 +36,6 @@ import org.opencdmp.query.TenantConfigurationQuery;
import org.opencdmp.service.encryption.EncryptionService; import org.opencdmp.service.encryption.EncryptionService;
import org.opencdmp.service.storage.StorageFileService; import org.opencdmp.service.storage.StorageFileService;
import org.opencdmp.service.tenant.TenantProperties; import org.opencdmp.service.tenant.TenantProperties;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeCacheService;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeFilterFunction;
import gr.cite.commons.web.oidc.filter.webflux.TokenExchangeModel;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.fieldset.BaseFieldSet;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -123,7 +123,7 @@ public class FileTransformerServiceImpl implements FileTransformerService {
if (cacheValue == null) { if (cacheValue == null) {
List<FileTransformerSourceEntity> fileTransformerSourceEntities = new ArrayList<>(this.fileTransformerProperties.getSources()); List<FileTransformerSourceEntity> fileTransformerSourceEntities = new ArrayList<>(this.fileTransformerProperties.getSources());
if (this.tenantScope.isSet() && this.tenantScope.isMultitenant()) { if (this.tenantScope.isSet() && this.tenantScope.isMultitenant()) {
TenantConfigurationQuery tenantConfigurationQuery = this.queryFactory.query(TenantConfigurationQuery.class).isActive(IsActive.Active).types(TenantConfigurationType.FileTransformerPlugins); TenantConfigurationQuery tenantConfigurationQuery = this.queryFactory.query(TenantConfigurationQuery.class).disableTracking().isActive(IsActive.Active).types(TenantConfigurationType.FileTransformerPlugins);
if (this.tenantScope.isDefaultTenant()) tenantConfigurationQuery.tenantIsSet(false); if (this.tenantScope.isDefaultTenant()) tenantConfigurationQuery.tenantIsSet(false);
else tenantConfigurationQuery.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); else tenantConfigurationQuery.tenantIsSet(true).tenantIds(this.tenantScope.getTenant());
TenantConfigurationEntity tenantConfiguration = tenantConfigurationQuery.firstAs(new BaseFieldSet().ensure(TenantConfiguration._fileTransformerPlugins)); TenantConfigurationEntity tenantConfiguration = tenantConfigurationQuery.firstAs(new BaseFieldSet().ensure(TenantConfiguration._fileTransformerPlugins));
@ -226,7 +226,7 @@ public class FileTransformerServiceImpl implements FileTransformerService {
FileTransformerRepository repository = this.getRepository(repositoryId); FileTransformerRepository repository = this.getRepository(repositoryId);
if (repository == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{format, FileTransformerRepository.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (repository == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{format, FileTransformerRepository.class.getSimpleName()}, LocaleContextHolder.getLocale()));
//GK: Second get the Target Data Management Plan //GK: Second get the Target Data Management Plan
DmpQuery query = this.queryFactory.query(DmpQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(dmpId); DmpQuery query = this.queryFactory.query(DmpQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(dmpId);
DmpModel dmpFileTransformerModel = this.builderFactory.builder(DmpCommonModelBuilder.class).useSharedStorage(repository.getConfiguration().isUseSharedStorage()).setRepositoryId(repository.getConfiguration().getFileTransformerId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(query.first()); DmpModel dmpFileTransformerModel = this.builderFactory.builder(DmpCommonModelBuilder.class).useSharedStorage(repository.getConfiguration().isUseSharedStorage()).setRepositoryId(repository.getConfiguration().getFileTransformerId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(query.first());
if (dmpFileTransformerModel == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpId, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (dmpFileTransformerModel == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{dmpId, Dmp.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -247,7 +247,7 @@ public class FileTransformerServiceImpl implements FileTransformerService {
if (repository == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{format, FileTransformerRepository.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (repository == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{format, FileTransformerRepository.class.getSimpleName()}, LocaleContextHolder.getLocale()));
//GK: Second get the Target Data Management Plan //GK: Second get the Target Data Management Plan
DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(descriptionId); DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).ids(descriptionId);
DescriptionModel descriptionFileTransformerModel = this.builderFactory.builder(DescriptionCommonModelBuilder.class).setRepositoryId(repository.getConfiguration().getFileTransformerId()).useSharedStorage(repository.getConfiguration().isUseSharedStorage()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(query.first()); DescriptionModel descriptionFileTransformerModel = this.builderFactory.builder(DescriptionCommonModelBuilder.class).setRepositoryId(repository.getConfiguration().getFileTransformerId()).useSharedStorage(repository.getConfiguration().isUseSharedStorage()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).build(query.first());
if (descriptionFileTransformerModel == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionId, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionFileTransformerModel == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{descriptionId, Description.class.getSimpleName()}, LocaleContextHolder.getLocale()));

View File

@ -1,5 +1,16 @@
package org.opencdmp.service.language; package org.opencdmp.service.language;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.IsActive; import org.opencdmp.commons.enums.IsActive;
@ -13,18 +24,6 @@ import org.opencdmp.model.deleter.LanguageDeleter;
import org.opencdmp.model.persist.LanguagePersist; import org.opencdmp.model.persist.LanguagePersist;
import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl; import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl;
import org.opencdmp.service.storage.StorageFileService; import org.opencdmp.service.storage.StorageFileService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.hibernate.FlushMode;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
@ -76,7 +75,7 @@ public class LanguageServiceImpl implements LanguageService {
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(LanguageEntity.class, model.getId()); data = this.entityManager.find(LanguageEntity.class, model.getId());
if (data == null) if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Language.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Language.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {

View File

@ -1,5 +1,17 @@
package org.opencdmp.service.lock; package org.opencdmp.service.lock;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.opencdmp.authorization.AffiliatedResource; import org.opencdmp.authorization.AffiliatedResource;
import org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
@ -16,18 +28,6 @@ import org.opencdmp.model.builder.LockBuilder;
import org.opencdmp.model.deleter.LockDeleter; import org.opencdmp.model.deleter.LockDeleter;
import org.opencdmp.model.persist.LockPersist; import org.opencdmp.model.persist.LockPersist;
import org.opencdmp.query.LockQuery; import org.opencdmp.query.LockQuery;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -94,7 +94,7 @@ public class LockServiceImpl implements LockService {
LockEntity data; LockEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(LockEntity.class, model.getId()); data = this.entityManager.find(LockEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Lock.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Lock.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!data.getLockedBy().equals(this.userScope.getUserId())) throw new MyApplicationException("Is not locked by that user"); if (!data.getLockedBy().equals(this.userScope.getUserId())) throw new MyApplicationException("Is not locked by that user");
if (!this.conventionService.hashValue(data.getTouchedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getTouchedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {
@ -118,7 +118,7 @@ public class LockServiceImpl implements LockService {
public LockStatus isLocked(UUID target, FieldSet fields) throws InvalidApplicationException { public LockStatus isLocked(UUID target, FieldSet fields) throws InvalidApplicationException {
LockStatus lockStatus = new LockStatus(); LockStatus lockStatus = new LockStatus();
LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first(); LockEntity lock = this.queryFactory.query(LockQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first();
if (lock == null) { if (lock == null) {
lockStatus.setStatus(false); lockStatus.setStatus(false);
@ -127,7 +127,7 @@ public class LockServiceImpl implements LockService {
if (lock.getLockedBy().equals(this.userScope.getUserId())) lockStatus.setStatus(false); if (lock.getLockedBy().equals(this.userScope.getUserId())) lockStatus.setStatus(false);
else { else {
if (new Date().getTime() - Date.from(lock.getTouchedAt()).getTime() > lockProperties.getLockInterval()) { if (new Date().getTime() - Date.from(lock.getTouchedAt()).getTime() > this.lockProperties.getLockInterval()) {
lockStatus.setStatus(false); lockStatus.setStatus(false);
this.deleteAndSave(lock.getId(), lock.getTarget()); this.deleteAndSave(lock.getId(), lock.getTarget());
} else lockStatus.setStatus(true); } else lockStatus.setStatus(true);
@ -138,7 +138,7 @@ public class LockServiceImpl implements LockService {
} }
public void lock(UUID target, LockTargetType targetType) throws InvalidApplicationException { public void lock(UUID target, LockTargetType targetType) throws InvalidApplicationException {
LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first(); LockEntity lock = this.queryFactory.query(LockQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first();
if (lock == null) { if (lock == null) {
this.persist(new LockPersist(target, targetType), null); this.persist(new LockPersist(target, targetType), null);
}else{ }else{
@ -151,7 +151,7 @@ public class LockServiceImpl implements LockService {
public void touch(UUID target) throws InvalidApplicationException { public void touch(UUID target) throws InvalidApplicationException {
LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first(); LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first();
if (lock == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{target, Lock.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (lock == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{target, Lock.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!lock.getLockedBy().equals(this.userScope.getUserId())) throw new MyApplicationException("Only the user who created that lock can touch it"); if (!lock.getLockedBy().equals(this.userScope.getUserId())) throw new MyApplicationException("Only the user who created that lock can touch it");
lock.setTouchedAt(Instant.now()); lock.setTouchedAt(Instant.now());
@ -162,7 +162,7 @@ public class LockServiceImpl implements LockService {
public void unlock(UUID target) throws InvalidApplicationException { public void unlock(UUID target) throws InvalidApplicationException {
LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first(); LockEntity lock = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).targetIds(target).first();
if (lock == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{target, Lock.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (lock == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{target, Lock.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!lock.getLockedBy().equals(this.userScope.getUserId())) { if (!lock.getLockedBy().equals(this.userScope.getUserId())) {
throw new InvalidApplicationException("Only the user who created that lock can delete it"); throw new InvalidApplicationException("Only the user who created that lock can delete it");
} }

View File

@ -1,5 +1,9 @@
package org.opencdmp.service.maintenance; package org.opencdmp.service.maintenance;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.logging.LoggerService;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.IsActive; import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.data.TenantEntity; import org.opencdmp.data.TenantEntity;
@ -14,10 +18,6 @@ import org.opencdmp.model.Tenant;
import org.opencdmp.model.user.User; import org.opencdmp.model.user.User;
import org.opencdmp.query.TenantQuery; import org.opencdmp.query.TenantQuery;
import org.opencdmp.query.UserQuery; import org.opencdmp.query.UserQuery;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.logging.LoggerService;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -63,7 +63,7 @@ public class MaintenanceServiceImpl implements MaintenanceService {
List<UserEntity> inactiveUsers; List<UserEntity> inactiveUsers;
try { try {
this.entityManager.disableTenantFilters(); this.entityManager.disableTenantFilters();
UserQuery userQuery = queryFactory.query(UserQuery.class); UserQuery userQuery = this.queryFactory.query(UserQuery.class).disableTracking();
userQuery.isActive(IsActive.Active); userQuery.isActive(IsActive.Active);
activeUsers = userQuery.collectAs(new BaseFieldSet().ensure(User._id)); activeUsers = userQuery.collectAs(new BaseFieldSet().ensure(User._id));
userQuery.isActive(IsActive.Inactive); userQuery.isActive(IsActive.Inactive);
@ -89,7 +89,7 @@ public class MaintenanceServiceImpl implements MaintenanceService {
List<TenantEntity> inactiveTenants; List<TenantEntity> inactiveTenants;
try { try {
this.entityManager.disableTenantFilters(); this.entityManager.disableTenantFilters();
TenantQuery tenantQuery = queryFactory.query(TenantQuery.class); TenantQuery tenantQuery = this.queryFactory.query(TenantQuery.class).disableTracking();
tenantQuery.isActive(IsActive.Active); tenantQuery.isActive(IsActive.Active);
activeTenants = tenantQuery.collectAs(new BaseFieldSet().ensure(Tenant._id).ensure(Tenant._code)); activeTenants = tenantQuery.collectAs(new BaseFieldSet().ensure(Tenant._id).ensure(Tenant._code));
tenantQuery.isActive(IsActive.Inactive); tenantQuery.isActive(IsActive.Inactive);

View File

@ -1,5 +1,11 @@
package org.opencdmp.service.metrics; package org.opencdmp.service.metrics;
import gr.cite.commons.web.keycloak.api.configuration.KeycloakClientProperties;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.logging.LoggerService;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Gauge;
import org.opencdmp.commons.enums.*; import org.opencdmp.commons.enums.*;
import org.opencdmp.commons.metrics.MetricLabels; import org.opencdmp.commons.metrics.MetricLabels;
import org.opencdmp.commons.metrics.MetricNames; import org.opencdmp.commons.metrics.MetricNames;
@ -7,12 +13,6 @@ import org.opencdmp.data.DmpDescriptionTemplateEntity;
import org.opencdmp.data.TenantEntityManager; import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.query.*; import org.opencdmp.query.*;
import org.opencdmp.service.keycloak.MyKeycloakAdminRestApi; import org.opencdmp.service.keycloak.MyKeycloakAdminRestApi;
import gr.cite.commons.web.keycloak.api.configuration.KeycloakClientProperties;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.logging.LoggerService;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Gauge;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -58,61 +58,61 @@ public class MetricsServiceImpl implements MetricsService {
try { try {
this.entityManager.disableTenantFilters(); this.entityManager.disableTenantFilters();
this.setGaugeValue(gauges, MetricNames.DMP, calculateDraftDmps(false), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.DMP, this.calculateDraftDmps(false), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.DMP, calculateFinalizedDmps(false), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.DMP, this.calculateFinalizedDmps(false), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.DMP, calculatePublishedDmps(false), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.DMP, this.calculatePublishedDmps(false), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.DMP, calculateDoiedDmps(false), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.DMP, this.calculateDoiedDmps(false), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, calculateDraftDmps(true), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, this.calculateDraftDmps(true), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, calculateFinalizedDmps(true), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, this.calculateFinalizedDmps(true), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, calculatePublishedDmps(true), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, this.calculatePublishedDmps(true), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, calculateDoiedDmps(true), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP, this.calculateDoiedDmps(true), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, calculateDraftDmpsWithGrant(false), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, this.calculateDraftDmpsWithGrant(false), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, calculateFinalizedDmpsWithGrant(false), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, this.calculateFinalizedDmpsWithGrant(false), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, calculatePublishedDmpsWithGrant(false), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, this.calculatePublishedDmpsWithGrant(false), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, calculateDoiedDmpsWithGrant(false), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.DMP_WITH_GRANT, this.calculateDoiedDmpsWithGrant(false), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, calculateDraftDmpsWithGrant(true), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, this.calculateDraftDmpsWithGrant(true), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, calculateFinalizedDmpsWithGrant(true), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, this.calculateFinalizedDmpsWithGrant(true), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, calculatePublishedDmpsWithGrant(true), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, this.calculatePublishedDmpsWithGrant(true), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, calculateDoiedDmpsWithGrant(true), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, this.calculateDoiedDmpsWithGrant(true), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.FUNDERS, calculateAllFunders(false), null); this.setGaugeValue(gauges, MetricNames.FUNDERS, this.calculateAllFunders(false), null);
this.setGaugeValue(gauges, MetricNames.GRANTS, calculateAllGrants(false), null); this.setGaugeValue(gauges, MetricNames.GRANTS, this.calculateAllGrants(false), null);
this.setGaugeValue(gauges, MetricNames.PROJECTS, calculateAllProjects(false), null); this.setGaugeValue(gauges, MetricNames.PROJECTS, this.calculateAllProjects(false), null);
this.setGaugeValue(gauges, MetricNames.RESEARCHERS, calculateAllResearchers(false), null); this.setGaugeValue(gauges, MetricNames.RESEARCHERS, this.calculateAllResearchers(false), null);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS, calculateAllFunders(true), null); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS, this.calculateAllFunders(true), null);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.GRANTS, calculateAllGrants(true), null); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.GRANTS, this.calculateAllGrants(true), null);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS, calculateAllProjects(true), null); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS, this.calculateAllProjects(true), null);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS, calculateAllResearchers(true), null); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS, this.calculateAllResearchers(true), null);
this.setGaugeValue(gauges, MetricNames.DATASET, calculateDraftDatasets(false), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.DATASET, this.calculateDraftDatasets(false), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.DATASET, calculateFinalizedDatasets(false), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.DATASET, this.calculateFinalizedDatasets(false), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.DATASET, calculatePublishedDatasets(false), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.DATASET, this.calculatePublishedDatasets(false), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.DATASET, calculateDoiedDatasets(false), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.DATASET, this.calculateDoiedDatasets(false), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, calculateDraftDatasets(true), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, this.calculateDraftDatasets(true), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, calculateFinalizedDatasets(true), MetricLabels.FINALIZED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, this.calculateFinalizedDatasets(true), MetricLabels.FINALIZED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, calculatePublishedDatasets(true), MetricLabels.PUBLISHED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, this.calculatePublishedDatasets(true), MetricLabels.PUBLISHED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, calculateDoiedDatasets(true), MetricLabels.DOIED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET, this.calculateDoiedDatasets(true), MetricLabels.DOIED);
this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, calculateDraftTemplates(false), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, this.calculateDraftTemplates(false), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, calculateFinalizedTemplates(false), MetricLabels.ACTIVE); this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, this.calculateFinalizedTemplates(false), MetricLabels.ACTIVE);
this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, calculateUsedTemplates(false), MetricLabels.USED); this.setGaugeValue(gauges, MetricNames.DATASET_TEMPLATE, this.calculateUsedTemplates(false), MetricLabels.USED);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, calculateDraftTemplates(true), MetricLabels.DRAFT); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, this.calculateDraftTemplates(true), MetricLabels.DRAFT);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, calculateFinalizedTemplates(true), MetricLabels.ACTIVE); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, this.calculateFinalizedTemplates(true), MetricLabels.ACTIVE);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, calculateUsedTemplates(true), MetricLabels.USED); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, this.calculateUsedTemplates(true), MetricLabels.USED);
this.setGaugeValue(gauges, MetricNames.LANGUAGES, calculateLanguages(), null); this.setGaugeValue(gauges, MetricNames.LANGUAGES, this.calculateLanguages(), null);
this.setGaugeValue(gauges, MetricNames.INSTALLATIONS, 1d, null); this.setGaugeValue(gauges, MetricNames.INSTALLATIONS, 1d, null);
this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS, 1d, null); this.setGaugeValue(gauges, MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS, 1d, null);
this.setGaugeValue(gauges, MetricNames.USERS, calculateActiveUsers(), MetricLabels.LOGGEDIN); this.setGaugeValue(gauges, MetricNames.USERS, this.calculateActiveUsers(), MetricLabels.LOGGEDIN);
this.setGaugeValue(gauges, MetricNames.USERS, calculateAllUsers(), MetricLabels.TOTAL); this.setGaugeValue(gauges, MetricNames.USERS, this.calculateAllUsers(), MetricLabels.TOTAL);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} finally { } finally {
@ -122,168 +122,168 @@ public class MetricsServiceImpl implements MetricsService {
@Override @Override
public Map<String, Gauge> gaugesBuild() { public Map<String, Gauge> gaugesBuild() {
registry.clear(); this.registry.clear();
return Stream.of(new Object[][]{ return Stream.of(new Object[][]{
{MetricNames.DMP, Gauge.build().name(MetricNames.DMP).help("Number of managed DMPs").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.DMP, Gauge.build().name(MetricNames.DMP).help("Number of managed DMPs").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.DMP, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DMP).help("Number of managed DMPs during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.DMP, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DMP).help("Number of managed DMPs during Nexus").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.FUNDERS, Gauge.build().name(MetricNames.FUNDERS).help("Number of registered Funders").register(registry.getPrometheusRegistry())}, {MetricNames.FUNDERS, Gauge.build().name(MetricNames.FUNDERS).help("Number of registered Funders").register(this.registry.getPrometheusRegistry())},
{MetricNames.GRANTS, Gauge.build().name(MetricNames.GRANTS).help("Number of registered Grants").register(registry.getPrometheusRegistry())}, {MetricNames.GRANTS, Gauge.build().name(MetricNames.GRANTS).help("Number of registered Grants").register(this.registry.getPrometheusRegistry())},
{MetricNames.PROJECTS, Gauge.build().name(MetricNames.PROJECTS).help("Number of registered Projects").register(registry.getPrometheusRegistry())}, {MetricNames.PROJECTS, Gauge.build().name(MetricNames.PROJECTS).help("Number of registered Projects").register(this.registry.getPrometheusRegistry())},
{MetricNames.RESEARCHERS, Gauge.build().name(MetricNames.RESEARCHERS).help("Number of Collaborators/Researchers").register(registry.getPrometheusRegistry())}, {MetricNames.RESEARCHERS, Gauge.build().name(MetricNames.RESEARCHERS).help("Number of Collaborators/Researchers").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS).help("Number of registered Funders during Nexus").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.FUNDERS).help("Number of registered Funders during Nexus").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.GRANTS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.GRANTS).help("Number of registered Grants during Nexus").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.GRANTS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.GRANTS).help("Number of registered Grants during Nexus").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS).help("Number of registered Projects during Nexus").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.PROJECTS).help("Number of registered Projects during Nexus").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS).help("Number of Collaborators/Researchers during Nexus").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.RESEARCHERS).help("Number of Collaborators/Researchers during Nexus").register(this.registry.getPrometheusRegistry())},
{MetricNames.DATASET, Gauge.build().name(MetricNames.DATASET).help("Number of managed Dataset Descriptions").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.DATASET, Gauge.build().name(MetricNames.DATASET).help("Number of managed Dataset Descriptions").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.DATASET, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DATASET).help("Number of managed Dataset Descriptions during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.DATASET, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DATASET).help("Number of managed Dataset Descriptions during Nexus").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates during Nexus").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.USERS, Gauge.build().name(MetricNames.USERS).help("Number of users").labelNames("type").register(registry.getPrometheusRegistry())}, {MetricNames.USERS, Gauge.build().name(MetricNames.USERS).help("Number of users").labelNames("type").register(this.registry.getPrometheusRegistry())},
{MetricNames.LANGUAGES, Gauge.build().name(MetricNames.LANGUAGES).help("Number of Languages").register(registry.getPrometheusRegistry())}, {MetricNames.LANGUAGES, Gauge.build().name(MetricNames.LANGUAGES).help("Number of Languages").register(this.registry.getPrometheusRegistry())},
{MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them during Nexus").labelNames("status").register(this.registry.getPrometheusRegistry())},
{MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.INSTALLATIONS).help("Number of Installations").register(registry.getPrometheusRegistry())}, {MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.INSTALLATIONS).help("Number of Installations").register(this.registry.getPrometheusRegistry())},
{MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS).help("Number of Installations").register(registry.getPrometheusRegistry())}, {MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.NEXUS_PREFIX + MetricNames.INSTALLATIONS).help("Number of Installations").register(this.registry.getPrometheusRegistry())},
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Gauge) data[1])); }).collect(Collectors.toMap(data -> (String) data[0], data -> (Gauge) data[1]));
} }
private double calculateDraftDmps(boolean forNexus) { private double calculateDraftDmps(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Draft).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().statuses(DmpStatus.Draft).isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateFinalizedDmps(boolean forNexus) { private double calculateFinalizedDmps(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Finalized).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().statuses(DmpStatus.Finalized).isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculatePublishedDmps(boolean forNexus) { private double calculatePublishedDmps(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Finalized).accessTypes(DmpAccessType.Public).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().statuses(DmpStatus.Finalized).accessTypes(DmpAccessType.Public).isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateDoiedDmps(boolean forNexus) { private double calculateDoiedDmps(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).types(EntityType.DMP).isActive(IsActive.Active); EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).disableTracking().types(EntityType.DMP).isActive(IsActive.Active);
dmpQuery.entityDoiSubQuery(entityDoiQuery); dmpQuery.entityDoiSubQuery(entityDoiQuery);
dmpQuery.setDistinct(true); dmpQuery.setDistinct(true);
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateDraftDmpsWithGrant(boolean forNexus) { private double calculateDraftDmpsWithGrant(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Draft).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Draft).disableTracking().isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active);
DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).referenceSubQuery(referenceQuery).isActives(IsActive.Active); DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().referenceSubQuery(referenceQuery).isActives(IsActive.Active);
dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery); dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery);
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateFinalizedDmpsWithGrant(boolean forNexus) { private double calculateFinalizedDmpsWithGrant(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Finalized).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().statuses(DmpStatus.Finalized).isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active);
DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).referenceSubQuery(referenceQuery).isActives(IsActive.Active); DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().referenceSubQuery(referenceQuery).isActives(IsActive.Active);
dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery); dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery);
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculatePublishedDmpsWithGrant(boolean forNexus) { private double calculatePublishedDmpsWithGrant(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Finalized).accessTypes(DmpAccessType.Public).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).statuses(DmpStatus.Finalized).disableTracking().accessTypes(DmpAccessType.Public).isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active);
DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).referenceSubQuery(referenceQuery).isActives(IsActive.Active); DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().referenceSubQuery(referenceQuery).isActives(IsActive.Active);
dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery); dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery);
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateDoiedDmpsWithGrant(boolean forNexus) { private double calculateDoiedDmpsWithGrant(boolean forNexus) {
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).disableTracking().isActive(IsActive.Active);
if (forNexus) if (forNexus)
dmpQuery.after(_config.getNexusDate()); dmpQuery.after(this._config.getNexusDate());
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active);
DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).referenceSubQuery(referenceQuery).isActives(IsActive.Active); DmpReferenceQuery dmpReferenceQuery = this.queryFactory.query(DmpReferenceQuery.class).disableTracking().referenceSubQuery(referenceQuery).isActives(IsActive.Active);
dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery); dmpQuery.dmpReferenceSubQuery(dmpReferenceQuery);
EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).isActive(IsActive.Active); EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).disableTracking().isActive(IsActive.Active);
dmpQuery.entityDoiSubQuery(entityDoiQuery); dmpQuery.entityDoiSubQuery(entityDoiQuery);
return dmpQuery.count(); return dmpQuery.count();
} }
private double calculateAllFunders(boolean forNexus) { private double calculateAllFunders(boolean forNexus) {
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getFunderIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getFunderIds()).isActive(IsActive.Active);
if (forNexus) if (forNexus)
referenceQuery.after(_config.getNexusDate()); referenceQuery.after(this._config.getNexusDate());
return referenceQuery.count(); return referenceQuery.count();
} }
private double calculateAllGrants(boolean forNexus) { private double calculateAllGrants(boolean forNexus) {
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getGrantIds()).isActive(IsActive.Active);
if (forNexus) if (forNexus)
referenceQuery.after(_config.getNexusDate()); referenceQuery.after(this._config.getNexusDate());
return referenceQuery.count(); return referenceQuery.count();
} }
private double calculateAllProjects(boolean forNexus) { private double calculateAllProjects(boolean forNexus) {
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getProjectIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getProjectIds()).isActive(IsActive.Active);
if (forNexus) if (forNexus)
referenceQuery.after(_config.getNexusDate()); referenceQuery.after(this._config.getNexusDate());
return referenceQuery.count(); return referenceQuery.count();
} }
private double calculateAllResearchers(boolean forNexus) { private double calculateAllResearchers(boolean forNexus) {
ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).typeIds(_config.getReferenceTypes().getResearcherIds()).isActive(IsActive.Active); ReferenceQuery referenceQuery = this.queryFactory.query(ReferenceQuery.class).disableTracking().typeIds(this._config.getReferenceTypes().getResearcherIds()).isActive(IsActive.Active);
if (forNexus) if (forNexus)
referenceQuery.after(_config.getNexusDate()); referenceQuery.after(this._config.getNexusDate());
return referenceQuery.count(); return referenceQuery.count();
} }
private double calculateDraftDatasets(boolean forNexus) { private double calculateDraftDatasets(boolean forNexus) {
DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).statuses(DescriptionStatus.Draft).isActive(IsActive.Active); DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).disableTracking().statuses(DescriptionStatus.Draft).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionQuery.createdAfter(_config.getNexusDate()); descriptionQuery.createdAfter(this._config.getNexusDate());
return descriptionQuery.count(); return descriptionQuery.count();
} }
private double calculateFinalizedDatasets(boolean forNexus) { private double calculateFinalizedDatasets(boolean forNexus) {
DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).statuses(DescriptionStatus.Finalized).isActive(IsActive.Active); DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).disableTracking().statuses(DescriptionStatus.Finalized).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionQuery.createdAfter(_config.getNexusDate()); descriptionQuery.createdAfter(this._config.getNexusDate());
return descriptionQuery.count(); return descriptionQuery.count();
} }
private double calculatePublishedDatasets(boolean forNexus) { private double calculatePublishedDatasets(boolean forNexus) {
DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).statuses(DescriptionStatus.Finalized).isActive(IsActive.Active); DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).disableTracking().statuses(DescriptionStatus.Finalized).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionQuery.createdAfter(_config.getNexusDate()); descriptionQuery.createdAfter(this._config.getNexusDate());
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active).statuses(DmpStatus.Finalized).accessTypes(DmpAccessType.Public); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active).disableTracking().statuses(DmpStatus.Finalized).accessTypes(DmpAccessType.Public);
descriptionQuery.dmpSubQuery(dmpQuery); descriptionQuery.dmpSubQuery(dmpQuery);
return descriptionQuery.count(); return descriptionQuery.count();
} }
private double calculateDoiedDatasets(boolean forNexus) { private double calculateDoiedDatasets(boolean forNexus) {
DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).statuses(DescriptionStatus.Finalized).isActive(IsActive.Active); DescriptionQuery descriptionQuery = this.queryFactory.query(DescriptionQuery.class).disableTracking().statuses(DescriptionStatus.Finalized).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionQuery.createdAfter(_config.getNexusDate()); descriptionQuery.createdAfter(this._config.getNexusDate());
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active); DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active);
EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).types(EntityType.DMP).isActive(IsActive.Active); EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).types(EntityType.DMP).isActive(IsActive.Active);
dmpQuery.entityDoiSubQuery(entityDoiQuery); dmpQuery.entityDoiSubQuery(entityDoiQuery);
@ -293,24 +293,24 @@ public class MetricsServiceImpl implements MetricsService {
} }
private double calculateDraftTemplates(boolean forNexus) { private double calculateDraftTemplates(boolean forNexus) {
DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).statuses(DescriptionTemplateStatus.Draft).isActive(IsActive.Active); DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().statuses(DescriptionTemplateStatus.Draft).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionTemplateQuery.after(_config.getNexusDate()); descriptionTemplateQuery.after(this._config.getNexusDate());
return descriptionTemplateQuery.count(); return descriptionTemplateQuery.count();
} }
private double calculateFinalizedTemplates(boolean forNexus) { private double calculateFinalizedTemplates(boolean forNexus) {
DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).statuses(DescriptionTemplateStatus.Finalized).versionStatuses(DescriptionTemplateVersionStatus.Current).isActive(IsActive.Active); DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().statuses(DescriptionTemplateStatus.Finalized).versionStatuses(DescriptionTemplateVersionStatus.Current).isActive(IsActive.Active);
if (forNexus) if (forNexus)
descriptionTemplateQuery.after(_config.getNexusDate()); descriptionTemplateQuery.after(this._config.getNexusDate());
return descriptionTemplateQuery.count(); return descriptionTemplateQuery.count();
} }
private double calculateUsedTemplates(boolean forNexus) { private double calculateUsedTemplates(boolean forNexus) {
DmpDescriptionTemplateQuery dmpDescriptionTemplateQuery = this.queryFactory.query(DmpDescriptionTemplateQuery.class).isActive(IsActive.Active); DmpDescriptionTemplateQuery dmpDescriptionTemplateQuery = this.queryFactory.query(DmpDescriptionTemplateQuery.class).disableTracking().isActive(IsActive.Active);
dmpDescriptionTemplateQuery.setDistinct(true); dmpDescriptionTemplateQuery.setDistinct(true);
if (forNexus) { if (forNexus) {
DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).after(_config.getNexusDate()); DescriptionTemplateQuery descriptionTemplateQuery = this.queryFactory.query(DescriptionTemplateQuery.class).disableTracking().isActive(IsActive.Active).after(this._config.getNexusDate());
dmpDescriptionTemplateQuery.descriptionTemplateSubQuery(descriptionTemplateQuery); dmpDescriptionTemplateQuery.descriptionTemplateSubQuery(descriptionTemplateQuery);
} }
return dmpDescriptionTemplateQuery.collectAs(new BaseFieldSet().ensure(DmpDescriptionTemplateEntity._descriptionTemplateGroupId)).size(); return dmpDescriptionTemplateQuery.collectAs(new BaseFieldSet().ensure(DmpDescriptionTemplateEntity._descriptionTemplateGroupId)).size();
@ -319,7 +319,7 @@ public class MetricsServiceImpl implements MetricsService {
private double calculateActiveUsers() { private double calculateActiveUsers() {
double result = -1; double result = -1;
try { try {
result = this.keycloakAdminRestApi.users().getUserSessionsCountByClientId(_config.getUsersLoginClient()); result = this.keycloakAdminRestApi.users().getUserSessionsCountByClientId(this._config.getUsersLoginClient());
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
@ -327,12 +327,12 @@ public class MetricsServiceImpl implements MetricsService {
} }
private double calculateAllUsers() { private double calculateAllUsers() {
UserQuery userQuery = this.queryFactory.query(UserQuery.class).isActive(IsActive.Active); UserQuery userQuery = this.queryFactory.query(UserQuery.class).disableTracking().isActive(IsActive.Active);
return userQuery.count(); return userQuery.count();
} }
private double calculateLanguages() { private double calculateLanguages() {
LanguageQuery languageQuery = this.queryFactory.query(LanguageQuery.class).isActive(IsActive.Active); LanguageQuery languageQuery = this.queryFactory.query(LanguageQuery.class).disableTracking().isActive(IsActive.Active);
return languageQuery.count(); return languageQuery.count();
} }

View File

@ -315,7 +315,7 @@ public class PrefillingSourceServiceImpl implements PrefillingSourceService {
} }
public List<Prefilling> searchPrefillings(PrefillingSearchRequest model) { public List<Prefilling> searchPrefillings(PrefillingSearchRequest model) {
PrefillingSourceEntity prefillingSourceEntity = this.queryFactory.query(PrefillingSourceQuery.class).ids(model.getPrefillingSourceId()).isActive(IsActive.Active).first(); PrefillingSourceEntity prefillingSourceEntity = this.queryFactory.query(PrefillingSourceQuery.class).disableTracking().ids(model.getPrefillingSourceId()).isActive(IsActive.Active).first();
if (prefillingSourceEntity == null) if (prefillingSourceEntity == null)
throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getPrefillingSourceId(), PrefillingSource.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getPrefillingSourceId(), PrefillingSource.class.getSimpleName()}, LocaleContextHolder.getLocale()));
@ -350,7 +350,7 @@ public class PrefillingSourceServiceImpl implements PrefillingSourceService {
public Description getPrefilledDescription(DescriptionPrefillingRequest model, FieldSet fieldSet) throws JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException { public Description getPrefilledDescription(DescriptionPrefillingRequest model, FieldSet fieldSet) throws JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException {
PrefillingSourceEntity prefillingSourceEntity = this.queryFactory.query(PrefillingSourceQuery.class).ids(model.getPrefillingSourceId()).first(); PrefillingSourceEntity prefillingSourceEntity = this.queryFactory.query(PrefillingSourceQuery.class).disableTracking().ids(model.getPrefillingSourceId()).first();
if (prefillingSourceEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getPrefillingSourceId(), PrefillingSource.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (prefillingSourceEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getPrefillingSourceId(), PrefillingSource.class.getSimpleName()}, LocaleContextHolder.getLocale()));
PrefillingSourceDefinitionEntity prefillingSourceDefinition = this.xmlHandlingService.fromXmlSafe(PrefillingSourceDefinitionEntity.class, prefillingSourceEntity.getDefinition()); PrefillingSourceDefinitionEntity prefillingSourceDefinition = this.xmlHandlingService.fromXmlSafe(PrefillingSourceDefinitionEntity.class, prefillingSourceEntity.getDefinition());
@ -368,7 +368,7 @@ public class PrefillingSourceServiceImpl implements PrefillingSourceService {
data = model.getData() == null ? new HashMap<>() : model.getData().getData(); data = model.getData() == null ? new HashMap<>() : model.getData().getData();
} }
DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getDescriptionTemplateId()); DescriptionTemplateEntity descriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getDescriptionTemplateId(), true);
if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (descriptionTemplateEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getDescriptionTemplateId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity descriptionTemplateDefinition = this.xmlHandlingService.fromXml(org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplateEntity.getDefinition()); org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity descriptionTemplateDefinition = this.xmlHandlingService.fromXml(org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplateEntity.getDefinition());

View File

@ -160,7 +160,7 @@ public class ReferenceServiceImpl implements ReferenceService {
public Boolean findReference(String reference, UUID referenceTypeId){ public Boolean findReference(String reference, UUID referenceTypeId){
if (this.conventionService.isNullOrEmpty(reference) || !this.conventionService.isValidGuid(referenceTypeId)) return false; if (this.conventionService.isNullOrEmpty(reference) || !this.conventionService.isValidGuid(referenceTypeId)) return false;
ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).references(reference).typeIds(referenceTypeId).isActive(IsActive.Active); ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).disableTracking().references(reference).typeIds(referenceTypeId).isActive(IsActive.Active);
if (query != null && query.count() > 0) return true; if (query != null && query.count() > 0) return true;
return false; return false;
@ -174,7 +174,7 @@ public class ReferenceServiceImpl implements ReferenceService {
lookup.getPage().setOffset(0); lookup.getPage().setOffset(0);
} }
ReferenceTypeEntity data = this.entityManager.find(ReferenceTypeEntity.class, lookup.getTypeId()); ReferenceTypeEntity data = this.entityManager.find(ReferenceTypeEntity.class, lookup.getTypeId(), true);
if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{lookup.getTypeId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{lookup.getTypeId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String like; String like;

View File

@ -1,5 +1,11 @@
package org.opencdmp.service.storage; package org.opencdmp.service.storage;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.StorageFilePermission; import org.opencdmp.commons.enums.StorageFilePermission;
@ -11,12 +17,6 @@ import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.model.StorageFile; import org.opencdmp.model.StorageFile;
import org.opencdmp.model.builder.StorageFileBuilder; import org.opencdmp.model.builder.StorageFileBuilder;
import org.opencdmp.model.persist.StorageFilePersist; import org.opencdmp.model.persist.StorageFilePersist;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.event.ApplicationReadyEvent;
@ -193,7 +193,7 @@ public class StorageFileServiceImpl implements StorageFileService {
@Override @Override
public boolean exists(UUID fileId) { public boolean exists(UUID fileId) {
try { try {
StorageFileEntity storageFile = this.entityManager.find(StorageFileEntity.class, fileId); StorageFileEntity storageFile = this.entityManager.find(StorageFileEntity.class, fileId, true);
if (storageFile == null) return false; if (storageFile == null) return false;
this.authorizeForce(storageFile, StorageFilePermission.Read); this.authorizeForce(storageFile, StorageFilePermission.Read);
@ -262,7 +262,7 @@ public class StorageFileServiceImpl implements StorageFileService {
public byte[] readAsBytesSafe(UUID fileId) { public byte[] readAsBytesSafe(UUID fileId) {
byte[] bytes = null; byte[] bytes = null;
try { try {
StorageFileEntity storageFile = this.entityManager.find(StorageFileEntity.class, fileId); StorageFileEntity storageFile = this.entityManager.find(StorageFileEntity.class, fileId, true);
if (storageFile == null) return null; if (storageFile == null) return null;
this.authorizeForce(storageFile, StorageFilePermission.Read); this.authorizeForce(storageFile, StorageFilePermission.Read);
@ -313,7 +313,7 @@ public class StorageFileServiceImpl implements StorageFileService {
if (!file.exists()) return null; if (!file.exists()) return null;
try(InputStream inputStream = new FileInputStream(file)){ try(InputStream inputStream = new FileInputStream(file)){
bytes = inputStream.readAllBytes(); bytes = inputStream.readAllBytes();
}; }
return bytes; return bytes;
} }

View File

@ -1,5 +1,18 @@
package org.opencdmp.service.supportivematerial; package org.opencdmp.service.supportivematerial;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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.xml.bind.JAXBException;
import org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.IsActive; import org.opencdmp.commons.enums.IsActive;
@ -14,19 +27,6 @@ import org.opencdmp.model.persist.SupportiveMaterialPersist;
import org.opencdmp.query.SupportiveMaterialQuery; import org.opencdmp.query.SupportiveMaterialQuery;
import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl; import org.opencdmp.service.dmpblueprint.DmpBlueprintServiceImpl;
import org.opencdmp.service.storage.StorageFileService; import org.opencdmp.service.storage.StorageFileService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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.xml.bind.JAXBException;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
@ -93,9 +93,9 @@ public class SupportiveMaterialServiceImpl implements SupportiveMaterialService{
if (isUpdate) { if (isUpdate) {
d = this.entityManager.find(SupportiveMaterialEntity.class, model.getId()); d = this.entityManager.find(SupportiveMaterialEntity.class, model.getId());
if (d == null) if (d == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), SupportiveMaterial.class.getSimpleName()}, LocaleContextHolder.getLocale())); throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), SupportiveMaterial.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} else { } else {
List<SupportiveMaterialEntity> data = this.queryFactory.query(SupportiveMaterialQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).languageCodes(model.getLanguageCode()).types(model.getType()).collect(); List<SupportiveMaterialEntity> data = this.queryFactory.query(SupportiveMaterialQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).languageCodes(model.getLanguageCode()).types(model.getType()).collect();
if(data != null && !data.isEmpty()){ if(data != null && !data.isEmpty()){
throw new MyApplicationException("Could not create a new Data with same type and lang code !"); throw new MyApplicationException("Could not create a new Data with same type and lang code !");

View File

@ -1,5 +1,16 @@
package org.opencdmp.service.tag; package org.opencdmp.service.tag;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.enums.IsActive; import org.opencdmp.commons.enums.IsActive;
@ -14,17 +25,6 @@ import org.opencdmp.model.Tag;
import org.opencdmp.model.builder.TagBuilder; import org.opencdmp.model.builder.TagBuilder;
import org.opencdmp.model.deleter.TagDeleter; import org.opencdmp.model.deleter.TagDeleter;
import org.opencdmp.model.persist.TagPersist; import org.opencdmp.model.persist.TagPersist;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -92,14 +92,14 @@ public class TagServiceImpl implements TagService {
TagEntity data; TagEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(TagEntity.class, model.getId()); data = this.entityManager.find(TagEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Tag.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Tag.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {
data = new TagEntity(); data = new TagEntity();
data.setId(UUID.randomUUID()); data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active); data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now()); data.setCreatedAt(Instant.now());
data.setCreatedById(userScope.getUserId()); data.setCreatedById(this.userScope.getUserId());
} }
data.setLabel(model.getLabel()); data.setLabel(model.getLabel());

View File

@ -151,8 +151,8 @@ public class TenantServiceImpl implements TenantService {
try { try {
this.tenantScope.setTempTenant(this.entityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode()); this.tenantScope.setTempTenant(this.entityManager.getEntityManager(), null, this.tenantScope.getDefaultTenantCode());
existingItems = this.queryFactory.query(UserRoleQuery.class).tenantIsSet(false).roles(this.authorizationProperties.getGlobalAdminRole()).collect(); existingItems = this.queryFactory.query(UserRoleQuery.class).disableTracking().tenantIsSet(false).roles(this.authorizationProperties.getGlobalAdminRole()).collect();
userCredentialEntities = this.queryFactory.query(UserCredentialQuery.class).userIds(existingItems.stream().map(UserRoleEntity::getUserId).distinct().toList()).collect(); userCredentialEntities = this.queryFactory.query(UserCredentialQuery.class).disableTracking().userIds(existingItems.stream().map(UserRoleEntity::getUserId).distinct().toList()).collect();
} finally { } finally {
this.tenantScope.removeTempTenant(this.entityManager.getEntityManager()); this.tenantScope.removeTempTenant(this.entityManager.getEntityManager());
} }

View File

@ -1,6 +1,19 @@
package org.opencdmp.service.tenantconfiguration; package org.opencdmp.service.tenantconfiguration;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.jetbrains.annotations.NotNull;
import org.opencdmp.authorization.AuthorizationFlags; import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission; import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.JsonHandlingService; import org.opencdmp.commons.JsonHandlingService;
@ -33,19 +46,6 @@ import org.opencdmp.query.TenantConfigurationQuery;
import org.opencdmp.service.encryption.EncryptionService; import org.opencdmp.service.encryption.EncryptionService;
import org.opencdmp.service.storage.StorageFileService; import org.opencdmp.service.storage.StorageFileService;
import org.opencdmp.service.tenant.TenantProperties; import org.opencdmp.service.tenant.TenantProperties;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
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 org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -132,7 +132,7 @@ public class TenantConfigurationServiceImpl implements TenantConfigurationServic
TenantConfigurationEntity data; TenantConfigurationEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(TenantConfigurationEntity.class, model.getId()); data = this.entityManager.find(TenantConfigurationEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
if (!data.getType().equals(model.getType())) throw new MyValidationException(this.errors.getTenantConfigurationTypeCanNotChange().getCode(), this.errors.getTenantConfigurationTypeCanNotChange().getMessage()); if (!data.getType().equals(model.getType())) throw new MyValidationException(this.errors.getTenantConfigurationTypeCanNotChange().getCode(), this.errors.getTenantConfigurationTypeCanNotChange().getMessage());
} else { } else {
@ -143,7 +143,7 @@ public class TenantConfigurationServiceImpl implements TenantConfigurationServic
data.setType(model.getType()); data.setType(model.getType());
} }
TenantConfigurationQuery tenantConfigurationQuery = this.queryFactory.query(TenantConfigurationQuery.class).excludedIds(data.getId()).isActive(IsActive.Active).types(data.getType()); TenantConfigurationQuery tenantConfigurationQuery = this.queryFactory.query(TenantConfigurationQuery.class).disableTracking().excludedIds(data.getId()).isActive(IsActive.Active).types(data.getType());
if (data.getTenantId() == null) tenantConfigurationQuery.tenantIsSet(false); if (data.getTenantId() == null) tenantConfigurationQuery.tenantIsSet(false);
else tenantConfigurationQuery.tenantIsSet(true).tenantIds(data.getTenantId()); else tenantConfigurationQuery.tenantIsSet(true).tenantIds(data.getTenantId());
if (tenantConfigurationQuery.count() > 0)throw new MyValidationException(this.errors.getMultipleTenantConfigurationTypeNotAllowed().getCode(), this.errors.getMultipleTenantConfigurationTypeNotAllowed().getMessage()); if (tenantConfigurationQuery.count() > 0)throw new MyValidationException(this.errors.getMultipleTenantConfigurationTypeNotAllowed().getCode(), this.errors.getMultipleTenantConfigurationTypeNotAllowed().getMessage());
@ -168,8 +168,8 @@ public class TenantConfigurationServiceImpl implements TenantConfigurationServic
this.entityManager.flush(); this.entityManager.flush();
if (data.getTenantId() != null) { if (data.getTenantId() != null) {
TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId()); TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId(), true);
if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (tenant == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType())); this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType()));
} else { } else {
this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType())); this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType()));
@ -281,7 +281,7 @@ public class TenantConfigurationServiceImpl implements TenantConfigurationServic
this.authorizationService.authorizeForce(Permission.DeleteTenantConfiguration); this.authorizationService.authorizeForce(Permission.DeleteTenantConfiguration);
TenantConfigurationEntity data = this.entityManager.find(TenantConfigurationEntity.class, id); TenantConfigurationEntity data = this.entityManager.find(TenantConfigurationEntity.class, id);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data.getType().equals(TenantConfigurationType.Logo)){ if (data.getType().equals(TenantConfigurationType.Logo)){
LogoTenantConfigurationEntity oldValue = this.conventionService.isNullOrEmpty(data.getValue()) ? null : this.jsonHandlingService.fromJsonSafe(LogoTenantConfigurationEntity.class, data.getValue()); LogoTenantConfigurationEntity oldValue = this.conventionService.isNullOrEmpty(data.getValue()) ? null : this.jsonHandlingService.fromJsonSafe(LogoTenantConfigurationEntity.class, data.getValue());
@ -290,8 +290,8 @@ public class TenantConfigurationServiceImpl implements TenantConfigurationServic
this.deleterFactory.deleter(TenantConfigurationDeleter.class).deleteAndSaveByIds(List.of(id)); this.deleterFactory.deleter(TenantConfigurationDeleter.class).deleteAndSaveByIds(List.of(id));
if (data.getTenantId() != null) { if (data.getTenantId() != null) {
TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId()); TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId(), true);
if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (tenant == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType())); this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType()));
} else { } else {
this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType())); this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType()));

View File

@ -1,46 +1,6 @@
package org.opencdmp.service.user; package org.opencdmp.service.user;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.AuthorizationProperties;
import org.opencdmp.authorization.OwnedResource;
import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.JsonHandlingService;
import org.opencdmp.commons.XmlHandlingService;
import org.opencdmp.commons.enums.ActionConfirmationStatus;
import org.opencdmp.commons.enums.ActionConfirmationType;
import org.opencdmp.commons.enums.ContactInfoType;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.enums.notification.NotificationContactType;
import org.opencdmp.commons.scope.tenant.TenantScope;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity;
import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity;
import org.opencdmp.commons.types.notification.*;
import org.opencdmp.commons.types.user.AdditionalInfoEntity;
import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity;
import org.opencdmp.commons.notification.NotificationProperties;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.*;
import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.event.UserTouchedEvent;
import org.opencdmp.event.EventBroker;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler;
import org.opencdmp.integrationevent.outbox.userremoval.UserRemovalIntegrationEventHandler;
import org.opencdmp.integrationevent.outbox.usertouched.UserTouchedIntegrationEventHandler;
import org.opencdmp.model.user.User;
import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.usercredential.UserCredential;
import org.opencdmp.model.builder.UserBuilder;
import org.opencdmp.model.deleter.*;
import org.opencdmp.model.persist.*;
import org.opencdmp.model.persist.actionconfirmation.MergeAccountConfirmationPersist;
import org.opencdmp.model.persist.actionconfirmation.RemoveCredentialRequestPersist;
import org.opencdmp.query.*;
import org.opencdmp.service.actionconfirmation.ActionConfirmationService;
import org.opencdmp.service.elastic.ElasticService;
import org.opencdmp.service.keycloak.KeycloakService;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory; import gr.cite.tools.data.deleter.DeleterFactory;
@ -60,6 +20,46 @@ import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode; import org.apache.commons.csv.QuoteMode;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.AuthorizationProperties;
import org.opencdmp.authorization.OwnedResource;
import org.opencdmp.authorization.Permission;
import org.opencdmp.commons.JsonHandlingService;
import org.opencdmp.commons.XmlHandlingService;
import org.opencdmp.commons.enums.ActionConfirmationStatus;
import org.opencdmp.commons.enums.ActionConfirmationType;
import org.opencdmp.commons.enums.ContactInfoType;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.enums.notification.NotificationContactType;
import org.opencdmp.commons.notification.NotificationProperties;
import org.opencdmp.commons.scope.tenant.TenantScope;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity;
import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity;
import org.opencdmp.commons.types.notification.*;
import org.opencdmp.commons.types.user.AdditionalInfoEntity;
import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.*;
import org.opencdmp.errorcode.ErrorThesaurusProperties;
import org.opencdmp.event.EventBroker;
import org.opencdmp.event.UserTouchedEvent;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEvent;
import org.opencdmp.integrationevent.outbox.notification.NotifyIntegrationEventHandler;
import org.opencdmp.integrationevent.outbox.userremoval.UserRemovalIntegrationEventHandler;
import org.opencdmp.integrationevent.outbox.usertouched.UserTouchedIntegrationEventHandler;
import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.builder.UserBuilder;
import org.opencdmp.model.deleter.*;
import org.opencdmp.model.persist.*;
import org.opencdmp.model.persist.actionconfirmation.MergeAccountConfirmationPersist;
import org.opencdmp.model.persist.actionconfirmation.RemoveCredentialRequestPersist;
import org.opencdmp.model.user.User;
import org.opencdmp.model.usercredential.UserCredential;
import org.opencdmp.query.*;
import org.opencdmp.service.actionconfirmation.ActionConfirmationService;
import org.opencdmp.service.elastic.ElasticService;
import org.opencdmp.service.keycloak.KeycloakService;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -71,7 +71,9 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@ -161,7 +163,7 @@ public class UserServiceImpl implements UserService {
UserEntity data; UserEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(UserEntity.class, model.getId()); data = this.entityManager.find(UserEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else { } else {
data = new UserEntity(); data = new UserEntity();
@ -220,7 +222,7 @@ public class UserServiceImpl implements UserService {
this.authorizationService.authorizeForce(Permission.ExportUsers); this.authorizationService.authorizeForce(Permission.ExportUsers);
FieldSet fieldSet = new BaseFieldSet().ensure(User._id).ensure(User._name).ensure(User._contacts + "." + UserContactInfo._value).ensure(User._contacts + "." + UserContactInfo._type); FieldSet fieldSet = new BaseFieldSet().ensure(User._id).ensure(User._name).ensure(User._contacts + "." + UserContactInfo._value).ensure(User._contacts + "." + UserContactInfo._type);
List<User> users = this.builderFactory.builder(UserBuilder.class).build(fieldSet, this.queryFactory.query(UserQuery.class).collectAs(fieldSet)); List<User> users = this.builderFactory.builder(UserBuilder.class).build(fieldSet, this.queryFactory.query(UserQuery.class).disableTracking().collectAs(fieldSet));
final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream out = new ByteArrayOutputStream();
final CSVFormat format = CSVFormat.DEFAULT.withHeader("User Id", "User Name", "User Email").withQuoteMode(QuoteMode.NON_NUMERIC); final CSVFormat format = CSVFormat.DEFAULT.withHeader("User Id", "User Name", "User Email").withQuoteMode(QuoteMode.NON_NUMERIC);
final CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format); final CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format);
@ -241,11 +243,11 @@ public class UserServiceImpl implements UserService {
logger.debug(new MapLogEntry("persisting data UserRole").And("model", model).And("fields", fields)); logger.debug(new MapLogEntry("persisting data UserRole").And("model", model).And("fields", fields));
this.authorizationService.authorizeForce(Permission.EditUser); this.authorizationService.authorizeForce(Permission.EditUser);
UserEntity data = this.entityManager.find(UserEntity.class, model.getId()); UserEntity data = this.entityManager.find(UserEntity.class, model.getId(), true);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
List<UserCredentialEntity> userCredentials = this.queryFactory.query(UserCredentialQuery.class).userIds(data.getId()).collect(); List<UserCredentialEntity> userCredentials = this.queryFactory.query(UserCredentialQuery.class).disableTracking().userIds(data.getId()).collect();
if (userCredentials.isEmpty()) if (userCredentials.isEmpty())
throw new MyApplicationException("Currently cannot update roles for this user"); throw new MyApplicationException("Currently cannot update roles for this user");
if (userCredentials.getFirst().getExternalId() == null) if (userCredentials.getFirst().getExternalId() == null)
@ -297,10 +299,10 @@ public class UserServiceImpl implements UserService {
} }
private void applyTenantRoles(UUID userId, String subjectId, UserRolePatchPersist model) throws InvalidApplicationException { private void applyTenantRoles(UUID userId, String subjectId, UserRolePatchPersist model) throws InvalidApplicationException {
if (!tenantScope.isSet()) throw new MyForbiddenException("tenant scope required"); if (!this.tenantScope.isSet()) throw new MyForbiddenException("tenant scope required");
UserRoleQuery userRoleQuery = this.queryFactory.query(UserRoleQuery.class).userIds(userId).roles(this.authorizationProperties.getAllowedTenantRoles()); UserRoleQuery userRoleQuery = this.queryFactory.query(UserRoleQuery.class).userIds(userId).roles(this.authorizationProperties.getAllowedTenantRoles());
if (tenantScope.isDefaultTenant()) userRoleQuery.tenantIsSet(false); if (this.tenantScope.isDefaultTenant()) userRoleQuery.tenantIsSet(false);
else userRoleQuery.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); else userRoleQuery.tenantIsSet(true).tenantIds(this.tenantScope.getTenant());
List<UserRoleEntity> existingItems = userRoleQuery.collect(); List<UserRoleEntity> existingItems = userRoleQuery.collect();
@ -348,7 +350,7 @@ public class UserServiceImpl implements UserService {
UserEntity data = this.entityManager.find(UserEntity.class, userId); UserEntity data = this.entityManager.find(UserEntity.class, userId);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo()); AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo());
if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity(); if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity();
@ -376,7 +378,7 @@ public class UserServiceImpl implements UserService {
UserEntity data = this.entityManager.find(UserEntity.class, userId); UserEntity data = this.entityManager.find(UserEntity.class, userId);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo()); AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo());
if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity(); if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity();
@ -403,7 +405,7 @@ public class UserServiceImpl implements UserService {
if (userId == null) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage()); if (userId == null) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage());
UserEntity data = this.entityManager.find(UserEntity.class, userId); UserEntity data = this.entityManager.find(UserEntity.class, userId);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo()); AdditionalInfoEntity additionalInfoEntity = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, data.getAdditionalInfo());
if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity(); if (additionalInfoEntity == null) additionalInfoEntity = new AdditionalInfoEntity();
@ -425,14 +427,14 @@ public class UserServiceImpl implements UserService {
//notifications //notifications
public void sendMergeAccountConfirmation(UserMergeRequestPersist model) throws InvalidApplicationException, JAXBException { public void sendMergeAccountConfirmation(UserMergeRequestPersist model) throws InvalidApplicationException, JAXBException {
UserContactInfoEntity userContactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).values(model.getEmail()).types(ContactInfoType.Email).first(); UserContactInfoEntity userContactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().values(model.getEmail()).types(ContactInfoType.Email).first();
if (userContactInfoEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getEmail(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (userContactInfoEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getEmail(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
UserEntity user = this.queryFactory.query(UserQuery.class).ids(userContactInfoEntity.getUserId()).isActive(IsActive.Active).first(); UserEntity user = this.queryFactory.query(UserQuery.class).ids(userContactInfoEntity.getUserId()).isActive(IsActive.Active).first();
if (user == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userContactInfoEntity.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (user == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userContactInfoEntity.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
String token = this.createMergeAccountConfirmation(model.getEmail()); String token = this.createMergeAccountConfirmation(model.getEmail());
createMergeNotificationEvent(token, user, model.getEmail(), NotificationContactType.EMAIL); this.createMergeNotificationEvent(token, user, model.getEmail(), NotificationContactType.EMAIL);
} }
private void createMergeNotificationEvent(String token, UserEntity user, String email, NotificationContactType type) throws InvalidApplicationException { private void createMergeNotificationEvent(String token, UserEntity user, String email, NotificationContactType type) throws InvalidApplicationException {
@ -441,22 +443,22 @@ public class UserServiceImpl implements UserService {
List<ContactPair> contactPairs = new ArrayList<>(); List<ContactPair> contactPairs = new ArrayList<>();
contactPairs.add(new ContactPair(ContactInfoType.Email, email)); contactPairs.add(new ContactPair(ContactInfoType.Email, email));
NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); NotificationContactData contactData = new NotificationContactData(contactPairs, null, null);
event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); event.setContactHint(this.jsonHandlingService.toJsonSafe(contactData));
event.setContactTypeHint(type); event.setContactTypeHint(type);
event.setNotificationType(notificationProperties.getMergeAccountConfirmationType()); event.setNotificationType(this.notificationProperties.getMergeAccountConfirmationType());
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{userName}", DataType.String, user.getName())); fieldInfoList.add(new FieldInfo("{userName}", DataType.String, user.getName()));
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token)); fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds()))); fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
data.setFields(fieldInfoList); data.setFields(fieldInfoList);
event.setData(jsonHandlingService.toJsonSafe(data)); event.setData(this.jsonHandlingService.toJsonSafe(data));
eventHandler.handle(event); this.eventHandler.handle(event);
} }
public void sendRemoveCredentialConfirmation(RemoveCredentialRequestPersist model) throws InvalidApplicationException, JAXBException { public void sendRemoveCredentialConfirmation(RemoveCredentialRequestPersist model) throws InvalidApplicationException, JAXBException {
UserCredentialEntity data = this.entityManager.find(UserCredentialEntity.class, model.getCredentialId()); UserCredentialEntity data = this.entityManager.find(UserCredentialEntity.class, model.getCredentialId(), true);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getCredentialId(), UserCredentialEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getCredentialId(), UserCredentialEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!data.getUserId().equals(this.userScope.getUserId())) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage()); if (!data.getUserId().equals(this.userScope.getUserId())) throw new MyForbiddenException(this.errors.getForbidden().getCode(), this.errors.getForbidden().getMessage());
@ -468,14 +470,14 @@ public class UserServiceImpl implements UserService {
NotifyIntegrationEvent event = new NotifyIntegrationEvent(); NotifyIntegrationEvent event = new NotifyIntegrationEvent();
event.setUserId(userId); event.setUserId(userId);
event.setContactTypeHint(type); event.setContactTypeHint(type);
event.setNotificationType(notificationProperties.getRemoveCredentialConfirmationType()); event.setNotificationType(this.notificationProperties.getRemoveCredentialConfirmationType());
NotificationFieldData data = new NotificationFieldData(); NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>(); List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token)); fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds()))); fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
data.setFields(fieldInfoList); data.setFields(fieldInfoList);
event.setData(jsonHandlingService.toJsonSafe(data)); event.setData(this.jsonHandlingService.toJsonSafe(data));
eventHandler.handle(event); this.eventHandler.handle(event);
} }
private String createMergeAccountConfirmation(String email) throws JAXBException, InvalidApplicationException { private String createMergeAccountConfirmation(String email) throws JAXBException, InvalidApplicationException {
@ -486,7 +488,7 @@ public class UserServiceImpl implements UserService {
persist.setMergeAccountConfirmation(new MergeAccountConfirmationPersist()); persist.setMergeAccountConfirmation(new MergeAccountConfirmationPersist());
persist.getMergeAccountConfirmation().setEmail(email); persist.getMergeAccountConfirmation().setEmail(email);
persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds())); persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds()));
validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist); this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
this.actionConfirmationService.persist(persist, null); this.actionConfirmationService.persist(persist, null);
return persist.getToken(); return persist.getToken();
@ -502,7 +504,7 @@ public class UserServiceImpl implements UserService {
persist.setRemoveCredentialRequest(new RemoveCredentialRequestPersist()); persist.setRemoveCredentialRequest(new RemoveCredentialRequestPersist());
persist.getRemoveCredentialRequest().setCredentialId(credentialId); persist.getRemoveCredentialRequest().setCredentialId(credentialId);
persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds())); persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds()));
validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist); this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
this.actionConfirmationService.persist(persist, null); this.actionConfirmationService.persist(persist, null);
return persist.getToken(); return persist.getToken();
@ -518,23 +520,23 @@ public class UserServiceImpl implements UserService {
public void confirmMergeAccount(String token) throws IOException, InvalidApplicationException { public void confirmMergeAccount(String token) throws IOException, InvalidApplicationException {
ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first(); ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first();
if (action == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (action == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.checkActionState(action); this.checkActionState(action);
MergeAccountConfirmationEntity mergeAccountConfirmationEntity = this.xmlHandlingService.fromXmlSafe(MergeAccountConfirmationEntity.class, action.getData()); MergeAccountConfirmationEntity mergeAccountConfirmationEntity = this.xmlHandlingService.fromXmlSafe(MergeAccountConfirmationEntity.class, action.getData());
if (mergeAccountConfirmationEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{mergeAccountConfirmationEntity, MergeAccountConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (mergeAccountConfirmationEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{mergeAccountConfirmationEntity, MergeAccountConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
UserContactInfoEntity userContactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).values(mergeAccountConfirmationEntity.getEmail()).types(ContactInfoType.Email).first(); UserContactInfoEntity userContactInfoEntity = this.queryFactory.query(UserContactInfoQuery.class).values(mergeAccountConfirmationEntity.getEmail()).types(ContactInfoType.Email).first();
if (userContactInfoEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{mergeAccountConfirmationEntity.getEmail(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (userContactInfoEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{mergeAccountConfirmationEntity.getEmail(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
UserEntity userToBeMerge = this.queryFactory.query(UserQuery.class).ids(userContactInfoEntity.getUserId()).isActive(IsActive.Active).first(); UserEntity userToBeMerge = this.queryFactory.query(UserQuery.class).ids(userContactInfoEntity.getUserId()).isActive(IsActive.Active).first();
if (userToBeMerge == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userContactInfoEntity.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (userToBeMerge == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{userContactInfoEntity.getUserId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.userScope.getUserIdSafe().equals(userToBeMerge.getId())) throw new MyForbiddenException("Only requested user can approve"); if (!this.userScope.getUserIdSafe().equals(userToBeMerge.getId())) throw new MyForbiddenException("Only requested user can approve");
UserEntity newUser = this.queryFactory.query(UserQuery.class).ids(action.getCreatedById()).isActive(IsActive.Active).first(); UserEntity newUser = this.queryFactory.query(UserQuery.class).ids(action.getCreatedById()).isActive(IsActive.Active).first();
if (newUser == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{action.getCreatedById(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (newUser == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{action.getCreatedById(), User.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!newUser.getId().equals(userToBeMerge.getId())){ if (!newUser.getId().equals(userToBeMerge.getId())){
this.mergeNewUserToOld(newUser, userToBeMerge); this.mergeNewUserToOld(newUser, userToBeMerge);
@ -656,15 +658,15 @@ public class UserServiceImpl implements UserService {
public void confirmRemoveCredential(String token) throws InvalidApplicationException { public void confirmRemoveCredential(String token) throws InvalidApplicationException {
ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.RemoveCredential).isActive(IsActive.Active).first(); ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.RemoveCredential).isActive(IsActive.Active).first();
if (action == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (action == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.checkActionState(action); this.checkActionState(action);
RemoveCredentialRequestEntity removeCredentialRequestEntity = this.xmlHandlingService.fromXmlSafe(RemoveCredentialRequestEntity.class, action.getData()); RemoveCredentialRequestEntity removeCredentialRequestEntity = this.xmlHandlingService.fromXmlSafe(RemoveCredentialRequestEntity.class, action.getData());
if (removeCredentialRequestEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{removeCredentialRequestEntity, RemoveCredentialRequestEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (removeCredentialRequestEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{removeCredentialRequestEntity, RemoveCredentialRequestEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
UserCredentialEntity userCredentialEntity = this.queryFactory.query(UserCredentialQuery.class).ids(removeCredentialRequestEntity.getCredentialId()).first(); UserCredentialEntity userCredentialEntity = this.queryFactory.query(UserCredentialQuery.class).ids(removeCredentialRequestEntity.getCredentialId()).first();
if (userCredentialEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{removeCredentialRequestEntity.getCredentialId(), UserCredential.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (userCredentialEntity == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{removeCredentialRequestEntity.getCredentialId(), UserCredential.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.userScope.getUserIdSafe().equals(userCredentialEntity.getId())) throw new MyForbiddenException("Only requested user can approve"); if (!this.userScope.getUserIdSafe().equals(userCredentialEntity.getId())) throw new MyForbiddenException("Only requested user can approve");

View File

@ -1,13 +1,5 @@
package org.opencdmp.service.user.settings; package org.opencdmp.service.user.settings;
import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.data.UserSettingsEntity;
import org.opencdmp.model.UserSettings;
import org.opencdmp.model.builder.UserSettingsBuilder;
import org.opencdmp.model.persist.UserSettingsPersist;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.exception.MyApplicationException;
@ -18,6 +10,14 @@ import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.logging.MapLogEntry;
import org.opencdmp.authorization.AuthorizationFlags;
import org.opencdmp.authorization.Permission;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.TenantEntityManager;
import org.opencdmp.data.UserSettingsEntity;
import org.opencdmp.model.UserSettings;
import org.opencdmp.model.builder.UserSettingsBuilder;
import org.opencdmp.model.persist.UserSettingsPersist;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -64,7 +64,7 @@ public class UserSettingsServiceImpl implements UserSettingsService {
UserSettingsEntity data; UserSettingsEntity data;
if (isUpdate) { if (isUpdate) {
data = this.entityManager.find(UserSettingsEntity.class, model.getId()); data = this.entityManager.find(UserSettingsEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), UserSettings.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), UserSettings.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} else { } else {
data = new UserSettingsEntity(); data = new UserSettingsEntity();
data.setCreatedAt(Instant.now()); data.setCreatedAt(Instant.now());