diff --git a/dmp-backend/core/pom.xml b/dmp-backend/core/pom.xml index ccd2a632e..883457036 100644 --- a/dmp-backend/core/pom.xml +++ b/dmp-backend/core/pom.xml @@ -19,6 +19,11 @@ org.springframework.boot spring-boot-starter-validation + + org.apache.commons + commons-csv + 1.10.0 + gr.cite validation diff --git a/dmp-backend/core/src/main/java/eu/eudat/audit/AuditableAction.java b/dmp-backend/core/src/main/java/eu/eudat/audit/AuditableAction.java index cefd68566..65c223b82 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/audit/AuditableAction.java +++ b/dmp-backend/core/src/main/java/eu/eudat/audit/AuditableAction.java @@ -67,4 +67,13 @@ public class AuditableAction { public static final EventId ReferenceType_Persist = new EventId(10002, "ReferenceType_Persist"); public static final EventId ReferenceType_Delete = new EventId(10003, "ReferenceType_Delete"); + public static final EventId User_Query = new EventId(11000, "User_Query"); + public static final EventId User_Lookup = new EventId(11001, "User_Lookup"); + public static final EventId User_Persist = new EventId(11002, "User_Persist"); + public static final EventId User_Delete = new EventId(11003, "User_Delete"); + public static final EventId User_LookupByEmail = new EventId(11004, "User_LookupByEmail"); + public static final EventId User_ExportCsv = new EventId(11005, "User_ExportCsv"); + public static final EventId User_PersistRoles = new EventId(11004, "User_PersistRoles"); + + } 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 bd2b828c1..f4bbb3950 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 @@ -47,6 +47,7 @@ public final class Permission { public static String BrowseUser = "BrowseUser"; public static String EditUser = "EditUser"; public static String DeleteUser = "DeleteUser"; + public static String ExportUsers = "ExportUsers"; //DescriptionTemplateType public static String BrowseDescriptionTemplateType = "BrowseDescriptionTemplateType"; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/user/AdditionalInfoEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/user/AdditionalInfoEntity.java index fd45eb24b..fdffd0844 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/user/AdditionalInfoEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/user/AdditionalInfoEntity.java @@ -1,10 +1,14 @@ package eu.eudat.commons.types.user; +import java.util.UUID; + public class AdditionalInfoEntity { private String avatarUrl; private String timezone; private String culture; private String language; + private String roleOrganization; + private UUID organizationId; public String getAvatarUrl() { return avatarUrl; @@ -37,4 +41,20 @@ public class AdditionalInfoEntity { public void setLanguage(String language) { this.language = language; } + + public UUID getOrganizationId() { + return organizationId; + } + + public void setOrganizationId(UUID organizationId) { + this.organizationId = organizationId; + } + + public String getRoleOrganization() { + return roleOrganization; + } + + public void setRoleOrganization(String roleOrganization) { + this.roleOrganization = roleOrganization; + } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java index 4c9e03fb0..aad5171ee 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java @@ -86,9 +86,9 @@ public class DmpEntity implements DataEntity { public static final String _finalizedAt = "finalizedAt"; @Column(name = "creator") - private UUID creator; + private UUID creatorId; - public static final String _creator = "creator"; + public static final String _creatorId = "creatorId"; @Column(name = "access_type", nullable = false) @Convert(converter = DmpAccessTypeConverter.class) @@ -97,9 +97,9 @@ public class DmpEntity implements DataEntity { public static final String _accessType = "accessType"; @Column(name = "blueprint") - private UUID blueprint; + private UUID blueprintId; - public static final String _blueprint = "blueprint"; + public static final String _blueprintId = "blueprintId"; @Column(name = "language") private String language; @@ -199,12 +199,12 @@ public class DmpEntity implements DataEntity { this.finalizedAt = finalizedAt; } - public UUID getCreator() { - return creator; + public UUID getCreatorId() { + return creatorId; } - public void setCreator(UUID creator) { - this.creator = creator; + public void setCreatorId(UUID creatorId) { + this.creatorId = creatorId; } public DmpAccessType getAccessType() { @@ -215,12 +215,12 @@ public class DmpEntity implements DataEntity { this.accessType = accessType; } - public UUID getBlueprint() { - return blueprint; + public UUID getBlueprintId() { + return blueprintId; } - public void setBlueprint(UUID blueprint) { - this.blueprint = blueprint; + public void setBlueprintId(UUID blueprintId) { + this.blueprintId = blueprintId; } public String getLanguage() { diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/DmpUserEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/DmpUserEntity.java index f1ae5c75b..1ed6aa352 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/DmpUserEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/DmpUserEntity.java @@ -27,9 +27,9 @@ public class DmpUserEntity implements DataEntity { public static final String _dmp = "dmp"; @Column(name = "user", columnDefinition = "uuid", nullable = false) - private UUID user; + private UUID userId; - public static final String _user = "user"; + public static final String _userId = "userId"; @Column(name = "role", nullable = false) @Convert(converter = DmpUserRoleConverter.class) @@ -69,12 +69,12 @@ public class DmpUserEntity implements DataEntity { this.dmp = dmp; } - public UUID getUser() { - return user; + public UUID getUserId() { + return userId; } - public void setUser(UUID user) { - this.user = user; + public void setUserId(UUID userId) { + this.userId = userId; } public DmpUserRole getRole() { diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java index f7e2cf4eb..7cc4e3926 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java @@ -68,8 +68,8 @@ public class ReferenceEntity { public static final String _updatedAt = "updatedAt"; @Column(name = "created_by", columnDefinition = "uuid") - private UUID createdBy; - public static final String _createdBy = "createdBy"; + private UUID createdById; + public static final String _createdById = "createdBy"; public UUID getId() { return id; @@ -167,11 +167,11 @@ public class ReferenceEntity { this.updatedAt = updatedAt; } - public UUID getCreatedBy() { - return createdBy; + public UUID getCreatedById() { + return createdById; } - public void setCreatedBy(UUID createdBy) { - this.createdBy = createdBy; + public void setCreatedById(UUID createdById) { + this.createdById = createdById; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/TagEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/TagEntity.java index 4887c4207..ac260f81b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/TagEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/TagEntity.java @@ -37,8 +37,8 @@ public class TagEntity { public static final String _updatedAt = "updatedAt"; @Column(name = "\"created_by\"", nullable = false) - private UUID createdBy; - public static final String _createdBy = "createdBy"; + private UUID createdById; + public static final String _createdById = "createdById"; public UUID getId() { return id; @@ -80,11 +80,11 @@ public class TagEntity { this.updatedAt = updatedAt; } - public UUID getCreatedBy() { - return createdBy; + public UUID getCreatedById() { + return createdById; } - public void setCreatedBy(UUID createdBy) { - this.createdBy = createdBy; + public void setCreatedById(UUID createdById) { + this.createdById = createdById; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/UserDescriptionTemplateEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/UserDescriptionTemplateEntity.java index 41c56bd93..bcf09cf14 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/UserDescriptionTemplateEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/UserDescriptionTemplateEntity.java @@ -21,8 +21,8 @@ public class UserDescriptionTemplateEntity implements DataEntity dmpReferences; public static final String _dmpReferences = "dmpReferences"; + private String hash; + public final static String _hash = "hash"; + public UUID getId() { return id; } @@ -156,4 +159,20 @@ public class Reference { public void setDmpReferences(List dmpReferences) { this.dmpReferences = dmpReferences; } + + public User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + 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/SupportiveMaterial.java b/dmp-backend/core/src/main/java/eu/eudat/model/SupportiveMaterial.java index ca552da3b..34c77f0eb 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/SupportiveMaterial.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/SupportiveMaterial.java @@ -30,6 +30,9 @@ public class SupportiveMaterial { private IsActive isActive; public static final String _isActive = "isActive"; + private String hash; + public final static String _hash = "hash"; + public UUID getId() { return id; } @@ -85,4 +88,12 @@ public class SupportiveMaterial { public void setIsActive(IsActive isActive) { this.isActive = isActive; } + + 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/Tag.java b/dmp-backend/core/src/main/java/eu/eudat/model/Tag.java index 43bab127f..bea557327 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/Tag.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/Tag.java @@ -17,7 +17,7 @@ public class Tag { public static final String _label = "label"; - private UUID createdBy; + private User createdBy; public static final String _createdBy = "createdBy"; @@ -53,11 +53,11 @@ public class Tag { this.label = label; } - public UUID getCreatedBy() { + public User getCreatedBy() { return createdBy; } - public void setCreatedBy(UUID createdBy) { + public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/UserAdditionalInfo.java b/dmp-backend/core/src/main/java/eu/eudat/model/UserAdditionalInfo.java index c9a1d7128..5ac898b80 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/UserAdditionalInfo.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/UserAdditionalInfo.java @@ -17,6 +17,12 @@ public class UserAdditionalInfo { private String language; public static final String _language = "language"; + + private String roleOrganization; + public static final String _roleOrganization = "roleOrganization"; + + private Reference organization; + public static final String _organization = "organization"; public String getAvatarUrl() { return avatarUrl; @@ -49,4 +55,20 @@ public class UserAdditionalInfo { public void setLanguage(String language) { this.language = language; } + + public String getRoleOrganization() { + return roleOrganization; + } + + public void setRoleOrganization(String roleOrganization) { + this.roleOrganization = roleOrganization; + } + + public Reference getOrganization() { + return organization; + } + + public void setOrganization(Reference organization) { + this.organization = organization; + } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/UserDescriptionTemplate.java b/dmp-backend/core/src/main/java/eu/eudat/model/UserDescriptionTemplate.java index 09a345a1f..b5df816d2 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/UserDescriptionTemplate.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/UserDescriptionTemplate.java @@ -15,9 +15,13 @@ public class UserDescriptionTemplate { public final static String _descriptionTemplate = "descriptionTemplate"; private DescriptionTemplate descriptionTemplate; + public final static String _role = "role"; private UserDescriptionTemplateRole role; + public final static String _user = "user"; + private User user; + public final static String _createdAt = "createdAt"; private Instant createdAt; @@ -85,4 +89,12 @@ public class UserDescriptionTemplate { public void setHash(String hash) { this.hash = hash; } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionBuilder.java index 5f2fe8611..e7d5d83bc 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionBuilder.java @@ -3,9 +3,9 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.types.description.PropertyDefinitionEntity; -import eu.eudat.commons.types.descriptiontemplate.DefinitionEntity; import eu.eudat.convention.ConventionService; import eu.eudat.data.DescriptionEntity; +import eu.eudat.data.UserRoleEntity; import eu.eudat.model.*; import eu.eudat.model.builder.descriptionpropertiesdefinition.PropertyDefinitionBuilder; import eu.eudat.query.*; @@ -71,6 +71,9 @@ public class DescriptionBuilder extends BaseBuilder> descriptionTagsMap = this.collectDescriptionTags(descriptionTagsFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Description._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + FieldSet definitionPropertiesFields = fields.extractPrefixed(this.asPrefix(Description._properties)); List models = new ArrayList<>(); for (DescriptionEntity d : data) { @@ -79,7 +82,6 @@ public class DescriptionBuilder extends BaseBuilder collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + private Map collectDmpDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionReferenceBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionReferenceBuilder.java index 5c5b5d021..4fa6bc883 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionReferenceBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DescriptionReferenceBuilder.java @@ -65,22 +65,13 @@ public class DescriptionReferenceBuilder extends BaseBuilder(); - FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag)); - Map referenceItemsMap = this.collectTags(referenceFields, data); + FieldSet tagFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag)); + Map tagItemsMap = this.collectTags(tagFields, data); FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._description)); Map descriptionItemsMap = this.collectDescriptions(descriptionFields, data); @@ -69,7 +69,8 @@ public class DescriptionTagBuilder extends BaseBuilder { FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpUsers)); Map> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Dmp._creator)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet blueprintFields = fields.extractPrefixed(this.asPrefix(Dmp._blueprint)); + Map blueprintItemsMap = this.collectDmpBlueprints(blueprintFields, data); + for (DmpEntity d : data) { Dmp m = new Dmp(); if (fields.hasField(this.asIndexer(Dmp._id))) m.setId(d.getId()); @@ -76,11 +83,12 @@ public class DmpBuilder extends BaseBuilder { if (fields.hasField(this.asIndexer(Dmp._isActive))) m.setIsActive(d.getIsActive()); if (fields.hasField(this.asIndexer(Dmp._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); if (fields.hasField(this.asIndexer(Dmp._accessType))) m.setAccessType(d.getAccessType()); - if (fields.hasField(this.asIndexer(Dmp._blueprint))) m.setBlueprint(d.getBlueprint()); if (fields.hasField(this.asIndexer(Dmp._language))) m.setLanguage(d.getLanguage()); if (fields.hasField(this.asIndexer(Dmp._versionStatus))) m.setVersionStatus(d.getVersionStatus()); if (fields.hasField(this.asIndexer(Dmp._publicAfter))) m.setPublicAfter(d.getPublicAfter()); if (fields.hasField(this.asIndexer(Dmp._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatorId())) m.setCreator(userItemsMap.get(d.getCreatorId())); + if (!blueprintFields.isEmpty() && blueprintItemsMap != null && blueprintItemsMap.containsKey(d.getBlueprintId())) m.setBlueprint(blueprintItemsMap.get(d.getBlueprintId())); if (dmpReferencesMap != null && !dmpReferencesMap.isEmpty() && dmpReferencesMap.containsKey(d.getId())) m.setDmpReferences(dmpReferencesMap.get(d.getId())); if (dmpUsersMap != null && !dmpUsersMap.isEmpty() && dmpUsersMap.containsKey(d.getId())) m.setDmpUsers(dmpUsersMap.get(d.getId())); @@ -108,6 +116,66 @@ public class DmpBuilder extends BaseBuilder { return itemMap; } + + private Map collectDmpBlueprints(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpBlueprint.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DmpBlueprint._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpEntity::getBlueprintId).distinct().collect(Collectors.toList()), + x -> { + DmpBlueprint item = new DmpBlueprint(); + item.setId(x); + return item; + }, + DmpBlueprint::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DmpBlueprint._id); + DmpBlueprintQuery q = this.queryFactory.query(DmpBlueprintQuery.class).authorize(this.authorize).ids(data.stream().map(DmpEntity::getBlueprintId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DmpBlueprint::getId); + } + if (!fields.hasField(DmpBlueprint._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpEntity::getCreatorId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpEntity::getCreatorId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } private Map> collectDmpUsers(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpDescriptionTemplateBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpDescriptionTemplateBuilder.java index fdae05e29..067ccdbf3 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpDescriptionTemplateBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpDescriptionTemplateBuilder.java @@ -62,20 +62,13 @@ public class DmpDescriptionTemplateBuilder extends BaseBuilder models = new ArrayList<>(); for (DmpDescriptionTemplateEntity d : data) { DmpDescriptionTemplate m = new DmpDescriptionTemplate(); - if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._id))) - m.setId(d.getId()); - if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._sectionId))) - m.setSectionId(d.getSectionId()); - if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._createdAt))) - m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._updatedAt))) - m.setUpdatedAt(d.getUpdatedAt()); - if (!templateFields.isEmpty() && templateItemsMap != null && templateItemsMap.containsKey(d.getDescriptionTemplateId())) { - m.setDescriptionTemplate(templateItemsMap.get(d.getDescriptionTemplateId())); - } - if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) { - m.setDmp(dmpItemsMap.get(d.getDmpId())); - } + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._sectionId))) m.setSectionId(d.getSectionId()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (!templateFields.isEmpty() && templateItemsMap != null && templateItemsMap.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(templateItemsMap.get(d.getDescriptionTemplateId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); 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/DmpReferenceBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpReferenceBuilder.java index 67f1f44d0..0c8f70963 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpReferenceBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpReferenceBuilder.java @@ -4,6 +4,7 @@ import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; import eu.eudat.data.DmpReferenceEntity; import eu.eudat.model.Dmp; +import eu.eudat.model.DmpDescriptionTemplate; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; import eu.eudat.query.DmpQuery; @@ -64,20 +65,13 @@ public class DmpReferenceBuilder extends BaseBuilder models = new ArrayList<>(); for (DmpReferenceEntity d : data) { DmpReference m = new DmpReference(); - if (fields.hasField(this.asIndexer(DmpReference._id))) - m.setId(d.getId()); - if (fields.hasField(this.asIndexer(DmpReference._data))) - m.setData(d.getData()); - if (fields.hasField(this.asIndexer(DmpReference._createdAt))) - m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(DmpReference._updatedAt))) - m.setUpdatedAt(d.getUpdatedAt()); - if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) { - m.setReference(referenceItemsMap.get(d.getReferenceId())); - } - if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) { - m.setDmp(dmpItemsMap.get(d.getDmpId())); - } + if (fields.hasField(this.asIndexer(DmpReference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpReference._data))) m.setData(d.getData()); + if (fields.hasField(this.asIndexer(DmpReference._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpReference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpReference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) m.setReference(referenceItemsMap.get(d.getReferenceId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); 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/DmpUserBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpUserBuilder.java index 270d3b622..33fc490a0 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpUserBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/DmpUserBuilder.java @@ -2,12 +2,11 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; +import eu.eudat.data.DescriptionEntity; import eu.eudat.data.DmpUserEntity; -import eu.eudat.data.UserEntity; -import eu.eudat.model.Dmp; -import eu.eudat.model.DmpUser; -import eu.eudat.model.Reference; +import eu.eudat.model.*; import eu.eudat.query.DmpQuery; +import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -55,62 +54,57 @@ public class DmpUserBuilder extends BaseBuilder{ if (fields == null || data == null || fields.isEmpty()) return new ArrayList<>(); - FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpUser._user)); - Map userItemsMap = this.collectUsers(userFields, data); - FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpUser._dmp)); Map dmpItemsMap = this.collectDmps(dmpFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpUser._user)); + Map userItemsMap = this.collectUsers(userFields, data); + List models = new ArrayList<>(); for (DmpUserEntity d : data) { DmpUser m = new DmpUser(); - if (fields.hasField(this.asIndexer(DmpUser._id))) - m.setId(d.getId()); - if (fields.hasField(this.asIndexer(DmpUser._role))) - m.setRole(d.getRole()); - if (fields.hasField(this.asIndexer(DmpUser._createdAt))) - m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(DmpUser._updatedAt))) - m.setUpdatedAt(d.getUpdatedAt()); - if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUser())) { - m.setUser(userItemsMap.get(d.getUser())); - } - if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmp())) { - m.setDmp(dmpItemsMap.get(d.getDmp())); - } + if (fields.hasField(this.asIndexer(DmpUser._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpUser._role))) m.setRole(d.getRole()); + if (fields.hasField(this.asIndexer(DmpUser._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpUser._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpReference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmp())) m.setDmp(dmpItemsMap.get(d.getDmp())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); return models; } - //TODO: Hookup user info when refactored - private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", UserEntity.class.getSimpleName()); + this.logger.debug("checking related - {}", User.class.getSimpleName()); - Map itemMap; - if (!fields.hasOtherField(this.asIndexer("id"))) { + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { itemMap = this.asEmpty( - data.stream().map(DmpUserEntity::getUser).distinct().collect(Collectors.toList()), + data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList()), x -> { - UserEntity item = new UserEntity(); + User item = new User(); item.setId(x); return item; }, - UserEntity::getId); + User::getId); } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure("id"); -// ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); -// itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); } - if (!fields.hasField(Reference._id)) { -// itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); } -// return itemMap; - return new HashMap<>(); + return itemMap; } private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicDmpUserBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicDmpUserBuilder.java index 971ff2c48..2f6029118 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicDmpUserBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicDmpUserBuilder.java @@ -3,10 +3,13 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; import eu.eudat.data.DmpUserEntity; +import eu.eudat.data.UserRoleEntity; import eu.eudat.model.PublicDmp; import eu.eudat.model.PublicDmpUser; import eu.eudat.model.PublicUser; +import eu.eudat.model.User; import eu.eudat.query.DmpQuery; +import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -55,7 +58,7 @@ public class PublicDmpUserBuilder extends BaseBuilder(); FieldSet userFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._user)); - Map userItemsMap = new HashMap<>(); //TODO + Map userItemsMap = this.collectUsers(userFields, data); FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._dmp)); Map dmpItemsMap = this.collectDmps(dmpFields, data); @@ -65,7 +68,7 @@ public class PublicDmpUserBuilder extends BaseBuilder collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + PublicUser item = new PublicUser(); + item.setId(x); + return item; + }, + PublicUser::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicUserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicUser::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicUserBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicUserBuilder.java index cbfa0f136..afabc7313 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicUserBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicUserBuilder.java @@ -1,18 +1,11 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.JsonHandlingService; -import eu.eudat.commons.types.user.AdditionalInfoEntity; import eu.eudat.convention.ConventionService; import eu.eudat.data.UserEntity; -import eu.eudat.model.*; -import eu.eudat.query.UserContactInfoQuery; -import eu.eudat.query.UserCredentialQuery; -import eu.eudat.query.UserRoleQuery; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; +import eu.eudat.model.PublicUser; +import eu.eudat.model.User; 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; @@ -23,68 +16,37 @@ 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) -public class UserBuilder extends BaseBuilder { - - private final QueryFactory queryFactory; - - private final BuilderFactory builderFactory; - private final JsonHandlingService jsonHandlingService; +public class PublicUserBuilder extends BaseBuilder { private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); @Autowired - public UserBuilder(ConventionService conventionService, - QueryFactory queryFactory, - BuilderFactory builderFactory, JsonHandlingService jsonHandlingService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserBuilder.class))); - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - this.jsonHandlingService = jsonHandlingService; + public PublicUserBuilder(ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicUserBuilder.class))); } - public UserBuilder authorize(EnumSet values) { + public PublicUserBuilder authorize(EnumSet values) { this.authorize = values; return this; } @Override - public List build(FieldSet fields, List data) throws MyApplicationException { + 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<>(); + List models = new ArrayList<>(); - FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(User._contacts)); - Map> contactsMap = this.collectUserContactInfos(contactsFields, data); - - FieldSet rolesFields = fields.extractPrefixed(this.asPrefix(User._roles)); - Map> rolesMap = this.collectUserRoles(rolesFields, data); - - FieldSet credentialsFields = fields.extractPrefixed(this.asPrefix(User._credentials)); - Map> credentialsMap = this.collectUserCredentials(credentialsFields, data); - - FieldSet additionalInfoFields = fields.extractPrefixed(this.asPrefix(User._additionalInfo)); for (UserEntity d : data) { - User m = new User(); + PublicUser m = new PublicUser(); if (fields.hasField(this.asIndexer(User._id))) m.setId(d.getId()); if (fields.hasField(this.asIndexer(User._name))) m.setName(d.getName()); - if (fields.hasField(this.asIndexer(User._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(User._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(User._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(User._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (contactsMap != null && !contactsFields.isEmpty() && contactsMap.containsKey(d.getId())) m.setContacts(contactsMap.get(d.getId())); - if (rolesMap != null && !rolesFields.isEmpty() && rolesMap.containsKey(d.getId())) m.setRoles(rolesMap.get(d.getId())); - if (credentialsMap != null && !credentialsFields.isEmpty() && credentialsMap.containsKey(d.getId())) m.setCredentials(credentialsMap.get(d.getId())); - if (!additionalInfoFields.isEmpty() && d.getAdditionalInfo() != null){ - AdditionalInfoEntity definition = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, d.getAdditionalInfo()); - m.setAdditionalInfo(this.builderFactory.builder(UserAdditionalInfoBuilder.class).authorize(this.authorize).build(additionalInfoFields, definition)); - } models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); @@ -92,58 +54,4 @@ public class UserBuilder extends BaseBuilder { return models; } - private Map> collectUserContactInfos(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName()); - - Map> itemMap; - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserContactInfo._user, User._id)); - UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserContactInfoBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); - - if (!fields.hasField(this.asIndexer(UserContactInfo._user, User._id))) { - itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { - x.getUser().setId(null); - }); - } - - return itemMap; - } - - private Map> collectUserRoles(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", UserRole.class.getSimpleName()); - - Map> itemMap; - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserRole._user, User._id)); - UserRoleQuery query = this.queryFactory.query(UserRoleQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserRoleBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); - - if (!fields.hasField(this.asIndexer(UserRole._user, User._id))) { - itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { - x.getUser().setId(null); - }); - } - - return itemMap; - } - - private Map> collectUserCredentials(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", UserCredential.class.getSimpleName()); - - Map> itemMap; - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserCredential._user, User._id)); - UserCredentialQuery query = this.queryFactory.query(UserCredentialQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserCredentialBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); - - if (!fields.hasField(this.asIndexer(UserCredential._user, User._id))) { - itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { - x.getUser().setId(null); - }); - } - - return itemMap; - } - } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java index d329512ce..2174e6ed3 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java @@ -4,11 +4,14 @@ import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.types.reference.DefinitionEntity; import eu.eudat.convention.ConventionService; +import eu.eudat.data.DescriptionEntity; import eu.eudat.data.ReferenceEntity; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; +import eu.eudat.model.User; import eu.eudat.model.builder.referencedefinition.DefinitionBuilder; import eu.eudat.query.DmpReferenceQuery; +import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -62,6 +65,9 @@ public class ReferenceBuilder extends BaseBuilder{ FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Reference._dmpReferences)); Map> dmpReferenceMap = this.collectDmpReferences(dmpReferencesFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Reference._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + List models = new ArrayList<>(); for (ReferenceEntity d : data) { Reference m = new Reference(); @@ -70,6 +76,7 @@ public class ReferenceBuilder extends BaseBuilder{ if (fields.hasField(this.asIndexer(Reference._createdAt))) m.setCreatedAt(d.getCreatedAt()); if (fields.hasField(this.asIndexer(Reference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); if (fields.hasField(this.asIndexer(Reference._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(Reference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); if (!definitionFields.isEmpty() && d.getDefinition() != null){ DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); m.setDefinition(this.builderFactory.builder(DefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); @@ -80,16 +87,44 @@ public class ReferenceBuilder extends BaseBuilder{ if (fields.hasField(this.asIndexer(Reference._source))) m.setSource(d.getSource()); if (fields.hasField(this.asIndexer(Reference._sourceType))) m.setSourceType(d.getSourceType()); if (fields.hasField(this.asIndexer(Reference._type))) m.setType(d.getType()); -// if (!userInfoFields.isEmpty() && d.getCreatedBy() != null){ -// //ToDo -// } - if (!dmpReferenceMap.isEmpty() && dmpReferenceMap != null && dmpReferenceMap.containsKey(d.getId())) m.setDmpReferences(dmpReferenceMap.get(d.getId())); + if (dmpReferenceMap != null && !dmpReferenceMap.isEmpty() && dmpReferenceMap.containsKey(d.getId())) m.setDmpReferences(dmpReferenceMap.get(d.getId())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById())); models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); return models; } + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(ReferenceEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(ReferenceEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + private Map> collectDmpReferences(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/SupportiveMaterialBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/SupportiveMaterialBuilder.java index c465cd702..b4c00042b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/SupportiveMaterialBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/SupportiveMaterialBuilder.java @@ -4,10 +4,7 @@ import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; import eu.eudat.data.DmpReferenceEntity; import eu.eudat.data.SupportiveMaterialEntity; -import eu.eudat.model.Dmp; -import eu.eudat.model.DmpReference; -import eu.eudat.model.Reference; -import eu.eudat.model.SupportiveMaterial; +import eu.eudat.model.*; import eu.eudat.query.DmpQuery; import eu.eudat.query.ReferenceQuery; import gr.cite.tools.data.builder.BuilderFactory; @@ -65,6 +62,7 @@ public class SupportiveMaterialBuilder extends BaseBuilder{ + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); @Autowired public TagBuilder( - ConventionService conventionService) { + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { super(conventionService, new LoggerService(LoggerFactory.getLogger(TagBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; } public TagBuilder authorize(EnumSet values) { @@ -40,6 +51,9 @@ public class TagBuilder extends BaseBuilder{ if (fields == null || data == null || fields.isEmpty()) return new ArrayList<>(); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Tag._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + List models = new ArrayList<>(); for (TagEntity d : data) { Tag m = new Tag(); @@ -48,10 +62,40 @@ public class TagBuilder extends BaseBuilder{ if (fields.hasField(this.asIndexer(Tag._createdAt))) m.setCreatedAt(d.getCreatedAt()); if (fields.hasField(this.asIndexer(Tag._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); if (fields.hasField(this.asIndexer(Tag._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(Tag._createdBy))) m.setCreatedBy(d.getCreatedBy()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById())); models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); return models; } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(TagEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(TagEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserAdditionalInfoBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserAdditionalInfoBuilder.java index c32a85c0b..b5d0cffad 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserAdditionalInfoBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserAdditionalInfoBuilder.java @@ -1,11 +1,13 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.commons.types.user.AdditionalInfoEntity; import eu.eudat.convention.ConventionService; -import eu.eudat.data.UserCredentialEntity; -import eu.eudat.model.User; -import eu.eudat.model.UserCredential; -import eu.eudat.query.UserQuery; +import eu.eudat.data.DescriptionReferenceEntity; +import eu.eudat.model.DescriptionReference; +import eu.eudat.model.Reference; +import eu.eudat.model.UserAdditionalInfo; +import eu.eudat.query.ReferenceQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -24,46 +26,46 @@ import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserCredentialBuilder extends BaseBuilder { +public class UserAdditionalInfoBuilder extends BaseBuilder { private final BuilderFactory builderFactory; private final QueryFactory queryFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); @Autowired - public UserCredentialBuilder( - ConventionService conventionService, - BuilderFactory builderFactory, QueryFactory queryFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserCredentialBuilder.class))); + public UserAdditionalInfoBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserAdditionalInfoBuilder.class))); this.builderFactory = builderFactory; this.queryFactory = queryFactory; } - public UserCredentialBuilder authorize(EnumSet values) { + public UserAdditionalInfoBuilder authorize(EnumSet values) { this.authorize = values; return this; } @Override - public List build(FieldSet fields, List data) throws MyApplicationException { + 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<>(); - FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserCredential._user)); - Map userItemsMap = this.collectUsers(userFields, data); + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._reference)); + Map referenceItemsMap = this.collectReferences(referenceFields, data); - List models = new ArrayList<>(); + List models = new ArrayList<>(); - for (UserCredentialEntity d : data) { - UserCredential m = new UserCredential(); - if (fields.hasField(this.asIndexer(UserCredential._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(UserCredential._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(UserCredential._externalId))) m.setExternalId(d.getExternalId()); - if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + for (AdditionalInfoEntity d : data) { + UserAdditionalInfo m = new UserAdditionalInfo(); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._language))) m.setLanguage(d.getLanguage()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._culture))) m.setCulture(d.getCulture()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._avatarUrl))) m.setAvatarUrl(d.getAvatarUrl()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._timezone))) m.setTimezone(d.getTimezone()); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getOrganizationId())) m.setOrganization(referenceItemsMap.get(d.getOrganizationId())); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._roleOrganization))) m.setRoleOrganization(d.getRoleOrganization()); models.add(m); } @@ -73,27 +75,29 @@ public class UserCredentialBuilder extends BaseBuilder collectUsers(FieldSet fields, List data) throws MyApplicationException { + + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", User.class.getSimpleName()); + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(User._id))) { + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { itemMap = this.asEmpty( - data.stream().map(UserCredentialEntity::getUserId).distinct().collect(Collectors.toList()), + data.stream().map(AdditionalInfoEntity::getOrganizationId).filter(Objects::nonNull).distinct().collect(Collectors.toList()), x -> { - User item = new User(); + Reference item = new Reference(); item.setId(x); return item; }, - User::getId); + Reference::getId); } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); - UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserCredentialEntity::getUserId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(AdditionalInfoEntity::getOrganizationId).filter(Objects::nonNull).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); } - if (!fields.hasField(User._id)) { + if (!fields.hasField(Reference._id)) { itemMap.forEach((id, item) -> { if (item != null) item.setId(null); @@ -102,5 +106,4 @@ public class UserCredentialBuilder extends BaseBuilder { +public class UserBuilder extends BaseBuilder { private final QueryFactory queryFactory; private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); @Autowired - public DmpBuilder(ConventionService conventionService, - QueryFactory queryFactory, - BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBuilder.class))); + public UserBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserBuilder.class))); this.queryFactory = queryFactory; this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; } - public DmpBuilder authorize(EnumSet values) { + public UserBuilder authorize(EnumSet values) { this.authorize = values; return this; } @Override - public List build(FieldSet fields, List data) throws MyApplicationException { + 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<>(); + List models = new ArrayList<>(); - FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpReferences)); - Map> dmpReferencesMap = this.collectDmpReferences(dmpReferencesFields, data); + FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(User._contacts)); + Map> contactsMap = this.collectUserContactInfos(contactsFields, data); - FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpUsers)); - Map> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data); + FieldSet rolesFields = fields.extractPrefixed(this.asPrefix(User._roles)); + Map> rolesMap = this.collectUserRoles(rolesFields, data); - for (DmpEntity d : data) { - Dmp m = new Dmp(); - if (fields.hasField(this.asIndexer(Dmp._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(Dmp._label))) m.setLabel(d.getLabel()); - if (fields.hasField(this.asIndexer(Dmp._version))) m.setVersion(d.getVersion()); - if (fields.hasField(this.asIndexer(Dmp._status))) m.setStatus(d.getStatus()); - if (fields.hasField(this.asIndexer(Dmp._properties))) m.setProperties(d.getProperties()); - if (fields.hasField(this.asIndexer(Dmp._groupId))) m.setGroupId(d.getGroupId()); - if (fields.hasField(this.asIndexer(Dmp._description))) m.setDescription(d.getDescription()); - if (fields.hasField(this.asIndexer(Dmp._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(Dmp._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(Dmp._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(Dmp._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); - if (fields.hasField(this.asIndexer(Dmp._accessType))) m.setAccessType(d.getAccessType()); - if (fields.hasField(this.asIndexer(Dmp._blueprint))) m.setBlueprint(d.getBlueprint()); - if (fields.hasField(this.asIndexer(Dmp._language))) m.setLanguage(d.getLanguage()); - if (fields.hasField(this.asIndexer(Dmp._versionStatus))) m.setVersionStatus(d.getVersionStatus()); - if (fields.hasField(this.asIndexer(Dmp._publicAfter))) m.setPublicAfter(d.getPublicAfter()); - if (fields.hasField(this.asIndexer(Dmp._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (dmpReferencesMap != null && !dmpReferencesMap.isEmpty() && dmpReferencesMap.containsKey(d.getId())) m.setDmpReferences(dmpReferencesMap.get(d.getId())); - if (dmpUsersMap != null && !dmpUsersMap.isEmpty() && dmpUsersMap.containsKey(d.getId())) m.setDmpUsers(dmpUsersMap.get(d.getId())); + FieldSet credentialsFields = fields.extractPrefixed(this.asPrefix(User._credentials)); + Map> credentialsMap = this.collectUserCredentials(credentialsFields, data); + FieldSet additionalInfoFields = fields.extractPrefixed(this.asPrefix(User._additionalInfo)); + for (UserEntity d : data) { + User m = new User(); + if (fields.hasField(this.asIndexer(User._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(User._name))) m.setName(d.getName()); + if (fields.hasField(this.asIndexer(User._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(User._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(User._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(User._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (contactsMap != null && !contactsFields.isEmpty() && contactsMap.containsKey(d.getId())) m.setContacts(contactsMap.get(d.getId())); + if (rolesMap != null && !rolesFields.isEmpty() && rolesMap.containsKey(d.getId())) m.setRoles(rolesMap.get(d.getId())); + if (credentialsMap != null && !credentialsFields.isEmpty() && credentialsMap.containsKey(d.getId())) m.setCredentials(credentialsMap.get(d.getId())); + if (!additionalInfoFields.isEmpty() && d.getAdditionalInfo() != null){ + AdditionalInfoEntity definition = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, d.getAdditionalInfo()); + m.setAdditionalInfo(this.builderFactory.builder(UserAdditionalInfoBuilder.class).authorize(this.authorize).build(additionalInfoFields, definition)); + } models.add(m); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); @@ -91,37 +92,54 @@ public class DmpBuilder extends BaseBuilder { return models; } - private Map> collectDmpReferences(FieldSet fields, List data) throws MyApplicationException { + private Map> collectUserContactInfos(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName()); - Map> itemMap; - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpReference._dmp, Dmp._id)); - DmpReferenceQuery query = this.queryFactory.query(DmpReferenceQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(DmpReferenceBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserContactInfo._user, User._id)); + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserContactInfoBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); - if (!fields.hasField(this.asIndexer(DmpReference._dmp, Dmp._id))) { - itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { - x.getDmp().setId(null); + if (!fields.hasField(this.asIndexer(UserContactInfo._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); }); } return itemMap; } - private Map> collectDmpUsers(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) - return null; - this.logger.debug("checking related - {}", DmpUser.class.getSimpleName()); + private Map> collectUserRoles(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserRole.class.getSimpleName()); - Map> itemMap; - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpUser._dmp, Dmp._id)); - DmpUserQuery query = this.queryFactory.query(DmpUserQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(DmpUserBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserRole._user, User._id)); + UserRoleQuery query = this.queryFactory.query(UserRoleQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserRoleBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); - if (!fields.hasField(this.asIndexer(DmpUser._dmp, Dmp._id))) { - itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { - x.getDmp().setId(null); + if (!fields.hasField(this.asIndexer(UserRole._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + + private Map> collectUserCredentials(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserCredential.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserCredential._user, User._id)); + UserCredentialQuery query = this.queryFactory.query(UserCredentialQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserCredentialBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserCredential._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); }); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserContactInfoBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserContactInfoBuilder.java index 5b36794a2..deff56581 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserContactInfoBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserContactInfoBuilder.java @@ -2,12 +2,13 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; -import eu.eudat.data.DescriptionTagEntity; +import eu.eudat.data.UserContactInfoEntity; import eu.eudat.model.Description; -import eu.eudat.model.DescriptionTag; -import eu.eudat.model.Tag; +import eu.eudat.model.User; +import eu.eudat.model.UserContactInfo; +import eu.eudat.model.User; import eu.eudat.query.DescriptionQuery; -import eu.eudat.query.TagQuery; +import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -26,7 +27,7 @@ import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class DescriptionTagBuilder extends BaseBuilder { +public class UserContactInfoBuilder extends BaseBuilder { private final BuilderFactory builderFactory; @@ -35,42 +36,39 @@ public class DescriptionTagBuilder extends BaseBuilder authorize = EnumSet.of(AuthorizationFlags.None); @Autowired - public DescriptionTagBuilder( + public UserContactInfoBuilder( ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTagBuilder.class))); + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserContactInfoBuilder.class))); this.builderFactory = builderFactory; this.queryFactory = queryFactory; } - public DescriptionTagBuilder authorize(EnumSet values) { + public UserContactInfoBuilder authorize(EnumSet values) { this.authorize = values; return this; } @Override - public List build(FieldSet fields, List data) throws MyApplicationException { + 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<>(); - FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag)); - Map referenceItemsMap = this.collectTags(referenceFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserContactInfo._user)); + Map userItemsMap = this.collectUsers(userFields, data); - FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._description)); - Map descriptionItemsMap = this.collectDescriptions(descriptionFields, data); + List models = new ArrayList<>(); - List models = new ArrayList<>(); - - for (DescriptionTagEntity d : data) { - DescriptionTag m = new DescriptionTag(); - if (fields.hasField(this.asIndexer(DescriptionTag._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(DescriptionTag._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(DescriptionTag._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(DescriptionTag._isActive))) m.setIsActive(d.getIsActive()); - if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getTagId())) m.setTag(referenceItemsMap.get(d.getTagId())); - if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) m.setDescription(descriptionItemsMap.get(d.getDescriptionId())); + for (UserContactInfoEntity d : data) { + UserContactInfo m = new UserContactInfo(); + if (fields.hasField(this.asIndexer(UserContactInfo._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserContactInfo._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserContactInfo._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(UserContactInfo._value))) m.setValue(d.getValue()); + if (fields.hasField(this.asIndexer(UserContactInfo._type))) m.setType(d.getType()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); models.add(m); } @@ -80,57 +78,27 @@ public class DescriptionTagBuilder extends BaseBuilder collectDescriptions(FieldSet fields, List data) throws MyApplicationException { + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", Description.class.getSimpleName()); + this.logger.debug("checking related - {}", User.class.getSimpleName()); - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(Tag._id))) { + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { itemMap = this.asEmpty( - data.stream().map(DescriptionTagEntity::getDescriptionId).distinct().collect(Collectors.toList()), + data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList()), x -> { - Description item = new Description(); + User item = new User(); item.setId(x); return item; }, - Description::getId); + User::getId); } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tag._id); - DescriptionQuery q = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionTagEntity::getDescriptionId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(DescriptionBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Description::getId); + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); } - if (!fields.hasField(Description._id)) { - itemMap.forEach((id, item) -> { - if (item != null) - item.setId(null); - }); - } - - return itemMap; - } - - private Map collectTags(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) - return null; - this.logger.debug("checking related - {}", Tag.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(Tag._id))) { - itemMap = this.asEmpty( - data.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList()), - x -> { - Tag item = new Tag(); - item.setId(x); - return item; - }, - Tag::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tag._id); - TagQuery q = this.queryFactory.query(TagQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(TagBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Tag::getId); - } - if (!fields.hasField(Tag._id)) { + if (!fields.hasField(User._id)) { itemMap.forEach((id, item) -> { if (item != null) item.setId(null); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserCredentialBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserCredentialBuilder.java index b6aab0515..c32a85c0b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserCredentialBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserCredentialBuilder.java @@ -5,7 +5,6 @@ import eu.eudat.convention.ConventionService; import eu.eudat.data.UserCredentialEntity; import eu.eudat.model.User; import eu.eudat.model.UserCredential; -import eu.eudat.model.UserCredential; import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserDescriptionTemplateBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserDescriptionTemplateBuilder.java index c9357c4bb..8100cdef4 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserDescriptionTemplateBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserDescriptionTemplateBuilder.java @@ -4,9 +4,12 @@ import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.XmlHandlingService; import eu.eudat.convention.ConventionService; import eu.eudat.data.UserDescriptionTemplateEntity; +import eu.eudat.model.Description; import eu.eudat.model.DescriptionTemplate; +import eu.eudat.model.User; import eu.eudat.model.UserDescriptionTemplate; import eu.eudat.query.DescriptionTemplateQuery; +import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -56,6 +59,8 @@ public class UserDescriptionTemplateBuilder extends BaseBuilder descriptionTemplateMap = this.collectDescriptionTemplates(descriptionTemplateFields, data); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Description._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); List models = new ArrayList<>(); for (UserDescriptionTemplateEntity d : data) { @@ -66,13 +71,44 @@ public class UserDescriptionTemplateBuilder extends BaseBuilder collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(UserDescriptionTemplateEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserDescriptionTemplateEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + private Map collectDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); @@ -80,7 +116,7 @@ public class UserDescriptionTemplateBuilder extends BaseBuilder itemMap = null; if (!fields.hasOtherField(this.asIndexer(DescriptionTemplate._id))) { itemMap = this.asEmpty( - data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplate).distinct().collect(Collectors.toList()), + data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList()), x -> { DescriptionTemplate item = new DescriptionTemplate(); item.setId(x); @@ -89,7 +125,7 @@ public class UserDescriptionTemplateBuilder extends BaseBuilder x.getId()); } else { FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._id); - DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).ids(data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplate).distinct().collect(Collectors.toList())); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).ids(data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).asForeignKey(q, clone, DescriptionTemplate::getId); } if (!fields.hasField(DescriptionTemplate._id)) { diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserRoleBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserRoleBuilder.java index deff56581..644a84fdd 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserRoleBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/UserRoleBuilder.java @@ -2,12 +2,9 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.convention.ConventionService; -import eu.eudat.data.UserContactInfoEntity; -import eu.eudat.model.Description; +import eu.eudat.data.UserRoleEntity; import eu.eudat.model.User; -import eu.eudat.model.UserContactInfo; -import eu.eudat.model.User; -import eu.eudat.query.DescriptionQuery; +import eu.eudat.model.UserRole; import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; @@ -27,7 +24,7 @@ import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserContactInfoBuilder extends BaseBuilder { +public class UserRoleBuilder extends BaseBuilder { private final BuilderFactory builderFactory; @@ -36,38 +33,36 @@ public class UserContactInfoBuilder extends BaseBuilder authorize = EnumSet.of(AuthorizationFlags.None); @Autowired - public UserContactInfoBuilder( + public UserRoleBuilder( ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserContactInfoBuilder.class))); + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserRoleBuilder.class))); this.builderFactory = builderFactory; this.queryFactory = queryFactory; } - public UserContactInfoBuilder authorize(EnumSet values) { + public UserRoleBuilder authorize(EnumSet values) { this.authorize = values; return this; } @Override - public List build(FieldSet fields, List data) throws MyApplicationException { + 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<>(); - FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserContactInfo._user)); + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserRole._user)); Map userItemsMap = this.collectUsers(userFields, data); - List models = new ArrayList<>(); + List models = new ArrayList<>(); - for (UserContactInfoEntity d : data) { - UserContactInfo m = new UserContactInfo(); - if (fields.hasField(this.asIndexer(UserContactInfo._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(UserContactInfo._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(UserContactInfo._ordinal))) m.setOrdinal(d.getOrdinal()); - if (fields.hasField(this.asIndexer(UserContactInfo._value))) m.setValue(d.getValue()); - if (fields.hasField(this.asIndexer(UserContactInfo._type))) m.setType(d.getType()); + for (UserRoleEntity d : data) { + UserRole m = new UserRole(); + if (fields.hasField(this.asIndexer(UserRole._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserRole._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserRole._role))) m.setRole(d.getRole()); if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); models.add(m); @@ -78,7 +73,7 @@ public class UserContactInfoBuilder extends BaseBuilder collectUsers(FieldSet fields, List data) throws MyApplicationException { + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { if (fields.isEmpty() || data.isEmpty()) return null; this.logger.debug("checking related - {}", User.class.getSimpleName()); @@ -86,7 +81,7 @@ public class UserContactInfoBuilder extends BaseBuilder itemMap; if (!fields.hasOtherField(this.asIndexer(User._id))) { itemMap = this.asEmpty( - data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList()), + data.stream().map(UserRoleEntity::getUserId).distinct().collect(Collectors.toList()), x -> { User item = new User(); item.setId(x); @@ -95,7 +90,7 @@ public class UserContactInfoBuilder extends BaseBuilder 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(UserContactInfoQuery.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; + + for (UserContactInfoEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); + } + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserCredentialDeleter.java b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserCredentialDeleter.java index ff11615d7..ac88df968 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserCredentialDeleter.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserCredentialDeleter.java @@ -1,7 +1,7 @@ package eu.eudat.model.deleter; -import eu.eudat.data.UserContactInfoEntity; -import eu.eudat.query.UserContactInfoQuery; +import eu.eudat.data.UserCredentialEntity; +import eu.eudat.query.UserCredentialQuery; import gr.cite.tools.data.deleter.Deleter; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.logging.LoggerService; @@ -20,16 +20,16 @@ import java.util.UUID; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserContactInfoDeleter implements Deleter { +public class UserCredentialDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoDeleter.class)); + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialDeleter.class)); private final EntityManager entityManager; protected final QueryFactory queryFactory; @Autowired - public UserContactInfoDeleter( + public UserCredentialDeleter( EntityManager entityManager, QueryFactory queryFactory ) { @@ -39,12 +39,12 @@ public class UserContactInfoDeleter implements Deleter { 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(UserContactInfoQuery.class).ids(ids).collect(); + List data = this.queryFactory.query(UserCredentialQuery.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 { + 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"); @@ -52,12 +52,12 @@ public class UserContactInfoDeleter implements Deleter { logger.trace("changes saved"); } - public void delete(List data) throws InvalidApplicationException { + 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; - for (UserContactInfoEntity item : data) { + for (UserCredentialEntity item : data) { logger.trace("deleting item {}", item.getId()); logger.trace("deleting item"); this.entityManager.remove(item); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserDeleter.java b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserDeleter.java index 55aa92e01..158b48dbc 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserDeleter.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserDeleter.java @@ -1,10 +1,8 @@ package eu.eudat.model.deleter; import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.DescriptionTagEntity; -import eu.eudat.data.TagEntity; -import eu.eudat.query.DescriptionTagQuery; -import eu.eudat.query.TagQuery; +import eu.eudat.data.*; +import eu.eudat.query.*; import gr.cite.tools.data.deleter.Deleter; import gr.cite.tools.data.deleter.DeleterFactory; import gr.cite.tools.data.query.QueryFactory; @@ -26,9 +24,9 @@ import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TagDeleter implements Deleter { +public class UserDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TagDeleter.class)); + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDeleter.class)); private final EntityManager entityManager; protected final QueryFactory queryFactory; @@ -36,7 +34,7 @@ public class TagDeleter implements Deleter { protected final DeleterFactory deleterFactory; @Autowired - public TagDeleter( + public UserDeleter( EntityManager entityManager, QueryFactory queryFactory, DeleterFactory deleterFactory @@ -48,12 +46,12 @@ public class TagDeleter implements Deleter { 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(TagQuery.class).ids(ids).collect(); + List data = this.queryFactory.query(UserQuery.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 { + 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"); @@ -61,20 +59,38 @@ public class TagDeleter implements Deleter { logger.trace("changes saved"); } - public void delete(List data) throws InvalidApplicationException { + 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; - List ids = data.stream().map(TagEntity::getId).distinct().collect(Collectors.toList()); + List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); { - logger.debug("checking related - {}", DescriptionTagEntity.class.getSimpleName()); - List items = this.queryFactory.query(DescriptionTagQuery.class).tagIds(ids).collect(); - DescriptionTagDeleter deleter = this.deleterFactory.deleter(DescriptionTagDeleter.class); + logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserRoleQuery.class).userIds(ids).collect(); + UserRoleDeleter deleter = this.deleterFactory.deleter(UserRoleDeleter.class); deleter.delete(items); } + { + logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); + UserCredentialDeleter deleter = this.deleterFactory.deleter(UserCredentialDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", UserContactInfoEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserContactInfoQuery.class).userIds(ids).collect(); + UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.class); + deleter.delete(items); + } +// { +// logger.debug("checking related - {}", DmpUserEntity.class.getSimpleName()); +// List items = this.queryFactory.query(DmpUserQuery.class).userIds(ids).collect(); +// DmpUserDeleter deleter = this.deleterFactory.deleter(DmpUserDeleter.class); +// deleter.delete(items); +// } Instant now = Instant.now(); - for (TagEntity item : data) { + for (UserEntity item : data) { logger.trace("deleting item {}", item.getId()); item.setIsActive(IsActive.Inactive); item.setUpdatedAt(now); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserRoleDeleter.java b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserRoleDeleter.java index f3d48b989..3738e8771 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserRoleDeleter.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/deleter/UserRoleDeleter.java @@ -1,11 +1,6 @@ package eu.eudat.model.deleter; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.DescriptionUserEntity; -import eu.eudat.data.UserEntity; import eu.eudat.data.UserRoleEntity; -import eu.eudat.query.DescriptionUserQuery; -import eu.eudat.query.UserQuery; import eu.eudat.query.UserRoleQuery; import gr.cite.tools.data.deleter.Deleter; import gr.cite.tools.data.deleter.DeleterFactory; @@ -28,34 +23,31 @@ import java.util.stream.Collectors; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserDeleter implements Deleter { +public class UserRoleDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDeleter.class)); + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserRoleDeleter.class)); private final EntityManager entityManager; protected final QueryFactory queryFactory; - protected final DeleterFactory deleterFactory; @Autowired - public UserDeleter( + public UserRoleDeleter( EntityManager entityManager, - QueryFactory queryFactory, - DeleterFactory deleterFactory + QueryFactory queryFactory ) { 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(UserQuery.class).ids(ids).collect(); + List data = this.queryFactory.query(UserRoleQuery.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 { + 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"); @@ -63,26 +55,16 @@ public class UserDeleter implements Deleter { logger.trace("changes saved"); } - public void delete(List data) throws InvalidApplicationException { + 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; - List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); - { - logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName()); - List items = this.queryFactory.query(UserRoleQuery.class).userIds(ids).collect(); - UserRoleDeleter deleter = this.deleterFactory.deleter(UserRoleDeleter.class); - deleter.delete(items); - } - Instant now = Instant.now(); - for (UserEntity item : data) { + for (UserRoleEntity 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"); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/deposit/DmpEntityDepositMapper.java b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/deposit/DmpEntityDepositMapper.java index 19247f35e..79a93eb8d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/deposit/DmpEntityDepositMapper.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/deposit/DmpEntityDepositMapper.java @@ -7,10 +7,9 @@ import eu.eudat.commons.types.xml.XmlBuilder; import eu.eudat.data.*; import eu.eudat.data.UserEntity; import eu.eudat.depositinterface.models.*; -import eu.eudat.query.DescriptionQuery; -import eu.eudat.query.DescriptionTemplateQuery; -import eu.eudat.query.DmpDescriptionTemplateQuery; -import eu.eudat.query.DmpUserQuery; +import eu.eudat.model.UserContactInfo; +import eu.eudat.query.*; +import gr.cite.tools.data.query.Ordering; import gr.cite.tools.data.query.QueryFactory; import jakarta.persistence.EntityManager; import org.slf4j.Logger; @@ -148,9 +147,11 @@ public class DmpEntityDepositMapper { private UserDMPDepositModel toUserDeposit(DmpUserEntity user) { UserDMPDepositModel userDMPDepositModel = new UserDMPDepositModel(); userDMPDepositModel.setUser(new UserInfoDepositModel()); - UserEntity userInfo = this.entityManager.find(UserEntity.class, user.getUser()); + UserEntity userInfo = this.entityManager.find(UserEntity.class, user.getUserId()); userDMPDepositModel.getUser().setName(userInfo.getName()); -// userDMPDepositModel.getUser().setEmail(userInfo.getEmail()); //TODO: GetEmail + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(userInfo.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + userDMPDepositModel.getUser().setEmail(query.first().getValue()); userDMPDepositModel.setRole(user.getRole().getValue().intValue()); return userDMPDepositModel; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserAdditionalInfoPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserAdditionalInfoPersist.java index 246057a16..20744529e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserAdditionalInfoPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserAdditionalInfoPersist.java @@ -1,28 +1,31 @@ -package eu.eudat.model; +package eu.eudat.model.persist; -import eu.eudat.commons.enums.ContactInfoType; +import eu.eudat.commons.validation.ValidId; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; -import java.time.Instant; import java.util.UUID; -public class UserAdditionalInfo { +public class UserAdditionalInfoPersist { + private String avatarUrl; - public static final String _avatarUrl = "avatarUrl"; - + + @NotNull(message = "{validation.empty}") + @NotEmpty(message = "{validation.empty}") private String timezone; - public static final String _timezone = "timezone"; - + + @NotNull(message = "{validation.empty}") + @NotEmpty(message = "{validation.empty}") private String culture; - public static final String _culture = "culture"; - + + @NotNull(message = "{validation.empty}") + @NotEmpty(message = "{validation.empty}") private String language; - public static final String _language = "language"; private String roleOrganization; - public static final String _roleOrganization = "roleOrganization"; - private String organization; - public static final String _organization = "organization"; + @ValidId(message = "{validation.invalidid}") + private UUID organizationId; public String getAvatarUrl() { return avatarUrl; @@ -64,11 +67,11 @@ public class UserAdditionalInfo { this.roleOrganization = roleOrganization; } - public String getOrganization() { - return organization; + public UUID getOrganizationId() { + return organizationId; } - public void setOrganization(String organization) { - this.organization = organization; + public void setOrganizationId(UUID organizationId) { + this.organizationId = organizationId; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserPersist.java index 52aabbac7..7f37c9865 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserPersist.java @@ -2,32 +2,43 @@ package eu.eudat.model.persist; import eu.eudat.commons.enums.DescriptionTemplateTypeStatus; +import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.validation.FieldNotNullIfOtherSet; import eu.eudat.commons.validation.ValidEnum; import eu.eudat.commons.validation.ValidId; - +import eu.eudat.data.DescriptionEntity; import eu.eudat.data.DescriptionTemplateTypeEntity; +import eu.eudat.data.UserEntity; +import eu.eudat.model.UserAdditionalInfo; +import eu.eudat.model.UserContactInfo; +import eu.eudat.model.UserCredential; +import eu.eudat.model.UserRole; +import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; + +import java.time.Instant; +import java.util.List; import java.util.UUID; @FieldNotNullIfOtherSet(message = "{validation.hashempty}") -public class DescriptionTemplateTypePersist { +public class UserPersist { @ValidId(message = "{validation.invalidid}") private UUID id; + @NotNull(message = "{validation.empty}") @NotEmpty(message = "{validation.empty}") - @Size(max = DescriptionTemplateTypeEntity._nameLength, message = "{validation.largerthanmax}") - private String name = null; + @Size(max = UserEntity._nameLength, message = "{validation.largerthanmax}") + private String name; private String hash; - @ValidEnum(message = "{validation.empty}") - private DescriptionTemplateTypeStatus status; - + @Valid + private UserAdditionalInfoPersist additionalInfo; + public UUID getId() { return id; } @@ -52,12 +63,12 @@ public class DescriptionTemplateTypePersist { this.hash = hash; } - public DescriptionTemplateTypeStatus getStatus() { - return status; + public UserAdditionalInfoPersist getAdditionalInfo() { + return additionalInfo; } - public void setStatus(DescriptionTemplateTypeStatus status) { - this.status = status; + public void setAdditionalInfo(UserAdditionalInfoPersist additionalInfo) { + this.additionalInfo = additionalInfo; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserRolePatchPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserRolePatchPersist.java index 7f37c9865..fceb1e87a 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserRolePatchPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/UserRolePatchPersist.java @@ -1,44 +1,31 @@ package eu.eudat.model.persist; -import eu.eudat.commons.enums.DescriptionTemplateTypeStatus; -import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.validation.FieldNotNullIfOtherSet; -import eu.eudat.commons.validation.ValidEnum; import eu.eudat.commons.validation.ValidId; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.DescriptionTemplateTypeEntity; import eu.eudat.data.UserEntity; -import eu.eudat.model.UserAdditionalInfo; -import eu.eudat.model.UserContactInfo; -import eu.eudat.model.UserCredential; -import eu.eudat.model.UserRole; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.time.Instant; import java.util.List; import java.util.UUID; @FieldNotNullIfOtherSet(message = "{validation.hashempty}") -public class UserPersist { +public class UserRolePatchPersist { + @NotNull(message = "{validation.empty}") @ValidId(message = "{validation.invalidid}") private UUID id; @NotNull(message = "{validation.empty}") - @NotEmpty(message = "{validation.empty}") - @Size(max = UserEntity._nameLength, message = "{validation.largerthanmax}") - private String name; + private List roles; + @NotNull(message = "{validation.empty}") private String hash; - @Valid - private UserAdditionalInfoPersist additionalInfo; - public UUID getId() { return id; } @@ -47,12 +34,12 @@ public class UserPersist { this.id = id; } - public String getName() { - return name; + public List getRoles() { + return roles; } - public void setName(String name) { - this.name = name; + public void setRoles(List roles) { + this.roles = roles; } public String getHash() { @@ -62,13 +49,5 @@ public class UserPersist { public void setHash(String hash) { this.hash = hash; } - - public UserAdditionalInfoPersist getAdditionalInfo() { - return additionalInfo; - } - - public void setAdditionalInfo(UserAdditionalInfoPersist additionalInfo) { - this.additionalInfo = additionalInfo; - } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionQuery.java index 4e50cc56c..552fc54a4 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionQuery.java @@ -263,6 +263,7 @@ public class DescriptionQuery extends QueryBase { else if (item.match(Description._status) || item.match(PublicDescription._status)) return DescriptionEntity._status; else if (item.match(Description._description) || item.match(PublicDescription._description)) return DescriptionEntity._description; else if (item.match(Description._createdBy)) return DescriptionEntity._createdById; + else if (item.prefix(Description._createdBy)) return DescriptionEntity._createdById; else if (item.match(Description._createdAt) || item.match(PublicDescription._createdAt)) return DescriptionEntity._createdAt; else if (item.match(Description._updatedAt) || item.match(PublicDescription._updatedAt)) return DescriptionEntity._updatedAt; else if (item.match(Description._isActive)) return DescriptionEntity._isActive; diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionReferenceQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionReferenceQuery.java index aa14a630d..cc92b1b9d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionReferenceQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DescriptionReferenceQuery.java @@ -166,7 +166,7 @@ public class DescriptionReferenceQuery extends QueryBase 0) { + if (!predicates.isEmpty()) { Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); return queryContext.CriteriaBuilder.and(predicatesArray); } else { @@ -224,6 +224,7 @@ public class DescriptionReferenceQuery extends QueryBase { else if (item.match(DescriptionTag._isActive)) return DescriptionTagEntity._isActive; else if (item.match(DescriptionTag._createdAt)) return DescriptionTagEntity._createdAt; else if (item.match(DescriptionTag._updatedAt)) return DescriptionTagEntity._updatedAt; + else if (item.match(DescriptionTag._hash)) return DescriptionTagEntity._updatedAt; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DmpDescriptionTemplateQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DmpDescriptionTemplateQuery.java index cdd3f31bd..b45168275 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DmpDescriptionTemplateQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DmpDescriptionTemplateQuery.java @@ -225,6 +225,7 @@ public class DmpDescriptionTemplateQuery extends QueryBase { else if (item.match(Dmp._isActive) ) return DmpEntity._isActive; else if (item.match(Dmp._finalizedAt) || item.match(PublicDmp._finalizedAt)) return DmpEntity._finalizedAt; else if (item.match(Dmp._accessType)) return DmpEntity._accessType; - else if (item.match(Dmp._creator)) return DmpEntity._creator; - else if (item.match(Dmp._blueprint)) return DmpEntity._blueprint; + else if (item.match(Dmp._creator)) return DmpEntity._creatorId; + else if (item.prefix(Dmp._creator)) return DmpEntity._blueprintId; + else if (item.match(Dmp._blueprint)) return DmpEntity._blueprintId; + else if (item.prefix(Dmp._blueprint)) return DmpEntity._blueprintId; else if (item.match(Dmp._language)) return DmpEntity._language; else if (item.match(Dmp._publicAfter)) return DmpEntity._publicAfter; else if (item.match(Dmp._versionStatus)) return DmpEntity._versionStatus; @@ -330,8 +325,8 @@ public class DmpQuery extends QueryBase { item.setIsActive(QueryBase.convertSafe(tuple, columns, DmpEntity._isActive, IsActive.class)); item.setFinalizedAt(QueryBase.convertSafe(tuple, columns, DmpEntity._finalizedAt, Instant.class)); item.setAccessType(QueryBase.convertSafe(tuple, columns, DmpEntity._accessType, DmpAccessType.class)); - item.setCreator(QueryBase.convertSafe(tuple, columns, DmpEntity._creator, UUID.class)); - item.setBlueprint(QueryBase.convertSafe(tuple, columns, DmpEntity._blueprint, UUID.class)); + item.setCreatorId(QueryBase.convertSafe(tuple, columns, DmpEntity._creatorId, UUID.class)); + item.setBlueprintId(QueryBase.convertSafe(tuple, columns, DmpEntity._blueprintId, UUID.class)); item.setLanguage(QueryBase.convertSafe(tuple, columns, DmpEntity._language, String.class)); item.setPublicAfter(QueryBase.convertSafe(tuple, columns, DmpEntity._publicAfter, Instant.class)); return item; diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DmpReferenceQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DmpReferenceQuery.java index 575e4c46f..3ed7e2c14 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DmpReferenceQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DmpReferenceQuery.java @@ -206,6 +206,7 @@ public class DmpReferenceQuery extends QueryBase { else if (item.match(DmpReference._data)) return DmpReferenceEntity._data; else if (item.match(DmpReference._createdAt)) return DmpReferenceEntity._createdAt; else if (item.match(DmpReference._updatedAt)) return DmpReferenceEntity._updatedAt; + else if (item.match(DmpReference._hash)) return DmpReferenceEntity._updatedAt; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/DmpUserQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/DmpUserQuery.java index 60e617652..a28f0ecdc 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/DmpUserQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/DmpUserQuery.java @@ -156,7 +156,7 @@ public class DmpUserQuery extends QueryBase { if (userId != null || usePublic ) { predicates.add(queryContext.CriteriaBuilder.or( usePublic ? queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._dmp)).value(queryUtilsService.buildPublicDmpAuthZSubQuery(queryContext.Query, queryContext.CriteriaBuilder, usePublic)) : queryContext.CriteriaBuilder.or(), //Creates a false query - userId != null ? queryContext.CriteriaBuilder.equal(queryContext.Root.get(DmpUserEntity._user), userId) : queryContext.CriteriaBuilder.or() //Creates a false query + userId != null ? queryContext.CriteriaBuilder.equal(queryContext.Root.get(DmpUserEntity._userId), userId) : queryContext.CriteriaBuilder.or() //Creates a false query )); } if (!predicates.isEmpty()) { @@ -189,7 +189,7 @@ public class DmpUserQuery extends QueryBase { predicates.add(inClause); } if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._user)); + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._userId)); for (UUID item : this.userIds) inClause.value(item); predicates.add(inClause); @@ -213,7 +213,7 @@ public class DmpUserQuery extends QueryBase { DmpUserEntity item = new DmpUserEntity(); item.setId(QueryBase.convertSafe(tuple, columns, DmpUserEntity._id, UUID.class)); item.setDmp(QueryBase.convertSafe(tuple, columns, DmpUserEntity._dmp, UUID.class)); - item.setUser(QueryBase.convertSafe(tuple, columns, DmpUserEntity._user, UUID.class)); + item.setUserId(QueryBase.convertSafe(tuple, columns, DmpUserEntity._userId, UUID.class)); item.setRole(QueryBase.convertSafe(tuple, columns, DmpUserEntity._role, DmpUserRole.class)); item.setCreatedAt(QueryBase.convertSafe(tuple, columns, DmpUserEntity._createdAt, Instant.class)); item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, DmpUserEntity._updatedAt, Instant.class)); @@ -224,10 +224,11 @@ public class DmpUserQuery extends QueryBase { protected String fieldNameOf(FieldResolver item) { if (item.match(DmpUser._id) || item.match(PublicDmpUser._id)) return DmpUserEntity._id; else if (item.prefix(DmpUser._dmp) || item.prefix(PublicDmpUser._dmp)) return DmpUserEntity._dmp; - else if (item.prefix(DmpUser._user) || item.prefix(PublicDmpUser._user)) return DmpUserEntity._user; + else if (item.prefix(DmpUser._user) || item.prefix(PublicDmpUser._user)) return DmpUserEntity._userId; else if (item.match(DmpUser._role) || item.match(PublicDmpUser._role)) return DmpUserEntity._role; else if (item.match(DmpUser._createdAt)) return DmpUserEntity._createdAt; else if (item.match(DmpUser._updatedAt)) return DmpUserEntity._updatedAt; + else if (item.match(DmpUser._hash)) return DmpUserEntity._updatedAt; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java index 20ceabddd..e5b3a01c2 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java @@ -4,13 +4,9 @@ import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.EntityDoiEntity; import eu.eudat.data.ReferenceEntity; -import eu.eudat.model.EntityDoi; import eu.eudat.model.PublicReference; import eu.eudat.model.Reference; -import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.tools.data.query.FieldResolver; import gr.cite.tools.data.query.QueryBase; import gr.cite.tools.data.query.QueryContext; @@ -219,7 +215,7 @@ public class ReferenceQuery extends QueryBase { item.setSource(QueryBase.convertSafe(tuple, columns, ReferenceEntity._source, String.class)); item.setSourceType(QueryBase.convertSafe(tuple, columns, ReferenceEntity._sourceType, ReferenceSourceType.class)); item.setType(QueryBase.convertSafe(tuple, columns, ReferenceEntity._type, ReferenceType.class)); - item.setCreatedBy(QueryBase.convertSafe(tuple, columns, ReferenceEntity._createdBy, UUID.class)); + item.setCreatedById(QueryBase.convertSafe(tuple, columns, ReferenceEntity._createdById, UUID.class)); return item; } @@ -230,6 +226,7 @@ public class ReferenceQuery extends QueryBase { else if (item.match(Reference._description) || item.match(PublicReference._description)) return ReferenceEntity._description; else if (item.match(Reference._createdAt)) return ReferenceEntity._createdAt; else if (item.match(Reference._updatedAt)) return ReferenceEntity._updatedAt; + else if (item.match(Reference._hash)) return ReferenceEntity._updatedAt; else if (item.match(Reference._isActive)) return ReferenceEntity._isActive; else if (item.match(Reference._definition)) return ReferenceEntity._definition; else if (item.match(Reference._abbreviation)) return ReferenceEntity._abbreviation; @@ -237,7 +234,7 @@ public class ReferenceQuery extends QueryBase { else if (item.match(Reference._source)) return ReferenceEntity._source; else if (item.match(Reference._sourceType)) return ReferenceEntity._sourceType; else if (item.match(Reference._type) || item.match(PublicReference._type)) return ReferenceEntity._type; - //else if (item.prefix(Reference._createdBy)) return ReferenceEntity._createdBy; + else if (item.prefix(Reference._createdBy)) return ReferenceEntity._createdById; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceTypeQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceTypeQuery.java index 661bb9c94..7bc0e599b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceTypeQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceTypeQuery.java @@ -106,16 +106,9 @@ public class ReferenceTypeQuery extends QueryBase { return this; } - private final UserScope userScope; - - private final AuthorizationService authService; public ReferenceTypeQuery( - UserScope userScope, - AuthorizationService authService ) { - this.userScope = userScope; - this.authService = authService; } @Override @@ -188,6 +181,7 @@ public class ReferenceTypeQuery extends QueryBase { else if (item.match(ReferenceType._code)) return ReferenceTypeEntity._code; else if (item.match(ReferenceType._createdAt)) return ReferenceTypeEntity._createdAt; else if (item.match(ReferenceType._updatedAt)) return ReferenceTypeEntity._updatedAt; + else if (item.match(ReferenceType._hash)) return ReferenceTypeEntity._updatedAt; else if (item.match(ReferenceType._isActive)) return ReferenceTypeEntity._isActive; else if (item.match(ReferenceType._definition)) return ReferenceTypeEntity._definition; else if (item.prefix(ReferenceType._definition)) return ReferenceTypeEntity._definition; diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/SupportiveMaterialQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/SupportiveMaterialQuery.java index 5601eb2dc..0cc1bdee1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/SupportiveMaterialQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/SupportiveMaterialQuery.java @@ -123,16 +123,8 @@ public class SupportiveMaterialQuery extends QueryBase return this; } - private final UserScope userScope; - - private final AuthorizationService authService; - public SupportiveMaterialQuery( - UserScope userScope, - AuthorizationService authService ) { - this.userScope = userScope; - this.authService = authService; } @Override @@ -213,6 +205,7 @@ public class SupportiveMaterialQuery extends QueryBase else if (item.match(SupportiveMaterial._payload)) return SupportiveMaterialEntity._payload; else if (item.match(SupportiveMaterial._createdAt)) return SupportiveMaterialEntity._createdAt; else if (item.match(SupportiveMaterial._updatedAt)) return SupportiveMaterialEntity._updatedAt; + else if (item.match(SupportiveMaterial._hash)) return SupportiveMaterialEntity._updatedAt; else if (item.match(SupportiveMaterial._isActive)) return SupportiveMaterialEntity._isActive; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/TagQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/TagQuery.java index df54eef9f..81f9de07d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/TagQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/TagQuery.java @@ -2,10 +2,8 @@ package eu.eudat.query; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.enums.IsActive; -import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.TagEntity; import eu.eudat.model.Tag; -import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.tools.data.query.FieldResolver; import gr.cite.tools.data.query.QueryBase; import gr.cite.tools.data.query.QueryContext; @@ -170,7 +168,7 @@ public class TagQuery extends QueryBase { predicates.add(inClause); } if (this.createdByIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TagEntity._createdBy)); + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TagEntity._createdById)); for (UUID item : this.createdByIds) inClause.value(item); predicates.add(inClause); @@ -187,9 +185,8 @@ public class TagQuery extends QueryBase { protected String fieldNameOf(FieldResolver item) { if (item.match(Tag._id)) return TagEntity._id; else if (item.match(Tag._label)) return TagEntity._label; - else if (item.prefix(Tag._createdBy)) return TagEntity._createdBy; - else if (item.match(Tag._createdBy)) return TagEntity._createdBy; - else if (item.match(Tag._createdBy)) return TagEntity._createdBy; + else if (item.prefix(Tag._createdBy)) return TagEntity._createdById; + else if (item.match(Tag._createdBy)) return TagEntity._createdById; else if (item.match(Tag._createdAt)) return TagEntity._createdAt; else if (item.match(Tag._updatedAt)) return TagEntity._updatedAt; else if (item.match(Tag._hash)) return TagEntity._updatedAt; @@ -202,7 +199,7 @@ public class TagQuery extends QueryBase { TagEntity item = new TagEntity(); item.setId(QueryBase.convertSafe(tuple, columns, TagEntity._id, UUID.class)); item.setLabel(QueryBase.convertSafe(tuple, columns, TagEntity._label, String.class)); - item.setCreatedBy(QueryBase.convertSafe(tuple, columns, TagEntity._createdBy, UUID.class)); + item.setCreatedById(QueryBase.convertSafe(tuple, columns, TagEntity._createdById, UUID.class)); item.setCreatedAt(QueryBase.convertSafe(tuple, columns, TagEntity._createdAt, Instant.class)); item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, TagEntity._updatedAt, Instant.class)); item.setIsActive(QueryBase.convertSafe(tuple, columns, TagEntity._isActive, IsActive.class)); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/UserDescriptionTemplateQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/UserDescriptionTemplateQuery.java index 06ead5ae1..f6910e024 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/UserDescriptionTemplateQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/UserDescriptionTemplateQuery.java @@ -3,9 +3,8 @@ package eu.eudat.query; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.UserDescriptionTemplateRole; -import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.UserDescriptionTemplateEntity; -import gr.cite.commons.web.authz.service.AuthorizationService; +import eu.eudat.model.UserDescriptionTemplate; import gr.cite.tools.data.query.FieldResolver; import gr.cite.tools.data.query.QueryBase; import gr.cite.tools.data.query.QueryContext; @@ -152,13 +151,13 @@ public class UserDescriptionTemplateQuery extends QueryBase inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._user)); + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._userId)); for (UUID item : this.userIds) inClause.value(item); predicates.add(inClause); } if (this.descriptionTemplateIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._descriptionTemplate)); + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._descriptionTemplateId)); for (UUID item : this.descriptionTemplateIds) inClause.value(item); predicates.add(inClause); @@ -193,8 +192,8 @@ public class UserDescriptionTemplateQuery extends QueryBase columns) { UserDescriptionTemplateEntity item = new UserDescriptionTemplateEntity(); item.setId(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._id, UUID.class)); - item.setUser(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._user, UUID.class)); - item.setDescriptionTemplate(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._descriptionTemplate, UUID.class)); + item.setUserId(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._userId, UUID.class)); + item.setDescriptionTemplateId(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._descriptionTemplateId, UUID.class)); item.setRole(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._role, UserDescriptionTemplateRole.class)); item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._createdAt, Instant.class)); item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._updatedAt, Instant.class)); @@ -204,13 +203,16 @@ public class UserDescriptionTemplateQuery extends QueryBase { private String like; private Collection ids; + private Collection emails; private Collection excludedIds; private Collection isActives; @@ -36,9 +41,11 @@ public class UserQuery extends QueryBase { private final UserScope userScope; private final AuthorizationService authService; - public UserQuery(UserScope userScope, AuthorizationService authService) { + private final QueryUtilsService queryUtilsService; + public UserQuery(UserScope userScope, AuthorizationService authService, QueryUtilsService queryUtilsService) { this.userScope = userScope; this.authService = authService; + this.queryUtilsService = queryUtilsService; } public UserQuery like(String value) { @@ -60,6 +67,21 @@ public class UserQuery extends QueryBase { this.ids = values; return this; } + + public UserQuery emails(String value) { + this.emails = List.of(value); + return this; + } + + public UserQuery emails(String... value) { + this.emails = Arrays.asList(value); + return this; + } + + public UserQuery emails(Collection values) { + this.emails = values; + return this; + } public UserQuery excludedIds(Collection values) { this.excludedIds = values; @@ -101,6 +123,7 @@ public class UserQuery extends QueryBase { return this.isEmpty(this.ids) || this.isEmpty(this.isActives) || + this.isEmpty(this.emails) || this.isEmpty(this.excludedIds); } @@ -153,6 +176,22 @@ public class UserQuery extends QueryBase { inClause.value(item); predicates.add(inClause); } + if (this.emails != null) { + Subquery userContactInfoSubquery = queryUtilsService.buildSubQuery(new BuildSubQueryInput<>( + new BuildSubQueryInput.Builder<>(UserContactInfoQuery.class, UUID.class, queryContext) + .keyPathFunc((subQueryRoot) -> subQueryRoot.get(UserContactInfoEntity._id)) + .filterFunc((subQueryRoot, cb) -> { + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._value)); + for (String item : this.emails) + inClause.value(item); + return inClause; + } + ) + )); + predicates.add(queryContext.CriteriaBuilder.in(queryContext.Root.get(UserEntity._id)).value(userContactInfoSubquery)); + } + + if (!predicates.isEmpty()) { Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); return queryContext.CriteriaBuilder.and(predicatesArray); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/UserLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/UserLookup.java index 7bc5c340b..a14bad5f1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/UserLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/UserLookup.java @@ -18,6 +18,7 @@ public class UserLookup extends Lookup { private String like; private List ids; + private List emails; private List excludedIds; private List isActive; @@ -58,6 +59,7 @@ public class UserLookup extends Lookup { UserQuery query = queryFactory.query(UserQuery.class); if (this.like != null) query.like(this.like); if (this.ids != null) query.ids(this.ids); + if (this.emails != null) query.emails(this.emails); if (this.excludedIds != null) query.excludedIds(this.excludedIds); if (this.isActive != null) query.isActive(this.isActive); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/utils/QueryUtilsServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/query/utils/QueryUtilsServiceImpl.java index 59543e160..9666cbe70 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/utils/QueryUtilsServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/utils/QueryUtilsServiceImpl.java @@ -66,7 +66,7 @@ public class QueryUtilsServiceImpl implements QueryUtilsService { .keyPathFunc((subQueryRoot) -> subQueryRoot.get(DmpUserEntity._dmp)) .filterFunc((subQueryRoot, cb) -> userId != null ? cb.and( - cb.equal(subQueryRoot.get(DmpUserEntity._user), userId), + cb.equal(subQueryRoot.get(DmpUserEntity._userId), userId), cb.equal(subQueryRoot.get(DmpUserEntity._isActive), IsActive.Active) ) : cb.or() //Creates a false query ) diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java index 5da6bc1ca..659c0b22c 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java @@ -17,6 +17,7 @@ import eu.eudat.data.UserDescriptionTemplateEntity; import eu.eudat.data.UserEntity; import eu.eudat.errorcode.ErrorThesaurusProperties; import eu.eudat.model.DescriptionTemplate; +import eu.eudat.model.UserContactInfo; import eu.eudat.model.builder.DescriptionTemplateBuilder; import eu.eudat.model.deleter.DescriptionTemplateDeleter; import eu.eudat.model.deleter.UserDescriptionTemplateDeleter; @@ -30,6 +31,7 @@ import eu.eudat.model.persist.UserDescriptionTemplatePersist; import eu.eudat.model.persist.descriptiontemplatedefinition.*; import eu.eudat.model.persist.descriptiontemplatedefinition.fielddata.BaseFieldDataPersist; import eu.eudat.query.DescriptionTemplateQuery; +import eu.eudat.query.UserContactInfoQuery; import eu.eudat.query.UserDescriptionTemplateQuery; import eu.eudat.service.fielddatahelper.FieldDataHelperService; import eu.eudat.service.fielddatahelper.FieldDataHelperServiceProvider; @@ -39,6 +41,7 @@ import eu.eudat.service.responseutils.ResponseUtilsService; 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.Ordering; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.exception.MyForbiddenException; @@ -182,14 +185,14 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic List items = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(id).collect(); List updatedCreatedIds = new ArrayList<>(); for (UserDescriptionTemplatePersist user : users) { - UserDescriptionTemplateEntity data = items.stream().filter(x -> x.getUser().equals(user.getUserId()) && x.getRole().equals(user.getRole())).findFirst().orElse(null); + UserDescriptionTemplateEntity data = items.stream().filter(x -> x.getUserId().equals(user.getUserId()) && x.getRole().equals(user.getRole())).findFirst().orElse(null); if (data == null){ data = new UserDescriptionTemplateEntity(); data.setId(UUID.randomUUID()); data.setIsActive(IsActive.Active); data.setCreatedAt(Instant.now()); - data.setDescriptionTemplate(id); - data.setUser(user.getUserId()); + data.setDescriptionTemplateId(id); + data.setUserId(user.getUserId()); data.setRole(user.getRole()); this.entityManager.persist(data); this.sendJoinMail(data); @@ -202,8 +205,8 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic } private void sendJoinMail(UserDescriptionTemplateEntity userDatasetProfile) { SimpleMail mail = new SimpleMail(); - UserEntity user = this.entityManager.find(UserEntity.class, userDatasetProfile.getUser()); - DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(userDatasetProfile.getDescriptionTemplate()).first(); + UserEntity user = this.entityManager.find(UserEntity.class, userDatasetProfile.getUserId()); + DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(userDatasetProfile.getDescriptionTemplateId()).first(); mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", descriptionTemplate.getLabel())); String content = this.mailService.getMailTemplateContent(environment.getProperty("email.dataset.template")); @@ -212,8 +215,9 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic content = content.replace("{host}", this.environment.getProperty("dmp.domain")); content = content.replace("{templateID}", descriptionTemplate.getId().toString()); mail.setContent(content); - //TODO: GetEmail -// mail.setTo(user.getEmail()); + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + mail.setTo(query.first().getValue()); try { this.mailService.sendSimpleMail(mail); } catch (Exception ex) { @@ -227,8 +231,8 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic data.setIsActive(IsActive.Active); data.setCreatedAt(Instant.now()); data.setRole(UserDescriptionTemplateRole.Owner); - data.setUser(userScope.getUserId()); - data.setDescriptionTemplate(descriptionTemplateEntity.getId()); + data.setUserId(userScope.getUserId()); + data.setDescriptionTemplateId(descriptionTemplateEntity.getId()); this.entityManager.persist(data); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java index a5909d7eb..00b55f606 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java @@ -167,7 +167,7 @@ public class DmpServiceImpl implements DmpService { newDmp.setLanguage(oldDmpEntity.getLanguage()); newDmp.setStatus(DmpStatus.Draft); newDmp.setProperties(oldDmpEntity.getProperties()); - newDmp.setBlueprint(model.getBlueprintId()); + newDmp.setBlueprintId(model.getBlueprintId()); List dmpUsers = this.queryFactory.query(DmpUserQuery.class) .dmpIds(model.getId()) @@ -186,7 +186,7 @@ public class DmpServiceImpl implements DmpService { DmpUserEntity newUser = new DmpUserEntity(); newUser.setId(UUID.randomUUID()); newUser.setDmp(newDmp.getId()); - newUser.setUser(dmpUser.getUser()); + newUser.setUserId(dmpUser.getUserId()); newUser.setRole(dmpUser.getRole()); newUser.setCreatedAt(Instant.now()); newUser.setUpdatedAt(Instant.now()); @@ -255,7 +255,7 @@ public class DmpServiceImpl implements DmpService { newDmp.setLanguage(existingDmpEntity.getLanguage()); newDmp.setStatus(DmpStatus.Draft); newDmp.setProperties(existingDmpEntity.getProperties()); - newDmp.setBlueprint(existingDmpEntity.getBlueprint()); + newDmp.setBlueprintId(existingDmpEntity.getBlueprintId()); List dmpUsers = this.queryFactory.query(DmpUserQuery.class) .dmpIds(model.getId()) @@ -274,7 +274,7 @@ public class DmpServiceImpl implements DmpService { DmpUserEntity newUser = new DmpUserEntity(); newUser.setId(UUID.randomUUID()); newUser.setDmp(newDmp.getId()); - newUser.setUser(dmpUser.getUser()); + newUser.setUserId(dmpUser.getUserId()); newUser.setRole(dmpUser.getRole()); newUser.setCreatedAt(Instant.now()); newUser.setUpdatedAt(Instant.now()); @@ -331,7 +331,7 @@ public class DmpServiceImpl implements DmpService { DmpUserEntity newUser = new DmpUserEntity(); newUser.setId(UUID.randomUUID()); newUser.setDmp(dmp); - newUser.setUser(dmpUser.getUser()); + newUser.setUserId(dmpUser.getUser()); newUser.setRole(dmpUser.getRole()); newUser.setCreatedAt(Instant.now()); newUser.setUpdatedAt(Instant.now()); @@ -393,14 +393,14 @@ public class DmpServiceImpl implements DmpService { data.setVersion((short) 1); data.setStatus(DmpStatus.Draft); data.setVersionStatus(DmpVersionStatus.Current); - data.setCreator(userScope.getUserId()); - data.setBlueprint(model.getBlueprint()); + data.setCreatorId(userScope.getUserId()); + data.setBlueprintId(model.getBlueprint()); data.setIsActive(IsActive.Active); data.setCreatedAt(Instant.now()); dmpUserEntity.setId(UUID.randomUUID()); dmpUserEntity.setDmp(data.getId()); - dmpUserEntity.setUser(userScope.getUserId()); + dmpUserEntity.setUserId(userScope.getUserId()); dmpUserEntity.setRole(DmpUserRole.Owner); dmpUserEntity.setCreatedAt(Instant.now()); dmpUserEntity.setUpdatedAt(Instant.now()); @@ -552,7 +552,7 @@ public class DmpServiceImpl implements DmpService { private boolean checkUserRoleIfExists(List dmpUserEntities, UUID dmp, UUID user, DmpUserRole role) { for (DmpUserEntity dmpUser : dmpUserEntities) { - if (dmpUser.getDmp().equals(dmp) && dmpUser.getUser().equals(user) && dmpUser.getRole() == role) { + if (dmpUser.getDmp().equals(dmp) && dmpUser.getUserId().equals(user) && dmpUser.getRole() == role) { dmpUserEntities.remove(dmpUser); return true; }; diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/user/UserService.java b/dmp-backend/core/src/main/java/eu/eudat/service/user/UserService.java index 6746ff861..06d90ab78 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/user/UserService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/user/UserService.java @@ -1,7 +1,11 @@ -package eu.eudat.service.descriptiontemplatetype; +package eu.eudat.service.user; +import com.fasterxml.jackson.core.JsonProcessingException; import eu.eudat.model.DescriptionTemplateType; +import eu.eudat.model.User; import eu.eudat.model.persist.DescriptionTemplateTypePersist; +import eu.eudat.model.persist.UserPersist; +import eu.eudat.model.persist.UserRolePatchPersist; import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.exception.MyForbiddenException; import gr.cite.tools.exception.MyNotFoundException; @@ -9,12 +13,16 @@ import gr.cite.tools.exception.MyValidationException; import gr.cite.tools.fieldset.FieldSet; import javax.management.InvalidApplicationException; +import java.io.IOException; import java.util.UUID; -public interface DescriptionTemplateTypeService { +public interface UserService { - DescriptionTemplateType persist(DescriptionTemplateTypePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; + User persist(UserPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException; void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; + byte[] exportCsv() throws IOException; + + User patchRoles(UserRolePatchPersist model, FieldSet fields) throws InvalidApplicationException; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/user/UserServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/user/UserServiceImpl.java index 64b798b42..4b74540c9 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/user/UserServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/user/UserServiceImpl.java @@ -1,20 +1,33 @@ package eu.eudat.service.user; +import com.fasterxml.jackson.core.JsonProcessingException; import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.authorization.OwnedResource; import eu.eudat.authorization.Permission; +import eu.eudat.commons.JsonHandlingService; +import eu.eudat.commons.enums.ContactInfoType; import eu.eudat.commons.enums.IsActive; +import eu.eudat.commons.types.user.AdditionalInfoEntity; import eu.eudat.convention.ConventionService; -import eu.eudat.data.DescriptionTemplateTypeEntity; +import eu.eudat.data.UserEntity; +import eu.eudat.data.UserRoleEntity; import eu.eudat.errorcode.ErrorThesaurusProperties; -import eu.eudat.event.DescriptionTemplateTypeTouchedEvent; +import eu.eudat.event.UserTouchedEvent; import eu.eudat.event.EventBroker; -import eu.eudat.model.DescriptionTemplateType; -import eu.eudat.model.builder.DescriptionTemplateTypeBuilder; -import eu.eudat.model.deleter.DescriptionTemplateTypeDeleter; -import eu.eudat.model.persist.DescriptionTemplateTypePersist; +import eu.eudat.model.User; +import eu.eudat.model.UserContactInfo; +import eu.eudat.model.builder.UserBuilder; +import eu.eudat.model.deleter.UserDeleter; +import eu.eudat.model.deleter.UserRoleDeleter; +import eu.eudat.model.persist.UserAdditionalInfoPersist; +import eu.eudat.model.persist.UserPersist; +import eu.eudat.model.persist.UserRolePatchPersist; +import eu.eudat.query.UserQuery; +import eu.eudat.query.UserRoleQuery; 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; @@ -24,6 +37,10 @@ import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; import jakarta.persistence.EntityManager; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.QuoteMode; +import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; @@ -31,14 +48,19 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Service; import javax.management.InvalidApplicationException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintWriter; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; @Service -public class DescriptionTemplateTypeServiceImpl implements UserService { +public class UserServiceImpl implements UserService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeServiceImpl.class)); + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserServiceImpl.class)); private final EntityManager entityManager; @@ -53,11 +75,11 @@ public class DescriptionTemplateTypeServiceImpl implements UserService { private final ErrorThesaurusProperties errors; private final MessageSource messageSource; - private final EventBroker eventBroker; - + private final JsonHandlingService jsonHandlingService; + private final QueryFactory queryFactory; @Autowired - public DescriptionTemplateTypeServiceImpl( + public UserServiceImpl( EntityManager entityManager, AuthorizationService authorizationService, DeleterFactory deleterFactory, @@ -65,7 +87,9 @@ public class DescriptionTemplateTypeServiceImpl implements UserService { ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, - EventBroker eventBroker) { + EventBroker eventBroker, + JsonHandlingService jsonHandlingService, + QueryFactory queryFactory) { this.entityManager = entityManager; this.authorizationService = authorizationService; this.deleterFactory = deleterFactory; @@ -74,48 +98,127 @@ public class DescriptionTemplateTypeServiceImpl implements UserService { this.errors = errors; this.messageSource = messageSource; this.eventBroker = eventBroker; + this.jsonHandlingService = jsonHandlingService; + this.queryFactory = queryFactory; } - public DescriptionTemplateType persist(DescriptionTemplateTypePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting data descriptionTemplateType").And("model", model).And("fields", fields)); - - this.authorizationService.authorizeForce(Permission.EditDescriptionTemplateType); + //region persist + + @Override + public User persist(UserPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { + logger.debug(new MapLogEntry("persisting data User").And("model", model).And("fields", fields)); + this.authorizationService.authorizeAtLeastOneForce(model.getId() != null ? List.of(new OwnedResource(model.getId())) : null, Permission.EditUser); + Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); - DescriptionTemplateTypeEntity data; + UserEntity 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())); + data = this.entityManager.find(UserEntity.class, model.getId()); + if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); } else { - data = new DescriptionTemplateTypeEntity(); + data = new UserEntity(); data.setId(UUID.randomUUID()); data.setIsActive(IsActive.Active); data.setCreatedAt(Instant.now()); } + data.setAdditionalInfo(this.jsonHandlingService.toJson(this.buildAdditionalInfoEntity(model.getAdditionalInfo()))); + 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(); - this.eventBroker.emit(new DescriptionTemplateTypeTouchedEvent(data.getId())); - return this.builderFactory.builder(DescriptionTemplateTypeBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, DescriptionTemplateType._id), data); + this.eventBroker.emit(new UserTouchedEvent(data.getId())); + return this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, User._id), data); } + private @NotNull AdditionalInfoEntity buildAdditionalInfoEntity(UserAdditionalInfoPersist persist){ + AdditionalInfoEntity data = new AdditionalInfoEntity(); + if (persist == null) return data; + data.setOrganizationId(persist.getOrganizationId()); + data.setRoleOrganization(persist.getRoleOrganization()); + data.setCulture(persist.getCulture()); + data.setTimezone(persist.getTimezone()); + data.setLanguage(persist.getLanguage()); + data.setAvatarUrl(persist.getAvatarUrl()); + return data; + } + + //endregion + + //region delete + + @Override public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting descriptionTemplateType: {}", id); + logger.debug("deleting User: {}", id); - this.authorizationService.authorizeForce(Permission.DeleteDescriptionTemplateType); + this.authorizationService.authorizeForce(Permission.DeleteUser); - this.deleterFactory.deleter(DescriptionTemplateTypeDeleter.class).deleteAndSaveByIds(List.of(id)); + this.deleterFactory.deleter(UserDeleter.class).deleteAndSaveByIds(List.of(id)); + } + + //endregion + + //region export + + @Override + public byte[] exportCsv() throws IOException { + this.authorizationService.authorizeForce(Permission.ExportUsers); + + FieldSet fieldSet = new BaseFieldSet().ensure(User._id).ensure(User._name).ensure(User._contacts + "." + UserContactInfo._value).ensure(User._contacts + "." + UserContactInfo._type); + List users = this.builderFactory.builder(UserBuilder.class).build(fieldSet, this.queryFactory.query(UserQuery.class).collectAs(fieldSet)); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final CSVFormat format = CSVFormat.DEFAULT.withHeader("User Id", "User Name", "User Email").withQuoteMode(QuoteMode.NON_NUMERIC); + final CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format); + + for (User user : users) { + csvPrinter.printRecord(user.getId(), user.getName(), (user.getContacts() != null ? String.join(" ", user.getContacts().stream().filter(x-> ContactInfoType.Email.equals(x.getType())).map(UserContactInfo::getValue).toList()) : "")); + } + + csvPrinter.flush(); + return out.toByteArray(); } -} + //endregion + + + @Override + public User patchRoles(UserRolePatchPersist model, FieldSet fields) throws InvalidApplicationException { + logger.debug(new MapLogEntry("persisting data UserRole").And("model", model).And("fields", fields)); + this.authorizationService.authorizeForce(Permission.EditUser); + UserEntity data = this.entityManager.find(UserEntity.class, model.getId()); + if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), User.class.getSimpleName()}, LocaleContextHolder.getLocale())); + if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); + + List existingItems = this.queryFactory.query(UserRoleQuery.class).userIds(data.getId()).collect(); + List foundIds = new ArrayList<>(); + for (String roleName : model.getRoles().stream().filter(x-> x != null && !x.isBlank()).distinct().toList()) { + UserRoleEntity item = existingItems.stream().filter(x-> x.getRole().equals(roleName)).findFirst().orElse(null); + if (item == null) { + item = new UserRoleEntity(); + item.setId(UUID.randomUUID()); + item.setUserId(data.getId()); + item.setRole(roleName); + item.setCreatedAt(Instant.now()); + this.entityManager.persist(item); + } + foundIds.add(item.getId()); + } + + this.entityManager.flush(); + + List toDelete = existingItems.stream().filter(x-> foundIds.stream().noneMatch(y-> y.equals(x.getId()))).collect(Collectors.toList()); + this.deleterFactory.deleter(UserRoleDeleter.class).deleteAndSave(toDelete); + + this.entityManager.flush(); + + this.eventBroker.emit(new UserTouchedEvent(data.getId())); + return this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, User._id), data); + } +} \ No newline at end of file diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java index 5a2a117b0..f82d6f597 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java @@ -1,131 +1,131 @@ -package eu.eudat.controllers; - -import eu.eudat.authorization.Permission; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem; -import eu.eudat.logic.managers.UserManager; -import eu.eudat.logic.services.ApiContext; -import eu.eudat.models.data.helpers.common.DataTableData; -import eu.eudat.models.data.helpers.responses.ResponseItem; -import eu.eudat.models.data.userinfo.UserCredential; -import eu.eudat.models.data.userinfo.UserListingModel; -import eu.eudat.models.data.userinfo.UserProfile; -import eu.eudat.types.ApiMessageCode; -import gr.cite.commons.web.authz.service.AuthorizationService; -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 jakarta.validation.Valid; - -import javax.management.InvalidApplicationException; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.UUID; - - - -@RestController -@CrossOrigin -@RequestMapping(value = "api/user") -public class Users extends BaseController { - - private UserManager userManager; - private final AuthorizationService authorizationService; - private final UserScope userScope; - - @Autowired - public Users(ApiContext apiContext, UserManager userManager, AuthorizationService authorizationService, UserScope userScope) { - super(apiContext); - this.userManager = userManager; - this.authorizationService = authorizationService; - this.userScope = userScope; - } - - @RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole); - - DataTableData dataTable = userManager.getPaged(userInfoTableRequestItem); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> updateRoles(@Valid @RequestBody UserListingModel userListingModel) throws InvalidApplicationException { - this.authorizationService.authorizeForce(Permission.AdminRole); - - userManager.editRoles(userListingModel); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); - } - - @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json") - public @ResponseBody - ResponseEntity> get(@PathVariable String id) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id); - UserProfile user = userManager.getSingle(userId); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(user).status(ApiMessageCode.NO_MESSAGE)); - } - - @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json") - public @ResponseBody - ResponseEntity>> getEmails(@PathVariable String id) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id); - List user = userManager.getCredentials(userId); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(user).status(ApiMessageCode.NO_MESSAGE)); - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json") - public @ResponseBody - ResponseEntity> saveSettings(@RequestBody Map settings) throws IOException, InvalidApplicationException { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - userManager.updateSettings(settings); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); - } - - @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - DataTableData dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); - } - - @RequestMapping(method = RequestMethod.GET, value = {"/getCsv"}) - public @ResponseBody - ResponseEntity exportCsv() throws Exception { - return userManager.exportToCsv(); - } - - @RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> find(@Valid @RequestBody String email) throws Exception { - this.authorizationService.authorizeForce(Permission.PublicRole); - UserProfile userProfile = userManager.getFromEmail(email); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(userProfile).status(ApiMessageCode.NO_MESSAGE)); - } - -} - - - - - - - - - - - +//package eu.eudat.controllers; +// +//import eu.eudat.authorization.Permission; +//import eu.eudat.commons.scope.user.UserScope; +//import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem; +//import eu.eudat.logic.managers.UserManager; +//import eu.eudat.logic.services.ApiContext; +//import eu.eudat.models.data.helpers.common.DataTableData; +//import eu.eudat.models.data.helpers.responses.ResponseItem; +//import eu.eudat.models.data.userinfo.UserCredential; +//import eu.eudat.models.data.userinfo.UserListingModel; +//import eu.eudat.models.data.userinfo.UserProfile; +//import eu.eudat.types.ApiMessageCode; +//import gr.cite.commons.web.authz.service.AuthorizationService; +//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 jakarta.validation.Valid; +// +//import javax.management.InvalidApplicationException; +//import java.io.IOException; +//import java.util.List; +//import java.util.Map; +//import java.util.UUID; +// +// +// +//@RestController +//@CrossOrigin +//@RequestMapping(value = "api/user") +//public class Users extends BaseController { +// +// private UserManager userManager; +// private final AuthorizationService authorizationService; +// private final UserScope userScope; +// +// @Autowired +// public Users(ApiContext apiContext, UserManager userManager, AuthorizationService authorizationService, UserScope userScope) { +// super(apiContext); +// this.userManager = userManager; +// this.authorizationService = authorizationService; +// this.userScope = userScope; +// } +// +//// @RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json") +//// public @ResponseBody +//// ResponseEntity>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { +//// this.authorizationService.authorizeForce(Permission.AdminRole); +//// +//// DataTableData dataTable = userManager.getPaged(userInfoTableRequestItem); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); +//// } +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json") +// public @ResponseBody +// ResponseEntity> updateRoles(@Valid @RequestBody UserListingModel userListingModel) throws InvalidApplicationException { +// this.authorizationService.authorizeForce(Permission.AdminRole); +// +// userManager.editRoles(userListingModel); +// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); +// } +// +//// @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json") +//// public @ResponseBody +//// ResponseEntity> get(@PathVariable String id) throws Exception { +//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); +//// +//// UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id); +//// UserProfile user = userManager.getSingle(userId); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(user).status(ApiMessageCode.NO_MESSAGE)); +//// } +// +//// @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json") +//// public @ResponseBody +//// ResponseEntity>> getEmails(@PathVariable String id) throws Exception { +//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); +//// +//// UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id); +//// List user = userManager.getCredentials(userId); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(user).status(ApiMessageCode.NO_MESSAGE)); +//// } +// +//// @Transactional +//// @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json") +//// public @ResponseBody +//// ResponseEntity> saveSettings(@RequestBody Map settings) throws IOException, InvalidApplicationException { +//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); +//// +//// userManager.updateSettings(settings); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); +//// } +// +//// @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json") +//// public @ResponseBody +//// ResponseEntity>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { +//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); +//// +//// DataTableData dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); +//// } +// +//// @RequestMapping(method = RequestMethod.GET, value = {"/getCsv"}) +//// public @ResponseBody +//// ResponseEntity exportCsv() throws Exception { +//// return userManager.exportToCsv(); +//// } +// +//// @RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json") +//// public @ResponseBody +//// ResponseEntity> find(@Valid @RequestBody String email) throws Exception { +//// this.authorizationService.authorizeForce(Permission.PublicRole); +//// UserProfile userProfile = userManager.getFromEmail(email); +//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(userProfile).status(ApiMessageCode.NO_MESSAGE)); +//// } +// +//} +// +// +// +// +// +// +// +// +// +// +// diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/UserController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/UserController.java index ad2576339..7524887fe 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/UserController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/UserController.java @@ -3,18 +3,19 @@ package eu.eudat.controllers.v2; import com.fasterxml.jackson.core.JsonProcessingException; import eu.eudat.audit.AuditableAction; import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.model.DescriptionTemplate; -import eu.eudat.model.DmpBlueprint; -import eu.eudat.model.builder.DescriptionTemplateBuilder; -import eu.eudat.model.censorship.DescriptionTemplateCensor; -import eu.eudat.model.censorship.DmpBlueprintCensor; -import eu.eudat.model.persist.DescriptionTemplatePersist; -import eu.eudat.model.persist.NewVersionDescriptionTemplatePersist; +import eu.eudat.commons.scope.user.UserScope; +import eu.eudat.data.UserEntity; +import eu.eudat.model.User; +import eu.eudat.model.UserRole; +import eu.eudat.model.builder.UserBuilder; +import eu.eudat.model.censorship.UserCensor; +import eu.eudat.model.persist.UserPersist; +import eu.eudat.model.persist.UserRolePatchPersist; import eu.eudat.model.result.QueryResult; -import eu.eudat.query.DescriptionTemplateQuery; -import eu.eudat.query.lookup.DescriptionTemplateLookup; -import eu.eudat.service.descriptiontemplate.DescriptionTemplateService; +import eu.eudat.query.UserQuery; +import eu.eudat.query.lookup.UserLookup; +import eu.eudat.service.responseutils.ResponseUtilsService; +import eu.eudat.service.user.UserService; import gr.cite.tools.auditing.AuditService; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.censor.CensorFactory; @@ -31,80 +32,139 @@ import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; -import org.xml.sax.SAXException; +import org.springframework.web.bind.annotation.*; import javax.management.InvalidApplicationException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.*; @RestController -@RequestMapping(path = "api/description-template") -public class DescriptionTemplateController { +@RequestMapping(path = "api/user") +public class UserController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateController.class)); + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserController.class)); private final BuilderFactory builderFactory; private final AuditService auditService; - private final DescriptionTemplateService descriptionTemplateTypeService; + private final UserService userTypeService; private final CensorFactory censorFactory; private final QueryFactory queryFactory; + private final UserScope userScope; private final MessageSource messageSource; + private final ResponseUtilsService responseUtilsService; - public DescriptionTemplateController( + public UserController( BuilderFactory builderFactory, AuditService auditService, - DescriptionTemplateService descriptionTemplateTypeService, + UserService userTypeService, CensorFactory censorFactory, QueryFactory queryFactory, - MessageSource messageSource) { + UserScope userScope, + MessageSource messageSource, + ResponseUtilsService responseUtilsService) { this.builderFactory = builderFactory; this.auditService = auditService; - this.descriptionTemplateTypeService = descriptionTemplateTypeService; + this.userTypeService = userTypeService; this.censorFactory = censorFactory; this.queryFactory = queryFactory; + this.userScope = userScope; this.messageSource = messageSource; + this.responseUtilsService = responseUtilsService; } @PostMapping("query") - public QueryResult query(@RequestBody DescriptionTemplateLookup lookup) throws MyApplicationException, MyForbiddenException { - logger.debug("querying {}", DescriptionTemplate.class.getSimpleName()); + public QueryResult query(@RequestBody UserLookup lookup) throws MyApplicationException, MyForbiddenException { + logger.debug("querying {}", User.class.getSimpleName()); - this.censorFactory.censor(DescriptionTemplateCensor.class).censor(lookup.getProject(), null); + this.censorFactory.censor(UserCensor.class).censor(lookup.getProject(), null); - DescriptionTemplateQuery query = lookup.enrich(this.queryFactory).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic); + UserQuery query = lookup.enrich(this.queryFactory).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic); - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), data); + List data = query.collectAs(lookup.getProject()); + List models = this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), data); long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - this.auditService.track(AuditableAction.DescriptionTemplate_Query, "lookup", lookup); + this.auditService.track(AuditableAction.User_Query, "lookup", lookup); //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); return new QueryResult<>(models, count); } @GetMapping("{id}") - public DescriptionTemplate get(@PathVariable("id") UUID id, FieldSet fieldSet, Locale locale) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("retrieving" + DescriptionTemplate.class.getSimpleName()).And("id", id).And("fields", fieldSet)); + public User get(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { + logger.debug(new MapLogEntry("retrieving" + User.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - this.censorFactory.censor(DescriptionTemplateCensor.class).censor(fieldSet, null); + this.censorFactory.censor(UserCensor.class).censor(fieldSet, null); - DescriptionTemplateQuery query = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).ids(id); - DescriptionTemplate model = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fieldSet, query.firstAs(fieldSet)); + UserQuery query = this.queryFactory.query(UserQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).ids(id); + User model = this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fieldSet, query.firstAs(fieldSet)); if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, DescriptionTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); + throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.auditService.track(AuditableAction.DescriptionTemplate_Lookup, Map.ofEntries( + this.auditService.track(AuditableAction.User_Lookup, Map.ofEntries( + new AbstractMap.SimpleEntry("id", id), + new AbstractMap.SimpleEntry("fields", fieldSet) + )); + //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); + + return model; + } + + @GetMapping("/by-email/{email}") + public User get(@PathVariable("email") String email, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { + logger.debug(new MapLogEntry("retrieving" + User.class.getSimpleName()).And("email", email).And("fields", fieldSet)); + + this.censorFactory.censor(UserCensor.class).censor(fieldSet, null); + + UserQuery query = this.queryFactory.query(UserQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).emails(email); + User model = this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fieldSet, query.firstAs(fieldSet)); + if (model == null) + throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{email, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + this.auditService.track(AuditableAction.User_LookupByEmail, Map.ofEntries( + new AbstractMap.SimpleEntry("email", email), + new AbstractMap.SimpleEntry("fields", fieldSet) + )); + //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); + + return model; + } + + @GetMapping("/export/csv") + public ResponseEntity exportCsv() throws MyApplicationException, MyForbiddenException, MyNotFoundException, IOException { + logger.debug(new MapLogEntry("export" + User.class.getSimpleName())); + +// this.censorFactory.censor(UserCensor.class).censor(fieldSet, null); + byte[] bytes = this.userTypeService.exportCsv(); + + + this.auditService.track(AuditableAction.User_ExportCsv, Map.ofEntries( + )); + //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); + return this.responseUtilsService.buildResponseFileFromText(new String(bytes, StandardCharsets.UTF_8), "Users_dump.csv"); + } + + @GetMapping("mine") + public User getMine(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { + logger.debug(new MapLogEntry("retrieving" + User.class.getSimpleName()).And("id", id).And("fields", fieldSet)); + + this.censorFactory.censor(UserCensor.class).censor(fieldSet, this.userScope.getUserId()); + + UserQuery query = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic); + User model = this.builderFactory.builder(UserBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(fieldSet, query.firstAs(fieldSet)); + if (model == null) + throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + this.auditService.track(AuditableAction.User_Lookup, Map.ofEntries( new AbstractMap.SimpleEntry("id", id), new AbstractMap.SimpleEntry("fields", fieldSet) )); @@ -115,11 +175,25 @@ public class DescriptionTemplateController { @PostMapping("persist") @Transactional - public DescriptionTemplate persist(@MyValidate @RequestBody DescriptionTemplatePersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { - logger.debug(new MapLogEntry("persisting" + DescriptionTemplate.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - DescriptionTemplate persisted = this.descriptionTemplateTypeService.persist(model, fieldSet); + public User persist(@MyValidate @RequestBody UserPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { + logger.debug(new MapLogEntry("persisting" + User.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); + User persisted = this.userTypeService.persist(model, fieldSet); - this.auditService.track(AuditableAction.DescriptionTemplate_Persist, Map.ofEntries( + this.auditService.track(AuditableAction.User_Persist, Map.ofEntries( + new AbstractMap.SimpleEntry("model", model), + new AbstractMap.SimpleEntry("fields", fieldSet) + )); + //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); + return persisted; + } + + @PostMapping("persist/roles") + @Transactional + public User persistRoles(@MyValidate @RequestBody UserRolePatchPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { + logger.debug(new MapLogEntry("persisting" + UserRole.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); + User persisted = this.userTypeService.patchRoles(model, fieldSet); + + this.auditService.track(AuditableAction.User_PersistRoles, Map.ofEntries( new AbstractMap.SimpleEntry("model", model), new AbstractMap.SimpleEntry("fields", fieldSet) )); @@ -130,88 +204,11 @@ public class DescriptionTemplateController { @DeleteMapping("{id}") @Transactional public void delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug(new MapLogEntry("retrieving" + DescriptionTemplate.class.getSimpleName()).And("id", id)); + logger.debug(new MapLogEntry("retrieving" + User.class.getSimpleName()).And("id", id)); - this.descriptionTemplateTypeService.deleteAndSave(id); + this.userTypeService.deleteAndSave(id); - this.auditService.track(AuditableAction.DescriptionTemplate_Delete, "id", id); + this.auditService.track(AuditableAction.User_Delete, "id", id); //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); } - - @GetMapping("clone/{id}") - public DescriptionTemplate buildClone(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("clone" + DmpBlueprint.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - - this.censorFactory.censor(DmpBlueprintCensor.class).censor(fieldSet, null); - - DescriptionTemplate model = this.descriptionTemplateTypeService.buildClone(id, fieldSet); - - this.auditService.track(AuditableAction.DescriptionTemplate_Clone, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return model; - } - - @PostMapping("new-version") - @Transactional - public DescriptionTemplate createNewVersion(@MyValidate @RequestBody NewVersionDescriptionTemplatePersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { - logger.debug(new MapLogEntry("persisting" + NewVersionDescriptionTemplatePersist.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - DescriptionTemplate persisted = this.descriptionTemplateTypeService.createNewVersion(model, fieldSet); - - this.auditService.track(AuditableAction.DescriptionTemplate_PersistNewVersion, Map.ofEntries( - new AbstractMap.SimpleEntry("model", model), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - return persisted; - } - - - - @RequestMapping(method = RequestMethod.GET, value = {"/xml/export/{id}"}, produces = "application/xml") - public @ResponseBody ResponseEntity getXml(@PathVariable UUID id) throws JAXBException, ParserConfigurationException, IOException, TransformerException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException { - logger.debug(new MapLogEntry("export" + DescriptionTemplate.class.getSimpleName()).And("id", id)); - - ResponseEntity response = this.descriptionTemplateTypeService.exportXml(id); - - this.auditService.track(AuditableAction.DescriptionTemplate_GetXml, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id) - )); - return response; - } - - @RequestMapping(method = RequestMethod.POST, value = {"/xml/import/{id}", "/xml/import"}) - public DescriptionTemplate importXml(@RequestParam("file") MultipartFile file, @PathVariable(value = "id", required = false) UUID id, FieldSet fieldSet) throws IOException, JAXBException, InvalidApplicationException, ParserConfigurationException, TransformerException, InstantiationException, IllegalAccessException, SAXException { - logger.debug(new MapLogEntry("import" + DescriptionTemplate.class.getSimpleName()).And("file", file).And("id", id)); - - this.censorFactory.censor(DescriptionTemplateCensor.class).censor(fieldSet, null); - - DescriptionTemplate model = this.descriptionTemplateTypeService.importXml(file.getBytes(), id, file.getOriginalFilename(), fieldSet); - - this.auditService.track(AuditableAction.DescriptionTemplate_Import, Map.ofEntries( - new AbstractMap.SimpleEntry("file", file), - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return model; - } - - @RequestMapping(method = RequestMethod.GET, value = {"/get-semantics"}, produces = "application/json") - public List getSemantics(@RequestParam(value = "query", required = false) String query) throws IOException { - logger.debug(new MapLogEntry("import" + DescriptionTemplate.class.getSimpleName()).And("query", query)); - - List semantics = this.descriptionTemplateTypeService.getSemantics(query); - - this.auditService.track(AuditableAction.DescriptionTemplate_GetSemantics, Map.ofEntries( - new AbstractMap.SimpleEntry("query", query) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return semantics; - } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java index 324baddc7..e9ffb1cd2 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java @@ -3,9 +3,13 @@ package eu.eudat.logic.managers; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.UserEntity; import eu.eudat.logic.services.ApiContext; +import eu.eudat.model.UserContactInfo; import eu.eudat.models.data.ContactEmail.ContactEmailModel; import eu.eudat.models.data.ContactEmail.PublicContactEmailModel; +import eu.eudat.query.UserContactInfoQuery; import eu.eudat.service.mail.SimpleMail; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; import org.springframework.core.env.Environment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -20,21 +24,25 @@ public class ContactEmailManager { private ApiContext apiContext; private Environment environment; private final UserScope userScope; + private final QueryFactory queryFactory; @Autowired - public ContactEmailManager(ApiContext apiContext, Environment environment, UserScope userScope) { + public ContactEmailManager(ApiContext apiContext, Environment environment, UserScope userScope, QueryFactory queryFactory) { this.apiContext = apiContext; this.environment = environment; this.userScope = userScope; + this.queryFactory = queryFactory; } public void sendContactEmail(ContactEmailModel contactEmailModel) throws MessagingException, InvalidApplicationException { UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId()); SimpleMail mail = new SimpleMail(); - String enrichedMail = ""; //TODO: GetEmailcontactEmailModel.getDescription() + "\n\n" + "Send by user: " + user.getEmail() ; + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + query.first().getValue() ; mail.setSubject(contactEmailModel.getSubject()); mail.setTo(environment.getProperty("contact_email.mail")); mail.setContent(enrichedMail); -// mail.setFrom(user.getEmail());//TODO: GetEmail + mail.setFrom(query.first().getValue()); apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); } 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 6d0dcf08e..c88105a79 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 @@ -500,14 +500,14 @@ public class DataManagementPlanManager { DmpEntity newDmp = dataManagementPlan.toDataModel(); if(dataManagementPlan.getProfile() != null){ - newDmp.setBlueprint(dataManagementPlan.getProfile().getId()); + newDmp.setBlueprintId(dataManagementPlan.getProfile().getId()); } if (newDmp.getStatus().equals(DmpStatus.Finalized)) { checkDmpValidationRules(newDmp); } UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId()); - newDmp.setCreator(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprint()).first(); + newDmp.setCreatorId(user.getId()); + DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); @@ -537,12 +537,12 @@ public class DataManagementPlanManager { DmpEntity finalNewDmp = newDmp; this.databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> root.get("dmp").in(finalNewDmp.getId())).toList(); if (this.databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> root.get("dmp").in(finalNewDmp.getId())).toList()!= null && - this.databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> root.get("dmp").in(finalNewDmp.getId())).toList().stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser())) + this.databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> root.get("dmp").in(finalNewDmp.getId())).toList().stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUserId())) .collect(Collectors.toList()).size() == 0) { List userDMPList = new ArrayList<>(this.databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> root.get("dmp").in(finalNewDmp.getId())).toList()); for (UserInfoListingModel userInfoListingModel : dataManagementPlan.getUsers()) { for (DmpUserEntity userDMP : userDMPList) { - if (!(userDMP.getUser().equals(userInfoListingModel.getId()))) { + if (!(userDMP.getUserId().equals(userInfoListingModel.getId()))) { apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP); } } @@ -669,7 +669,7 @@ public class DataManagementPlanManager { checkDmpValidationRules(tempDMP); } UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(tempDMP.getBlueprint()).first(); + DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(tempDMP.getBlueprintId()).first(); if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); @@ -715,12 +715,12 @@ public class DataManagementPlanManager { if (latestVersionDMP.get(0).getVersion().equals(oldDmp.getVersion())) { DmpEntity newDmp = dataManagementPlan.toDataModel(); - newDmp.setBlueprint(oldDmp.getBlueprint()); + newDmp.setBlueprintId(oldDmp.getBlueprintId()); newDmp.setProperties(oldDmp.getProperties()); newDmp.setProperties(oldDmp.getProperties()); UserEntity user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - newDmp.setCreator(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprint()).first(); + newDmp.setCreatorId(user.getId()); + DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); } @@ -786,7 +786,7 @@ public class DataManagementPlanManager { .getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), oldDmp.getId())) .toList().stream().forEach(userDMP -> { DmpUserEntity temp = new DmpUserEntity(); - temp.setUser(userDMP.getUser()); + temp.setUserId(userDMP.getUserId()); temp.setRole(userDMP.getRole()); temp.setDmp(newDmp.getId()); apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(temp); @@ -810,13 +810,13 @@ public class DataManagementPlanManager { public UUID clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan) throws Exception { DmpEntity oldDmp = databaseRepository.getDmpDao().find(uuid); DmpEntity newDmp = dataManagementPlan.toDataModel(); - newDmp.setBlueprint(oldDmp.getBlueprint()); + newDmp.setBlueprintId(oldDmp.getBlueprintId()); newDmp.setProperties(oldDmp.getProperties()); newDmp.setProperties(oldDmp.getProperties()); UserEntity user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - newDmp.setCreator(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprint()).first(); + newDmp.setCreatorId(user.getId()); + DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); } @@ -1426,7 +1426,7 @@ public class DataManagementPlanManager { // // Space below Datasets. // XWPFParagraph parBreakDatasets = document.createParagraph(); - DefinitionEntity dmpBlueprint = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, this.queryFactory.query(DmpBlueprintQuery.class).ids(dmpEntity.getBlueprint()).first().getDefinition()); + DefinitionEntity dmpBlueprint = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, this.queryFactory.query(DmpBlueprintQuery.class).ids(dmpEntity.getBlueprintId()).first().getDefinition()); for(SectionEntity section: dmpBlueprint.getSections()){ wordBuilder.addParagraphContent("Section " + section.getOrdinal(), document, ParagraphStyle.HEADER1, BigInteger.ZERO, 0); XWPFParagraph sectionInfoParagraph = document.createParagraph(); @@ -1805,7 +1805,7 @@ public class DataManagementPlanManager { // dmpElement.appendChild(costs); // } - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first(); + DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(); Element dmpProfileElement = xmlDoc.createElement("dmpProfile"); Element dmpProfileName = xmlDoc.createElement("dmpProfileName"); if (!(dmpBlueprint == null)) { @@ -1823,15 +1823,15 @@ public class DataManagementPlanManager { Element dmpContactElement = xmlDoc.createElement("contact"); Element dmpContactName = xmlDoc.createElement("name"); Element dmpContactEmail = xmlDoc.createElement("email"); - if(dmp.getCreator() != null){ - dmpContactName.setTextContent(this.databaseRepository.getUserInfoDao().find(dmp.getCreator()).getName()); + if(dmp.getCreatorId() != null){ + dmpContactName.setTextContent(this.databaseRepository.getUserInfoDao().find(dmp.getCreatorId()).getName()); //TODO dmpContactEmail.setTextContent(this.databaseRepository.getUserInfoDao().find(dmp.getCreator()).getEmail()); } else{ Iterator users = new ArrayList().iterator(); //TODO dmp.getUsers().iterator(); if(users.hasNext()){ DmpUserEntity creator = users.next(); - dmpContactName.setTextContent(this.databaseRepository.getUserInfoDao().find(creator.getUser()).getName()); + dmpContactName.setTextContent(this.databaseRepository.getUserInfoDao().find(creator.getUserId()).getName()); //TODO .setTextContent(this.databaseRepository.getUserInfoDao().find(creator.getUser()).getEmail()); } } @@ -1846,7 +1846,7 @@ public class DataManagementPlanManager { Element dmpContributorName = xmlDoc.createElement("name"); Element dmpContributorEmail= xmlDoc.createElement("email"); DmpUserEntity contributor = users.next(); - dmpContributorName.setTextContent(this.databaseRepository.getUserInfoDao().find(contributor.getUser()).getName()); + dmpContributorName.setTextContent(this.databaseRepository.getUserInfoDao().find(contributor.getUserId()).getName()); //TODO dmpContributorEmail.setTextContent(this.databaseRepository.getUserInfoDao().find(contributor.getUser()).getEmail()); dmpContributorElement.appendChild(dmpContributorName); dmpContributorElement.appendChild(dmpContributorEmail); @@ -1856,7 +1856,7 @@ public class DataManagementPlanManager { // Funder. Element funder = xmlDoc.createElement("funder"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first(), DmpBlueprintSystemFieldType.Grant) && this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first(), DmpBlueprintSystemFieldType.Funder)) { + if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Grant) && this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Funder)) { Element funderLabel = xmlDoc.createElement("label"); Element funderId = xmlDoc.createElement("id"); //TODO @@ -1875,7 +1875,7 @@ public class DataManagementPlanManager { dmpElement.appendChild(funder); // Grant. Element grant = xmlDoc.createElement("grant"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first(), DmpBlueprintSystemFieldType.Grant)) { + if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Grant)) { Element grantLabel = xmlDoc.createElement("label"); Element grantId = xmlDoc.createElement("id"); //TODO @@ -1894,7 +1894,7 @@ public class DataManagementPlanManager { dmpElement.appendChild(grant); // Project. Element project = xmlDoc.createElement("project"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first(), DmpBlueprintSystemFieldType.Project)) { + if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Project)) { Element projectId = xmlDoc.createElement("id"); Element projectLabel = xmlDoc.createElement("label"); Element projectDescription = xmlDoc.createElement("description"); @@ -1945,7 +1945,7 @@ public class DataManagementPlanManager { Element extraFields = xmlDoc.createElement("extraFields"); Map dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference>() {}); - DefinitionEntity blueprint = new DefinitionEntity().fromXml(XmlBuilder.fromXml(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprint()).first().getDefinition()).getDocumentElement()); + DefinitionEntity blueprint = new DefinitionEntity().fromXml(XmlBuilder.fromXml(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first().getDefinition()).getDocumentElement()); blueprint.getSections().forEach(section -> { section.getFields().forEach(fieldModel -> { @@ -2330,7 +2330,7 @@ public class DataManagementPlanManager { dmp.setLabel(file.getOriginalFilename()); UserEntity me = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId()); dmp.setUpdatedAt(Instant.now()); - dmp.setCreator(me.getId()); + dmp.setCreatorId(me.getId()); //TODO // Map extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class); // extraProperties.put("contact", me.getId().toString()); @@ -2408,7 +2408,7 @@ public class DataManagementPlanManager { private void assignUser(DmpEntity dmp, UserEntity userInfo, DmpUserRole role) { DmpUserEntity userDMP = new DmpUserEntity(); userDMP.setDmp(dmp.getId()); - userDMP.setUser(userInfo.getId()); + userDMP.setUserId(userInfo.getId()); userDMP.setRole(role); databaseRepository.getUserDmpDao().createOrUpdate(userDMP); } @@ -2683,7 +2683,7 @@ public class DataManagementPlanManager { private void sendNotification(DmpEntity dmp, UserEntity user, NotificationType notificationType) throws InvalidApplicationException { List userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList(); for (DmpUserEntity userDMP : userDMPS) { - if (!userDMP.getUser().equals(user.getId())) { + if (!userDMP.getUserId().equals(user.getId())) { Notification notification = new Notification(); notification.setUserId(user); notification.setType(notificationType); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java index dfb6aaf09..6364e848c 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java @@ -32,6 +32,7 @@ import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.forms.VisibilityRuleService; import eu.eudat.logic.services.forms.VisibilityRuleServiceImpl; import eu.eudat.logic.services.operations.DatabaseRepository; +import eu.eudat.model.UserContactInfo; import eu.eudat.model.file.FileEnvelope; import eu.eudat.logic.utilities.documents.types.ParagraphStyle; import eu.eudat.logic.utilities.documents.word.WordBuilder; @@ -50,9 +51,11 @@ import eu.eudat.models.data.listingmodels.DatasetListingModel; import eu.eudat.models.data.user.composite.PagedDatasetProfile; import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpDescriptionTemplateQuery; +import eu.eudat.query.UserContactInfoQuery; import eu.eudat.queryable.QueryableList; import eu.eudat.types.MetricNames; import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.query.Ordering; import gr.cite.tools.data.query.QueryFactory; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; @@ -727,14 +730,14 @@ public class DatasetManager { private void sendNotification(DescriptionEntity descriptionEntity, DmpEntity dmp, UserEntity user, NotificationType notificationType) throws InvalidApplicationException { List userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList(); for (DmpUserEntity userDMP : userDMPS) { - if (!userDMP.getUser().equals(user.getId())) { + if (!userDMP.getUserId().equals(user.getId())) { Notification notification = new Notification(); notification.setUserId(user); notification.setType(notificationType); notification.setNotifyState(NotifyState.PENDING); notification.setIsActive(ActiveStatus.ACTIVE); notification.setData("{" + - "\"userId\": \"" + userDMP.getUser() + "\"" + + "\"userId\": \"" + userDMP.getUserId() + "\"" + ", \"id\": \"" + descriptionEntity.getId() + "\"" + ", \"name\": \"" + descriptionEntity.getLabel() + "\"" + ", \"path\": \"" + notificationPaths.get(notificationType) + "\"" + @@ -742,7 +745,10 @@ public class DatasetManager { notification.setCreatedAt(new Date()); notification.setUpdatedAt(notification.getCreatedAt()); notification.setContactTypeHint(ContactType.EMAIL); - //notification.setContactHint(databaseRepository.getUserInfoDao().find(userDMP.getUser()).getEmail()); //TODO: GetEmail + + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(userDMP.getUserId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + notification.setContactHint(query.first().getValue()); databaseRepository.getNotificationDao().createOrUpdate(notification); } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/InvitationsManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/InvitationsManager.java index 35cbf8a10..1b10e490a 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/InvitationsManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/InvitationsManager.java @@ -54,7 +54,7 @@ public class InvitationsManager { List userInfoToUserDmp = new LinkedList<>(); for (UserEntity userInfo : alreadySignedInUsersEntities) { DmpUserEntity userDMP = new DmpUserEntity(); - userDMP.setUser(userInfo.getId()); + userDMP.setUserId(userInfo.getId()); userDMP.setRole(DmpUserRole.of(invitation.getRole().shortValue())); userInfoToUserDmp.add(userDMP); /*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(principalUser, userInfo)) { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MergeEmailConfirmationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MergeEmailConfirmationManager.java index 586ddf2d4..e3df1a4e6 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MergeEmailConfirmationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MergeEmailConfirmationManager.java @@ -90,7 +90,7 @@ public class MergeEmailConfirmationManager { databaseRepository.getCredentialDao().createOrUpdate(credential); List userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList(); userDmps.forEach(userDmp -> { - userDmp.setUser(newUser.getId()); + userDmp.setUserId(newUser.getId()); databaseRepository.getUserDmpDao().createOrUpdate(userDmp); }); //TODO diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java index 7f98ab9ef..ea313e396 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java @@ -86,7 +86,7 @@ public class QuickWizardManager { private void assignUser(DmpEntity dmp, UserEntity userInfo, ApiContext apiContext) { DmpUserEntity userDMP = new DmpUserEntity(); userDMP.setDmp(dmp.getId()); - userDMP.setUser(userInfo.getId()); + userDMP.setUserId(userInfo.getId()); userDMP.setRole(DmpUserRole.User); apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java index 0c87e5ef8..bf42959f6 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java @@ -9,6 +9,10 @@ import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException; import eu.eudat.exceptions.emailconfirmation.TokenExpiredException; import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.operations.DatabaseRepository; +import eu.eudat.model.UserContactInfo; +import eu.eudat.query.UserContactInfoQuery; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -26,11 +30,13 @@ public class UnlinkEmailConfirmationManager { private ApiContext apiContext; private DatabaseRepository databaseRepository; + private final QueryFactory queryFactory; @Autowired - public UnlinkEmailConfirmationManager(ApiContext apiContext) { + public UnlinkEmailConfirmationManager(ApiContext apiContext, QueryFactory queryFactory) { this.apiContext = apiContext; this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.queryFactory = queryFactory; } @Transactional @@ -74,15 +80,16 @@ public class UnlinkEmailConfirmationManager { public void sendConfirmationEmail(String email, UUID userId, Integer provider) throws InvalidApplicationException { UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); -//TODO: GetEmail -// if (user.getEmail() != null && !user.getEmail().equals(email)) { -// apiContext.getUtilitiesService().getConfirmationEmailService().createUnlinkConfirmationEmail( -// databaseRepository.getLoginConfirmationEmailDao(), -// apiContext.getUtilitiesService().getMailService(), -// email, -// user, -// provider -// ); -// } + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + if (query.first().getValue() != null && !query.first().getValue().equals(email)) { + apiContext.getUtilitiesService().getConfirmationEmailService().createUnlinkConfirmationEmail( + databaseRepository.getLoginConfirmationEmailDao(), + apiContext.getUtilitiesService().getMailService(), + email, + user, + provider + ); + } } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java index 33e512dad..009b131dd 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java @@ -7,8 +7,12 @@ import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.dao.entities.EmailConfirmationDao; import eu.eudat.data.old.EmailConfirmation; import eu.eudat.data.UserEntity; +import eu.eudat.model.UserContactInfo; +import eu.eudat.query.UserContactInfoQuery; import eu.eudat.service.mail.MailService; import eu.eudat.service.mail.SimpleMail; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; @@ -27,11 +31,13 @@ public class ConfirmationEmailServiceImpl implements ConfirmationEmailService { //private Logger logger; private Environment environment; private final UserScope userScope; + private final QueryFactory queryFactory; - public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment, UserScope userScope) { + public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment, UserScope userScope, QueryFactory queryFactory) { // this.logger = logger; this.environment = environment; this.userScope = userScope; + this.queryFactory = queryFactory; } @Override @@ -173,7 +179,9 @@ public class ConfirmationEmailServiceImpl implements ConfirmationEmailService { public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UserEntity user, Integer provider) throws InvalidApplicationException { EmailConfirmation confirmationEmail = new EmailConfirmation(); -// confirmationEmail.setEmail(user.getEmail());//TODO: GetEmail + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + confirmationEmail.setEmail(query.first().getValue()); confirmationEmail.setExpiresAt(Date .from(new Date() .toInstant() diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java index bb43231d5..3d15be611 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java @@ -7,9 +7,13 @@ import eu.eudat.data.dao.entities.DMPDao; import eu.eudat.data.dao.entities.InvitationDao; import eu.eudat.data.old.Invitation; import eu.eudat.data.UserEntity; +import eu.eudat.model.UserContactInfo; import eu.eudat.models.data.invitation.Properties; +import eu.eudat.query.UserContactInfoQuery; import eu.eudat.service.mail.MailService; import eu.eudat.service.mail.SimpleMail; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -31,9 +35,11 @@ public class InvitationServiceImpl implements InvitationService { private Environment environment; @Autowired - public InvitationServiceImpl(Environment environment) { + public InvitationServiceImpl(Environment environment, QueryFactory queryFactory) { this.environment = environment; + this.queryFactory = queryFactory; } + private final QueryFactory queryFactory; @Override public void assignToDmp(DMPDao dmpDao, List users, DmpEntity dmp) { @@ -56,7 +62,9 @@ public class InvitationServiceImpl implements InvitationService { for (UserEntity userInfo : users) { Invitation invitation = new Invitation(); // invitation.setDmp(dmp); //TODO -// invitation.setInvitationEmail(userInfo.getEmail()); //TODO: GetEmail + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(userInfo.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); + invitation.setInvitationEmail(query.first().getValue()); invitation.setUser(creator); invitation.setToken(UUID.randomUUID()); invitation.setAcceptedInvitation(false); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/ContributorRDAMapper.java b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/ContributorRDAMapper.java index 9044a8913..e587e2f87 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/ContributorRDAMapper.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/ContributorRDAMapper.java @@ -9,14 +9,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -import java.util.*; public class ContributorRDAMapper { private static final Logger logger = LoggerFactory.getLogger(ContributorRDAMapper.class); public static Contributor toRDA(DmpUserEntity userDMP) { Contributor rda = new Contributor(); - rda.setContributorId(ContributorIdRDAMapper.toRDA(userDMP.getUser())); + rda.setContributorId(ContributorIdRDAMapper.toRDA(userDMP.getUserId())); // if (userDMP.getUser().getName() == null) { //TODO // throw new IllegalArgumentException("Contributor Name is missing"); // } diff --git a/dmp-backend/web/src/main/resources/config/db-devel.yml b/dmp-backend/web/src/main/resources/config/db-devel.yml index e0fe27a33..e5299bb04 100644 --- a/dmp-backend/web/src/main/resources/config/db-devel.yml +++ b/dmp-backend/web/src/main/resources/config/db-devel.yml @@ -7,4 +7,4 @@ spring: show-sql: true properties: hibernate: - format_sql: true \ No newline at end of file + format_sql: false \ No newline at end of file diff --git a/dmp-backend/web/src/main/resources/config/permissions.yml b/dmp-backend/web/src/main/resources/config/permissions.yml index b7bd7cf54..742d26662 100644 --- a/dmp-backend/web/src/main/resources/config/permissions.yml +++ b/dmp-backend/web/src/main/resources/config/permissions.yml @@ -168,6 +168,13 @@ permissions: allowAnonymous: false allowAuthenticated: false DeleteUser: + roles: + - Admin + claims: [ ] + clients: [ ] + allowAnonymous: false + allowAuthenticated: false + ExportUsers: roles: - Admin claims: [ ]