Resolving issues with validators, removing old validation methods

This commit is contained in:
Thomas Georgios Giannos 2024-01-05 13:32:38 +02:00
parent 7ba374d844
commit 897d099c2c
28 changed files with 461 additions and 606 deletions

View File

@ -1,11 +0,0 @@
package eu.eudat.commons.validation.old;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class EnumNotNull implements ConstraintValidator<ValidEnum,Object> {
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value != null;
}
}

View File

@ -1,22 +0,0 @@
package eu.eudat.commons.validation.old;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Constraint( validatedBy = { FieldNotNullIfOtherSetValidator.class } )
@Documented
@Target( { ElementType.TYPE } )
@Retention( RetentionPolicy.RUNTIME )
public @interface FieldNotNullIfOtherSet {
Class<?>[] groups() default {};
String notNullField() default "id";
String otherSetField() default "hash";
String failOn() default "hash";
String message() default "hash is required if id is set";
Class<? extends Payload>[] payload() default {};
}

View File

@ -1,36 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import org.springframework.beans.BeanWrapperImpl;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Objects;
public class FieldNotNullIfOtherSetValidator implements ConstraintValidator<FieldNotNullIfOtherSet, Object> {
private String notNullField;
private String otherSetField;
@Override
public void initialize(FieldNotNullIfOtherSet constraintAnnotation) {
this.notNullField = constraintAnnotation.notNullField();
this.otherSetField = constraintAnnotation.otherSetField();
}
@Override
public boolean isValid(Object entity, ConstraintValidatorContext context) {
Object notNullValue = new BeanWrapperImpl(entity)
.getPropertyValue(this.notNullField);
Object otherSetValue = new BeanWrapperImpl(entity)
.getPropertyValue(this.otherSetField);
boolean hashIsString = Objects.equals(new BeanWrapperImpl(entity)
.getPropertyType(this.otherSetField), String.class);
boolean hashValueEmpty = otherSetValue == null || (hashIsString && ((String)otherSetValue).isBlank());
if (notNullValue != null && hashValueEmpty) return false;
return true;
}
}

View File

@ -1,29 +0,0 @@
package eu.eudat.commons.validation.old;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = FieldsValueMatchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsValueMatch {
Class<?>[] groups() default {};
String field();
String fieldMatch();
String failOn();
String message() default "Fields values don't match!";
Class<? extends Payload>[] payload() default {};
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface List {
FieldsValueMatch[] value();
}
}

View File

@ -1,32 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.commons.validation.old.FieldsValueMatch;
import org.springframework.beans.BeanWrapperImpl;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {
private String field;
private String fieldMatch;
@Override
public void initialize(FieldsValueMatch constraintAnnotation) {
this.field = constraintAnnotation.field();
this.fieldMatch = constraintAnnotation.fieldMatch();
}
@Override
public boolean isValid(Object entity, ConstraintValidatorContext context) {
Object fieldValue = new BeanWrapperImpl(entity).getPropertyValue(field);
Object fieldMatchValue = new BeanWrapperImpl(entity).getPropertyValue(fieldMatch);
if (fieldValue != null) {
return fieldValue.equals(fieldMatchValue);
} else {
return fieldMatchValue == null;
}
}
}

View File

@ -1,21 +0,0 @@
package eu.eudat.commons.validation.old;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Constraint( validatedBy = { RequiredOneFieldValidator.class } )
@Documented
@Target( { ElementType.TYPE } )
@Retention( RetentionPolicy.RUNTIME )
public @interface RequiredOneField {
String message() default "One field is required";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] fieldNames();
}

View File

@ -1,41 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.commons.validation.old.RequiredOneField;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.PropertyUtils;
public class RequiredOneFieldValidator implements ConstraintValidator<RequiredOneField, Object> {
private String[] fieldNames;
public void initialize(RequiredOneField constraintAnnotation) {
this.fieldNames = constraintAnnotation.fieldNames();
}
public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {
if (object == null) {
return true;
}
int requiredCount = 0;
try {
for (String fieldName:fieldNames){
Object property = PropertyUtils.getProperty(object, fieldName);
if (property != null) {
requiredCount = requiredCount + 1;
}
}
if (requiredCount == 1){
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
}

View File

@ -1,17 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.commons.validation.old.EnumNotNull;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Constraint(validatedBy = EnumNotNull.class)
@Documented
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidEnum {
String message() default "enum is required";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -1,18 +0,0 @@
package eu.eudat.commons.validation.old;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Constraint( validatedBy = { ValidIdValidator.class } )
@Documented
@Target( { ElementType.FIELD } )
@Retention( RetentionPolicy.RUNTIME )
public @interface ValidId {
Class<?>[] groups() default {};
String message() default "id set but not valid";
Class<? extends Payload>[] payload() default {};
}

View File

@ -1,41 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.commons.validation.old.ValidId;
import eu.eudat.convention.ConventionService;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.UUID;
public class ValidIdValidator implements ConstraintValidator<ValidId, Object> {
@Autowired
private ConventionService conventionService;
@Override
public void initialize(ValidId constraintAnnotation) { }
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
if(o == null) return true;
else if(o instanceof UUID){
UUID uuidId = (UUID)o;
return this.conventionService.isValidGuid(uuidId);
}
else if(o instanceof Integer){
Integer intId = (Integer)o;
return this.conventionService.isValidId(intId);
}
else{
String stringId = o.toString();
UUID uuidId = null;
try {
uuidId = UUID.fromString(stringId);
}catch (Exception ex){
return false;
}
return this.conventionService.isValidGuid(uuidId);
}
}
}

View File

@ -1,33 +0,0 @@
package eu.eudat.commons.validation.old;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import gr.cite.tools.exception.MyValidationException;
import gr.cite.tools.validation.BaseValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.validation.Validator;
import java.util.List;
import java.util.Map;
@Service
public class ValidationServiceImpl extends BaseValidationService {
private final ErrorThesaurusProperties errors;
@Autowired
public ValidationServiceImpl(Validator validator, ErrorThesaurusProperties errors) {
super(validator);
this.errors = errors;
}
@Override
public <T> void validateForce(T item, Class<?>... groups) {
List<Map.Entry<String, List<String>>> validationErrors = this.validate(item, groups);
if (validationErrors != null && !validationErrors.isEmpty()) {
throw new MyValidationException(this.errors.getModelValidation().getCode(),
this.errors.getModelValidation().getMessage(),
validationErrors);
}
}
}

View File

@ -1,15 +1,14 @@
package eu.eudat.integrationevent.outbox.notification;
import eu.eudat.audit.AuditableAction;
import eu.eudat.commons.enums.ContactInfoType;
import eu.eudat.commons.enums.notification.NotificationContactType;
import eu.eudat.commons.enums.notification.NotificationNotifyState;
import eu.eudat.commons.enums.notification.NotificationTrackingProcess;
import eu.eudat.commons.enums.notification.NotificationTrackingState;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.data.UserContactInfoEntity;
import eu.eudat.data.UserEntity;
import eu.eudat.integrationevent.outbox.OutboxIntegrationEvent;
import eu.eudat.integrationevent.outbox.OutboxService;
import eu.eudat.model.persist.notification.NotificationPersist;
import eu.eudat.query.UserContactInfoQuery;
@ -19,7 +18,6 @@ import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.validation.ValidationService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -28,79 +26,86 @@ import org.springframework.web.context.annotation.RequestScope;
import javax.management.InvalidApplicationException;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@Component
@RequestScope
public class NotificationIntegrationEventHandlerImpl implements NotificationIntegrationEventHandler {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationIntegrationEventHandlerImpl.class));
private final NotificationService notificationService;
private final ValidationService validationService;
private final QueryFactory queryFactory;
private final AuditService auditService;
private final OutboxService outboxService;
@Autowired
public NotificationIntegrationEventHandlerImpl(
OutboxService outboxService,
NotificationService notificationService,
ValidationService validationService,
QueryFactory queryFactory,
AuditService auditService) {
this.outboxService = outboxService;
this.notificationService = notificationService;
this.validationService = validationService;
this.queryFactory = queryFactory;
this.auditService = auditService;
}
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationIntegrationEventHandlerImpl.class));
@Override
public void handle(NotificationIntegrationEvent event) throws InvalidApplicationException {
private final NotificationService notificationService;
private final QueryFactory queryFactory;
private final AuditService auditService;
private final OutboxService outboxService;
private final ValidatorFactory validatorFactory;
@Autowired
public NotificationIntegrationEventHandlerImpl(
OutboxService outboxService,
NotificationService notificationService,
QueryFactory queryFactory,
AuditService auditService, ValidatorFactory validatorFactory) {
this.outboxService = outboxService;
this.notificationService = notificationService;
this.validatorFactory = validatorFactory;
this.queryFactory = queryFactory;
this.auditService = auditService;
}
@Override
public void handle(NotificationIntegrationEvent event) throws InvalidApplicationException {
// OutboxIntegrationEvent message = new OutboxIntegrationEvent();
// message.setMessageId(UUID.randomUUID());
// message.setType(OutboxIntegrationEvent.NOTIFY);
// message.setEvent(event);
// this.outboxService.publish(message);
NotificationPersist persist = new NotificationPersist();
persist.setType(event.getNotificationType());
persist.setUserId(event.getUserId());
persist.setContactHint(event.getContactHint());
persist.setContactTypeHint(event.getContactTypeHint());
persist.setData(event.getData());
persist.setNotifyState(NotificationNotifyState.PENDING);
persist.setNotifiedWith(NotificationContactType.EMAIL);
persist.setRetryCount(0);
persist.setTrackingState(NotificationTrackingState.UNDEFINED);
persist.setTrackingProcess(NotificationTrackingProcess.PENDING);
persist.setTrackingData(null);
persist.setProvenanceRef(event.getProvenanceRef());
persist.setNotifiedAt(Instant.now());
//validationService.validateForce(persist); //TODO
if (isNotificationConsistent(persist)) {
notificationService.persist(persist, null);
auditService.track(AuditableAction.Notification_Persist, "notification_event", event);
}
}
NotificationPersist persist = new NotificationPersist();
persist.setType(event.getNotificationType());
persist.setUserId(event.getUserId());
persist.setContactHint(event.getContactHint());
persist.setContactTypeHint(event.getContactTypeHint());
persist.setData(event.getData());
persist.setNotifyState(NotificationNotifyState.PENDING);
persist.setNotifiedWith(NotificationContactType.EMAIL);
persist.setRetryCount(0);
persist.setTrackingState(NotificationTrackingState.UNDEFINED);
persist.setTrackingProcess(NotificationTrackingProcess.PENDING);
persist.setTrackingData(null);
persist.setProvenanceRef(event.getProvenanceRef());
persist.setNotifiedAt(Instant.now());
validatorFactory.validator(NotificationPersist.NotificationPersistValidator.class).validateForce(persist);
if (isNotificationConsistent(persist)) {
notificationService.persist(persist, null);
auditService.track(AuditableAction.Notification_Persist, "notification_event", event);
}
}
private boolean isNotificationConsistent(NotificationPersist notification) {
switch (notification.getContactTypeHint()){
case IN_APP:{
if (notification.getUserId() == null) return false;
private boolean isNotificationConsistent(NotificationPersist notification) {
switch (notification.getContactTypeHint()) {
case IN_APP: {
if (notification.getUserId() == null)
return false;
List<UserEntity> users = this.queryFactory.query(UserQuery.class).ids(notification.getUserId()).collect();
return users.size() > 0;
}
case EMAIL:{
if (notification.getContactHint() != null && !notification.getContactHint().isBlank()) return true;
List<UserEntity> users = this.queryFactory.query(UserQuery.class).ids(notification.getUserId()).collect();
return !users.isEmpty();
}
case EMAIL: {
if (notification.getContactHint() != null && !notification.getContactHint().isBlank())
return true;
if (notification.getUserId() == null) return false;
if (notification.getUserId() == null)
return false;
List<UserContactInfoEntity> userContactInfoEntities = this.queryFactory.query(UserContactInfoQuery.class).types(ContactInfoType.Email).userIds(notification.getUserId()).collect();
return userContactInfoEntities.size() > 0;
}
default:
throw new MyApplicationException("invalid type " + notification.getContactTypeHint());
}
}
List<UserContactInfoEntity> userContactInfoEntities = this.queryFactory.query(UserContactInfoQuery.class).types(ContactInfoType.Email).userIds(notification.getUserId()).collect();
return !userContactInfoEntities.isEmpty();
}
default:
throw new MyApplicationException("invalid type " + notification.getContactTypeHint());
}
}
}

View File

@ -90,13 +90,13 @@ public class CloneDmpPersist {
.must(() -> this.isValidGuid(item.getId()))
.failOn(CloneDmpPersist._id).failWith(messageSource.getMessage("Validation_Required", new Object[]{CloneDmpPersist._id}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> this.isEmpty(item.getLabel()))
.must(() -> !this.isEmpty(item.getLabel()))
.failOn(CloneDmpPersist._label).failWith(messageSource.getMessage("Validation_Required", new Object[]{CloneDmpPersist._label}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> this.isEmpty(item.getDescription()))
.must(() -> !this.isEmpty(item.getDescription()))
.failOn(CloneDmpPersist._description).failWith(messageSource.getMessage("Validation_Required", new Object[]{CloneDmpPersist._description}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> this.isNull(item.getDescriptions()))
.must(() -> !this.isNull(item.getDescriptions()))
.failOn(CloneDmpPersist._descriptions).failWith(messageSource.getMessage("Validation_Required", new Object[]{CloneDmpPersist._descriptions}, LocaleContextHolder.getLocale()))
);
}

View File

@ -3,7 +3,6 @@ package eu.eudat.model.persist;
import eu.eudat.commons.enums.DescriptionStatus;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DescriptionEntity;
@ -19,7 +18,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@FieldNotNullIfOtherSet(message = "{validation.hashempty}")
public class DescriptionPersist {
private UUID id;
@ -193,19 +191,23 @@ public class DescriptionPersist {
.must(() -> this.isValidGuid(item.getDmpId()))
.failOn(DescriptionPersist._dmpId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._dmpId}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DescriptionStatus.Finalized)
.must(() -> this.isValidGuid(item.getDescriptionTemplateId()))
.failOn(DescriptionPersist._descriptionTemplateId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._descriptionTemplateId}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DescriptionStatus.Finalized)
.must(() -> this.isValidGuid(item.getDmpDescriptionTemplateId()))
.failOn(DescriptionPersist._dmpDescriptionTemplateId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._dmpDescriptionTemplateId}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getStatus()))
.failOn(DescriptionPersist._status).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._status}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DescriptionStatus.Finalized)
.must(() -> !this.isNull(item.getTags()))
.failOn(DescriptionPersist._tags).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._tags}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DescriptionStatus.Finalized)
.must(() -> !this.isNull(item.getProperties()))
.failOn(DescriptionPersist._properties).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._properties}, LocaleContextHolder.getLocale())),
this.refSpec()
@ -214,10 +216,11 @@ public class DescriptionPersist {
.over(item.getProperties())
.using(() -> this.validatorFactory.validator(PropertyDefinitionPersist.PropertyDefinitionPersistValidator.class)),
this.spec()
.iff(() -> item.getStatus() == DescriptionStatus.Finalized)
.must(() -> !this.isNull(item.getReferences()))
.failOn(DescriptionPersist._references).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionPersist._references}, LocaleContextHolder.getLocale())),
this.navSpec()
.iff(() -> !this.isNull(item.getReferences()))
.iff(() -> item.getStatus() == DescriptionStatus.Finalized && !this.isNull(item.getReferences()))
.on(DescriptionPersist._references)
.over(item.getReferences())
.using(() -> this.validatorFactory.validator(DescriptionReferencePersist.DescriptionReferencePersistValidator.class))

View File

@ -75,7 +75,7 @@ public class DescriptionStatusPersist {
protected List<Specification> specifications(DescriptionStatusPersist item) {
return Arrays.asList(
this.spec()
.must(() -> !this.isValidGuid(item.getId()))
.must(() -> this.isValidGuid(item.getId()))
.failOn(DescriptionStatusPersist._id).failWith(messageSource.getMessage("Validation_Required", new Object[]{DescriptionStatusPersist._id}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> this.isValidGuid(item.getId()))

View File

@ -1,9 +1,11 @@
package eu.eudat.model.persist;
import eu.eudat.commons.enums.DmpStatus;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import eu.eudat.model.persist.validation.StatusAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
@ -42,12 +44,14 @@ public class DmpDescriptionTemplatePersist {
@Component(DmpDescriptionTemplatePersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class DmpDescriptionTemplatePersistValidator extends BaseValidator<DmpDescriptionTemplatePersist> {
public static class DmpDescriptionTemplatePersistValidator extends BaseValidator<DmpDescriptionTemplatePersist> implements StatusAware<DmpStatus> {
public static final String ValidatorName = "DmpDescriptionTemplatePersistValidator";
private final MessageSource messageSource;
private DmpStatus status;
protected DmpDescriptionTemplatePersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) {
super(conventionService, errors);
this.messageSource = messageSource;
@ -62,13 +66,21 @@ public class DmpDescriptionTemplatePersist {
protected List<Specification> specifications(DmpDescriptionTemplatePersist item) {
return Arrays.asList(
this.spec()
.iff(() -> this.status == DmpStatus.Finalized)
.must(() -> this.isValidGuid(item.getDescriptionTemplateGroupId()))
.failOn(DmpDescriptionTemplatePersist._descriptionTemplateGroupId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpDescriptionTemplatePersist._descriptionTemplateGroupId}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> this.status == DmpStatus.Finalized)
.must(() -> this.isValidGuid(item.getSectionId()))
.failOn(DmpDescriptionTemplatePersist._sectionId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpDescriptionTemplatePersist._sectionId}, LocaleContextHolder.getLocale()))
);
}
@Override
public DmpDescriptionTemplatePersistValidator setStatus(DmpStatus status) {
this.status = status;
return this;
}
}
}

View File

@ -4,20 +4,11 @@ import eu.eudat.commons.enums.DmpAccessType;
import eu.eudat.commons.enums.DmpStatus;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.old.ValidEnum;
import eu.eudat.commons.validation.old.ValidId;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DescriptionEntity;
import eu.eudat.data.DmpEntity;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import eu.eudat.model.persist.descriptionproperties.PropertyDefinitionPersist;
import eu.eudat.model.persist.dmpproperties.DmpPropertiesPersist;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
@ -197,33 +188,37 @@ public class DmpPersist {
.must(() -> !this.isNull(item.getStatus()))
.failOn(DmpPersist._status).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpPersist._status}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DmpStatus.Finalized)
.must(() -> this.isValidGuid(item.getBlueprint()))
.failOn(DmpPersist._blueprint).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpPersist._blueprint}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> item.getStatus() == DmpStatus.Finalized)
.must(() -> !this.isNull(item.getProperties()))
.failOn(DmpPersist._properties).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpPersist._properties}, LocaleContextHolder.getLocale())),
this.refSpec()
.iff(() -> !this.isNull(item.getProperties()))
.on(DmpPersist._properties)
.over(item.getProperties())
.using(() -> this.validatorFactory.validator(DmpPropertiesPersist.DmpPropertiesPersistValidator.class)),
.using(() -> this.validatorFactory.validator(DmpPropertiesPersist.DmpPropertiesPersistValidator.class).setStatus(item.getStatus())),
this.spec()
.iff(() -> item.getStatus() == DmpStatus.Finalized)
.must(() -> !this.isNull(item.getReferences()))
.failOn(DmpPersist._references).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpPersist._references}, LocaleContextHolder.getLocale())),
this.navSpec()
.iff(() -> !this.isNull(item.getReferences()))
.iff(() -> item.getStatus() == DmpStatus.Finalized && !this.isNull(item.getReferences()))
.on(DmpPersist._references)
.over(item.getReferences())
.using(() -> this.validatorFactory.validator(DmpReferencePersist.DmpReferencePersistValidator.class)),
this.spec()
.iff(() -> item.getStatus() == DmpStatus.Finalized)
.must(() -> !this.isNull(item.getDescriptionTemplates()))
.failOn(DmpPersist._descriptionTemplates).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpPersist._descriptionTemplates}, LocaleContextHolder.getLocale())),
this.navSpec()
.iff(() -> !this.isNull(item.getDescriptionTemplates()))
.on(DmpPersist._descriptionTemplates)
.over(item.getDescriptionTemplates())
.using(() -> this.validatorFactory.validator(DmpDescriptionTemplatePersist.DmpDescriptionTemplatePersistValidator.class))
.using(() -> this.validatorFactory.validator(DmpDescriptionTemplatePersist.DmpDescriptionTemplatePersistValidator.class).setStatus(item.getStatus()))
);
}
}

View File

@ -109,6 +109,7 @@ public class DmpReferencePersist {
.using(() -> this.validatorFactory.validator(ReferencePersist.ReferencePersistValidator.class))
);
}
}
}

View File

@ -63,7 +63,7 @@ public class DmpUserInviteTypePersist {
return Arrays.asList(
this.spec()
.iff(() -> this.isEmpty(item.getEmail()))
.must(() -> !this.isValidGuid(item.getUserId()))
.must(() -> this.isValidGuid(item.getUserId()))
.failOn(DmpUserInviteTypePersist._userId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpUserInviteTypePersist._userId}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isValidGuid(item.getUserId()))

View File

@ -63,7 +63,7 @@ public class DmpUserPersist {
protected List<Specification> specifications(DmpUserPersist item) {
return Arrays.asList(
this.spec()
.must(() -> !this.isValidGuid(item.getUser()))
.must(() -> this.isValidGuid(item.getUser()))
.failOn(DmpUserPersist._user).failWith(messageSource.getMessage("Validation_Required", new Object[]{DmpUserPersist._user}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getRole()))

View File

@ -119,7 +119,7 @@ public class NewVersionDmpPersist {
.must(() -> !this.isEmpty(item.getDescription()))
.failOn(NewVersionDmpPersist._description).failWith(messageSource.getMessage("Validation_Required", new Object[]{NewVersionDmpPersist._description}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isValidGuid(item.getBlueprintId()))
.must(() -> this.isValidGuid(item.getBlueprintId()))
.failOn(NewVersionDmpPersist._blueprintId).failWith(messageSource.getMessage("Validation_Required", new Object[]{NewVersionDmpPersist._blueprintId}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getDescriptions()))

View File

@ -86,7 +86,7 @@ public class DepositRequest {
.must(() -> !this.isEmpty(item.getRepositoryId()))
.failOn(DepositRequest._repositoryId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DepositRequest._repositoryId}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isValidGuid(item.getDmpId()))
.must(() -> this.isValidGuid(item.getDmpId()))
.failOn(DepositRequest._dmpId).failWith(messageSource.getMessage("Validation_Required", new Object[]{DepositRequest._dmpId}, LocaleContextHolder.getLocale()))
);
}

View File

@ -1,10 +1,13 @@
package eu.eudat.model.persist.dmpproperties;
import eu.eudat.commons.enums.DmpStatus;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import eu.eudat.model.persist.DmpPersist;
import eu.eudat.model.persist.validation.StatusAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@ -40,12 +43,14 @@ public class DmpPropertiesPersist {
@Component(DmpPropertiesPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class DmpPropertiesPersistValidator extends BaseValidator<DmpPropertiesPersist> {
public static class DmpPropertiesPersistValidator extends BaseValidator<DmpPropertiesPersist> implements StatusAware<DmpStatus> {
public static final String ValidatorName = "DmpPropertiesPersistValidator";
private final ValidatorFactory validatorFactory;
private DmpStatus status;
protected DmpPropertiesPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, ValidatorFactory validatorFactory) {
super(conventionService, errors);
this.validatorFactory = validatorFactory;
@ -60,17 +65,24 @@ public class DmpPropertiesPersist {
protected List<Specification> specifications(DmpPropertiesPersist item) {
return Arrays.asList(
this.refSpec()
.iff(() -> !this.isNull(item.getDmpBlueprintValues()))
.iff(() -> this.status == DmpStatus.Finalized && !this.isNull(item.getDmpBlueprintValues()))
.on(DmpPropertiesPersist._dmpBlueprintValues)
.over(item.getDmpBlueprintValues())
.using(() -> this.validatorFactory.validator(DmpBlueprintValuePersist.DmpBlueprintValuePersistValidator.class)),
this.refSpec()
.iff(() -> !this.isNull(item.getContacts()))
.iff(() -> this.status == DmpStatus.Finalized && !this.isNull(item.getContacts()))
.on(DmpPropertiesPersist._contacts)
.over(item.getContacts())
.using(() -> this.validatorFactory.validator(DmpContactPersist.DmpContactPersistValidator.class))
);
}
@Override
public DmpPropertiesPersistValidator setStatus(DmpStatus status) {
this.status = status;
return this;
}
}
}

View File

@ -4,23 +4,29 @@ import eu.eudat.commons.enums.notification.NotificationContactType;
import eu.eudat.commons.enums.notification.NotificationNotifyState;
import eu.eudat.commons.enums.notification.NotificationTrackingProcess;
import eu.eudat.commons.enums.notification.NotificationTrackingState;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.old.ValidId;
import jakarta.validation.constraints.NotNull;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@FieldNotNullIfOtherSet(message = "{validation.hashempty}")
public class NotificationPersist {
@ValidId(message = "{validation.invalidid}")
private UUID id;
@NotNull(message = "{validation.empty}")
private UUID userId;
public static final String _userId = "userId";
private UUID type;
private NotificationContactType contactTypeHint;
@ -47,6 +53,8 @@ public class NotificationPersist {
private String hash;
public static final String _hash = "hash";
public UUID getId() {
return id;
}
@ -166,4 +174,41 @@ public class NotificationPersist {
public void setHash(String hash) {
this.hash = hash;
}
@Component(NotificationPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class NotificationPersistValidator extends BaseValidator<NotificationPersist> {
public static final String ValidatorName = "NotificationPersistValidator";
private final MessageSource messageSource;
protected NotificationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) {
super(conventionService, errors);
this.messageSource = messageSource;
}
@Override
protected Class<NotificationPersist> modelClass() {
return NotificationPersist.class;
}
@Override
protected List<Specification> specifications(NotificationPersist item) {
return Arrays.asList(
this.spec()
.iff(() -> this.isValidGuid(item.getId()))
.must(() -> this.isValidHash(item.getHash()))
.failOn(NotificationPersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationPersist._hash}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isValidGuid(item.getId()))
.must(() -> !this.isValidHash(item.getHash()))
.failOn(NotificationPersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> this.isValidGuid(item.getUserId()))
.failOn(NotificationPersist._userId).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationPersist._userId}, LocaleContextHolder.getLocale()))
);
}
}
}

View File

@ -2,14 +2,10 @@ package eu.eudat.model.persist.referencedefinition;
import eu.eudat.commons.enums.ReferenceFieldDataType;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.old.ValidEnum;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import eu.eudat.model.persist.DescriptionTemplateTypePersist;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;

View File

@ -0,0 +1,7 @@
package eu.eudat.model.persist.validation;
public interface StatusAware<T extends Enum<?>> {
StatusAware<T> setStatus(T status);
}

View File

@ -13,6 +13,7 @@ import eu.eudat.commons.types.descriptiontemplate.*;
import eu.eudat.commons.types.descriptiontemplate.fielddata.BaseFieldDataEntity;
import eu.eudat.commons.types.descriptiontemplate.importexport.*;
import eu.eudat.commons.types.notification.*;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.configurations.notification.NotificationProperties;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DescriptionTemplateEntity;
@ -81,11 +82,13 @@ import java.util.stream.Collectors;
@Service
public class DescriptionTemplateServiceImpl implements DescriptionTemplateService {
private List<Semantic> semantics = null;
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateServiceImpl.class));
private final EntityManager entityManager;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@ -93,20 +96,33 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
private final DeleterFactory deleterFactory;
private final BuilderFactory builderFactory;
private final ConventionService conventionService;
private final MessageSource messageSource;
private final XmlHandlingService xmlHandlingService;
private final FieldDataHelperServiceProvider fieldDataHelperServiceProvider;
private final QueryFactory queryFactory;
private final ErrorThesaurusProperties errors;
private final ValidationService validationService;
private final TenantScope tenantScope;
private final ResponseUtilsService responseUtilsService;
private final StorageFileService storageFileService;
private final JsonHandlingService jsonHandlingService;
private final NotificationIntegrationEventHandler eventHandler;
private final NotificationProperties notificationProperties;
private final ValidatorFactory validatorFactory;
@Autowired
public DescriptionTemplateServiceImpl(
EntityManager entityManager,
@ -116,7 +132,15 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
ConventionService conventionService,
MessageSource messageSource,
XmlHandlingService xmlHandlingService,
FieldDataHelperServiceProvider fieldDataHelperServiceProvider, QueryFactory queryFactory, ErrorThesaurusProperties errors, ValidationService validationService, TenantScope tenantScope, ResponseUtilsService responseUtilsService, StorageFileService storageFileService, JsonHandlingService jsonHandlingService, NotificationIntegrationEventHandler eventHandler, NotificationProperties notificationProperties) {
FieldDataHelperServiceProvider fieldDataHelperServiceProvider,
QueryFactory queryFactory, ErrorThesaurusProperties errors,
TenantScope tenantScope,
ResponseUtilsService responseUtilsService,
StorageFileService storageFileService,
JsonHandlingService jsonHandlingService,
NotificationIntegrationEventHandler eventHandler,
NotificationProperties notificationProperties,
ValidatorFactory validatorFactory) {
this.entityManager = entityManager;
this.userScope = userScope;
this.authorizationService = authorizationService;
@ -128,15 +152,15 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.fieldDataHelperServiceProvider = fieldDataHelperServiceProvider;
this.queryFactory = queryFactory;
this.errors = errors;
this.validationService = validationService;
this.tenantScope = tenantScope;
this.responseUtilsService = responseUtilsService;
this.storageFileService = storageFileService;
this.jsonHandlingService = jsonHandlingService;
this.eventHandler = eventHandler;
this.notificationProperties = notificationProperties;
this.validatorFactory = validatorFactory;
}
//region Persist
public DescriptionTemplate persist(DescriptionTemplatePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
@ -149,9 +173,12 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
DescriptionTemplateEntity data;
if (isUpdate) {
data = this.entityManager.find(DescriptionTemplateEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.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() == DescriptionTemplateStatus.Finalized) throw new MyForbiddenException("Can not update finalized template");
if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.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() == DescriptionTemplateStatus.Finalized)
throw new MyForbiddenException("Can not update finalized template");
} else {
data = new DescriptionTemplateEntity();
data.setId(UUID.randomUUID());
@ -159,7 +186,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setCreatedAt(Instant.now());
data.setGroupId(UUID.randomUUID());
data.setVersionStatus(DescriptionTemplateVersionStatus.Current);
data.setVersion((short)1);
data.setVersion((short) 1);
}
data.setDescription(model.getDescription());
@ -173,22 +200,24 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.entityManager.merge(data);
else
this.entityManager.persist(data);
this.persistUsers(data.getId(), model.getUsers());
if (!isUpdate) this.addOwner(data);
if (!isUpdate)
this.addOwner(data);
this.entityManager.flush();
return this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, DescriptionTemplate._id), data);
}
private void persistUsers(UUID id, List<UserDescriptionTemplatePersist> users) throws InvalidApplicationException {
if (users == null) users = new ArrayList<>();
if (users == null)
users = new ArrayList<>();
List<UserDescriptionTemplateEntity> items = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(id).collect();
List<UUID> updatedCreatedIds = new ArrayList<>();
for (UserDescriptionTemplatePersist user : users) {
UserDescriptionTemplateEntity data = items.stream().filter(x -> x.getUserId().equals(user.getUserId()) && x.getRole().equals(user.getRole())).findFirst().orElse(null);
if (data == null){
if (data == null) {
data = new UserDescriptionTemplateEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
@ -202,10 +231,11 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
}
updatedCreatedIds.add(data.getId());
}
List<UserDescriptionTemplateEntity> toDelete = items.stream().filter(x-> updatedCreatedIds.stream().noneMatch(y-> y.equals(x.getId()))).collect(Collectors.toList());
List<UserDescriptionTemplateEntity> toDelete = items.stream().filter(x -> updatedCreatedIds.stream().noneMatch(y -> y.equals(x.getId()))).collect(Collectors.toList());
this.deleterFactory.deleter(UserDescriptionTemplateDeleter.class).delete(toDelete);
}
private void sendJoinMail(UserDescriptionTemplateEntity userDescriptionTemplate) throws InvalidApplicationException {
NotificationIntegrationEvent event = new NotificationIntegrationEvent();
event.setTenant(tenantScope.getTenant());
@ -233,6 +263,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
eventHandler.handle(event);
}
private void addOwner(DescriptionTemplateEntity descriptionTemplateEntity) throws InvalidApplicationException {
UserDescriptionTemplateEntity data = new UserDescriptionTemplateEntity();
data.setId(UUID.randomUUID());
@ -245,18 +276,19 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.entityManager.persist(data);
}
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist){
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist) {
DefinitionEntity data = new DefinitionEntity();
if (persist == null) return data;
if (!this.conventionService.isListNullOrEmpty(persist.getSections())){
if (persist == null)
return data;
if (!this.conventionService.isListNullOrEmpty(persist.getSections())) {
data.setSections(new ArrayList<>());
for (SectionPersist sectionPersist: persist.getSections()) {
for (SectionPersist sectionPersist : persist.getSections()) {
data.getSections().add(this.buildSectionEntity(sectionPersist));
}
}
if (!this.conventionService.isListNullOrEmpty(persist.getPages())){
if (!this.conventionService.isListNullOrEmpty(persist.getPages())) {
data.setPages(new ArrayList<>());
for (PagePersist pagePersist: persist.getPages()) {
for (PagePersist pagePersist : persist.getPages()) {
data.getPages().add(this.buildPageEntity(pagePersist));
}
}
@ -264,9 +296,10 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return data;
}
private @NotNull SectionEntity buildSectionEntity(SectionPersist persist){
private @NotNull SectionEntity buildSectionEntity(SectionPersist persist) {
SectionEntity data = new SectionEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setDescription(persist.getDescription());
@ -276,16 +309,16 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setPage(persist.getPage());
data.setTitle(persist.getTitle());
if (!this.conventionService.isListNullOrEmpty(persist.getSections())){
if (!this.conventionService.isListNullOrEmpty(persist.getSections())) {
data.setSections(new ArrayList<>());
for (SectionPersist sectionPersist: persist.getSections()) {
for (SectionPersist sectionPersist : persist.getSections()) {
data.getSections().add(this.buildSectionEntity(sectionPersist));
}
}
if (!this.conventionService.isListNullOrEmpty(persist.getFieldSets())){
if (!this.conventionService.isListNullOrEmpty(persist.getFieldSets())) {
data.setFieldSets(new ArrayList<>());
for (FieldSetPersist fieldSetPersist: persist.getFieldSets()) {
for (FieldSetPersist fieldSetPersist : persist.getFieldSets()) {
data.getFieldSets().add(this.buildFieldSetEntity(fieldSetPersist));
}
}
@ -293,9 +326,10 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return data;
}
private @NotNull FieldSetEntity buildFieldSetEntity(FieldSetPersist persist){
private @NotNull FieldSetEntity buildFieldSetEntity(FieldSetPersist persist) {
FieldSetEntity data = new FieldSetEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setDescription(persist.getDescription());
@ -304,22 +338,24 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setNumbering(persist.getNumbering());
data.setAdditionalInformation(persist.getAdditionalInformation());
data.setTitle(persist.getTitle());
if (persist.getMultiplicity() != null) data.setMultiplicity(this.buildMultiplicityEntity(persist.getMultiplicity()));
if (persist.getMultiplicity() != null)
data.setMultiplicity(this.buildMultiplicityEntity(persist.getMultiplicity()));
data.setHasCommentField(persist.getHasCommentField());
data.setTitle(persist.getTitle());
if (!this.conventionService.isListNullOrEmpty(persist.getFields())){
if (!this.conventionService.isListNullOrEmpty(persist.getFields())) {
data.setFields(new ArrayList<>());
for (FieldPersist fieldPersist: persist.getFields()) {
for (FieldPersist fieldPersist : persist.getFields()) {
data.getFields().add(this.buildFieldEntity(fieldPersist));
}
}
return data;
}
private @NotNull FieldEntity buildFieldEntity(FieldPersist persist){
private @NotNull FieldEntity buildFieldEntity(FieldPersist persist) {
FieldEntity data = new FieldEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setOrdinal(persist.getOrdinal());
@ -328,56 +364,65 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setDefaultValue(persist.getDefaultValue());
data.setValidations(persist.getValidations());
data.setIncludeInExport(persist.getIncludeInExport());
if (persist.getData() != null) data.setData(this.buildFieldDataEntity(persist.getData()));
if (persist.getData() != null)
data.setData(this.buildFieldDataEntity(persist.getData()));
if (!this.conventionService.isListNullOrEmpty(persist.getVisibilityRules())){
if (!this.conventionService.isListNullOrEmpty(persist.getVisibilityRules())) {
data.setVisibilityRules(new ArrayList<>());
for (RulePersist fieldPersist: persist.getVisibilityRules()) {
for (RulePersist fieldPersist : persist.getVisibilityRules()) {
data.getVisibilityRules().add(this.buildRuleEntity(fieldPersist));
}
}
return data;
}
private BaseFieldDataEntity<?> buildFieldDataEntity(BaseFieldDataPersist persist){
if (persist == null) return null;
private BaseFieldDataEntity<?> buildFieldDataEntity(BaseFieldDataPersist persist) {
if (persist == null)
return null;
return this.fieldDataHelperServiceProvider.get(persist.getFieldType()).applyPersist(persist);
}
private @NotNull RuleEntity buildRuleEntity(RulePersist persist){
private @NotNull RuleEntity buildRuleEntity(RulePersist persist) {
RuleEntity data = new RuleEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setTarget(persist.getTarget());
data.setValue(persist.getValue());
return data;
}
private @NotNull MultiplicityEntity buildMultiplicityEntity(MultiplicityPersist persist){
private @NotNull MultiplicityEntity buildMultiplicityEntity(MultiplicityPersist persist) {
MultiplicityEntity data = new MultiplicityEntity();
if (persist == null) return data;
if (persist == null)
return data;
if (persist.getMax() != null) data.setMax(persist.getMax());
if (persist.getMin() != null) data.setMin(persist.getMin());
if (persist.getPlaceholder() != null) data.setPlaceholder(persist.getPlaceholder());
if (persist.getTableView() != null) data.setTableView(persist.getTableView());
if (persist.getMax() != null)
data.setMax(persist.getMax());
if (persist.getMin() != null)
data.setMin(persist.getMin());
if (persist.getPlaceholder() != null)
data.setPlaceholder(persist.getPlaceholder());
if (persist.getTableView() != null)
data.setTableView(persist.getTableView());
return data;
}
private @NotNull PageEntity buildPageEntity(PagePersist persist){
private @NotNull PageEntity buildPageEntity(PagePersist persist) {
PageEntity data = new PageEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setOrdinal(persist.getOrdinal());
data.setTitle(persist.getTitle());
return data;
}
//endregion
//region Delete
public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException {
logger.debug("deleting dataset: {}", id);
@ -387,9 +432,9 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
}
//endregion
//region Clone
public DescriptionTemplate buildClone(UUID id, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException {
logger.debug(new MapLogEntry("persisting data").And("id", id).And("fields", fields));
@ -397,7 +442,8 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
DescriptionTemplateQuery query = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).ids(id);
DescriptionTemplate model = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fields, query.firstAs(fields));
if (model == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (model == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
model.setLabel(model.getLabel() + " new ");
model.setId(null);
@ -408,80 +454,89 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return model;
}
private void reassignDefinition(Definition model){
if (model == null) return;
private void reassignDefinition(Definition model) {
if (model == null)
return;
if (model.getSections() != null){
if (model.getSections() != null) {
for (Section section : model.getSections()) {
this.reassignSection(section);
}
}
if (model.getPages() != null){
if (model.getPages() != null) {
for (Page page : model.getPages()) {
this.reassignPage(page);
}
}
}
private void reassignPage(Page model){
if (model == null) return;
private void reassignPage(Page model) {
if (model == null)
return;
model.setId(UUID.randomUUID().toString());
}
private void reassignSection(Section model){
if (model == null) return;
private void reassignSection(Section model) {
if (model == null)
return;
model.setId(UUID.randomUUID().toString());
if (model.getSections() != null){
if (model.getSections() != null) {
for (Section section : model.getSections()) {
this.reassignSection(section);
}
}
if (model.getFieldSets() != null){
if (model.getFieldSets() != null) {
for (eu.eudat.model.descriptiontemplatedefinition.FieldSet fieldSet : model.getFieldSets()) {
this.reassignFieldSet(fieldSet);
}
}
}
private void reassignFieldSet(eu.eudat.model.descriptiontemplatedefinition.FieldSet model){
if (model == null) return;
private void reassignFieldSet(eu.eudat.model.descriptiontemplatedefinition.FieldSet model) {
if (model == null)
return;
model.setId(UUID.randomUUID().toString());
if (model.getFields() != null){
if (model.getFields() != null) {
for (Field field : model.getFields()) {
this.reassignField(field);
}
}
}
private void reassignField(Field model){
if (model == null) return;
private void reassignField(Field model) {
if (model == null)
return;
model.setId(UUID.randomUUID().toString());
}
//endregion
//region NewVersion
public DescriptionTemplate createNewVersion(NewVersionDescriptionTemplatePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
logger.debug(new MapLogEntry("persisting data descriptionTemplateType").And("model", model).And("fields", fields));
this.authorizationService.authorizeForce(Permission.CreateNewVersionDescriptionTemplate);
DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, model.getId());
if (oldDescriptionTemplateEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
if (oldDescriptionTemplateEntity == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (!this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()).equals(model.getHash()))
throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage());
DescriptionTemplateQuery latestVersionDescriptionTemplateEntityQuery = this.queryFactory.query(DescriptionTemplateQuery.class).versionStatuses(DescriptionTemplateVersionStatus.Current).groupIds(oldDescriptionTemplateEntity.getGroupId());
List<DescriptionTemplateEntity> latestVersionDescriptionTemplates = latestVersionDescriptionTemplateEntityQuery.collect();
if (latestVersionDescriptionTemplates.isEmpty()) throw new MyValidationException("Previous template not found");
if (latestVersionDescriptionTemplates.size() > 1) throw new MyValidationException("Multiple previous template found");
if (!latestVersionDescriptionTemplates.get(0).getVersion().equals(oldDescriptionTemplateEntity.getVersion())){
if (latestVersionDescriptionTemplates.isEmpty())
throw new MyValidationException("Previous template not found");
if (latestVersionDescriptionTemplates.size() > 1)
throw new MyValidationException("Multiple previous template found");
if (!latestVersionDescriptionTemplates.get(0).getVersion().equals(oldDescriptionTemplateEntity.getVersion())) {
throw new MyValidationException(this.errors.getDescriptionTemplateNewVersionConflict().getCode(), this.errors.getDescriptionTemplateNewVersionConflict().getMessage());
}
DescriptionTemplateEntity data = new DescriptionTemplateEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
@ -489,32 +544,32 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
data.setUpdatedAt(Instant.now());
data.setVersionStatus(DescriptionTemplateVersionStatus.Current);
data.setGroupId(oldDescriptionTemplateEntity.getGroupId());
data.setVersion((short)(oldDescriptionTemplateEntity.getVersion() + 1));
data.setVersion((short) (oldDescriptionTemplateEntity.getVersion() + 1));
data.setDescription(model.getDescription());
data.setLabel(model.getLabel());
data.setTypeId(model.getType());
data.setLanguage(model.getLanguage());
data.setStatus(model.getStatus());
data.setDefinition(this.xmlHandlingService.toXml(this.buildDefinitionEntity(model.getDefinition())));
this.entityManager.persist(data);
this.persistUsers(data.getId(), model.getUsers());
//this.addOwner(data);
oldDescriptionTemplateEntity.setVersionStatus(DescriptionTemplateVersionStatus.Previous);
this.entityManager.merge(oldDescriptionTemplateEntity);
this.entityManager.flush();
return this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, DescriptionTemplate._id), data);
}
//endregion
//region Import
public DescriptionTemplate importXml(byte[] bytes, UUID id, String label, FieldSet fields) throws MyForbiddenException, MyNotFoundException, JAXBException, ParserConfigurationException, TransformerException, InvalidApplicationException, IOException, InstantiationException, IllegalAccessException, SAXException {
logger.debug(new MapLogEntry("import data").And("bytes", bytes).And("fields", fields));
@ -529,7 +584,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
persist.setLanguage(importXml.getLanguage());
persist.setType(importXml.getType());
persist.setDefinition(this.xmlDefinitionToPersist(importXml));
this.validationService.validateForce(persist);
this.validatorFactory.validator(DescriptionTemplatePersist.DescriptionTemplatePersistValidator.class).validateForce(persist);
return this.persist(persist, fields);
} else {
NewVersionDescriptionTemplatePersist persist = new NewVersionDescriptionTemplatePersist();
@ -540,19 +595,21 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
persist.setLanguage(importXml.getLanguage());
persist.setDefinition(this.xmlDefinitionToPersist(importXml));
persist.setType(importXml.getType());
DescriptionTemplateEntity oldDescriptionTemplateEntity = this.entityManager.find(DescriptionTemplateEntity.class, id);
if (oldDescriptionTemplateEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (oldDescriptionTemplateEntity == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
persist.setHash(this.conventionService.hashValue(oldDescriptionTemplateEntity.getUpdatedAt()));
this.validationService.validateForce(persist);
this.validatorFactory.validator(DescriptionTemplatePersist.DescriptionTemplatePersistValidator.class).validateForce(persist);
return this.createNewVersion(persist, fields);
}
}
public DefinitionPersist xmlDefinitionToPersist(DescriptionTemplateImportExport importExport){
public DefinitionPersist xmlDefinitionToPersist(DescriptionTemplateImportExport importExport) {
DefinitionPersist definitionPersist = new DefinitionPersist();
if(importExport == null) return null;
if (importExport == null)
return null;
List<PagePersist> pagesDatasetEntity = new LinkedList<>();
List<SectionPersist> sectionDatasetEntity = new LinkedList<>();
if (!this.conventionService.isListNullOrEmpty(importExport.getPages())) {
@ -570,8 +627,8 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return definitionPersist;
}
public PagePersist xmlPageToPersist(PageImportExport importExport){
public PagePersist xmlPageToPersist(PageImportExport importExport) {
PagePersist pageEntity = new PagePersist();
pageEntity.setId(importExport.getId());
pageEntity.setOrdinal(importExport.getOrdinal());
@ -594,7 +651,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
sectionEntity.setPage(importExport.getPage());
sectionEntity.setDescription(importExport.getDescription());
List<FieldSetPersist> fieldSetEntity = new LinkedList<>();
if(!this.conventionService.isListNullOrEmpty(importExport.getFieldSets())) {
if (!this.conventionService.isListNullOrEmpty(importExport.getFieldSets())) {
for (FieldSetImportExport xmlFieldSet : importExport.getFieldSets()) {
fieldSetEntity.add(this.toFieldSetModel(xmlFieldSet));
}
@ -606,7 +663,6 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return sectionEntity;
}
public FieldSetPersist toFieldSetModel(FieldSetImportExport importExport) {
FieldSetPersist fieldSet1Entity = new FieldSetPersist();
fieldSet1Entity.setId(importExport.getId());
@ -619,7 +675,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
fieldSet1Entity.setAdditionalInformation(importExport.getAdditionalInformation());
List<FieldPersist> fieldsEntity = new LinkedList<>();
if (!this.conventionService.isListNullOrEmpty(importExport.getFields())){
if (!this.conventionService.isListNullOrEmpty(importExport.getFields())) {
for (FieldImportExport xmlField : importExport.getFields()) {
fieldsEntity.add(this.xmlFieldToPersist(xmlField));
}
@ -628,15 +684,14 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return fieldSet1Entity;
}
public FieldPersist xmlFieldToPersist(FieldImportExport importExport) {
FieldPersist fieldEntity = new FieldPersist();
FieldPersist fieldEntity = new FieldPersist();
fieldEntity.setId(importExport.getId());
fieldEntity.setOrdinal(importExport.getOrdinal());
fieldEntity.setValidations(importExport.getValidations());
fieldEntity.setDefaultValue(importExport.getDefaultValue());
List<RulePersist> rulePersists = new ArrayList<>();
if(importExport.getVisibilityRules() !=null) {
if (importExport.getVisibilityRules() != null) {
for (RuleImportExport xmlRule : importExport.getVisibilityRules()) {
rulePersists.add(this.toRuleModel(xmlRule));
}
@ -652,14 +707,13 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return fieldEntity;
}
public RulePersist toRuleModel(RuleImportExport importExport){
public RulePersist toRuleModel(RuleImportExport importExport) {
RulePersist ruleEntity = new RulePersist();
ruleEntity.setTarget(importExport.getTarget());
ruleEntity.setValue(importExport.getValue());
return ruleEntity;
}
public MultiplicityPersist xmlMultiplicityToPersist(MultiplicityImportXml importXml) {
MultiplicityPersist multiplicityEntity = new MultiplicityPersist();
multiplicityEntity.setMax(importXml.getMax());
@ -668,9 +722,9 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
multiplicityEntity.setTableView(importXml.getTableView());
return multiplicityEntity;
}
//endregion
//region Export
@Override
@ -679,20 +733,21 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.authorizationService.authorizeForce(Permission.ExportDescriptionTemplate);
DescriptionTemplateEntity data = this.entityManager.find(DescriptionTemplateEntity.class, id);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DefinitionEntity definition = this.xmlHandlingService.fromXml(DefinitionEntity.class, data.getDefinition());
String xml = this.xmlHandlingService.toXml(this.definitionXmlToExport(data, definition));
return this.responseUtilsService.buildResponseFileFromText(xml, data.getLabel() + ".xml");
}
private DescriptionTemplateImportExport definitionXmlToExport(DescriptionTemplateEntity data, DefinitionEntity entity){
private DescriptionTemplateImportExport definitionXmlToExport(DescriptionTemplateEntity data, DefinitionEntity entity) {
DescriptionTemplateImportExport xml = new DescriptionTemplateImportExport();
xml.setType(data.getTypeId());
xml.setLanguage(data.getLanguage());
xml.setDescription(data.getDescription());
List<PageImportExport> pagesDatasetEntity = new LinkedList<>();
for (PageEntity xmlPage: entity.getPages()) {
for (PageEntity xmlPage : entity.getPages()) {
pagesDatasetEntity.add(this.pageXmlToExport(xmlPage, entity.getSections()));
}
xml.setPages(pagesDatasetEntity);
@ -700,7 +755,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return xml;
}
private PageImportExport pageXmlToExport(PageEntity entity, List<SectionEntity> sectionEntities){
private PageImportExport pageXmlToExport(PageEntity entity, List<SectionEntity> sectionEntities) {
PageImportExport xml = new PageImportExport();
xml.setId(entity.getId());
xml.setOrdinal(entity.getOrdinal());
@ -714,7 +769,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
}
}
xml.setSections(sectionsListEntity);
return xml;
}
@ -728,14 +783,14 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
}
}
xml.setSections(sectionsListEntity);
xml.setId(entity.getId());
xml.setOrdinal(entity.getOrdinal());
xml.setTitle(entity.getTitle());
xml.setPage(entity.getPage());
xml.setDescription(entity.getDescription());
List<FieldSetImportExport> fieldSetEntity = new LinkedList<>();
if(!this.conventionService.isListNullOrEmpty(entity.getFieldSets())) {
if (!this.conventionService.isListNullOrEmpty(entity.getFieldSets())) {
for (FieldSetEntity xmlFieldSet : entity.getFieldSets()) {
fieldSetEntity.add(this.fieldSetXmlToExport(xmlFieldSet));
}
@ -746,7 +801,6 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return xml;
}
private FieldSetImportExport fieldSetXmlToExport(FieldSetEntity entity) {
FieldSetImportExport fieldSet1Entity = new FieldSetImportExport();
fieldSet1Entity.setId(entity.getId());
@ -759,7 +813,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
fieldSet1Entity.setAdditionalInformation(entity.getAdditionalInformation());
List<FieldImportExport> fieldsEntity = new LinkedList<>();
if (entity.getFields() != null){
if (entity.getFields() != null) {
for (FieldEntity xmlField : entity.getFields()) {
fieldsEntity.add(this.fieldXmlToExport(xmlField));
}
@ -768,15 +822,14 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return fieldSet1Entity;
}
private FieldImportExport fieldXmlToExport(FieldEntity entity) {
FieldImportExport xml = new FieldImportExport();
FieldImportExport xml = new FieldImportExport();
xml.setId(entity.getId());
xml.setOrdinal(entity.getOrdinal());
xml.setValidations(entity.getValidations());
xml.setDefaultValue(entity.getDefaultValue());
List<RuleImportExport> rulePersists = new ArrayList<>();
if(!this.conventionService.isListNullOrEmpty(entity.getVisibilityRules())) {
if (!this.conventionService.isListNullOrEmpty(entity.getVisibilityRules())) {
for (RuleEntity xmlRule : entity.getVisibilityRules()) {
rulePersists.add(this.toRuleModel(xmlRule));
}
@ -792,14 +845,13 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
return xml;
}
private RuleImportExport toRuleModel(RuleEntity entity){
private RuleImportExport toRuleModel(RuleEntity entity) {
RuleImportExport xml = new RuleImportExport();
xml.setTarget(entity.getTarget());
xml.setValue(entity.getValue());
return xml;
}
private MultiplicityImportXml multiplicityXmlToExport(MultiplicityEntity entity) {
MultiplicityImportXml xml = new MultiplicityImportXml();
xml.setMax(entity.getMax());
@ -808,25 +860,25 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
xml.setTableView(entity.getTableView());
return xml;
}
//endregion
//region
@Override
public List<String> getSemantics(String query) throws IOException {
List<Semantic> semantics = this.getSemantics();
List<String> filteredSemantics = semantics.stream().map(Semantic::getName).collect(Collectors.toList());
if(query != null && !query.isEmpty()){
if (query != null && !query.isEmpty()) {
filteredSemantics = semantics.stream().filter(x -> x.getCategory().contains(query) || x.getName().contains(query)).map(Semantic::getName).collect(Collectors.toList());
}
return filteredSemantics;
}
@Override
public List<Semantic> getSemantics() throws IOException {
this.authorizationService.authorizeForce(Permission.BrowseDescriptionTemplate);
if (semantics == null) {
semantics = new ArrayList<>();
this.loadSemantics();
@ -840,13 +892,12 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
try {
String json = new String(bytes, StandardCharsets.UTF_8);
semantics = List.of(jsonHandlingService.fromJson(Semantic[].class, json));
}
catch (IOException e) {
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
//endregion
}

View File

@ -4,9 +4,13 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.XmlHandlingService;
import eu.eudat.commons.enums.*;
import eu.eudat.commons.enums.DmpBlueprintFieldCategory;
import eu.eudat.commons.enums.DmpBlueprintStatus;
import eu.eudat.commons.enums.DmpBlueprintSystemFieldType;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.types.dmpblueprint.*;
import eu.eudat.commons.types.dmpblueprint.importexport.*;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DmpBlueprintEntity;
import eu.eudat.errorcode.ErrorThesaurusProperties;
@ -33,7 +37,6 @@ import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import gr.cite.tools.validation.ValidationService;
import jakarta.persistence.EntityManager;
import jakarta.xml.bind.JAXBException;
import org.jetbrains.annotations.NotNull;
@ -70,13 +73,19 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
private final BuilderFactory builderFactory;
private final ConventionService conventionService;
private final MessageSource messageSource;
private final QueryFactory queryFactory;
private final ResponseUtilsService responseUtilsService;
private final XmlHandlingService xmlHandlingService;
private final ErrorThesaurusProperties errors;
private final ValidationService validationService;
private final ValidatorFactory validatorFactory;
@Autowired
public DmpBlueprintServiceImpl(
EntityManager entityManager,
@ -85,10 +94,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
BuilderFactory builderFactory,
ConventionService conventionService,
MessageSource messageSource, QueryFactory queryFactory,
ResponseUtilsService responseUtilsService,
ResponseUtilsService responseUtilsService,
XmlHandlingService xmlHandlingService,
ErrorThesaurusProperties errors,
ValidationService validationService) {
ErrorThesaurusProperties errors,
ValidatorFactory validatorFactory) {
this.entityManager = entityManager;
this.authorizationService = authorizationService;
this.deleterFactory = deleterFactory;
@ -99,7 +108,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
this.responseUtilsService = responseUtilsService;
this.xmlHandlingService = xmlHandlingService;
this.errors = errors;
this.validationService = validationService;
this.validatorFactory = validatorFactory;
}
//region Persist
@ -114,8 +123,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
DmpBlueprintEntity data;
if (isUpdate) {
data = this.entityManager.find(DmpBlueprintEntity.class, model.getId());
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DmpBlueprint.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 == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DmpBlueprint.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 DmpBlueprintEntity();
data.setId(UUID.randomUUID());
@ -127,46 +138,51 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
data.setStatus(model.getStatus());
data.setUpdatedAt(Instant.now());
data.setDefinition(this.xmlHandlingService.toXml(this.buildDefinitionEntity(model.getDefinition())));
if (isUpdate) this.entityManager.merge(data);
else this.entityManager.persist(data);
if (isUpdate)
this.entityManager.merge(data);
else
this.entityManager.persist(data);
this.entityManager.flush();
return this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, DmpBlueprint._id), data);
}
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist){
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist) {
DefinitionEntity data = new DefinitionEntity();
if (persist == null) return data;
if (!this.conventionService.isListNullOrEmpty(persist.getSections())){
if (persist == null)
return data;
if (!this.conventionService.isListNullOrEmpty(persist.getSections())) {
data.setSections(new ArrayList<>());
for (SectionPersist sectionPersist: persist.getSections()) {
for (SectionPersist sectionPersist : persist.getSections()) {
data.getSections().add(this.buildSectionEntity(sectionPersist));
}
}
return data;
}
private @NotNull SectionEntity buildSectionEntity(SectionPersist persist){
private @NotNull SectionEntity buildSectionEntity(SectionPersist persist) {
SectionEntity data = new SectionEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setDescription(persist.getDescription());
data.setLabel(persist.getLabel());
data.setOrdinal(persist.getOrdinal());
data.setHasTemplates(persist.getHasTemplates());
if (!this.conventionService.isListNullOrEmpty(persist.getFields())){
if (!this.conventionService.isListNullOrEmpty(persist.getFields())) {
data.setFields(new ArrayList<>());
for (FieldPersist fieldPersist: persist.getFields()) {
for (FieldPersist fieldPersist : persist.getFields()) {
data.getFields().add(this.buildExtraFieldEntity(fieldPersist));
}
}
if (!this.conventionService.isListNullOrEmpty(persist.getDescriptionTemplates())){
if (!this.conventionService.isListNullOrEmpty(persist.getDescriptionTemplates())) {
data.setDescriptionTemplates(new ArrayList<>());
for (DescriptionTemplatePersist descriptionTemplatePersist: persist.getDescriptionTemplates()) {
for (DescriptionTemplatePersist descriptionTemplatePersist : persist.getDescriptionTemplates()) {
data.getDescriptionTemplates().add(this.buildDescriptionTemplateEntity(descriptionTemplatePersist));
}
}
@ -174,9 +190,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
return data;
}
private @NotNull DescriptionTemplateEntity buildDescriptionTemplateEntity(DescriptionTemplatePersist persist){
private @NotNull DescriptionTemplateEntity buildDescriptionTemplateEntity(DescriptionTemplatePersist persist) {
DescriptionTemplateEntity data = new DescriptionTemplateEntity();
if (persist == null) return data;
if (persist == null)
return data;
data.setId(persist.getId());
data.setDescriptionTemplateId(persist.getDescriptionTemplateId());
@ -187,16 +204,17 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
return data;
}
private @NotNull FieldEntity buildExtraFieldEntity(FieldPersist persist){
if (persist == null) return new ExtraFieldEntity();
private @NotNull FieldEntity buildExtraFieldEntity(FieldPersist persist) {
if (persist == null)
return new ExtraFieldEntity();
FieldEntity data;
if (DmpBlueprintFieldCategory.Extra.equals(persist.getCategory())){
if (DmpBlueprintFieldCategory.Extra.equals(persist.getCategory())) {
ExtraFieldEntity dataTyped = new ExtraFieldEntity();
dataTyped.setType(((ExtraFieldPersist)persist).getDataType());
dataTyped.setType(((ExtraFieldPersist) persist).getDataType());
data = dataTyped;
} else {
SystemFieldEntity dataTyped = new SystemFieldEntity();
dataTyped.setType(((SystemFieldPersist)persist).getSystemFieldType());
dataTyped.setType(((SystemFieldPersist) persist).getSystemFieldType());
data = dataTyped;
}
data.setId(persist.getId());
@ -213,7 +231,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
//endregion
//region Delete
public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException {
logger.debug("deleting : {}", id);
@ -223,20 +241,22 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
}
//endregion
//region FieldInBlueprint
public boolean fieldInBlueprint(DmpBlueprintEntity dmpBlueprintEntity, DmpBlueprintSystemFieldType type) {
DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, dmpBlueprintEntity.getDefinition());
if (definition == null || definition.getSections() == null) return false;
for(SectionEntity section: definition.getSections()){
if (section.getFields() == null) continue;
for(FieldEntity field: section.getFields()){
if(field.getCategory().equals(DmpBlueprintFieldCategory.System)){
SystemFieldEntity systemField = (SystemFieldEntity)field;
if(systemField.getType().equals(type)){
if (definition == null || definition.getSections() == null)
return false;
for (SectionEntity section : definition.getSections()) {
if (section.getFields() == null)
continue;
for (FieldEntity field : section.getFields()) {
if (field.getCategory().equals(DmpBlueprintFieldCategory.System)) {
SystemFieldEntity systemField = (SystemFieldEntity) field;
if (systemField.getType().equals(type)) {
return true;
}
}
@ -245,9 +265,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
return false;
}
public boolean fieldInBlueprint(UUID id, DmpBlueprintSystemFieldType type) {
public boolean fieldInBlueprint(UUID id, DmpBlueprintSystemFieldType type) {
DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, id);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
return this.fieldInBlueprint(data, type);
}
@ -262,71 +283,78 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
DmpBlueprintQuery query = this.queryFactory.query(DmpBlueprintQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).ids(id);
DmpBlueprint model = this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fields, query.firstAs(fields));
if (model == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (model == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
model.setLabel(model.getLabel() + " new ");
model.setId(null);
model.setHash(null);
model.setStatus(DmpBlueprintStatus.Draft);
this.reassignDefinition(model.getDefinition());
return model;
}
private void reassignDefinition(Definition model){
if (model == null) return;
if (model.getSections() != null){
private void reassignDefinition(Definition model) {
if (model == null)
return;
if (model.getSections() != null) {
for (Section section : model.getSections()) {
this.reassignSection(section);
}
}
}
private void reassignSection(Section model){
if (model == null) return;
private void reassignSection(Section model) {
if (model == null)
return;
model.setId(UUID.randomUUID());
if (model.getFields() != null){
if (model.getFields() != null) {
for (Field field : model.getFields()) {
this.reassignField(field);
}
}
if (model.getDescriptionTemplates() != null){
if (model.getDescriptionTemplates() != null) {
for (DescriptionTemplate descriptionTemplate : model.getDescriptionTemplates()) {
this.reassignDescriptionTemplate(descriptionTemplate);
}
}
}
private void reassignField(Field model){
if (model == null) return;
private void reassignField(Field model) {
if (model == null)
return;
model.setId(UUID.randomUUID());
}
private void reassignDescriptionTemplate(DescriptionTemplate model){
if (model == null) return;
private void reassignDescriptionTemplate(DescriptionTemplate model) {
if (model == null)
return;
model.setId(UUID.randomUUID());
}
//endregion
//region Export
public ResponseEntity<byte[]> exportXml(UUID id) throws MyForbiddenException, MyNotFoundException, JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, TransformerException, InvalidApplicationException {
logger.debug(new MapLogEntry("persisting data").And("id", id));
this.authorizationService.authorizeForce(Permission.ExportDmpBlueprint);
DmpBlueprintEntity data = this.entityManager.find(DmpBlueprintEntity.class, id);
if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale()));
DefinitionEntity dmpDefinition = this.xmlHandlingService.fromXml(DefinitionEntity.class, data.getDefinition());
String xml = this.xmlHandlingService.toXml(this.definitionXmlToExport(dmpDefinition));
return this.responseUtilsService.buildResponseFileFromText(xml, data.getLabel() + ".xml");
}
private DefinitionImportExport definitionXmlToExport(DefinitionEntity entity){
if (entity == null) return null;
private DefinitionImportExport definitionXmlToExport(DefinitionEntity entity) {
if (entity == null)
return null;
DefinitionImportExport xml = new DefinitionImportExport();
List<SectionImportExport> dmpBlueprintSections = new ArrayList<>();
if (!this.conventionService.isListNullOrEmpty(entity.getSections())) {
@ -347,19 +375,19 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
xml.setHasTemplates(entity.getHasTemplates());
List<SystemFieldImportExport> dmpBlueprintSystemFieldModels = new LinkedList<>();
if (!this.conventionService.isListNullOrEmpty(entity.getFields())) {
for (SystemFieldEntity systemField : entity.getFields().stream().filter(x-> x.getCategory() == DmpBlueprintFieldCategory.System).map(x-> (SystemFieldEntity)x).toList()) {
for (SystemFieldEntity systemField : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.System).map(x -> (SystemFieldEntity) x).toList()) {
dmpBlueprintSystemFieldModels.add(this.systemFieldXmlToExport(systemField));
}
}
xml.setSystemFields(dmpBlueprintSystemFieldModels);
List<ExtraFieldImportExport> dmpBlueprintExtraFieldModels = new LinkedList<>();
if (!this.conventionService.isListNullOrEmpty(entity.getFields())) {
for (ExtraFieldEntity systemField : entity.getFields().stream().filter(x-> x.getCategory() == DmpBlueprintFieldCategory.Extra).map(x-> (ExtraFieldEntity)x).toList()) {
for (ExtraFieldEntity systemField : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.Extra).map(x -> (ExtraFieldEntity) x).toList()) {
dmpBlueprintExtraFieldModels.add(this.extraFieldXmlToExport(systemField));
}
}
xml.setExtraFields(dmpBlueprintExtraFieldModels);
List<DescriptionTemplateImportExport> dmpBlueprintDescriptionTemplates = new LinkedList<>();
if (!this.conventionService.isListNullOrEmpty(entity.getDescriptionTemplates())) {
for (DescriptionTemplateEntity descriptionTemplate : entity.getDescriptionTemplates()) {
@ -404,11 +432,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
return xml;
}
//endregion
//region Import
public DmpBlueprint importXml(byte[] bytes, String label, FieldSet fields) throws MyForbiddenException, MyNotFoundException, JAXBException, ParserConfigurationException, TransformerException, InvalidApplicationException, IOException, InstantiationException, IllegalAccessException, SAXException {
logger.debug(new MapLogEntry("import data").And("bytes", bytes).And("label", label).And("fields", fields));
@ -418,16 +445,18 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
persist.setLabel(label);
persist.setStatus(DmpBlueprintStatus.Draft);
BlueprintImportExport dmpDefinition = this.xmlHandlingService.fromXml(BlueprintImportExport.class, new String(bytes, StandardCharsets.UTF_8));
if(dmpDefinition != null) persist.setDefinition(this.xmlDefinitionToPersist(dmpDefinition.getDmpBlueprintDefinition()));
this.validationService.validateForce(persist);
BlueprintImportExport dmpDefinition = this.xmlHandlingService.fromXml(BlueprintImportExport.class, new String(bytes, StandardCharsets.UTF_8));
if (dmpDefinition != null)
persist.setDefinition(this.xmlDefinitionToPersist(dmpDefinition.getDmpBlueprintDefinition()));
this.validatorFactory.validator(DmpBlueprintPersist.DmpBlueprintPersistValidator.class).validateForce(persist);
return this.persist(persist, fields);
}
private DefinitionPersist xmlDefinitionToPersist(DefinitionImportExport importXml){
if (importXml == null) return null;
private DefinitionPersist xmlDefinitionToPersist(DefinitionImportExport importXml) {
if (importXml == null)
return null;
DefinitionPersist persist = new DefinitionPersist();
List<SectionPersist> dmpBlueprintSections = new ArrayList<>();
if (!this.conventionService.isListNullOrEmpty(importXml.getSections())) {
@ -503,7 +532,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService {
persist.setRequired(importXml.isRequired());
return persist;
}
//endregion
}