argos/dmp-backend/core/src/main/java/eu/eudat/service/description/DescriptionServiceImpl.java

419 lines
21 KiB
Java

package eu.eudat.service.description;
import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.JsonHandlingService;
import eu.eudat.commons.XmlHandlingService;
import eu.eudat.commons.enums.DescriptionStatus;
import eu.eudat.commons.enums.DmpStatus;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.types.description.FieldEntity;
import eu.eudat.commons.types.description.PropertyDefinitionEntity;
import eu.eudat.commons.types.reference.DefinitionEntity;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.*;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import eu.eudat.event.DescriptionTouchedEvent;
import eu.eudat.event.EventBroker;
import eu.eudat.model.Description;
import eu.eudat.model.DescriptionReference;
import eu.eudat.model.builder.DescriptionBuilder;
import eu.eudat.model.deleter.DescriptionDeleter;
import eu.eudat.model.deleter.DescriptionReferenceDeleter;
import eu.eudat.model.deleter.DescriptionTagDeleter;
import eu.eudat.model.persist.DescriptionPersist;
import eu.eudat.model.persist.DescriptionReferencePersist;
import eu.eudat.model.persist.DescriptionStatusPersist;
import eu.eudat.model.persist.ReferencePersist;
import eu.eudat.model.persist.descriptionproperties.FieldPersist;
import eu.eudat.model.persist.descriptionproperties.PropertyDefinitionPersist;
import eu.eudat.model.persist.referencedefinition.DefinitionPersist;
import eu.eudat.query.*;
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.persistence.EntityManager;
import org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class DescriptionServiceImpl implements DescriptionService {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionServiceImpl.class));
private final EntityManager entityManager;
private final AuthorizationService authorizationService;
private final DeleterFactory deleterFactory;
private final BuilderFactory builderFactory;
private final ConventionService conventionService;
private final ErrorThesaurusProperties errors;
private final MessageSource messageSource;
private final EventBroker eventBroker;
private final QueryFactory queryFactory;
private final JsonHandlingService jsonHandlingService;
private final UserScope userScope;
private final XmlHandlingService xmlHandlingService;
@Autowired
public DescriptionServiceImpl(
EntityManager entityManager,
AuthorizationService authorizationService,
DeleterFactory deleterFactory,
BuilderFactory builderFactory,
ConventionService conventionService,
ErrorThesaurusProperties errors,
MessageSource messageSource,
EventBroker eventBroker,
QueryFactory queryFactory,
JsonHandlingService jsonHandlingService,
UserScope userScope,
XmlHandlingService xmlHandlingService) {
this.entityManager = entityManager;
this.authorizationService = authorizationService;
this.deleterFactory = deleterFactory;
this.builderFactory = builderFactory;
this.conventionService = conventionService;
this.errors = errors;
this.messageSource = messageSource;
this.eventBroker = eventBroker;
this.queryFactory = queryFactory;
this.jsonHandlingService = jsonHandlingService;
this.userScope = userScope;
this.xmlHandlingService = xmlHandlingService;
}
//region Persist
@Override
public Description persist(DescriptionPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException {
logger.debug(new MapLogEntry("persisting data dmp").And("model", model).And("fields", fields));
this.authorizationService.authorizeForce(Permission.EditDescription);
Boolean isUpdate = this.conventionService.isValidGuid(model.getId());
DescriptionEntity data;
if (isUpdate) {
data = this.entityManager.find(DescriptionEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(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 (data.getStatus() == DescriptionStatus.Finalized) throw new MyForbiddenException("Can not update finalized template");
} else {
data = new DescriptionEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now());
}
data.setLabel(model.getLabel());
data.setProperties(this.jsonHandlingService.toJson(this.buildPropertyDefinitionEntity(model.getProperties())));
data.setStatus(model.getStatus());
data.setDescription(model.getDescription());
data.setDescriptionTemplateId(model.getDescriptionTemplateId());
data.setDmpDescriptionTemplateId(model.getDmpDescriptionTemplateId());
data.setUpdatedAt(Instant.now());
if (isUpdate) this.entityManager.merge(data);
else this.entityManager.persist(data);
this.persistTags(data.getId(), model.getTags());
this.entityManager.flush();
this.eventBroker.emit(new DescriptionTouchedEvent(data.getId()));
return this.builderFactory.builder(DescriptionBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, Description._id), data);
}
@Override
public Description persistStatus(DescriptionStatusPersist model, FieldSet fields) {
logger.debug(new MapLogEntry("persisting data dmp").And("model", model).And("fields", fields));
this.authorizationService.authorizeForce(Permission.EditDescription);
DescriptionEntity data = this.entityManager.find(DescriptionEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(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 (!data.getStatus().equals(model.getStatus())){
if (data.getStatus() == DescriptionStatus.Finalized){
DmpEntity dmpEntity = this.entityManager.find(DmpEntity.class, data.getDmpId());
if (dmpEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getDmpId(), DmpEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if(dmpEntity.getStatus() .equals(DmpStatus.Finalized)) throw new MyValidationException(this.errors.getDmpIsFinalized().getCode(), this.errors.getDmpIsFinalized().getMessage());
}
data.setStatus(model.getStatus());
data.setUpdatedAt(Instant.now());
this.entityManager.merge(data);
this.entityManager.flush();
this.eventBroker.emit(new DescriptionTouchedEvent(data.getId()));
}
return this.builderFactory.builder(DescriptionBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, Description._id), data);
}
private @NotNull PropertyDefinitionEntity buildPropertyDefinitionEntity(PropertyDefinitionPersist persist){
PropertyDefinitionEntity data = new PropertyDefinitionEntity();
if (persist == null) return data;
if (!this.conventionService.isListNullOrEmpty(persist.getFields())){
data.setFields(new ArrayList<>());
for (FieldPersist sectionPersist: persist.getFields()) {
data.getFields().add(this.buildFieldEntity(sectionPersist));
}
}
return data;
}
private @NotNull FieldEntity buildFieldEntity(FieldPersist persist){
FieldEntity data = new FieldEntity();
if (persist == null) return data;
data.setKey(persist.getKey());
data.setValue(persist.getValue());
return data;
}
private void persistTags(UUID id, List<String> tagLabels) throws InvalidApplicationException {
if (tagLabels == null) tagLabels = new ArrayList<>();
tagLabels = tagLabels.stream().filter(x-> x != null && !x.isBlank()).toList();
List<DescriptionTagEntity> items = this.queryFactory.query(DescriptionTagQuery.class).isActive(IsActive.Active).descriptionIds(id).collect();
List<TagEntity> tagsAlreadyLinked = this.queryFactory.query(TagQuery.class).isActive(IsActive.Active).ids(items.stream().map(DescriptionTagEntity::getTagId).collect(Collectors.toList())).collect();
List<String> tagLabelsToAdd = tagLabels.stream().filter(x-> tagsAlreadyLinked.stream().noneMatch(y-> y.getLabel() != null && y.getLabel().equalsIgnoreCase(x))).toList();
List<TagEntity> existingTags = this.queryFactory.query(TagQuery.class).isActive(IsActive.Active).labels(tagLabelsToAdd).createdByIds(this.userScope.getUserId()).collect();
List<UUID> updatedCreatedIds = new ArrayList<>();
for (String tagLabel : tagLabels) {
TagEntity alreadyLinkedTag = tagsAlreadyLinked.stream().filter(x-> x.getLabel() != null && x.getLabel().equalsIgnoreCase(tagLabel)).findFirst().orElse(null);
if (alreadyLinkedTag != null){
updatedCreatedIds.addAll(items.stream().filter(x-> x.getTagId().equals(alreadyLinkedTag.getId())).map(DescriptionTagEntity::getId).toList());
} else{
TagEntity existingTag = existingTags.stream().filter(x-> x.getLabel() != null && x.getLabel().equalsIgnoreCase(tagLabel)).findFirst().orElse(null);
if (existingTag == null){
existingTag = new TagEntity();
existingTag.setId(UUID.randomUUID());
existingTag.setLabel(tagLabel);
existingTag.setIsActive(IsActive.Active);
existingTag.setCreatedAt(Instant.now());
existingTag.setUpdatedAt(Instant.now());
this.entityManager.persist(existingTag);
}
DescriptionTagEntity link = new DescriptionTagEntity();
link.setId(UUID.randomUUID());
link.setTagId(existingTag.getId());
link.setDescriptionId(id);
link.setIsActive(IsActive.Active);
link.setCreatedAt(Instant.now());
link.setUpdatedAt(Instant.now());
this.entityManager.persist(link);
updatedCreatedIds.add(link.getId());
}
}
List<DescriptionTagEntity> toDelete = items.stream().filter(x-> updatedCreatedIds.stream().noneMatch(y-> y.equals(x.getId()))).collect(Collectors.toList());
this.deleterFactory.deleter(DescriptionTagDeleter.class).delete(toDelete);
}
private void persistDescriptionReferences(UUID id, List<DescriptionReferencePersist> models) throws InvalidApplicationException {
if (models == null) models = new ArrayList<>();
List<DescriptionReferenceEntity> items = this.queryFactory.query(DescriptionReferenceQuery.class).isActive(IsActive.Active).descriptionIds(id).collect();
List<ReferenceEntity> existingReferences = this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).ids(models.stream().filter(x-> this.conventionService.isValidGuid(x.getReference().getId())).map(x-> x.getReference().getId()).distinct().toList()).collect();
List<UUID> updatedCreatedIds = new ArrayList<>();
for (DescriptionReferencePersist model : models) {
Boolean isUpdate = this.conventionService.isValidGuid(model.getId());
DescriptionReferenceEntity data;
if (isUpdate) {
data = items.stream().filter(x -> x.getId().equals(model.getId())).findFirst().orElse(null);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionReference.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 (!data.getReferenceId().equals(model.getReference().getId())) throw new MyForbiddenException("Can not change reference of DescriptionReferenceEntity");
} else {
data = new DescriptionReferenceEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now());
}
ReferenceEntity referenceEntity = this.persisReference(existingReferences, model.getReference());
data.setReferenceId(referenceEntity.getId());
data.setUpdatedAt(Instant.now());
if (isUpdate) this.entityManager.merge(data);
else this.entityManager.persist(data);
updatedCreatedIds.add(data.getId());
}
List<DescriptionReferenceEntity> toDelete = items.stream().filter(x-> updatedCreatedIds.stream().noneMatch(y-> y.equals(x.getId()))).collect(Collectors.toList());
this.deleterFactory.deleter(DescriptionReferenceDeleter.class).delete(toDelete);
}
private ReferenceEntity persisReference(List<ReferenceEntity> existingReferences, ReferencePersist model) throws InvalidApplicationException {
Boolean isUpdate = this.conventionService.isValidGuid(model.getId());
ReferenceEntity data;
if (isUpdate) {
data = existingReferences.stream().filter(x -> x.getId().equals(model.getId())).findFirst().orElse(null);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionReference.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
} else {
data = new ReferenceEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now());
}
data.setDefinition(this.xmlHandlingService.toXmlSafe(this.buildDefinitionEntity(model.getDefinition())));
data.setUpdatedAt(Instant.now());
data.setReference(model.getReference());
data.setAbbreviation(model.getAbbreviation());
data.setSource(model.getSource());
data.setSourceType(model.getSourceType());
data.setUpdatedAt(Instant.now());
if (isUpdate) this.entityManager.merge(data);
else this.entityManager.persist(data);
return data;
}
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist){
DefinitionEntity data = new DefinitionEntity();
if (persist == null) return data;
if (!this.conventionService.isListNullOrEmpty(persist.getFields())){
data.setFields(new ArrayList<>());
for (eu.eudat.model.persist.referencedefinition.FieldPersist fieldPersist: persist.getFields()) {
data.getFields().add(this.buildFieldEntity(fieldPersist));
}
}
return data;
}
private @NotNull eu.eudat.commons.types.reference.FieldEntity buildFieldEntity(eu.eudat.model.persist.referencedefinition.FieldPersist persist){
eu.eudat.commons.types.reference.FieldEntity data = new eu.eudat.commons.types.reference.FieldEntity();
if (persist == null) return data;
data.setCode(persist.getCode());
data.setDataType(persist.getDataType());
data.setCode(persist.getCode());
return data;
}
//endregion
//region delete
@Override
public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException, IOException {
logger.debug("deleting description: {}", id);
this.authorizationService.authorizeForce(Permission.DeleteDescription);
this.deleterFactory.deleter(DescriptionDeleter.class).deleteAndSaveByIds(List.of(id), false);
}
//endregion
//region clone
@Override
public void clone(UUID dmpId, UUID descriptionId) throws InvalidApplicationException {
logger.debug("cloning description: {} with dmp: {}", descriptionId, dmpId);
this.authorizationService.authorizeForce(Permission.CloneDescription);
DescriptionEntity existing = this.queryFactory.query(DescriptionQuery.class).ids(descriptionId).isActive(IsActive.Active).first();
DescriptionEntity newDescription = new DescriptionEntity();
newDescription.setId(UUID.randomUUID());
newDescription.setLabel(existing.getLabel());
newDescription.setDescription(existing.getDescription());
newDescription.setStatus(DescriptionStatus.Draft);
newDescription.setProperties(existing.getProperties());
newDescription.setDmpId(dmpId);
newDescription.setDmpDescriptionTemplateId(existing.getDmpDescriptionTemplateId());
newDescription.setDescriptionTemplateId(existing.getDescriptionTemplateId());
newDescription.setCreatedById(userScope.getUserId());
newDescription.setCreatedAt(Instant.now());
newDescription.setUpdatedAt(Instant.now());
newDescription.setIsActive(IsActive.Active);
this.entityManager.persist(newDescription);
List<DescriptionReferenceEntity> descriptionReferences = this.queryFactory.query(DescriptionReferenceQuery.class)
.descriptionIds(existing.getId())
.isActive(IsActive.Active)
.collect();
List<DescriptionTagEntity> descriptionTags = this.queryFactory.query(DescriptionTagQuery.class)
.descriptionIds(existing.getId())
.isActive(IsActive.Active)
.collect();
for (DescriptionReferenceEntity descriptionReference : descriptionReferences) {
DescriptionReferenceEntity newReference = new DescriptionReferenceEntity();
newReference.setId(UUID.randomUUID());
newReference.setDescriptionId(newDescription.getId());
newReference.setReferenceId(descriptionReference.getReferenceId());
newReference.setCreatedAt(Instant.now());
newReference.setUpdatedAt(Instant.now());
newReference.setIsActive(IsActive.Active);
this.entityManager.persist(newReference);
}
for(DescriptionTagEntity descriptionTag : descriptionTags) {
DescriptionTagEntity newTag = new DescriptionTagEntity();
newTag.setId(UUID.randomUUID());
newTag.setDescriptionId(newDescription.getId());
newTag.setTagId(descriptionTag.getTagId());
newTag.setCreatedAt(Instant.now());
newTag.setUpdatedAt(Instant.now());
newTag.setIsActive(IsActive.Active);
this.entityManager.persist(newTag);
}
this.entityManager.flush();
}
//endregion
}