From a38342e534fc29643224a139d62bbd830f2fcb89 Mon Sep 17 00:00:00 2001 From: Thomas Georgios Giannos Date: Wed, 18 Oct 2023 17:58:36 +0300 Subject: [PATCH 1/5] Removed EntityDao logic, added template stack, controller not yet implemented, db script not yet run --- .../eu/eudat/authorization/Permission.java | 5 + .../eu/eudat/commons/enums/EntityType.java | 26 ++- .../java/eu/eudat/data/CredentialEntity.java | 2 +- .../data/DescriptionTemplateTypeEntity.java | 17 +- .../java/eu/eudat/data/EntityDoiEntity.java | 127 ++++++++++ .../converters/enums/EntityTypeConverter.java | 14 ++ .../eu/eudat/data/helpers/EntityBinder.java | 15 -- .../src/main/java/eu/eudat/data/old/DMP.java | 7 +- .../java/eu/eudat/data/old/EntityDoi.java | 119 ---------- .../eu/eudat/event/EntityDoiTouchedEvent.java | 24 ++ .../main/java/eu/eudat/event/EventBroker.java | 4 + .../main/java/eu/eudat/model/EntityDoi.java | 119 ++++++++++ .../DescriptionTemplateTypeBuilder.java | 35 +-- .../eudat/model/builder/EntityDoiBuilder.java | 72 ++++++ .../DescriptionTemplateTypeCensor.java | 7 +- .../model/censorship/EntityDoiCensor.java | 36 +++ .../DescriptionTemplateTypeDeleter.java | 5 +- .../eudat/model/deleter/EntityDoiDeleter.java | 79 +++++++ .../eudat/model/persist/EntityDoiPersist.java | 61 +++++ .../query/DescriptionTemplateTypeQuery.java | 41 +++- .../java/eu/eudat/query/EntityDoiQuery.java | 218 ++++++++++++++++++ .../lookup/DescriptionTemplateTypeLookup.java | 19 +- .../eudat/query/lookup/EntityDoiLookup.java | 43 ++++ .../DescriptionTemplateTypeService.java | 2 + .../DescriptionTemplateTypeServiceImpl.java | 20 +- .../eu/eudat/service/EntityDoiService.java | 22 ++ .../eudat/service/EntityDoiServiceImpl.java | 138 +++++++++++ .../eudat/data/dao/entities/EntityDoiDao.java | 10 - .../data/dao/entities/EntityDoiDaoImpl.java | 56 ----- .../managers/DataManagementPlanManager.java | 20 +- .../operations/DatabaseRepository.java | 4 +- .../operations/DatabaseRepositoryImpl.java | 41 ++-- .../java/eu/eudat/models/data/doi/Doi.java | 21 +- .../models/data/rda/DmpRDAExportModel.java | 4 +- .../eudat/models/rda/mapper/DmpRDAMapper.java | 8 +- .../publicapi/models/doi/DoiPublicModel.java | 13 +- .../00.01.002_Align_Entity_Doi_table.sql | 23 ++ 37 files changed, 1176 insertions(+), 301 deletions(-) create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/EntityDoiEntity.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/EntityTypeConverter.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/helpers/EntityBinder.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/old/EntityDoi.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/event/EntityDoiTouchedEvent.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/EntityDoi.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/EntityDoiBuilder.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/censorship/EntityDoiCensor.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/deleter/EntityDoiDeleter.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/persist/EntityDoiPersist.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/query/EntityDoiQuery.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/query/lookup/EntityDoiLookup.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiService.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiServiceImpl.java delete mode 100644 dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDao.java delete mode 100644 dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDaoImpl.java create mode 100644 dmp-db-scema/updates/00.01.002_Align_Entity_Doi_table.sql diff --git a/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java b/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java index 947de0f03..a2cbd35de 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java +++ b/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java @@ -15,6 +15,11 @@ public final class Permission { public static String EditDescriptionTemplateType = "EditDescriptionTemplateType"; public static String DeleteDescriptionTemplateType = "DeleteDescriptionTemplateType"; + //DescriptionTemplateType + public static String BrowseEntityDoi = "BrowseEntityDoi"; + public static String EditEntityDoi = "EditEntityDoi"; + public static String DeleteEntityDoi = "DeleteEntityDoi"; + // UI Pages public static String ViewDescriptionTemplateTypePage = "ViewDescriptionTemplateTypePage"; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/EntityType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/EntityType.java index c5c56dbbd..79002fcd7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/EntityType.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/EntityType.java @@ -1,4 +1,28 @@ package eu.eudat.commons.enums; -public enum EntityType { +import eu.eudat.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum EntityType implements DatabaseEnum { + + DMP((short) 0); + + private final Short value; + + EntityType(Short value) { + this.value = value; + } + + @Override + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(EntityType.class); + + public static EntityType of(Short i) { + return map.get(i); + } + } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/CredentialEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/CredentialEntity.java index 8c7686853..a95d73200 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/CredentialEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/CredentialEntity.java @@ -6,7 +6,7 @@ import eu.eudat.data.converters.DateToUTCConverter; import eu.eudat.data.converters.enums.ProviderTypeConverter; import eu.eudat.data.converters.enums.IsActiveConverter; -import eu.eudat.data.helpers.EntityBinder; +import eu.eudat.data.old.helpers.EntityBinder; import eu.eudat.queryable.queryableentity.DataEntity; import jakarta.persistence.*; import java.util.Date; diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionTemplateTypeEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionTemplateTypeEntity.java index bf584c74d..487f07775 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionTemplateTypeEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionTemplateTypeEntity.java @@ -16,30 +16,35 @@ public class DescriptionTemplateTypeEntity { @Id @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) private UUID id; - public final static String _id = "id"; + + public static final String _id = "id"; @Column(name = "name", length = 500, nullable = false) private String name; - public final static String _name = "name"; + + public static final String _name = "name"; @Column(name = "created_at", nullable = false) private Instant createdAt; - public final static String _createdAt = "createdAt"; + + public static final String _createdAt = "createdAt"; @Column(name = "updated_at", nullable = false) private Instant updatedAt; - public final static String _updatedAt = "updatedAt"; + + public static final String _updatedAt = "updatedAt"; @Column(name = "is_active", nullable = false) @Convert(converter = IsActiveConverter.class) private IsActive isActive; - public final static String _isActive = "isActive"; + + public static final String _isActive = "isActive"; @Column(name = "status", nullable = false) @Convert(converter = DescriptionTemplateTypeStatusConverter.class) private DescriptionTemplateTypeStatus status; - public final static String _status = "status"; + public static final String _status = "status"; public UUID getId() { return id; diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/EntityDoiEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/EntityDoiEntity.java new file mode 100644 index 000000000..edb31da6c --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/EntityDoiEntity.java @@ -0,0 +1,127 @@ +package eu.eudat.data; + +import eu.eudat.commons.enums.EntityType; +import eu.eudat.commons.enums.IsActive; +import eu.eudat.data.converters.DateToUTCConverter; +import eu.eudat.data.converters.enums.IsActiveConverter; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +@Entity +@Table(name = "\"EntityDoi\"") +public class EntityDoiEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Enumerated(EnumType.STRING) + @Column(name = "entity_type", nullable = false) + private EntityType entityType; + + public static final String _entityType = "entityType"; + + @Column(name = "repository_id", nullable = false) + private String repositoryId; + + public static final String _repositoryId = "repositoryId"; + + @Column(name = "doi", nullable = false) + private String doi; + + public static final String _doi = "doi"; + + @Column(name = "created_at", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "entity_id", nullable = false) + private UUID entityId; + + public static final String _entityId = "entityId"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public EntityType getEntityType() { + return entityType; + } + + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } + + public String getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getDoi() { + return doi; + } + + public void setDoi(String doi) { + this.doi = doi; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/EntityTypeConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/EntityTypeConverter.java new file mode 100644 index 000000000..c6814bdea --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/EntityTypeConverter.java @@ -0,0 +1,14 @@ +package eu.eudat.data.converters.enums; + +import eu.eudat.commons.enums.EntityType; +import jakarta.persistence.Converter; + +@Converter +public class EntityTypeConverter extends DatabaseEnumConverter{ + + @Override + protected EntityType of(Short i) { + return EntityType.of(i); + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/helpers/EntityBinder.java b/dmp-backend/core/src/main/java/eu/eudat/data/helpers/EntityBinder.java deleted file mode 100644 index 39c921317..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/data/helpers/EntityBinder.java +++ /dev/null @@ -1,15 +0,0 @@ -package eu.eudat.data.helpers; - -import jakarta.persistence.Tuple; - -import java.util.List; - -public class EntityBinder { - public static T fromTuple(List tuple, String path) { - try { - return (T) tuple.get(0).get(path); - }catch (IllegalArgumentException illegalArgument){ - return null; - } - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/old/DMP.java b/dmp-backend/core/src/main/java/eu/eudat/data/old/DMP.java index 1fb54000a..f11b96f13 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/old/DMP.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/old/DMP.java @@ -1,6 +1,7 @@ package eu.eudat.data.old; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.data.converters.DateToUTCConverter; import eu.eudat.queryable.queryableentity.DataEntity; import org.hibernate.annotations.GenericGenerator; @@ -183,7 +184,7 @@ public class DMP implements DataEntity { private Date publishedAt; @OneToMany(mappedBy = "entityId", fetch = FetchType.LAZY) - private Set dois; + private Set dois; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "\"Project\"") @@ -340,10 +341,10 @@ public class DMP implements DataEntity { this.publishedAt = publishedAt; } - public Set getDois() { + public Set getDois() { return dois; } - public void setDois(Set dois) { + public void setDois(Set dois) { this.dois = dois; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/old/EntityDoi.java b/dmp-backend/core/src/main/java/eu/eudat/data/old/EntityDoi.java deleted file mode 100644 index f0df55771..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/data/old/EntityDoi.java +++ /dev/null @@ -1,119 +0,0 @@ -package eu.eudat.data.old; - -import eu.eudat.data.converters.DateToUTCConverter; -import eu.eudat.data.old.helpers.EntityBinder; -import eu.eudat.queryable.queryableentity.DataEntity; - -import jakarta.persistence.*; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -@Entity -@Table(name = "\"EntityDoi\"") -public class EntityDoi implements DataEntity { - public enum EntityType { - DMP - } - - @Id - @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") - private UUID id; - - @Enumerated(EnumType.STRING) - @Column(name = "\"EntityType\"", nullable = false) - private EntityType entityType; - - @Column(name = "\"RepositoryId\"", nullable = false) - private String repositoryId; - - @Column(name = "\"Doi\"", nullable = false) - private String doi; - - @Column(name = "\"CreatedAt\"", nullable = false) - @Convert(converter = DateToUTCConverter.class) - private Date createdAt; - - @Column(name = "\"UpdatedAt\"", nullable = false) - @Convert(converter = DateToUTCConverter.class) - private Date updatedAt; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "\"EntityId\"", nullable = false) - private DMP entityId; - - public UUID getId() { - return id; - } - public void setId(UUID id) { - this.id = id; - } - - public EntityType getEntityType() { - return entityType; - } - public void setEntityType(EntityType entityType) { - this.entityType = entityType; - } - - public String getRepositoryId() { - return repositoryId; - } - public void setRepositoryId(String repositoryId) { - this.repositoryId = repositoryId; - } - - public String getDoi() { - return doi; - } - public void setDoi(String doi) { - this.doi = doi; - } - - public Date getCreatedAt() { - return createdAt; - } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } - - public Date getUpdatedAt() { - return updatedAt; - } - public void setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - } - - public DMP getEntityId() { - return entityId; - } - public void setEntityId(DMP entityId) { - this.entityId = entityId; - } - - @Override - public void update(EntityDoi doi) { - this.entityType = doi.getEntityType(); - this.repositoryId = doi.getRepositoryId(); - this.doi = doi.getDoi(); - this.createdAt = doi.getCreatedAt(); - this.updatedAt = doi.getUpdatedAt(); - this.entityId = doi.getEntityId(); - } - - @Override - public UUID getKeys() { - return this.id; - } - - @Override - public EntityDoi buildFromTuple(List tuple, List fields, String base) { - String currentBase = base.isEmpty() ? "" : base + "."; - if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); - if (fields.contains(currentBase + "entityId")) - this.entityId = tuple.stream().map(x -> new DMP().buildFromTuple(Arrays.asList(x), fields , base.isEmpty() ? "entityId" : base + "." + "entityId")).collect(Collectors.toList()).get(0); - return this; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/event/EntityDoiTouchedEvent.java b/dmp-backend/core/src/main/java/eu/eudat/event/EntityDoiTouchedEvent.java new file mode 100644 index 000000000..f211d7dbc --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/event/EntityDoiTouchedEvent.java @@ -0,0 +1,24 @@ +package eu.eudat.event; + +import java.util.UUID; + +public class EntityDoiTouchedEvent { + + public EntityDoiTouchedEvent() { + } + + public EntityDoiTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/event/EventBroker.java b/dmp-backend/core/src/main/java/eu/eudat/event/EventBroker.java index c8fca7df1..f3c40355e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/event/EventBroker.java +++ b/dmp-backend/core/src/main/java/eu/eudat/event/EventBroker.java @@ -37,4 +37,8 @@ public class EventBroker { public void emit(DescriptionTemplateTypeTouchedEvent event) { this.applicationEventPublisher.publishEvent(event); } + + public void emit(EntityDoiTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/EntityDoi.java b/dmp-backend/core/src/main/java/eu/eudat/model/EntityDoi.java new file mode 100644 index 000000000..9c6be1c80 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/EntityDoi.java @@ -0,0 +1,119 @@ +package eu.eudat.model; + +import eu.eudat.commons.enums.EntityType; +import eu.eudat.commons.enums.IsActive; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +public class EntityDoi { + + private UUID id; + + public static final String _id = "id"; + + private EntityType entityType; + + public static final String _entityType = "entityType"; + + private String repositoryId; + + public static final String _repositoryId = "repositoryId"; + + private String doi; + + public static final String _doi = "doi"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private UUID entityId; + + public static final String _entityId = "entityId"; + + private String hash; + + public static final String _hash = "hash"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public EntityType getEntityType() { + return entityType; + } + + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } + + public String getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getDoi() { + return doi; + } + + public void setDoi(String doi) { + this.doi = doi; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionTemplateTypeBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionTemplateTypeBuilder.java index 044703435..83053e81e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionTemplateTypeBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionTemplateTypeBuilder.java @@ -1,14 +1,10 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.JsonHandlingService; import eu.eudat.convention.ConventionService; import eu.eudat.data.DescriptionTemplateTypeEntity; import eu.eudat.model.DescriptionTemplateType; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.DataLogEntry; import gr.cite.tools.logging.LoggerService; @@ -19,7 +15,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.*; -import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @@ -39,21 +34,29 @@ public class DescriptionTemplateTypeBuilder extends BaseBuilder build(FieldSet fields, List datas) throws MyApplicationException { - this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(datas).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); this.logger.trace(new DataLogEntry("requested fields", fields)); - if (fields == null || datas == null || fields.isEmpty()) return new ArrayList<>(); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); List models = new ArrayList<>(); - for (DescriptionTemplateTypeEntity d : datas) { + for (DescriptionTemplateTypeEntity d : data) { DescriptionTemplateType m = new DescriptionTemplateType(); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._name))) m.setName(d.getName()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._status))) m.setStatus(d.getStatus()); - if (fields.hasField(this.asIndexer(DescriptionTemplateType._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._name))) + m.setName(d.getName()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._status))) + m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._hash))) + m.setHash(this.hashValue(d.getUpdatedAt())); models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/EntityDoiBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/EntityDoiBuilder.java new file mode 100644 index 000000000..a4cff8bd7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/EntityDoiBuilder.java @@ -0,0 +1,72 @@ +package eu.eudat.model.builder; + +import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.convention.ConventionService; +import eu.eudat.data.EntityDoiEntity; +import eu.eudat.model.EntityDoi; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public EntityDoiBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(EntityDoiBuilder.class))); + } + + public EntityDoiBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (EntityDoiEntity d : data) { + EntityDoi m = new EntityDoi(); + if (fields.hasField(this.asIndexer(EntityDoi._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(EntityDoi._doi))) + m.setDoi(d.getDoi()); + if (fields.hasField(this.asIndexer(EntityDoi._entityId))) + m.setEntityId(d.getEntityId()); + if (fields.hasField(this.asIndexer(EntityDoi._entityType))) + m.setEntityType(d.getEntityType()); + if (fields.hasField(this.asIndexer(EntityDoi._repositoryId))) + m.setRepositoryId(d.getRepositoryId()); + if (fields.hasField(this.asIndexer(EntityDoi._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(EntityDoi._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(EntityDoi._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(EntityDoi._hash))) + m.setHash(hashValue(d.getUpdatedAt())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/DescriptionTemplateTypeCensor.java b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/DescriptionTemplateTypeCensor.java index b941be7e2..39a1f409c 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/DescriptionTemplateTypeCensor.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/DescriptionTemplateTypeCensor.java @@ -15,10 +15,12 @@ import java.util.UUID; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class DescriptionTemplateTypeCensor extends BaseCensor{ +public class DescriptionTemplateTypeCensor extends BaseCensor { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeCensor.class)); + protected final AuthorizationService authService; + public DescriptionTemplateTypeCensor(ConventionService conventionService, AuthorizationService authService) { super(conventionService); this.authService = authService; @@ -26,7 +28,8 @@ public class DescriptionTemplateTypeCensor extends BaseCensor{ public void censor(FieldSet fields, UUID userId) { logger.debug(new DataLogEntry("censoring fields", fields)); - if (fields.isEmpty()) return; + if (fields.isEmpty()) + return; this.authService.authorizeForce(Permission.BrowseDescriptionTemplateType); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/EntityDoiCensor.java b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/EntityDoiCensor.java new file mode 100644 index 000000000..55cfed580 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/EntityDoiCensor.java @@ -0,0 +1,36 @@ +package eu.eudat.model.censorship; + +import eu.eudat.authorization.Permission; +import eu.eudat.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiCensor extends BaseCensor{ + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EntityDoiCensor.class)); + + protected final AuthorizationService authService; + + public EntityDoiCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseEntityDoi); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/DescriptionTemplateTypeDeleter.java b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/DescriptionTemplateTypeDeleter.java index 068a2b94a..c27f4e7a8 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/DescriptionTemplateTypeDeleter.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/DescriptionTemplateTypeDeleter.java @@ -28,7 +28,9 @@ public class DescriptionTemplateTypeDeleter implements Deleter { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeDeleter.class)); private final EntityManager entityManager; + protected final QueryFactory queryFactory; + protected final DeleterFactory deleterFactory; @Autowired @@ -59,7 +61,8 @@ public class DescriptionTemplateTypeDeleter implements Deleter { public void delete(List data) throws InvalidApplicationException { logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - if (data == null || data.isEmpty()) return; + if (data == null || data.isEmpty()) + return; Instant now = Instant.now(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/EntityDoiDeleter.java b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/EntityDoiDeleter.java new file mode 100644 index 000000000..e090d092c --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/EntityDoiDeleter.java @@ -0,0 +1,79 @@ +package eu.eudat.model.deleter; + +import eu.eudat.commons.enums.IsActive; +import eu.eudat.data.DescriptionTemplateTypeEntity; +import eu.eudat.query.DescriptionTemplateTypeQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import jakarta.persistence.EntityManager; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeDeleter.class)); + + private final EntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public EntityDoiDeleter( + EntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionTemplateTypeQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (DescriptionTemplateTypeEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/EntityDoiPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/EntityDoiPersist.java new file mode 100644 index 000000000..96d57d5d9 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/EntityDoiPersist.java @@ -0,0 +1,61 @@ +package eu.eudat.model.persist; + +import eu.eudat.commons.validation.FieldNotNullIfOtherSet; +import eu.eudat.commons.validation.ValidId; + +import java.util.UUID; + +@FieldNotNullIfOtherSet(message = "{validation.hashempty}") +public class EntityDoiPersist { + + @ValidId(message = "{validation.invalidid}") + private UUID id; + + private UUID entityId; + + private String repositoryId; + + private String doi; + + private String hash; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public String getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getDoi() { + return doi; + } + + public void setDoi(String doi) { + this.doi = doi; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionTemplateTypeQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionTemplateTypeQuery.java index 13dbec3ad..059a2470c 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionTemplateTypeQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionTemplateTypeQuery.java @@ -25,10 +25,15 @@ import java.util.*; public class DescriptionTemplateTypeQuery extends QueryBase { private String like; + private Collection ids; + private Collection isActives; + private Collection statuses; + private Collection excludedIds; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); public DescriptionTemplateTypeQuery like(String value) { @@ -102,6 +107,7 @@ public class DescriptionTemplateTypeQuery extends QueryBase predicates = new ArrayList<>(); if (this.ids != null) { CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DescriptionTemplateTypeEntity._id)); - for (UUID item : this.ids) inClause.value(item); + for (UUID item : this.ids) + inClause.value(item); predicates.add(inClause); } if (this.like != null && !this.like.isEmpty()) { @@ -135,21 +142,24 @@ public class DescriptionTemplateTypeQuery extends QueryBase inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DescriptionTemplateTypeEntity._isActive)); - for (IsActive item : this.isActives) inClause.value(item); + for (IsActive item : this.isActives) + inClause.value(item); predicates.add(inClause); } if (this.statuses != null) { CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DescriptionTemplateTypeEntity._status)); - for (DescriptionTemplateTypeStatus item : this.statuses) inClause.value(item); + for (DescriptionTemplateTypeStatus item : this.statuses) + inClause.value(item); predicates.add(inClause); } if (this.excludedIds != null) { CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DescriptionTemplateTypeEntity._id)); - for (UUID item : this.excludedIds) notInClause.value(item); + for (UUID item : this.excludedIds) + notInClause.value(item); predicates.add(notInClause.not()); } - if (predicates.size() > 0) { + if (!predicates.isEmpty()) { Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); return queryContext.CriteriaBuilder.and(predicatesArray); } else { @@ -171,13 +181,20 @@ public class DescriptionTemplateTypeQuery extends QueryBase { + + private Collection ids; + + private Collection isActives; + + private Collection types; + + private Collection excludedIds; + + private Collection dois; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + public EntityDoiQuery ids(UUID value) { + this.ids = List.of(value); + return this; + } + + public EntityDoiQuery ids(UUID... value) { + this.ids = Arrays.asList(value); + return this; + } + + public EntityDoiQuery ids(Collection values) { + this.ids = values; + return this; + } + + public EntityDoiQuery isActive(IsActive value) { + this.isActives = List.of(value); + return this; + } + + public EntityDoiQuery isActive(IsActive... value) { + this.isActives = Arrays.asList(value); + return this; + } + + public EntityDoiQuery isActive(Collection values) { + this.isActives = values; + return this; + } + + public EntityDoiQuery types(EntityType value) { + this.types = List.of(value); + return this; + } + + public EntityDoiQuery types(EntityType... value) { + this.types = Arrays.asList(value); + return this; + } + + public EntityDoiQuery types(Collection values) { + this.types = values; + return this; + } + + public EntityDoiQuery excludedIds(Collection values) { + this.excludedIds = values; + return this; + } + + public EntityDoiQuery excludedIds(UUID value) { + this.excludedIds = List.of(value); + return this; + } + + public EntityDoiQuery excludedIds(UUID... value) { + this.excludedIds = Arrays.asList(value); + return this; + } + + public EntityDoiQuery dois(Collection values) { + this.dois = values; + return this; + } + + public EntityDoiQuery dois(String value) { + this.dois = List.of(value); + return this; + } + + public EntityDoiQuery dois(String... value) { + this.dois = Arrays.asList(value); + return this; + } + + public EntityDoiQuery authorize(EnumSet values) { + this.authorize = values; + return this; + } + + private final UserScope userScope; + + private final AuthorizationService authService; + + public EntityDoiQuery( + UserScope userScope, + AuthorizationService authService + ) { + this.userScope = userScope; + this.authService = authService; + } + + @Override + protected Class entityClass() { + return EntityDoiEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return this.isEmpty(this.ids) || this.isEmpty(this.isActives) || this.isEmpty(this.excludedIds) || this.isEmpty(this.types); + } + + @Override + protected Predicate applyFilters(QueryContext queryContext) { + List predicates = new ArrayList<>(); + if (this.ids != null) { + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityDoiEntity._id)); + for (UUID item : this.ids) + inClause.value(item); + predicates.add(inClause); + } + if (this.isActives != null) { + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityDoiEntity._isActive)); + for (IsActive item : this.isActives) + inClause.value(item); + predicates.add(inClause); + } + + if (this.types != null) { + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityDoiEntity._entityType)); + for (EntityType item : this.types) + inClause.value(item); + predicates.add(inClause); + } + if (this.excludedIds != null) { + CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityDoiEntity._id)); + for (UUID item : this.excludedIds) + notInClause.value(item); + predicates.add(notInClause.not()); + } + if (this.dois != null) { + CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityDoiEntity._doi)); + for (String item : this.dois) + notInClause.value(item); + predicates.add(notInClause.not()); + } + if (!predicates.isEmpty()) { + Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); + return queryContext.CriteriaBuilder.and(predicatesArray); + } else { + return null; + } + } + + @Override + protected EntityDoiEntity convert(Tuple tuple, Set columns) { + EntityDoiEntity item = new EntityDoiEntity(); + item.setId(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._id, UUID.class)); + item.setDoi(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._doi, String.class)); + item.setRepositoryId(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._repositoryId, String.class)); + item.setEntityId(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._entityId, UUID.class)); + item.setEntityType(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._entityType, EntityType.class)); + item.setCreatedAt(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._createdAt, Instant.class)); + item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._updatedAt, Instant.class)); + item.setIsActive(QueryBase.convertSafe(tuple, columns, EntityDoiEntity._isActive, IsActive.class)); + return item; + } + + @Override + protected String fieldNameOf(FieldResolver item) { + if (item.match(EntityDoiEntity._id)) + return EntityDoiEntity._id; + else if (item.match(EntityDoiEntity._doi)) + return EntityDoiEntity._doi; + else if (item.match(EntityDoiEntity._repositoryId)) + return EntityDoiEntity._repositoryId; + else if (item.match(EntityDoiEntity._entityId)) + return EntityDoiEntity._entityId; + else if (item.match(EntityDoiEntity._entityType)) + return EntityDoiEntity._entityType; + else if (item.match(EntityDoiEntity._createdAt)) + return EntityDoiEntity._createdAt; + else if (item.match(EntityDoiEntity._updatedAt)) + return EntityDoiEntity._updatedAt; + else if (item.match(EntityDoiEntity._isActive)) + return EntityDoiEntity._isActive; + else + return null; + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/DescriptionTemplateTypeLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/DescriptionTemplateTypeLookup.java index 26192428a..f12fe2bf9 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/DescriptionTemplateTypeLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/DescriptionTemplateTypeLookup.java @@ -12,9 +12,13 @@ import java.util.UUID; public class DescriptionTemplateTypeLookup extends Lookup { private String like; + private List isActive; + private List statuses; + private List ids; + private List excludedIds; public String getLike() { @@ -51,11 +55,16 @@ public class DescriptionTemplateTypeLookup extends Lookup { public DescriptionTemplateTypeQuery enrich(QueryFactory queryFactory) { DescriptionTemplateTypeQuery query = queryFactory.query(DescriptionTemplateTypeQuery.class); - if (this.like != null) query.like(this.like); - if (this.isActive != null) query.isActive(this.isActive); - if (this.statuses != null) query.statuses(this.statuses); - if (this.ids != null) query.ids(this.ids); - if (this.excludedIds != null) query.excludedIds(this.excludedIds); + if (this.like != null) + query.like(this.like); + if (this.isActive != null) + query.isActive(this.isActive); + if (this.statuses != null) + query.statuses(this.statuses); + if (this.ids != null) + query.ids(this.ids); + if (this.excludedIds != null) + query.excludedIds(this.excludedIds); this.enrichCommon(query); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/EntityDoiLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/EntityDoiLookup.java new file mode 100644 index 000000000..a6c15e357 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/EntityDoiLookup.java @@ -0,0 +1,43 @@ +package eu.eudat.query.lookup; + +import eu.eudat.commons.enums.EntityType; +import eu.eudat.commons.enums.IsActive; +import eu.eudat.query.EntityDoiQuery; +import gr.cite.tools.data.query.Lookup; +import gr.cite.tools.data.query.QueryFactory; + +import java.util.List; +import java.util.UUID; + +public class EntityDoiLookup extends Lookup { + + private List isActive; + + private List types; + + private List ids; + + private List excludedIds; + + private List dois; + + public EntityDoiQuery enrich(QueryFactory queryFactory) { + EntityDoiQuery query = queryFactory.query(EntityDoiQuery.class); + if (this.isActive != null) + query.isActive(this.isActive); + if (this.types != null) + query.types(this.types); + if (this.ids != null) + query.ids(this.ids); + if (this.excludedIds != null) + query.excludedIds(this.excludedIds); + if (this.dois != null) { + query.dois(this.dois); + } + + this.enrichCommon(query); + + return query; + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeService.java b/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeService.java index 35b8473b2..a95a300d1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeService.java @@ -12,7 +12,9 @@ import javax.management.InvalidApplicationException; import java.util.UUID; public interface DescriptionTemplateTypeService { + DescriptionTemplateType persist(DescriptionTemplateTypePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; + } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeServiceImpl.java index 188ff36fb..993021564 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/DescriptionTemplateTypeServiceImpl.java @@ -41,17 +41,27 @@ import java.util.UUID; @Service @RequestScope public class DescriptionTemplateTypeServiceImpl implements DescriptionTemplateTypeService { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeServiceImpl.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; @Autowired @@ -88,7 +98,8 @@ public class DescriptionTemplateTypeServiceImpl implements DescriptionTemplateTy DescriptionTemplateTypeEntity data; if (isUpdate) { data = this.entityManager.find(DescriptionTemplateTypeEntity.class, model.getId()); - if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplateType.class.getSimpleName()}, LocaleContextHolder.getLocale())); + if (data == null) + throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), DescriptionTemplateType.class.getSimpleName()}, LocaleContextHolder.getLocale())); } else { data = new DescriptionTemplateTypeEntity(); data.setId(UUID.randomUUID()); @@ -99,8 +110,10 @@ public class DescriptionTemplateTypeServiceImpl implements DescriptionTemplateTy data.setName(model.getName()); data.setStatus(model.getStatus()); data.setUpdatedAt(Instant.now()); - 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(); @@ -115,5 +128,6 @@ public class DescriptionTemplateTypeServiceImpl implements DescriptionTemplateTy this.deleterFactory.deleter(DescriptionTemplateTypeDeleter.class).deleteAndSaveByIds(List.of(id)); } + } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiService.java b/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiService.java new file mode 100644 index 000000000..df6211d19 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiService.java @@ -0,0 +1,22 @@ +package eu.eudat.service; + +import eu.eudat.model.DescriptionTemplateType; +import eu.eudat.model.EntityDoi; +import eu.eudat.model.persist.DescriptionTemplateTypePersist; +import eu.eudat.model.persist.EntityDoiPersist; +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.FieldSet; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +public interface EntityDoiService { + + EntityDoi persist(EntityDoiPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; + + void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiServiceImpl.java new file mode 100644 index 000000000..cbe47a1b2 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/EntityDoiServiceImpl.java @@ -0,0 +1,138 @@ +package eu.eudat.service; + +import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.authorization.Permission; +import eu.eudat.commons.JsonHandlingService; +import eu.eudat.commons.enums.EntityType; +import eu.eudat.commons.enums.IsActive; +import eu.eudat.convention.ConventionService; +import eu.eudat.data.DescriptionTemplateTypeEntity; +import eu.eudat.data.EntityDoiEntity; +import eu.eudat.errorcode.ErrorThesaurusProperties; +import eu.eudat.event.DescriptionTemplateTypeTouchedEvent; +import eu.eudat.event.EntityDoiTouchedEvent; +import eu.eudat.event.EventBroker; +import eu.eudat.model.DescriptionTemplateType; +import eu.eudat.model.EntityDoi; +import eu.eudat.model.builder.DescriptionTemplateTypeBuilder; +import eu.eudat.model.builder.EntityDoiBuilder; +import eu.eudat.model.deleter.DescriptionTemplateTypeDeleter; +import eu.eudat.model.deleter.EntityDoiDeleter; +import eu.eudat.model.persist.DescriptionTemplateTypePersist; +import eu.eudat.model.persist.EntityDoiPersist; +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.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class EntityDoiServiceImpl implements EntityDoiService { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EntityDoiServiceImpl.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; + + @Autowired + public EntityDoiServiceImpl( + EntityManager entityManager, + AuthorizationService authorizationService, + DeleterFactory deleterFactory, + BuilderFactory builderFactory, + ConventionService conventionService, + ErrorThesaurusProperties errors, + MessageSource messageSource, + EventBroker eventBroker, + QueryFactory queryFactory, + JsonHandlingService jsonHandlingService) { + 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; + } + + public EntityDoi persist(EntityDoiPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { + logger.debug(new MapLogEntry("persisting data EntityDoi").And("model", model).And("fields", fields)); + + this.authorizationService.authorizeForce(Permission.EditEntityDoi); + + Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); + + EntityDoiEntity data; + if (isUpdate) { + data = this.entityManager.find(EntityDoiEntity.class, model.getId()); + if (data == null) + throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), EntityDoi.class.getSimpleName()}, LocaleContextHolder.getLocale())); + } else { + data = new EntityDoiEntity(); + data.setId(UUID.randomUUID()); + data.setIsActive(IsActive.Active); + data.setCreatedAt(Instant.now()); + } + + data.setEntityType(EntityType.DMP); + data.setEntityId(model.getEntityId()); + data.setRepositoryId(model.getRepositoryId()); + data.setDoi(model.getDoi()); + data.setUpdatedAt(Instant.now()); + if (isUpdate) + this.entityManager.merge(data); + else + this.entityManager.persist(data); + + this.entityManager.flush(); + + this.eventBroker.emit(new EntityDoiTouchedEvent(data.getId())); + return this.builderFactory.builder(EntityDoiBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, EntityDoi._id), data); + } + + public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { + logger.debug("deleting dataset: {}", id); + + this.authorizationService.authorizeForce(Permission.DeleteEntityDoi); + + this.deleterFactory.deleter(EntityDoiDeleter.class).deleteAndSaveByIds(List.of(id)); + } + +} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDao.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDao.java deleted file mode 100644 index b675cc138..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDao.java +++ /dev/null @@ -1,10 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.data.dao.DatabaseAccessLayer; -import eu.eudat.data.old.EntityDoi; - -import java.util.UUID; - -public interface EntityDoiDao extends DatabaseAccessLayer { - EntityDoi findFromDoi(String doi); -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDaoImpl.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDaoImpl.java deleted file mode 100644 index c955dda63..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/EntityDoiDaoImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.data.dao.DatabaseAccess; -import eu.eudat.data.dao.databaselayer.service.DatabaseService; -import eu.eudat.data.old.EntityDoi; -import eu.eudat.queryable.QueryableList; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - -@Component("EntityDoiDao") -public class EntityDoiDaoImpl extends DatabaseAccess implements EntityDoiDao { - - @Autowired - public EntityDoiDaoImpl(DatabaseService databaseService){ - super(databaseService); - } - - - @Override - public EntityDoi createOrUpdate(EntityDoi item) { - return this.getDatabaseService().createOrUpdate(item, EntityDoi.class); - } - - @Override - public CompletableFuture createOrUpdateAsync(EntityDoi item) { - return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); - } - - @Override - public EntityDoi find(UUID id) { - return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); - } - - @Override - public EntityDoi findFromDoi(String doi) { - return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("doi"), doi)).getSingle(); - } - - @Override - public EntityDoi find(UUID id, String hint) { - return null; - } - - @Override - public void delete(EntityDoi item) { - this.getDatabaseService().delete(item); - } - - @Override - public QueryableList asQueryable() { - return this.getDatabaseService().getQueryable(EntityDoi.class); - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java index abeb71ff6..37dca6d08 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java @@ -2,8 +2,10 @@ package eu.eudat.logic.managers; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.commons.enums.EntityType; import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration; import eu.eudat.configurations.dynamicgrant.entities.Property; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.data.dao.criteria.*; import eu.eudat.data.dao.entities.*; import eu.eudat.data.old.DescriptionTemplate; @@ -2449,8 +2451,8 @@ public class DataManagementPlanManager { for (DMP dmp: dmps) { if (!dmp.getId().equals(selfId)) { if (dmp.getDois() != null && !dmp.getDois().isEmpty()) { - for (Iterator it = dmp.getDois().iterator(); it.hasNext(); ) { - EntityDoi entityDoi = it.next(); + for (Iterator it = dmp.getDois().iterator(); it.hasNext(); ) { + EntityDoiEntity entityDoi = it.next(); if(entityDoi.getRepositoryId().equals(repositoryId)){ return entityDoi.getDoi(); } @@ -2505,16 +2507,16 @@ public class DataManagementPlanManager { Doi doiModel = null; if (finalDoi != null) { - EntityDoi doiEntity = new EntityDoi(); + EntityDoiEntity doiEntity = new EntityDoiEntity(); doiEntity.setId(UUID.randomUUID()); - doiEntity.setEntityType(EntityDoi.EntityType.DMP); + doiEntity.setEntityType(EntityType.DMP); doiEntity.setDoi(finalDoi); doiEntity.setRepositoryId(depositRequest.getRepositoryId()); - Date now = new Date(); - doiEntity.setCreatedAt(now); - doiEntity.setUpdatedAt(now); - doiEntity.setEntityId(dmp); - apiContext.getOperationsContext().getDatabaseRepository().getEntityDoiDao().createOrUpdate(doiEntity); + doiEntity.setCreatedAt(Instant.now()); + doiEntity.setUpdatedAt(Instant.now()); + doiEntity.setEntityId(dmp.getId()); + //TODO: Save doi +// apiContext.getOperationsContext().getDatabaseRepository().getEntityDoiDao().createOrUpdate(doiEntity); dmp.getDois().add(doiEntity); apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java index 3e6c949fb..83517459a 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java @@ -3,8 +3,8 @@ package eu.eudat.logic.services.operations; import eu.eudat.data.dao.entities.*; import eu.eudat.data.dao.entities.security.CredentialDao; - public interface DatabaseRepository { + DataRepositoryDao getDataRepositoryDao(); DatasetDao getDatasetDao(); @@ -59,7 +59,5 @@ public interface DatabaseRepository { FileUploadDao getFileUploadDao(); - EntityDoiDao getEntityDoiDao(); - void detachEntity(T entity); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java index 56d62d3d4..f35b5c3ec 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java @@ -2,43 +2,66 @@ package eu.eudat.logic.services.operations; import eu.eudat.data.dao.entities.*; import eu.eudat.data.dao.entities.security.CredentialDao; +import jakarta.persistence.EntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import jakarta.persistence.EntityManager; - - @Service("databaseRepository") public class DatabaseRepositoryImpl implements DatabaseRepository { private DataRepositoryDao dataRepositoryDao; + private DatasetDao datasetDao; + private DatasetProfileDao datasetProfileDao; + private DMPDao dmpDao; + private DmpDatasetProfileDao dmpDatasetProfileDao; + private OrganisationDao organisationDao; + private GrantDao GrantDao; + private RegistryDao registryDao; + private ResearcherDao researcherDao; + private ServiceDao serviceDao; + private UserInfoDao userInfoDao; + private InvitationDao invitationDao; + private CredentialDao credentialDao; + private ExternalDatasetDao externalDatasetDao; + private UserRoleDao userRoleDao; + private UserDatasetProfileDao userDatasetProfileDao; + private UserDmpDao userDmpDao; + private ContentDao contentDao; + private DMPProfileDao dmpProfileDao; + private DatasetExternalDatasetDao datasetExternalDatasetDao; + private DatasetServiceDao datasetServiceDao; + private EmailConfirmationDao loginConfirmationEmailDao; + private ProjectDao projectDao; + private FunderDao funderDao; + private LockDao lockDao; + private NotificationDao notificationDao; + private FileUploadDao fileUploadDao; - private EntityDoiDao entityDoiDao; private EntityManager entityManager; @@ -317,16 +340,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository { this.fileUploadDao = fileUploadDao; } - @Override - public EntityDoiDao getEntityDoiDao() { - return entityDoiDao; - } - - @Autowired - public void setEntityDoiDao(EntityDoiDao entityDoiDao) { - this.entityDoiDao = entityDoiDao; - } - public void detachEntity(T entity) { this.entityManager.detach(entity); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/doi/Doi.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/doi/Doi.java index 906146129..58fc97398 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/doi/Doi.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/doi/Doi.java @@ -1,13 +1,13 @@ package eu.eudat.models.data.doi; -import eu.eudat.data.old.EntityDoi; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.models.DataModel; import eu.eudat.models.data.dmp.DataManagementPlan; import java.util.Date; import java.util.UUID; -public class Doi implements DataModel { +public class Doi { private UUID id; private String repositoryId; private String doi; @@ -57,28 +57,25 @@ public class Doi implements DataModel { this.dmp = dmp; } - @Override - public Doi fromDataModel(EntityDoi entity) { + public Doi fromDataModel(EntityDoiEntity entity) { this.id = entity.getId(); this.repositoryId = entity.getRepositoryId(); this.doi = entity.getDoi(); - this.createdAt = entity.getCreatedAt(); - this.updatedAt = entity.getUpdatedAt(); + this.createdAt = Date.from(entity.getCreatedAt()); + this.updatedAt = Date.from(entity.getUpdatedAt()); return this; } - @Override - public EntityDoi toDataModel() throws Exception { - EntityDoi entityDoi = new EntityDoi(); + public EntityDoiEntity toDataModel() throws Exception { + EntityDoiEntity entityDoi = new EntityDoiEntity(); entityDoi.setId(this.id); entityDoi.setRepositoryId(this.repositoryId); entityDoi.setDoi(this.doi); - entityDoi.setCreatedAt(this.createdAt); - entityDoi.setUpdatedAt(this.updatedAt); + entityDoi.setCreatedAt(this.createdAt.toInstant()); + entityDoi.setUpdatedAt(this.updatedAt.toInstant()); return entityDoi; } - @Override public String getHint() { return null; } diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java index 724d667ad..5dc13f059 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java @@ -1,8 +1,8 @@ package eu.eudat.models.data.rda; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.data.old.DMP; import eu.eudat.data.old.Dataset; -import eu.eudat.data.old.EntityDoi; import eu.eudat.data.old.UserDMP; import eu.eudat.logic.managers.DatasetManager; import eu.eudat.models.data.security.Principal; @@ -147,7 +147,7 @@ public class DmpRDAExportModel { dmpRda.description = entity.getDescription().replace("\n", " "); if (entity.getDois() != null && !entity.getDois().isEmpty()) { boolean zenodoDoi = false; - for(EntityDoi doi: entity.getDois()){ + for(EntityDoiEntity doi: entity.getDois()){ if(doi.getRepositoryId().equals("Zenodo")){ dmpRda.dmp_id = new IdRDAExportModel(doi.getDoi(), "zenodo"); zenodoDoi = true; diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java index e93aa35fd..6ac1c3a02 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java @@ -1,5 +1,6 @@ package eu.eudat.models.rda.mapper; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.data.old.*; import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.utilities.helpers.StreamDistinctBy; @@ -52,7 +53,7 @@ public class DmpRDAMapper { } Dmp rda = new Dmp(); if (dmp.getDois() != null && !dmp.getDois().isEmpty()) { - for(EntityDoi doi: dmp.getDois()){ + for(EntityDoiEntity doi: dmp.getDois()){ if(doi.getRepositoryId().equals("Zenodo")){ rda.setDmpId(DmpIdRDAMapper.toRDA(doi.getDoi())); } @@ -128,8 +129,9 @@ public class DmpRDAMapper { entity.setLabel(rda.getTitle()); if (rda.getDmpId().getType() == DmpId.Type.DOI) { try { - EntityDoi doi = apiContext.getOperationsContext().getDatabaseRepository().getEntityDoiDao().findFromDoi(rda.getDmpId().getIdentifier()); - Set dois = new HashSet<>(); + //TODO: Find from doi = rda.getDmpId().getIdentifier() + EntityDoiEntity doi = new EntityDoiEntity(); + Set dois = new HashSet<>(); dois.add(doi); entity.setDois(dois); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/publicapi/models/doi/DoiPublicModel.java b/dmp-backend/web/src/main/java/eu/eudat/publicapi/models/doi/DoiPublicModel.java index ec0b12d52..cafb4d86d 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/publicapi/models/doi/DoiPublicModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/publicapi/models/doi/DoiPublicModel.java @@ -1,12 +1,12 @@ package eu.eudat.publicapi.models.doi; -import eu.eudat.data.old.EntityDoi; +import eu.eudat.data.EntityDoiEntity; import eu.eudat.logic.utilities.helpers.LabelGenerator; import eu.eudat.models.DataModel; import java.util.UUID; -public class DoiPublicModel implements DataModel, LabelGenerator { +public class DoiPublicModel implements LabelGenerator { private UUID id; private String repositoryId; private String doi; @@ -32,17 +32,15 @@ public class DoiPublicModel implements DataModel, Lab this.doi = doi; } - @Override - public DoiPublicModel fromDataModel(EntityDoi entity) { + public DoiPublicModel fromDataModel(EntityDoiEntity entity) { this.id = entity.getId(); this.repositoryId = entity.getRepositoryId(); this.doi = entity.getDoi(); return this; } - @Override - public EntityDoi toDataModel() throws Exception { - EntityDoi entity = new EntityDoi(); + public EntityDoiEntity toDataModel() throws Exception { + EntityDoiEntity entity = new EntityDoiEntity(); entity.setId(this.getId()); entity.setRepositoryId(this.getRepositoryId()); entity.setDoi(this.getDoi()); @@ -54,7 +52,6 @@ public class DoiPublicModel implements DataModel, Lab return this.getDoi(); } - @Override public String getHint() { return null; } diff --git a/dmp-db-scema/updates/00.01.002_Align_Entity_Doi_table.sql b/dmp-db-scema/updates/00.01.002_Align_Entity_Doi_table.sql new file mode 100644 index 000000000..b85c9c7f3 --- /dev/null +++ b/dmp-db-scema/updates/00.01.002_Align_Entity_Doi_table.sql @@ -0,0 +1,23 @@ +ALTER TABLE public."EntityDoi" + RENAME "ID" TO id; + +ALTER TABLE public."EntityDoi" + RENAME "EntityType" TO entity_type; + +ALTER TABLE public."EntityDoi" + RENAME "RepositoryId" TO repository_id; + +ALTER TABLE public."EntityDoi" + RENAME "Doi" TO doi; + +ALTER TABLE public."EntityDoi" + RENAME "CreatedAt" TO created_at; + +ALTER TABLE public."EntityDoi" + RENAME "UpdatedAt" TO updated_at; + +ALTER TABLE public."EntityDoi" + RENAME "EntityId" TO entity_id; + +ALTER TABLE public."EntityDoi" + ADD COLUMN is_active smallint NOT NULL DEFAULT 1 \ No newline at end of file From 7cba7b2346755c10d0d9e49502bcf5f170f2b26e Mon Sep 17 00:00:00 2001 From: amentis Date: Wed, 18 Oct 2023 18:05:39 +0300 Subject: [PATCH 2/5] add external references service --- .../v2/ExternalReferencesController.java | 103 ++++++++++ .../controllers/v2/ValidationController.java | 37 ++++ .../logic/proxy/fetching/RemoteFetcher.java | 49 +++++ .../logic/services/ValidationService.java | 30 +++ .../ExternalReferencesCacheOptions.java | 10 + .../ExternalReferencesCacheService.java | 67 +++++++ .../ExternalReferencesService.java | 135 +++++++++++++ .../externalreferences/FunderService.java | 66 ++++++ .../externalreferences/ProjectService.java | 61 ++++++ .../eudat/models/data/ExternalReference.java | 126 ++++++++++++ .../eudat/models/data/ExternalReference2.java | 188 ++++++++++++++++++ 11 files changed, 872 insertions(+) create mode 100644 dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ExternalReferencesController.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ValidationController.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/ValidationService.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheOptions.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheService.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesService.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/FunderService.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ProjectService.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference.java create mode 100644 dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference2.java diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ExternalReferencesController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ExternalReferencesController.java new file mode 100644 index 000000000..8d4efddaa --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ExternalReferencesController.java @@ -0,0 +1,103 @@ +package eu.eudat.controllers.v2; + +import eu.eudat.controllers.BaseController; +import eu.eudat.data.old.DataRepository; +import eu.eudat.data.old.Registry; +import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest; +import eu.eudat.data.query.items.item.project.ProjectCriteriaRequest; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.services.ApiContext; +import eu.eudat.logic.services.externalreferences.ExternalReferencesService; +import eu.eudat.logic.services.externalreferences.FunderService; +import eu.eudat.logic.services.externalreferences.ProjectService; +import eu.eudat.models.data.ExternalReference; +import eu.eudat.models.data.ExternalReference2; +import eu.eudat.models.data.datarepository.DataRepositoryModel; +import eu.eudat.models.data.funder.Funder; +import eu.eudat.models.data.helpers.responses.ResponseItem; +import eu.eudat.models.data.project.Project; +import eu.eudat.models.data.registries.RegistryModel; +import eu.eudat.models.data.security.Principal; +import eu.eudat.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(path = {"api/external-references"}) +public class ExternalReferencesController extends BaseController { + + private final FunderService funderService; + private final ExternalReferencesService externalReferencesService; + private final ProjectService projectService; + + @Autowired + public ExternalReferencesController( + ApiContext apiContext, + FunderService funderService, + ExternalReferencesService externalReferencesService, + ProjectService projectService + ) { + super(apiContext); + this.funderService = funderService; + this.externalReferencesService = externalReferencesService; + this.projectService = projectService; + } + + @PostMapping(path = {"funders"}, consumes = "application/json", produces = "application/json") + public @ResponseBody ResponseEntity>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.funderService.getCriteriaWithExternal(funderCriteria, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @PostMapping(path = {"projects"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.projectService.getCriteriaWithExternal(projectCriteria, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + + + @GetMapping(path = {"data-repo/{externalType}"}, produces = "application/json") + public @ResponseBody ResponseEntity>> listExternalReferecnes(@RequestParam(value = "externalType") String externalType, @RequestParam(value = "query", required = false) String query, + @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List externalReferences = this.externalReferencesService.getExternalReference(externalType, query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(externalReferences)); + } + + @Transactional + @PostMapping(path = {"data-repo/persist"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createExternalReferecnes(@RequestBody ExternalReference externalReference, Principal principal) throws Exception { + ExternalReference newExternalReference = this.externalReferencesService.createDataRepo(externalReference, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(newExternalReference).status(ApiMessageCode.SUCCESS_MESSAGE)); + } + + + + + @GetMapping(path = {"{externalType}"}, produces = "application/json") + public @ResponseBody ResponseEntity>> listExternalReferecnes2(@RequestParam(value = "externalType") String externalType, @RequestParam(value = "query", required = false) String query, + @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List externalReferences = this.externalReferencesService.getExternalReference2(externalType, query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(externalReferences)); + } + + @Transactional + @PostMapping(value = {"{externalType}/persist"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody ExternalReference2 externalReference, Principal principal) throws Exception { + ExternalReference2 newExternalReference = this.externalReferencesService.create(externalReference, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(newExternalReference).status(ApiMessageCode.SUCCESS_MESSAGE)); + } + +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ValidationController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ValidationController.java new file mode 100644 index 000000000..d61525bd2 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ValidationController.java @@ -0,0 +1,37 @@ +package eu.eudat.controllers.v2; + +import eu.eudat.controllers.BaseController; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.services.ApiContext; +import eu.eudat.logic.services.ValidationService; +import eu.eudat.models.data.helpers.responses.ResponseItem; +import eu.eudat.models.data.security.Principal; +import eu.eudat.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@CrossOrigin +@RequestMapping(path = {"api/validation"}) +public class ValidationController extends BaseController { + + private ValidationService validationService; + + @Autowired + public ValidationController(ApiContext apiContext, ValidationService validationService) { + super(apiContext); + this.validationService = validationService; + } + + @GetMapping(path = {""}, produces = "application/json") + public @ResponseBody + ResponseEntity> validate( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + Boolean isValid = this.validationService.validateIdentifier(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(isValid).status(ApiMessageCode.NO_MESSAGE)); + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/proxy/fetching/RemoteFetcher.java b/dmp-backend/web/src/main/java/eu/eudat/logic/proxy/fetching/RemoteFetcher.java index 86a9742f9..325720e60 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/proxy/fetching/RemoteFetcher.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/proxy/fetching/RemoteFetcher.java @@ -50,6 +50,55 @@ public class RemoteFetcher { ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); } + public List> get(String externalType, ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = null; + FetchStrategy fetchStrategy = null; + switch (externalType){ + case "taxonomies": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getTaxonomies().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getTaxonomies().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getTaxonomies().getFetchMode(); + break; + case "licenses": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getLicenses().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getLicenses().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getLicenses().getFetchMode(); + break; + case "publications": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getPublications().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getPublications().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getPublications().getFetchMode(); + break; + case "journals": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getJournals().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getJournals().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getJournals().getFetchMode(); + break; + case "pubRepositories": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getPubRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getPubRepositories().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getPubRepositories().getFetchMode(); + break; + case "dataRepositories": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getRepositories().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getRepositories().getFetchMode(); + break; + case "registries": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRegistries().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getRegistries().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getRegistries().getFetchMode(); + break; + case "services": + urlConfigs = key != null && !key.isEmpty() ? configLoader.getExternalUrls().getServices().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getServices().getUrls(); + fetchStrategy = configLoader.getExternalUrls().getServices().getFetchMode(); + break; + } + + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + @Cacheable(value = "repositories", keyGenerator = "externalUrlsKeyGenerator") public List> getRepositories(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { List urlConfigs = diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/ValidationService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/ValidationService.java new file mode 100644 index 000000000..76c3a14a2 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/ValidationService.java @@ -0,0 +1,30 @@ +package eu.eudat.logic.services; + +import eu.eudat.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ValidationService { + + private RemoteFetcher remoteFetcher; + + @Autowired + public ValidationService(RemoteFetcher remoteFetcher) { + super(); + this.remoteFetcher = remoteFetcher; + } + + public Boolean validateIdentifier(String identifier, String type, Principal principal) throws NoURLFound, HugeResultSet { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(identifier); + Integer count = this.remoteFetcher.findEntries(externalUrlCriteria, type); + return principal != null && count > 0; + } + + + +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheOptions.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheOptions.java new file mode 100644 index 000000000..08fa2b99a --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheOptions.java @@ -0,0 +1,10 @@ +package eu.eudat.logic.services.externalreferences; + +import gr.cite.tools.cache.CacheOptions; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "cache.external-reference") +public class ExternalReferencesCacheOptions extends CacheOptions { +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheService.java new file mode 100644 index 000000000..d27effce5 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesCacheService.java @@ -0,0 +1,67 @@ +package eu.eudat.logic.services.externalreferences; + +import eu.eudat.logic.proxy.config.ExternalUrlCriteria; +import gr.cite.tools.cache.CacheService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Locale; + +@Service +public class ExternalReferencesCacheService extends CacheService { + + public static class ExternalReferencesCacheValue { + + public ExternalReferencesCacheValue() {} + + public ExternalReferencesCacheValue(String externalType, ExternalUrlCriteria externalUrlCriteria) { + this.externalType = externalType; + this.externalUrlCriteria = externalUrlCriteria; + } + + private String externalType; + + private ExternalUrlCriteria externalUrlCriteria; + + public String getExternalType() { + return externalType; + } + + public void setExternalType(String externalType) { + this.externalType = externalType; + } + + public ExternalUrlCriteria getExternalUrlCriteria() { + return externalUrlCriteria; + } + + public void setExternalUrlCriteria(ExternalUrlCriteria externalUrlCriteria) { + this.externalUrlCriteria = externalUrlCriteria; + } + } + + @Autowired + public ExternalReferencesCacheService(ExternalReferencesCacheOptions options) { + super(options); + } + + @Override + protected Class valueClass() {return ExternalReferencesCacheValue.class;} + + public String keyOf(ExternalReferencesCacheValue value) { + return this.buildKey(value.getExternalType(), value.getExternalUrlCriteria()); + } + + public String buildKey(String externalType, ExternalUrlCriteria externalUrlCriteria) { + HashMap keyParts = new HashMap<>(); + + keyParts.put("$type$", externalType.toLowerCase(Locale.ROOT)); + + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append(externalUrlCriteria); + keyParts.put("$criteria$", stringBuffer.toString().toLowerCase(Locale.ROOT)); + + return this.generateKey(keyParts); + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesService.java new file mode 100644 index 000000000..039b81a53 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ExternalReferencesService.java @@ -0,0 +1,135 @@ +package eu.eudat.logic.services.externalreferences; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.data.dao.criteria.RegistryCriteria; +import eu.eudat.data.dao.criteria.ServiceCriteria; + +import eu.eudat.data.old.DataRepository; +import eu.eudat.data.old.Registry; +import eu.eudat.data.old.Service; +import eu.eudat.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.services.ApiContext; +import eu.eudat.models.data.ExternalReference; +import eu.eudat.models.data.ExternalReference2; +import eu.eudat.models.data.security.Principal; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Service +public class ExternalReferencesService {//implements ExternalReferencesService{ + + private final ApiContext apiContext; + + public ExternalReferencesService(ApiContext apiContext) { + this.apiContext = apiContext; + } + + // external references: + // taxonomies, + // licenses, + // publications, + // journals, + // pubRepositories, + // dataRepositories + + public ExternalReference createDataRepo(ExternalReference externalReference, Principal principal) throws Exception { + // only dataRepositories, pubRepositories, journals + DataRepository dataRepository = externalReference.toDataModel(); + dataRepository.getCreationUser().setId(principal.getId()); + + dataRepository = apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().createOrUpdate(dataRepository); + return new ExternalReference().fromDataModel(dataRepository); + } + + public List getExternalReference(String externalType, String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().get(externalType, externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + + List list = new LinkedList<>(); + if((externalType.equals("dataRepositories") || externalType.equals("pubRepositories") || externalType.equals("journals"))){ + criteria.setCreationUserId(principal.getId()); + if (type.equals("")) { + List dataRepositoryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().getWithCriteria(criteria)).toList(); + list = dataRepositoryList.stream().map(item -> new ExternalReference().fromDataModel(item)).collect(Collectors.toList()); + } + } + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + list.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, ExternalReference.class)).collect(Collectors.toList())); + list = list.stream().filter(x -> x.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); + return list; + } + + + + // external references2: + // registries, + // services + + public ExternalReference2 create(ExternalReference2 externalReference, Principal principal) throws Exception { + if (externalReference.getLabel() == null || externalReference.getAbbreviation() == null || externalReference.getUri() == null) { + throw new Exception("Missing mandatory entity."); + } + + ExternalReference2 newExternalReference = null; + if(externalReference.getExternalType().equals("registries")){ + Registry registry = externalReference.toDataModelRegistry(); + registry.getCreationUser().setId(principal.getId()); + registry = apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().createOrUpdate(registry); + newExternalReference = new ExternalReference2().fromDataModel(registry); + } else if (externalReference.getExternalType().equals("services")) { + Service service = externalReference.toDataModelService(); + service.getCreationUser().setId(principal.getId()); + service = apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().createOrUpdate(service); + newExternalReference = new ExternalReference2().fromDataModel(service); + } + + return newExternalReference; + } + + + public List getExternalReference2(String externalType, String query, String type, Principal principal) throws HugeResultSet,NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().get(externalType,externalUrlCriteria, type); + + List list = new LinkedList<>(); + + if (externalType.equals("registries")){ + RegistryCriteria criteria = new RegistryCriteria(); + + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + + if (type.equals("")) { + List registryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().getWithCriteria(criteria)).toList(); + list = registryList.stream().map(item -> new ExternalReference2().fromDataModel(item)).collect(Collectors.toList()); + } + } else if (externalType.equals("services")) { + ServiceCriteria criteria = new ServiceCriteria(); + + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + + if (type.equals("")) { + List serviceList = (this.apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().getWithCriteria(criteria)).toList(); + list = serviceList.stream().map(item -> new ExternalReference2().fromDataModel(item)).collect(Collectors.toList()); + } + } + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + list.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, ExternalReference2.class)).collect(Collectors.toList())); + + return list; + } + +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/FunderService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/FunderService.java new file mode 100644 index 000000000..db4740f38 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/FunderService.java @@ -0,0 +1,66 @@ +package eu.eudat.logic.services.externalreferences; + +import eu.eudat.data.old.UserInfo; +import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest; +import eu.eudat.logic.builders.model.models.FunderBuilder; +import eu.eudat.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.logic.services.ApiContext; +import eu.eudat.logic.utilities.helpers.ListHelper; +import eu.eudat.models.data.external.ExternalSourcesItemModel; +import eu.eudat.models.data.external.FundersExternalSourcesModel; +import eu.eudat.models.data.funder.Funder; +import eu.eudat.models.data.security.Principal; +import eu.eudat.queryable.QueryableList; +import org.springframework.stereotype.Service; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class FunderService { + + private ApiContext apiContext; + private RemoteFetcher remoteFetcher; + private ListHelper listHelper; + + public FunderService(ApiContext apiContext, RemoteFetcher remoteFetcher, ListHelper listHelper) { + this.apiContext = apiContext; + this.remoteFetcher = remoteFetcher; + this.listHelper = listHelper; + } + + public List getCriteriaWithExternal(FunderCriteriaRequest funderCriteria, Principal principal) throws HugeResultSet, NoURLFound { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + funderCriteria.getCriteria().setReference("dmp:"); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getWithCritetia(funderCriteria.getCriteria()); + QueryableList authItems = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getAuthenticated(items, userInfo); + List funders = authItems.select(item -> new Funder().fromDataModel(item)); + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(funderCriteria.getCriteria().getLike()); + List> remoteRepos = remoteFetcher.getFunders(externalUrlCriteria); + FundersExternalSourcesModel fundersExternalSourcesModel = new FundersExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : fundersExternalSourcesModel) { + Funder funder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(FunderBuilder.class) + .reference(externalListingItem.getRemoteId()).label(externalListingItem.getName()) + .status(eu.eudat.data.old.Funder.Status.fromInteger(0)) + .key(externalListingItem.getKey()) + .source(externalListingItem.getTag()) + .build(); + if (externalListingItem.getSource() != null) { + funder.setSource(externalListingItem.getSource()); + } else { + funder.setSource(externalListingItem.getTag()); + } + + funders.add(funder); + } + funders.sort(Comparator.comparing(Funder::getLabel)); + funders = funders.stream().filter(listHelper.distinctByKey(Funder::getLabel)).collect(Collectors.toList()); + return funders; + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ProjectService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ProjectService.java new file mode 100644 index 000000000..f17958665 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/externalreferences/ProjectService.java @@ -0,0 +1,61 @@ +package eu.eudat.logic.services.externalreferences; + +import eu.eudat.data.query.items.item.project.ProjectCriteriaRequest; +import eu.eudat.logic.builders.model.models.ProjectBuilder; +import eu.eudat.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.logic.services.ApiContext; +import eu.eudat.logic.utilities.helpers.ListHelper; +import eu.eudat.models.data.external.ExternalSourcesItemModel; +import eu.eudat.models.data.external.ProjectsExternalSourcesModel; +import eu.eudat.models.data.project.Project; +import eu.eudat.models.data.security.Principal; +import eu.eudat.queryable.QueryableList; +import org.springframework.stereotype.Service; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class ProjectService { + + private ApiContext apiContext; + private RemoteFetcher remoteFetcher; + private ListHelper listHelper; + + public ProjectService(ApiContext apiContext, ListHelper listHelper) { + this.apiContext = apiContext; + this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher(); + this.listHelper = listHelper; + } + + public List getCriteriaWithExternal(ProjectCriteriaRequest projectCriteria, Principal principal) throws HugeResultSet, NoURLFound { + eu.eudat.data.old.UserInfo userInfo = new eu.eudat.data.old.UserInfo(); + userInfo.setId(principal.getId()); + projectCriteria.getCriteria().setReference("dmp:"); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getWithCritetia(projectCriteria.getCriteria()); + QueryableList authItems = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getAuthenticated(items, userInfo); + List projects = authItems.select(item -> new Project().fromDataModel(item)); + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(projectCriteria.getCriteria().getLike()); + List> remoteRepos = remoteFetcher.getProjects(externalUrlCriteria); + ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : projectsExternalSourcesModel) { + Project project = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ProjectBuilder.class) + .reference(externalListingItem.getRemoteId()).label(externalListingItem.getName()) + .description(externalListingItem.getDescription()).uri(externalListingItem.getUri()) + .abbreviation(externalListingItem.getAbbreviation()).status(eu.eudat.data.old.Project.Status.fromInteger(0)) + .key(externalListingItem.getKey()) + .source(externalListingItem.getTag()) + .build(); + + projects.add(project); + } + projects.sort(Comparator.comparing(Project::getLabel)); + projects = projects.stream().filter(listHelper.distinctByKey(Project::getLabel)).collect(Collectors.toList()); + return projects; + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference.java new file mode 100644 index 000000000..73b2698b0 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference.java @@ -0,0 +1,126 @@ +package eu.eudat.models.data; + + + +import eu.eudat.data.old.DataRepository; +import eu.eudat.data.old.UserInfo; + +import java.util.Date; +import java.util.UUID; + +public class ExternalReference { + private UUID id; + private String name; + private String pid; + private String abbreviation; + private String uri; + private Date created; + private Date modified; + private String tag; // Api fetching the data + private String source; // Actual harvested source + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getPid() { + return pid; + } + public void setPid(String pid) { + this.pid = pid; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public Date getCreated() { + return created; + } + public void setCreated(Date created) { + this.created = created; + } + + public Date getModified() { + return modified; + } + public void setModified(Date modified) { + this.modified = modified; + } + + public String getTag() { + return tag; + } + public void setTag(String tag) { + this.tag = tag; + } + + public String getSource() { + return source; + } + public void setSource(String source) { + this.source = source; + } + + + public ExternalReference fromDataModel(DataRepository entity) { + this.setAbbreviation(entity.getAbbreviation()); + this.setName(entity.getLabel()); + this.setUri(entity.getUri()); + this.setId(entity.getId()); + this.setPid(entity.getReference()); + String source1 = entity.getReference().substring(0, entity.getReference().indexOf(":")); + if (source1.equals("dmp")) { + this.source = "Internal"; + } else { + this.source = source1; + } + return this; + } + + public DataRepository toDataModel() throws Exception { + DataRepository dataRepository = new DataRepository(); + dataRepository.setId(this.id != null ? this.id : UUID.randomUUID()); + dataRepository.setAbbreviation(this.abbreviation); + dataRepository.setCreated(this.created != null ? this.created : new Date()); + dataRepository.setModified(new Date()); + dataRepository.setLabel(this.name); + if (this.source != null) { + if (this.source.equals("Internal") || this.source.equals(this.id.toString().substring(0, this.source.length()))) { + dataRepository.setReference(this.id.toString()); + } else { + dataRepository.setReference(this.source + ":" + dataRepository.getId()); + } + } else { + dataRepository.setReference("dmp:" + dataRepository.getId()); + } + dataRepository.setUri(this.uri); + dataRepository.setStatus((short) 0); + dataRepository.setCreationUser(new UserInfo()); + return dataRepository; + } + + public String getHint() { + return null; + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference2.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference2.java new file mode 100644 index 000000000..764890742 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/ExternalReference2.java @@ -0,0 +1,188 @@ +package eu.eudat.models.data; + + + +import eu.eudat.data.old.Registry; +import eu.eudat.data.old.Service; +import eu.eudat.data.old.UserInfo; + +import java.util.Date; +import java.util.UUID; + +public class ExternalReference2 { + private UUID id; + private String label; + private String name; + private String pid; + private String abbreviation; + private String uri; + private Date created; + private Date modified; + private String reference; + private String tag; + private String source; + + private String externalType; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getPid() { + return pid; + } + public void setPid(String pid) { + this.pid = pid; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public Date getCreated() { + return created; + } + public void setCreated(Date created) { + this.created = created; + } + + public Date getModified() { + return modified; + } + public void setModified(Date modified) { + this.modified = modified; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getTag() { + return tag; + } + public void setTag(String tag) { + this.tag = tag; + } + + public String getSource() { + return source; + } + public void setSource(String source) { + this.source = source; + } + + public String getExternalType() {return externalType;} + + public void setExternalType(String externalType) {this.externalType = externalType;} + + public ExternalReference2 fromDataModel(Service entity) { + this.abbreviation = entity.getAbbreviation(); + this.created = entity.getCreated(); + this.id = entity.getId(); + this.label = entity.getLabel(); + this.name = entity.getLabel(); + this.modified = entity.getModified(); + this.uri = entity.getUri(); + String source = entity.getReference().substring(0, entity.getReference().indexOf(":")); + if (source.equals("dmp")) { + this.source = "Internal"; + } else { + this.source = source; + } + this.externalType = "services"; + return this; + } + + public ExternalReference2 fromDataModel(Registry entity) { + this.id = entity.getId(); + this.abbreviation = entity.getAbbreviation(); + this.created = entity.getCreated(); + this.label = entity.getLabel(); + this.name = entity.getLabel(); + this.modified = entity.getModified(); + this.uri = entity.getUri(); + String source1 = entity.getReference().substring(0, entity.getReference().indexOf(":")); + if (source1.equals("dmp")) { + this.source = "Internal"; + } else { + this.source = source1; + } + this.reference = entity.getReference(); + this.externalType = "registries"; + return this; + } + + public Service toDataModelService() throws Exception { + Service service = new Service(); + service.setId(this.id != null ? this.id : UUID.randomUUID()); + service.setAbbreviation(this.abbreviation); + service.setCreated(this.created != null ? this.created : new Date()); + service.setLabel(this.label != null ? this.label : this.name); + service.setModified(new Date()); + service.setUri(this.uri); + if (this.source == null) this.source = "dmp"; + if (this.reference == null) this.reference = service.getId().toString(); + if (this.source.equals(this.reference.substring(0, this.source.length()))) { + service.setReference(this.reference); + } else { + service.setReference(this.source + ":" + this.reference); + } + service.setModified(new Date()); + service.setStatus((short) 0); + service.setCreationUser(new UserInfo()); + return service; + } + + public Registry toDataModelRegistry() throws Exception { + Registry registry = new Registry(); + registry.setAbbreviation(this.abbreviation); + registry.setCreated(this.created != null ? this.created : new Date()); + registry.setId(this.id != null ? this.id : UUID.randomUUID()); + registry.setLabel(this.label != null ? this.label : this.name); + registry.setUri(this.uri); + registry.setModified(new Date()); + if (this.source == null) this.source = "dmp"; + if (this.source.equals(registry.getId().toString().substring(0, this.source.length()))) { + registry.setReference(registry.getId().toString()); + } else { + registry.setReference(this.source + ":" + registry.getId()); + } + registry.setStatus((short)0); + registry.setCreationUser(new UserInfo()); + return registry; + } + + public String getHint() { + return null; + } +} From 093837c3950e6e0e5878c19be31b5420a3526754 Mon Sep 17 00:00:00 2001 From: George Kalampokis Date: Wed, 18 Oct 2023 18:13:32 +0300 Subject: [PATCH 3/5] Fix DMP user ownership error --- dmp-frontend/src/app/core/model/auth/principal.ts | 1 + dmp-frontend/src/app/core/services/auth/auth.service.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/dmp-frontend/src/app/core/model/auth/principal.ts b/dmp-frontend/src/app/core/model/auth/principal.ts index c0012e7cd..27609c091 100644 --- a/dmp-frontend/src/app/core/model/auth/principal.ts +++ b/dmp-frontend/src/app/core/model/auth/principal.ts @@ -19,6 +19,7 @@ export interface AppPrincipalInfo{ notBefore: Date; authenticatedAt: Date; expiresAt: Date; + userId: Guid; more: Record } export interface UserProfileInfo { diff --git a/dmp-frontend/src/app/core/services/auth/auth.service.ts b/dmp-frontend/src/app/core/services/auth/auth.service.ts index 66238f10a..a69d35d4d 100644 --- a/dmp-frontend/src/app/core/services/auth/auth.service.ts +++ b/dmp-frontend/src/app/core/services/auth/auth.service.ts @@ -125,9 +125,9 @@ export class AuthService extends BaseService { if ( this.appAccount && this.appAccount.principal && - this.appAccount.principal.subject + this.appAccount.principal.userId ) { - return this.appAccount.principal.subject; + return this.appAccount.principal.userId; } return null; } From 5885e3ae5cf28cb51596531551de494cbb9b805b Mon Sep 17 00:00:00 2001 From: George Kalampokis Date: Wed, 18 Oct 2023 18:14:02 +0300 Subject: [PATCH 4/5] Fix DMP's funder tab --- .../funding-info/funding-info.component.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/dmp-frontend/src/app/ui/dmp/editor/funding-info/funding-info.component.ts b/dmp-frontend/src/app/ui/dmp/editor/funding-info/funding-info.component.ts index 1663bcce9..88220c5b4 100644 --- a/dmp-frontend/src/app/ui/dmp/editor/funding-info/funding-info.component.ts +++ b/dmp-frontend/src/app/ui/dmp/editor/funding-info/funding-info.component.ts @@ -74,7 +74,7 @@ export class FundingInfoComponent extends BaseComponent implements OnInit { return ''; } - ngOnInit() { + ngOnInit() { const grantRequestItem: RequestItem = new RequestItem(); grantRequestItem.criteria = new GrantCriteria(); @@ -388,7 +388,7 @@ export class FundingInfoComponent extends BaseComponent implements OnInit { if(this.isRequired) this.funderFormGroup.get('reference').setValidators(Validators.required); this.funderFormGroup.get('reference').updateValueAndValidity(); - + } else if (this.isClone && !this.isNewVersion) { if (this.funderFormGroup.get('existFunder')) { this.funderFormGroup.get('existFunder').enable(); @@ -435,9 +435,17 @@ export class FundingInfoComponent extends BaseComponent implements OnInit { } } + private hasNewFunder(funder: any) { + return funder.label !== null && funder.label !== undefined && funder.label !== '' && funder.reference !== undefined && funder.reference !== undefined && funder.reference !== ''; + } + + private hasExistingFunder(funder: any) { + return funder.existFunder !== null && funder.existFunder !== undefined && funder.existFunder.reference !== null && funder.existFunder.reference !== undefined; + } + funderValueChanged(funder: any) { - if ((funder.label !== "" && funder.label !== null && funder.label !== undefined && !isNullOrUndefined(funder.reference) && funder.reference.length ) - || (funder.existFunder !== null && funder.existFunder !== undefined && funder.existFunder.id !== undefined)) { + + if (this.hasNewFunder(funder) || this.hasExistingFunder(funder)) { //this.grantformGroup.reset(); this.grantformGroup.enable(); this.setGrantValidators(); From dc752f73cad3ed5e5b6f5f523196802da3419e96 Mon Sep 17 00:00:00 2001 From: George Kalampokis Date: Wed, 18 Oct 2023 18:15:52 +0300 Subject: [PATCH 5/5] Partially fix Deposit Logic and add support for upcomming micro-services --- dmp-backend/core/pom.xml | 5 +++ .../configurations/DepositConfiguration.java | 35 +++++++++++++++++ .../configurations/DepositProperties.java | 25 ++++++++++++ .../eudat/repository/DepositRepository.java | 39 +++++++++++++++++++ .../managers/DataManagementPlanManager.java | 2 + .../eudat/logic/managers/DepositManager.java | 19 ++++++--- .../mapper/DMPToDepositMapper.java | 3 ++ .../eudat/models/rda/mapper/DmpRDAMapper.java | 26 +++++++------ .../src/main/resources/config/application.yml | 5 ++- .../web/src/main/resources/config/deposit.yml | 3 ++ 10 files changed, 143 insertions(+), 19 deletions(-) create mode 100644 dmp-backend/core/src/main/java/eu/eudat/configurations/DepositConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/configurations/DepositProperties.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/repository/DepositRepository.java create mode 100644 dmp-backend/web/src/main/resources/config/deposit.yml diff --git a/dmp-backend/core/pom.xml b/dmp-backend/core/pom.xml index 09e82047c..2275a1d4f 100644 --- a/dmp-backend/core/pom.xml +++ b/dmp-backend/core/pom.xml @@ -35,6 +35,11 @@ oidc-authz 2.1.0 + + gr.cite.opendmp + repositorydepositbase + 1.0.4 + diff --git a/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositConfiguration.java new file mode 100644 index 000000000..cf208d12b --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositConfiguration.java @@ -0,0 +1,35 @@ +package eu.eudat.configurations; + +import eu.eudat.depositinterface.repository.RepositoryDeposit; +import eu.eudat.repository.DepositRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.ArrayList; +import java.util.List; + +@Configuration +@EnableConfigurationProperties({DepositProperties.class}) +public class DepositConfiguration { + + private final DepositProperties properties; + + @Autowired + public DepositConfiguration(DepositProperties properties) { + this.properties = properties; + } + + @Bean + @Qualifier("depositClients") + public List depositClients() { + List clients = new ArrayList<>(); + for (String url: properties.getUrls()) { + clients.add(new DepositRepository(WebClient.builder().baseUrl(url + "/api/deposit").build())); + } + return clients; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositProperties.java b/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositProperties.java new file mode 100644 index 000000000..aa7a37f40 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/configurations/DepositProperties.java @@ -0,0 +1,25 @@ +package eu.eudat.configurations; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.ConstructorBinding; + +import java.util.List; + +@ConfigurationProperties(prefix = "deposit") +public class DepositProperties { + + private List urls; + + @ConstructorBinding + public DepositProperties(List urls) { + this.urls = urls; + } + + public List getUrls() { + return urls; + } + + public void setUrls(List urls) { + this.urls = urls; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/repository/DepositRepository.java b/dmp-backend/core/src/main/java/eu/eudat/repository/DepositRepository.java new file mode 100644 index 000000000..c0dd332b3 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/repository/DepositRepository.java @@ -0,0 +1,39 @@ +package eu.eudat.repository; + +import eu.eudat.depositinterface.models.DMPDepositModel; +import eu.eudat.depositinterface.repository.RepositoryDeposit; +import eu.eudat.depositinterface.repository.RepositoryDepositConfiguration; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.List; + +public class DepositRepository implements RepositoryDeposit { + + private final WebClient depositClient; + + public DepositRepository(WebClient depositClient) { + this.depositClient = depositClient; + } + + + @Override + public String deposit(String repositoryId, DMPDepositModel dmpDepositModel, String repositoryAccessToken) throws Exception { + return depositClient.post().uri("/" + repositoryId, uriBuilder -> uriBuilder.queryParam("authToken", repositoryAccessToken).build()).bodyValue(dmpDepositModel).exchangeToMono(mono -> mono.bodyToMono(String.class)).block(); + } + + @Override + public String authenticate(String repositoryId, String code) { + return depositClient.get().uri("/authenticate/" + repositoryId, uriBuilder -> uriBuilder.queryParam("authToken", code).build()).exchangeToMono(mono -> mono.bodyToMono(String.class)).block(); + } + + @Override + public List getConfiguration() { + return depositClient.get().uri("/configuration").exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() {})).block(); + } + + @Override + public String getLogo(String repositoryId) { + return depositClient.get().uri("/logo/" + repositoryId).exchangeToMono(mono -> mono.bodyToMono(String.class)).block(); + } +} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java index 37dca6d08..2148b5f81 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java @@ -1960,6 +1960,7 @@ public class DataManagementPlanManager { return fileEnvelope; } + @Transactional public FileEnvelope getRDAJsonDocument(String id, Principal principal) throws Exception { DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); if (!dmp.isPublic() && dmp.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) @@ -2464,6 +2465,7 @@ public class DataManagementPlanManager { return null; } + @Transactional public Doi createDoi(DepositRequest depositRequest, Principal principal) throws Exception { DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(UUID.fromString(depositRequest.getDmpId())); if (!isUserOwnerOfDmp(dmp, principal)) diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DepositManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DepositManager.java index fa8e20d42..a1208e747 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DepositManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DepositManager.java @@ -6,10 +6,14 @@ import eu.eudat.models.data.doi.DepositRequest; import eu.eudat.models.data.doi.Doi; import eu.eudat.models.data.doi.RepositoryConfig; import eu.eudat.models.data.security.Principal; +import jakarta.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; import java.util.ArrayList; import java.util.List; @@ -19,18 +23,20 @@ import java.util.Optional; public class DepositManager { private static final Logger logger = LoggerFactory.getLogger(DepositManager.class); - private List repositories; + //private List repositories; private DataManagementPlanManager dataManagementPlanManager; + private final List depositClients; @Autowired - public DepositManager(List repositories, DataManagementPlanManager dataManagementPlanManager){ - this.repositories = repositories; + public DepositManager(/*List repositories,*/ DataManagementPlanManager dataManagementPlanManager, @Qualifier("depositClients") List depositClients){ + //this.repositories = repositories; this.dataManagementPlanManager = dataManagementPlanManager; + this.depositClients = depositClients; } public List getAvailableRepos() { List reposConfigModel = new ArrayList<>(); - for (RepositoryDeposit r: this.repositories) { + for (RepositoryDeposit r: this.depositClients) { List repoConf = r.getConfiguration(); if(repoConf != null) { for(RepositoryDepositConfiguration cf: repoConf){ @@ -43,7 +49,7 @@ public class DepositManager { } public String authenticate(String id, String code) { - for(RepositoryDeposit r: this.repositories){ + for(RepositoryDeposit r: this.depositClients){ if(r.getConfiguration().stream().anyMatch(x -> x.getRepositoryId().equals(id))){ return r.authenticate(id, code); } @@ -51,12 +57,13 @@ public class DepositManager { return null; } + @Transactional public Doi deposit(DepositRequest depositRequest, Principal principal) throws Exception { return this.dataManagementPlanManager.createDoi(depositRequest, principal); } public String getRepositoryLogo(String repositoryId){ - for(RepositoryDeposit r: this.repositories){ + for(RepositoryDeposit r: this.depositClients){ Optional cf = r.getConfiguration().stream().filter(x -> x.getRepositoryId().equals(repositoryId)).findFirst(); if(cf.isPresent()){ return cf.get().isHasLogo() ? r.getLogo(repositoryId) : null; diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java b/dmp-backend/web/src/main/java/eu/eudat/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java index db21be3e7..ccb614755 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import eu.eudat.data.old.*; import eu.eudat.depositinterface.models.*; import eu.eudat.logic.utilities.builders.XmlBuilder; +import jakarta.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; @@ -25,6 +26,7 @@ public class DMPToDepositMapper { private static final Logger logger = LoggerFactory.getLogger(DMPToDepositMapper.class); private static final ObjectMapper mapper = new ObjectMapper(); + @Transactional public static DMPDepositModel fromDMP(DMP entity, FileEnvelope pdfFile, FileEnvelope jsonFile, File supportingFilesZip, String previousDOI) { DMPDepositModel deposit = new DMPDepositModel(); deposit.setId(entity.getId()); @@ -49,6 +51,7 @@ public class DMPToDepositMapper { return deposit; } + @Transactional private static DatasetDepositModel fromDataset(Dataset entity){ DatasetDepositModel deposit = new DatasetDepositModel(); deposit.setLabel(entity.getLabel()); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java index 6ac1c3a02..b2c061b15 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DmpRDAMapper.java @@ -88,20 +88,24 @@ public class DmpRDAMapper { rda.getCost().add(CostRDAMapper.toRDA((Map)costl)); }); } - UserInfo contactDb = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString((String) extraProperties.get("contact"))); - UserInfo contact = new UserInfo(); - contact.setId(contactDb.getId()); - contact.setName(contactDb.getName()); - contact.setEmail(contactDb.getEmail()); - if(contact.getEmail() == null){ - for(UserDMP userDMP: dmp.getUsers()){ - if(userDMP.getDmp().getId() == dmp.getId() && userDMP.getUser().getEmail() != null){ - contact.setEmail(userDMP.getUser().getEmail()); - break; + try { + UserInfo contactDb = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString((String) extraProperties.get("contact"))); + UserInfo contact = new UserInfo(); + contact.setId(contactDb.getId()); + contact.setName(contactDb.getName()); + contact.setEmail(contactDb.getEmail()); + if (contact.getEmail() == null) { + for (UserDMP userDMP : dmp.getUsers()) { + if (userDMP.getDmp().getId() == dmp.getId() && userDMP.getUser().getEmail() != null) { + contact.setEmail(userDMP.getUser().getEmail()); + break; + } } } + rda.setContact(ContactRDAMapper.toRDA(contact)); + } catch (NoResultException e) { + logger.error(e.getMessage(), e); } - rda.setContact(ContactRDAMapper.toRDA(contact)); } /*UserInfo creator; diff --git a/dmp-backend/web/src/main/resources/config/application.yml b/dmp-backend/web/src/main/resources/config/application.yml index ced49fdd3..e795cc7d6 100644 --- a/dmp-backend/web/src/main/resources/config/application.yml +++ b/dmp-backend/web/src/main/resources/config/application.yml @@ -14,5 +14,6 @@ spring: optional:classpath:config/elasticsearch.yml[.yml], optional:classpath:config/elasticsearch-${spring.profiles.active}.yml[.yml], optional:file:../config/elasticsearch-${spring.profiles.active}.yml[.yml], optional:classpath:config/file-path.yml[.yml], optional:classpath:config/file-path-${spring.profiles.active}.yml[.yml], optional:file:../config/file-path-${spring.profiles.active}.yml[.yml], optional:classpath:config/idpclaims.yml[.yml], optional:classpath:config/idpclaims-${spring.profiles.active}.yml[.yml], optional:file:../config/idpclaims-${spring.profiles.active}.yml[.yml], - optional:classpath:config/external.yml[.yml], optional:classpath:config/external-${spring.profiles.active}.yml[.yml], optional:file:../config/external-${spring.profiles.active}.yml[.yml] - optional:classpath:config/swagger.yml[.yml], optional:classpath:config/swagger-${spring.profiles.active}.yml[.yml], optional:file:../config/swagger-${spring.profiles.active}.yml[.yml] + optional:classpath:config/external.yml[.yml], optional:classpath:config/external-${spring.profiles.active}.yml[.yml], optional:file:../config/external-${spring.profiles.active}.yml[.yml], + optional:classpath:config/swagger.yml[.yml], optional:classpath:config/swagger-${spring.profiles.active}.yml[.yml], optional:file:../config/swagger-${spring.profiles.active}.yml[.yml], + optional:classpath:config/deposit.yml[.yml], optional:classpath:config/deposit-${spring.profiles.active}.yml[.yml], optional:file:../config/deposit-${spring.profiles.active}.yml[.yml] diff --git a/dmp-backend/web/src/main/resources/config/deposit.yml b/dmp-backend/web/src/main/resources/config/deposit.yml new file mode 100644 index 000000000..bf19ffbd5 --- /dev/null +++ b/dmp-backend/web/src/main/resources/config/deposit.yml @@ -0,0 +1,3 @@ +deposit: + urls: + - http://localhost:8080 \ No newline at end of file