user changes

This commit is contained in:
Efstratios Giannopoulos 2023-11-20 17:09:24 +02:00
parent 3b3dc6fffd
commit 6de7268465
90 changed files with 1496 additions and 1015 deletions

View File

@ -19,6 +19,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>gr.cite</groupId>
<artifactId>validation</artifactId>

View File

@ -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");
}

View File

@ -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";

View File

@ -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;
}
}

View File

@ -86,9 +86,9 @@ public class DmpEntity implements DataEntity<DmpEntity, UUID> {
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<DmpEntity, UUID> {
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<DmpEntity, UUID> {
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<DmpEntity, UUID> {
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() {

View File

@ -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() {

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -21,8 +21,8 @@ public class UserDescriptionTemplateEntity implements DataEntity<UserDescription
public static final String _id = "id";
@Column(name = "\"user\"", nullable = false)
private UUID user;
public static final String _user = "user";
private UUID userId;
public static final String _userId = "userId";
@Column(name = "is_active", nullable = false)
@Convert(converter = IsActiveConverter.class)
@ -39,8 +39,8 @@ public class UserDescriptionTemplateEntity implements DataEntity<UserDescription
public static final String _updatedAt = "updatedAt";
@Column(name = "\"description_template\"", nullable = false)
private UUID descriptionTemplate;
public static final String _descriptionTemplate = "descriptionTemplate";
private UUID descriptionTemplateId;
public static final String _descriptionTemplateId = "descriptionTemplateId";
@Column(name = "role", nullable = false)
@Convert(converter = UserDescriptionTemplateRoleConverter.class)
@ -55,12 +55,12 @@ public class UserDescriptionTemplateEntity implements DataEntity<UserDescription
this.id = id;
}
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 IsActive getIsActive() {
@ -87,12 +87,12 @@ public class UserDescriptionTemplateEntity implements DataEntity<UserDescription
this.updatedAt = updatedAt;
}
public UUID getDescriptionTemplate() {
return descriptionTemplate;
public UUID getDescriptionTemplateId() {
return descriptionTemplateId;
}
public void setDescriptionTemplate(UUID descriptionTemplate) {
this.descriptionTemplate = descriptionTemplate;
public void setDescriptionTemplateId(UUID descriptionTemplateId) {
this.descriptionTemplateId = descriptionTemplateId;
}
public UserDescriptionTemplateRole getRole() {

View File

@ -58,7 +58,7 @@ public class DmpElasticBuilder extends BaseElasticBuilder<DmpElasticEntity, DmpE
m.setStatus(d.getStatus());
m.setAccessType(d.getAccessType());
m.setLanguage(d.getLanguage());
m.setBlueprintId(d.getBlueprint());
m.setBlueprintId(d.getBlueprintId());
m.setGroupId(d.getGroupId());
m.setFinalizedAt(Date.from(d.getFinalizedAt()));
if (referenceElasticEntityMap != null) m.setReferences(referenceElasticEntityMap.getOrDefault(d.getId(), null));

View File

@ -36,7 +36,7 @@ public class NestedCollaboratorElasticBuilder extends BaseElasticBuilder<NestedC
NestedCollaboratorElasticEntity m = new NestedCollaboratorElasticEntity();
m.setId(d.getId());
m.setRole(d.getRole());
m.setName(d.getUser().toString()); //TODO: Get UserName
m.setName(d.getUserId().toString()); //TODO: Get UserName
models.add(m);
}
this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0));

View File

@ -60,7 +60,7 @@ public class NestedDmpElasticBuilder extends BaseElasticBuilder<NestedDmpElastic
m.setStatus(d.getStatus());
m.setAccessType(d.getAccessType());
m.setLanguage(d.getLanguage());
m.setBlueprintId(d.getBlueprint());
m.setBlueprintId(d.getBlueprintId());
m.setGroupId(d.getGroupId());
m.setGroupId(d.getGroupId());
m.setVersionStatus(d.getVersionStatus());

View File

@ -6,15 +6,11 @@ public class UserTouchedEvent {
public UserTouchedEvent() {
}
public UserTouchedEvent(UUID userId, String subjectId, String previousSubjectId) {
public UserTouchedEvent(UUID userId) {
this.userId = userId;
this.subjectId = subjectId;
this.previousSubjectId = previousSubjectId;
}
private UUID userId;
private String subjectId;
private String previousSubjectId;
public UUID getUserId() {
return userId;
@ -23,20 +19,4 @@ public class UserTouchedEvent {
public void setUserId(UUID userId) {
this.userId = userId;
}
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getPreviousSubjectId() {
return previousSubjectId;
}
public void setPreviousSubjectId(String previousSubjectId) {
this.previousSubjectId = previousSubjectId;
}
}

View File

@ -31,7 +31,7 @@ public class Description {
public static final String _description = "description";
private UUID createdBy;
private User createdBy;
public static final String _createdBy = "createdBy";
@ -112,11 +112,11 @@ public class Description {
this.description = description;
}
public UUID getCreatedBy() {
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UUID createdBy) {
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}

View File

@ -31,6 +31,10 @@ public class DescriptionReference {
public static final String _isActive = "isActive";
private String hash;
public static final String _hash = "hash";
public UUID getId() {
return id;
}
@ -79,4 +83,11 @@ public class DescriptionReference {
this.isActive = isActive;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -31,6 +31,10 @@ public class DescriptionTag {
public static final String _isActive = "isActive";
private String hash;
public static final String _hash = "hash";
public UUID getId() {
return id;
}
@ -79,4 +83,11 @@ public class DescriptionTag {
this.isActive = isActive;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -63,7 +63,7 @@ public class Dmp {
public static final String _publishedAt = "publishedAt";
private UUID creator;
private User creator;
public static final String _creator = "creator";
@ -71,7 +71,7 @@ public class Dmp {
public static final String _accessType = "accessType";
private UUID blueprint;
private DmpBlueprint blueprint;
public static final String _blueprint = "blueprint";
@ -191,11 +191,11 @@ public class Dmp {
this.publishedAt = publishedAt;
}
public UUID getCreator() {
public User getCreator() {
return creator;
}
public void setCreator(UUID creator) {
public void setCreator(User creator) {
this.creator = creator;
}
@ -207,11 +207,11 @@ public class Dmp {
this.accessType = accessType;
}
public UUID getBlueprint() {
public DmpBlueprint getBlueprint() {
return blueprint;
}
public void setBlueprint(UUID blueprint) {
public void setBlueprint(DmpBlueprint blueprint) {
this.blueprint = blueprint;
}

View File

@ -37,6 +37,9 @@ public class DmpDescriptionTemplate{
public static final String _isActive = "isActive";
public final static String _hash = "hash";
private String hash;
public UUID getId() {
return id;
}
@ -92,4 +95,12 @@ public class DmpDescriptionTemplate{
public void setIsActive(IsActive isActive) {
this.isActive = isActive;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -24,6 +24,9 @@ public class DmpReference {
public static final String _updatedAt = "updatedAt";
public final static String _hash = "hash";
private String hash;
public UUID getId() {
return id;
}
@ -63,4 +66,12 @@ public class DmpReference {
public Instant getUpdatedAt() {return updatedAt;}
public void setUpdatedAt(Instant updatedAt) {this.updatedAt = updatedAt;}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -19,30 +19,27 @@ public class DmpUser {
public static final String _dmp = "dmp";
@Column(name = "user", columnDefinition = "uuid", nullable = false)
private UserEntity user;
private User user;
public static final String _user = "user";
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private String hash;
public final static String _hash = "hash";
private DmpUserRole role;
public static final String _role = "role";
@Column(name = "created_at", nullable = false)
private Instant createdAt;
public static final String _createdAt = "createdAt";
@Column(name = "updated_at", nullable = false)
private Instant updatedAt;
public static final String _updatedAt = "updatedAt";
@Column(name = "is_active", nullable = false)
@Convert(converter = IsActiveConverter.class)
private IsActive isActive;
public static final String _isActive = "isActive";
public UUID getId() {
return id;
@ -60,11 +57,11 @@ public class DmpUser {
this.dmp = dmp;
}
public UserEntity getUser() {
public User getUser() {
return user;
}
public void setUser(UserEntity user) {
public void setUser(User user) {
this.user = user;
}
@ -100,4 +97,11 @@ public class DmpUser {
this.isActive = isActive;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -47,12 +47,15 @@ public class Reference {
private Instant updatedAt;
public static final String _updatedAt = "updatedAt";
//private UserInfo createdBy; ToDo
//public static final String _createdBy = "createdBy";
private User createdBy;
public static final String _createdBy = "createdBy";
private List<DmpReference> 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<DmpReference> 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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}

View File

@ -18,6 +18,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;
}
}

View File

@ -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;
}
}

View File

@ -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<Description, DescriptionEnti
FieldSet descriptionTagsFields = fields.extractPrefixed(this.asPrefix(Description._descriptionTags));
Map<UUID, List<DescriptionTag>> descriptionTagsMap = this.collectDescriptionTags(descriptionTagsFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(Description._createdBy));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
FieldSet definitionPropertiesFields = fields.extractPrefixed(this.asPrefix(Description._properties));
List<Description> models = new ArrayList<>();
for (DescriptionEntity d : data) {
@ -79,7 +82,6 @@ public class DescriptionBuilder extends BaseBuilder<Description, DescriptionEnti
if (fields.hasField(this.asIndexer(Description._label))) m.setLabel(d.getLabel());
if (fields.hasField(this.asIndexer(Description._status))) m.setStatus(d.getStatus());
if (fields.hasField(this.asIndexer(Description._description))) m.setDescription(d.getDescription());
if (fields.hasField(this.asIndexer(Description._createdBy))) m.setCreatedBy(d.getCreatedById());
if (fields.hasField(this.asIndexer(Description._createdAt))) m.setCreatedAt(d.getCreatedAt());
if (fields.hasField(this.asIndexer(Description._updatedAt))) m.setUpdatedAt(d.getUpdatedAt());
if (fields.hasField(this.asIndexer(Description._isActive))) m.setIsActive(d.getIsActive());
@ -89,6 +91,7 @@ public class DescriptionBuilder extends BaseBuilder<Description, DescriptionEnti
if (!dmpDescriptionTemplateFields.isEmpty() && dmpDescriptionTemplateItemsMap != null && dmpDescriptionTemplateItemsMap.containsKey(d.getDmpDescriptionTemplateId())) m.setDmpDescriptionTemplate(dmpDescriptionTemplateItemsMap.get(d.getDmpDescriptionTemplateId()));
if (!descriptionReferencesFields.isEmpty() && descriptionReferencesMap != null && descriptionReferencesMap.containsKey(d.getId())) m.setDescriptionReferences(descriptionReferencesMap.get(d.getId()));
if (!descriptionTagsFields.isEmpty() && descriptionTagsMap != null && descriptionTagsMap.containsKey(d.getId())) m.setDescriptionTags(descriptionTagsMap.get(d.getId()));
if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById()));
if (!definitionPropertiesFields.isEmpty() && d.getProperties() != null){
PropertyDefinitionEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(PropertyDefinitionEntity.class, d.getProperties());
m.setProperties(this.builderFactory.builder(PropertyDefinitionBuilder.class).authorize(this.authorize).build(definitionPropertiesFields, propertyDefinition));
@ -101,6 +104,36 @@ public class DescriptionBuilder extends BaseBuilder<Description, DescriptionEnti
return models;
}
private Map<UUID, User> collectUsers(FieldSet fields, List<DescriptionEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, User> 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<UUID, DmpDescriptionTemplate> collectDmpDescriptionTemplates(FieldSet fields, List<DescriptionEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;

View File

@ -65,22 +65,13 @@ public class DescriptionReferenceBuilder extends BaseBuilder<DescriptionReferenc
for (DescriptionReferenceEntity d : data) {
DescriptionReference m = new DescriptionReference();
if (fields.hasField(this.asIndexer(DescriptionReference._id)))
m.setId(d.getId());
if (fields.hasField(this.asIndexer(DescriptionReference._createdAt)))
m.setCreatedAt(d.getCreatedAt());
if (fields.hasField(this.asIndexer(DescriptionReference._updatedAt)))
m.setUpdatedAt(d.getUpdatedAt());
if (fields.hasField(this.asIndexer(DescriptionReference._isActive)))
m.setIsActive(d.getIsActive());
if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) {
m.setReference(referenceItemsMap.get(d.getReferenceId()));
}
if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) {
m.setDescription(descriptionItemsMap.get(d.getDescriptionId()));
}
if (fields.hasField(this.asIndexer(DescriptionReference._id))) m.setId(d.getId());
if (fields.hasField(this.asIndexer(DescriptionReference._createdAt))) m.setCreatedAt(d.getCreatedAt());
if (fields.hasField(this.asIndexer(DescriptionReference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt());
if (fields.hasField(this.asIndexer(DescriptionReference._hash))) m.setHash(this.hashValue(d.getUpdatedAt()));
if (fields.hasField(this.asIndexer(DescriptionReference._isActive))) m.setIsActive(d.getIsActive());
if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) m.setReference(referenceItemsMap.get(d.getReferenceId()));
if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) m.setDescription(descriptionItemsMap.get(d.getDescriptionId()));
models.add(m);
}

View File

@ -55,8 +55,8 @@ public class DescriptionTagBuilder extends BaseBuilder<DescriptionTag, Descripti
if (fields == null || data == null || fields.isEmpty())
return new ArrayList<>();
FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag));
Map<UUID, Tag> referenceItemsMap = this.collectTags(referenceFields, data);
FieldSet tagFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag));
Map<UUID, Tag> tagItemsMap = this.collectTags(tagFields, data);
FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._description));
Map<UUID, Description> descriptionItemsMap = this.collectDescriptions(descriptionFields, data);
@ -69,7 +69,8 @@ public class DescriptionTagBuilder extends BaseBuilder<DescriptionTag, Descripti
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 (fields.hasField(this.asIndexer(DescriptionTag._hash))) m.setHash(this.hashValue(d.getUpdatedAt()));
if (!tagFields.isEmpty() && tagItemsMap != null && tagItemsMap.containsKey(d.getTagId())) m.setTag(tagItemsMap.get(d.getTagId()));
if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) m.setDescription(descriptionItemsMap.get(d.getDescriptionId()));
models.add(m);

View File

@ -4,9 +4,10 @@ import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DmpEntity;
import eu.eudat.model.*;
import eu.eudat.query.DescriptionQuery;
import eu.eudat.query.DmpBlueprintQuery;
import eu.eudat.query.DmpReferenceQuery;
import eu.eudat.query.DmpUserQuery;
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 +63,12 @@ public class DmpBuilder extends BaseBuilder<Dmp, DmpEntity> {
FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpUsers));
Map<UUID, List<DmpUser>> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(Dmp._creator));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
FieldSet blueprintFields = fields.extractPrefixed(this.asPrefix(Dmp._blueprint));
Map<UUID, DmpBlueprint> 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<Dmp, DmpEntity> {
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()));
@ -109,6 +117,66 @@ public class DmpBuilder extends BaseBuilder<Dmp, DmpEntity> {
return itemMap;
}
private Map<UUID, DmpBlueprint> collectDmpBlueprints(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", DmpBlueprint.class.getSimpleName());
Map<UUID, DmpBlueprint> 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<UUID, User> collectUsers(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, User> 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<UUID, List<DmpUser>> collectDmpUsers(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;

View File

@ -62,20 +62,13 @@ public class DmpDescriptionTemplateBuilder extends BaseBuilder<DmpDescriptionTem
List<DmpDescriptionTemplate> 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));

View File

@ -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<DmpReference, DmpReferenceE
List<DmpReference> 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));

View File

@ -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<DmpUser, DmpUserEntity>{
if (fields == null || data == null || fields.isEmpty())
return new ArrayList<>();
FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpUser._user));
Map<UUID, UserEntity> userItemsMap = this.collectUsers(userFields, data);
FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpUser._dmp));
Map<UUID, Dmp> dmpItemsMap = this.collectDmps(dmpFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpUser._user));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
List<DmpUser> 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<UUID, UserEntity> collectUsers(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {
private Map<UUID, User> collectUsers(FieldSet fields, List<DmpUserEntity> 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<UUID, UserEntity> itemMap;
if (!fields.hasOtherField(this.asIndexer("id"))) {
Map<UUID, User> 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<UUID, Dmp> collectDmps(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {

View File

@ -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<PublicDmpUser, DmpUserEnti
return new ArrayList<>();
FieldSet userFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._user));
Map<UUID, PublicUser> userItemsMap = new HashMap<>(); //TODO
Map<UUID, PublicUser> userItemsMap = this.collectUsers(userFields, data);
FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._dmp));
Map<UUID, PublicDmp> dmpItemsMap = this.collectDmps(dmpFields, data);
@ -65,7 +68,7 @@ public class PublicDmpUserBuilder extends BaseBuilder<PublicDmpUser, DmpUserEnti
PublicDmpUser m = new PublicDmpUser();
if (fields.hasField(this.asIndexer(PublicDmpUser._id))) m.setId(d.getId());
if (fields.hasField(this.asIndexer(PublicDmpUser._role))) m.setRole(d.getRole());
if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUser())) m.setUser(userItemsMap.get(d.getUser()));
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()));
models.add(m);
}
@ -73,6 +76,36 @@ public class PublicDmpUserBuilder extends BaseBuilder<PublicDmpUser, DmpUserEnti
return models;
}
private Map<UUID, PublicUser> collectUsers(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, PublicUser> 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<UUID, PublicDmp> collectDmps(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;

View File

@ -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<User, UserEntity> {
private final QueryFactory queryFactory;
private final BuilderFactory builderFactory;
private final JsonHandlingService jsonHandlingService;
public class PublicUserBuilder extends BaseBuilder<PublicUser, UserEntity> {
private EnumSet<AuthorizationFlags> 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<AuthorizationFlags> values) {
public PublicUserBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<User> build(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
public List<PublicUser> build(FieldSet fields, List<UserEntity> 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<User> models = new ArrayList<>();
List<PublicUser> models = new ArrayList<>();
FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(User._contacts));
Map<UUID, List<UserContactInfo>> contactsMap = this.collectUserContactInfos(contactsFields, data);
FieldSet rolesFields = fields.extractPrefixed(this.asPrefix(User._roles));
Map<UUID, List<UserRole>> rolesMap = this.collectUserRoles(rolesFields, data);
FieldSet credentialsFields = fields.extractPrefixed(this.asPrefix(User._credentials));
Map<UUID, List<UserCredential>> 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<User, UserEntity> {
return models;
}
private Map<UUID, List<UserContactInfo>> collectUserContactInfos(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName());
Map<UUID, List<UserContactInfo>> 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<UUID, List<UserRole>> collectUserRoles(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", UserRole.class.getSimpleName());
Map<UUID, List<UserRole>> 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<UUID, List<UserCredential>> collectUserCredentials(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", UserCredential.class.getSimpleName());
Map<UUID, List<UserCredential>> 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;
}
}

View File

@ -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<Reference, ReferenceEntity>{
FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Reference._dmpReferences));
Map<UUID, List<DmpReference>> dmpReferenceMap = this.collectDmpReferences(dmpReferencesFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(Reference._createdBy));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
List<Reference> models = new ArrayList<>();
for (ReferenceEntity d : data) {
Reference m = new Reference();
@ -70,6 +76,7 @@ public class ReferenceBuilder extends BaseBuilder<Reference, ReferenceEntity>{
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<Reference, ReferenceEntity>{
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<UUID, User> collectUsers(FieldSet fields, List<ReferenceEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, User> 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<UUID, List<DmpReference>> collectDmpReferences(FieldSet fields, List<ReferenceEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", DmpReference.class.getSimpleName());

View File

@ -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<SupportiveMaterial, S
if (fields.hasField(this.asIndexer(SupportiveMaterial._createdAt))) m.setCreatedAt(d.getCreatedAt());
if (fields.hasField(this.asIndexer(SupportiveMaterial._updatedAt))) m.setUpdatedAt(d.getUpdatedAt());
if (fields.hasField(this.asIndexer(SupportiveMaterial._isActive))) m.setIsActive(d.getIsActive());
if (fields.hasField(this.asIndexer(SupportiveMaterial._hash))) m.setHash(this.hashValue(d.getUpdatedAt()));
models.add(m);
}
this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0));

View File

@ -4,7 +4,12 @@ import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.TagEntity;
import eu.eudat.model.Tag;
import eu.eudat.model.User;
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;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.DataLogEntry;
import gr.cite.tools.logging.LoggerService;
@ -15,17 +20,23 @@ 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 TagBuilder extends BaseBuilder<Tag, TagEntity>{
private final QueryFactory queryFactory;
private final BuilderFactory builderFactory;
private EnumSet<AuthorizationFlags> 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<AuthorizationFlags> values) {
@ -40,6 +51,9 @@ public class TagBuilder extends BaseBuilder<Tag, TagEntity>{
if (fields == null || data == null || fields.isEmpty())
return new ArrayList<>();
FieldSet userFields = fields.extractPrefixed(this.asPrefix(Tag._createdBy));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
List<Tag> models = new ArrayList<>();
for (TagEntity d : data) {
Tag m = new Tag();
@ -48,10 +62,40 @@ public class TagBuilder extends BaseBuilder<Tag, TagEntity>{
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<UUID, User> collectUsers(FieldSet fields, List<TagEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, User> 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;
}
}

View File

@ -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<UserCredential, UserCredentialEntity> {
public class UserAdditionalInfoBuilder extends BaseBuilder<UserAdditionalInfo, AdditionalInfoEntity> {
private final BuilderFactory builderFactory;
private final QueryFactory queryFactory;
private EnumSet<AuthorizationFlags> 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<AuthorizationFlags> values) {
public UserAdditionalInfoBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<UserCredential> build(FieldSet fields, List<UserCredentialEntity> data) throws MyApplicationException {
public List<UserAdditionalInfo> build(FieldSet fields, List<AdditionalInfoEntity> 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<UUID, User> userItemsMap = this.collectUsers(userFields, data);
FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._reference));
Map<UUID, Reference> referenceItemsMap = this.collectReferences(referenceFields, data);
List<UserCredential> models = new ArrayList<>();
List<UserAdditionalInfo> 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<UserCredential, UserCrede
return models;
}
private Map<UUID, User> collectUsers(FieldSet fields, List<UserCredentialEntity> data) throws MyApplicationException {
private Map<UUID, Reference> collectReferences(FieldSet fields, List<AdditionalInfoEntity> 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<UUID, User> itemMap;
if (!fields.hasOtherField(this.asIndexer(User._id))) {
Map<UUID, Reference> 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<UserCredential, UserCrede
return itemMap;
}
}

View File

@ -1,12 +1,14 @@
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.DmpEntity;
import eu.eudat.data.UserEntity;
import eu.eudat.model.*;
import eu.eudat.query.DescriptionQuery;
import eu.eudat.query.DmpReferenceQuery;
import eu.eudat.query.DmpUserQuery;
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 gr.cite.tools.exception.MyApplicationException;
@ -25,65 +27,64 @@ import java.util.stream.Collectors;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DmpBuilder extends BaseBuilder<Dmp, DmpEntity> {
public class UserBuilder extends BaseBuilder<User, UserEntity> {
private final QueryFactory queryFactory;
private final BuilderFactory builderFactory;
private final JsonHandlingService jsonHandlingService;
private EnumSet<AuthorizationFlags> authorize = EnumSet.of(AuthorizationFlags.None);
@Autowired
public DmpBuilder(ConventionService conventionService,
public UserBuilder(ConventionService conventionService,
QueryFactory queryFactory,
BuilderFactory builderFactory) {
super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBuilder.class)));
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<AuthorizationFlags> values) {
public UserBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<Dmp> build(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
public List<User> build(FieldSet fields, List<UserEntity> 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<Dmp> models = new ArrayList<>();
List<User> models = new ArrayList<>();
FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpReferences));
Map<UUID, List<DmpReference>> dmpReferencesMap = this.collectDmpReferences(dmpReferencesFields, data);
FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(User._contacts));
Map<UUID, List<UserContactInfo>> contactsMap = this.collectUserContactInfos(contactsFields, data);
FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpUsers));
Map<UUID, List<DmpUser>> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data);
FieldSet rolesFields = fields.extractPrefixed(this.asPrefix(User._roles));
Map<UUID, List<UserRole>> 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<UUID, List<UserCredential>> 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<Dmp, DmpEntity> {
return models;
}
private Map<UUID, List<DmpReference>> collectDmpReferences(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
private Map<UUID, List<UserContactInfo>> collectUserContactInfos(FieldSet fields, List<UserEntity> 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<UUID, List<DmpReference>> 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<UUID, List<UserContactInfo>> 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<UUID, List<DmpUser>> collectDmpUsers(FieldSet fields, List<DmpEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", DmpUser.class.getSimpleName());
private Map<UUID, List<UserRole>> collectUserRoles(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", UserRole.class.getSimpleName());
Map<UUID, List<DmpUser>> 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<UUID, List<UserRole>> 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<UUID, List<UserCredential>> collectUserCredentials(FieldSet fields, List<UserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty()) return null;
this.logger.debug("checking related - {}", UserCredential.class.getSimpleName());
Map<UUID, List<UserCredential>> 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);
});
}

View File

@ -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<DescriptionTag, DescriptionTagEntity> {
public class UserContactInfoBuilder extends BaseBuilder<UserContactInfo, UserContactInfoEntity> {
private final BuilderFactory builderFactory;
@ -35,42 +36,39 @@ public class DescriptionTagBuilder extends BaseBuilder<DescriptionTag, Descripti
private EnumSet<AuthorizationFlags> 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<AuthorizationFlags> values) {
public UserContactInfoBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<DescriptionTag> build(FieldSet fields, List<DescriptionTagEntity> data) throws MyApplicationException {
public List<UserContactInfo> build(FieldSet fields, List<UserContactInfoEntity> 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<UUID, Tag> referenceItemsMap = this.collectTags(referenceFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserContactInfo._user));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._description));
Map<UUID, Description> descriptionItemsMap = this.collectDescriptions(descriptionFields, data);
List<UserContactInfo> models = new ArrayList<>();
List<DescriptionTag> 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<DescriptionTag, Descripti
return models;
}
private Map<UUID, Description> collectDescriptions(FieldSet fields, List<DescriptionTagEntity> data) throws MyApplicationException {
private Map<UUID, User> collectUsers(FieldSet fields, List<UserContactInfoEntity> 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<UUID, Description> itemMap;
if (!fields.hasOtherField(this.asIndexer(Tag._id))) {
Map<UUID, User> 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<UUID, Tag> collectTags(FieldSet fields, List<DescriptionTagEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", Tag.class.getSimpleName());
Map<UUID, Tag> 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);

View File

@ -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;

View File

@ -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<UserDescriptionT
FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asPrefix(UserDescriptionTemplate._descriptionTemplate));
Map<UUID, DescriptionTemplate> descriptionTemplateMap = this.collectDescriptionTemplates(descriptionTemplateFields, data);
FieldSet userFields = fields.extractPrefixed(this.asPrefix(Description._createdBy));
Map<UUID, User> userItemsMap = this.collectUsers(userFields, data);
List<UserDescriptionTemplate> models = new ArrayList<>();
for (UserDescriptionTemplateEntity d : data) {
@ -66,13 +71,44 @@ public class UserDescriptionTemplateBuilder extends BaseBuilder<UserDescriptionT
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._isActive))) m.setIsActive(d.getIsActive());
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._role))) m.setRole(d.getRole());
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._hash))) m.setHash(this.hashValue(d.getUpdatedAt()));
if (!descriptionTemplateFields.isEmpty() && descriptionTemplateMap != null && descriptionTemplateMap.containsKey(d.getDescriptionTemplate())) m.setDescriptionTemplate(descriptionTemplateMap.get(d.getDescriptionTemplate()));
if (!descriptionTemplateFields.isEmpty() && descriptionTemplateMap != null && descriptionTemplateMap.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(descriptionTemplateMap.get(d.getDescriptionTemplateId()));
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;
}
private Map<UUID, User> collectUsers(FieldSet fields, List<UserDescriptionTemplateEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", User.class.getSimpleName());
Map<UUID, User> 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<UUID, DescriptionTemplate> collectDescriptionTemplates(FieldSet fields, List<UserDescriptionTemplateEntity> 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<UserDescriptionT
Map<UUID, DescriptionTemplate> 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<UserDescriptionT
x -> 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)) {

View File

@ -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<UserContactInfo, UserContactInfoEntity> {
public class UserRoleBuilder extends BaseBuilder<UserRole, UserRoleEntity> {
private final BuilderFactory builderFactory;
@ -36,38 +33,36 @@ public class UserContactInfoBuilder extends BaseBuilder<UserContactInfo, UserCon
private EnumSet<AuthorizationFlags> 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<AuthorizationFlags> values) {
public UserRoleBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<UserContactInfo> build(FieldSet fields, List<UserContactInfoEntity> data) throws MyApplicationException {
public List<UserRole> build(FieldSet fields, List<UserRoleEntity> 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<UUID, User> userItemsMap = this.collectUsers(userFields, data);
List<UserContactInfo> models = new ArrayList<>();
List<UserRole> 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<UserContactInfo, UserCon
return models;
}
private Map<UUID, User> collectUsers(FieldSet fields, List<UserContactInfoEntity> data) throws MyApplicationException {
private Map<UUID, User> collectUsers(FieldSet fields, List<UserRoleEntity> 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<UserContactInfo, UserCon
Map<UUID, User> 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<UserContactInfo, UserCon
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(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList()));
UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserRoleEntity::getUserId).distinct().collect(Collectors.toList()));
itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId);
}
if (!fields.hasField(User._id)) {

View File

@ -54,9 +54,8 @@ public class DescriptionCensor extends BaseCensor {
FieldSet propertiesFields = fields.extractPrefixed(this.asIndexerPrefix(Description._properties));
this.censorFactory.censor(PropertyDefinitionCensor.class).censor(propertiesFields, userId);
//ToDo
// FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Description._createdBy));
// this.censorFactory.censor(UserInfo.class).censor(createdByFields, userId);
FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Description._createdBy));
this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId);
}
}

View File

@ -44,6 +44,8 @@ public class DmpCensor extends BaseCensor {
this.censorFactory.censor(DmpUserCensor.class).censor(dmpUsersFields, userId);
FieldSet dmpReferencesFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._dmpReferences));
this.censorFactory.censor(DmpReferenceCensor.class).censor(dmpReferencesFields, userId);
FieldSet creatorFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._creator));
this.censorFactory.censor(UserCensor.class).censor(creatorFields, userId);
}
}

View File

@ -40,6 +40,8 @@ public class DmpUserCensor extends BaseCensor {
this.authService.authorizeForce(Permission.BrowseDmpUser);
FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(DmpUser._dmp));
this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId);
FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(DmpUser._user));
this.censorFactory.censor(UserCensor.class).censor(userFields, userId);
}
}

View File

@ -43,9 +43,8 @@ public class ReferenceCensor extends BaseCensor {
this.censorFactory.censor(DefinitionCensor.class).censor(definitionFields, userId);
FieldSet dmpReferencesFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._dmpReferences));
this.censorFactory.censor(DmpReferenceCensor.class).censor(dmpReferencesFields, userId);
//ToDo
//FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._createdBy));
//this.censorFactory.censor(UserInfo.class).censor(definitionFields, userId);
FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._createdBy));
this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId);
}
}

View File

@ -40,9 +40,8 @@ public class TagCensor extends BaseCensor {
return;
this.authService.authorizeForce(Permission.BrowseTag);
//ToDo
// FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Tag._createdBy));
// this.censorFactory.censor(UserInfo.class).censor(createdByFields, userId);
FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Tag._createdBy));
this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId);
}
}

View File

@ -38,8 +38,10 @@ public class UserDescriptionTemplateCensor extends BaseCensor {
return;
this.authService.authorizeForce(Permission.BrowseDescriptionTemplate);
FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._descriptionTemplate));
this.censorFactory.censor(DescriptionTemplateCensor.class).censor(userFields, userId);
FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._descriptionTemplate));
this.censorFactory.censor(DescriptionTemplateCensor.class).censor(descriptionTemplateFields, userId);
FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._user));
this.censorFactory.censor(UserCensor.class).censor(userFields, userId);
}
}

View File

@ -0,0 +1,68 @@
package eu.eudat.model.deleter;
import eu.eudat.data.UserContactInfoEntity;
import eu.eudat.query.UserContactInfoQuery;
import gr.cite.tools.data.deleter.Deleter;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import jakarta.persistence.EntityManager;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserContactInfoDeleter implements Deleter {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoDeleter.class));
private final EntityManager entityManager;
protected final QueryFactory queryFactory;
@Autowired
public UserContactInfoDeleter(
EntityManager entityManager,
QueryFactory queryFactory
) {
this.entityManager = entityManager;
this.queryFactory = queryFactory;
}
public void deleteAndSaveByIds(List<UUID> ids) throws InvalidApplicationException {
logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids));
List<UserContactInfoEntity> 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<UserContactInfoEntity> 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<UserContactInfoEntity> 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");
}
}
}

View File

@ -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<UUID> ids) throws InvalidApplicationException {
logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids));
List<UserContactInfoEntity> data = this.queryFactory.query(UserContactInfoQuery.class).ids(ids).collect();
List<UserCredentialEntity> 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<UserContactInfoEntity> data) throws InvalidApplicationException {
public void deleteAndSave(List<UserCredentialEntity> 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<UserContactInfoEntity> data) throws InvalidApplicationException {
public void delete(List<UserCredentialEntity> 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);

View File

@ -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<UUID> ids) throws InvalidApplicationException {
logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids));
List<TagEntity> data = this.queryFactory.query(TagQuery.class).ids(ids).collect();
List<UserEntity> 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<TagEntity> data) throws InvalidApplicationException {
public void deleteAndSave(List<UserEntity> 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<TagEntity> data) throws InvalidApplicationException {
public void delete(List<UserEntity> data) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0));
if (data == null || data.isEmpty())
return;
List<UUID> ids = data.stream().map(TagEntity::getId).distinct().collect(Collectors.toList());
List<UUID> ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList());
{
logger.debug("checking related - {}", DescriptionTagEntity.class.getSimpleName());
List<DescriptionTagEntity> items = this.queryFactory.query(DescriptionTagQuery.class).tagIds(ids).collect();
DescriptionTagDeleter deleter = this.deleterFactory.deleter(DescriptionTagDeleter.class);
logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName());
List<UserRoleEntity> 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<UserCredentialEntity> 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<UserContactInfoEntity> 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<DmpUserEntity> 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);

View File

@ -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<UUID> ids) throws InvalidApplicationException {
logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids));
List<UserEntity> data = this.queryFactory.query(UserQuery.class).ids(ids).collect();
List<UserRoleEntity> 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<UserEntity> data) throws InvalidApplicationException {
public void deleteAndSave(List<UserRoleEntity> 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<UserEntity> data) throws InvalidApplicationException {
public void delete(List<UserRoleEntity> data) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0));
if (data == null || data.isEmpty())
return;
List<UUID> ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList());
{
logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName());
List<UserRoleEntity> 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");
}
}

View File

@ -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;

View File

@ -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;
}
}

View File

@ -2,31 +2,42 @@ 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;
}
}

View File

@ -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<String> 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<String> getRoles() {
return roles;
}
public void setName(String name) {
this.name = name;
public void setRoles(List<String> 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;
}
}

View File

@ -263,6 +263,7 @@ public class DescriptionQuery extends QueryBase<DescriptionEntity> {
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;

View File

@ -166,7 +166,7 @@ public class DescriptionReferenceQuery extends QueryBase<DescriptionReferenceEnt
));
predicates.add(queryContext.CriteriaBuilder.in(queryContext.Root.get(DescriptionReferenceEntity._descriptionId)).value(descriptionSubquery));
}
if (predicates.size() > 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<DescriptionReferenceEnt
else if (item.prefix(DescriptionReference._reference)) return DescriptionReferenceEntity._referenceId;
else if (item.match(DescriptionReference._createdAt)) return DescriptionReferenceEntity._createdAt;
else if (item.match(DescriptionReference._updatedAt)) return DescriptionReferenceEntity._updatedAt;
else if (item.match(DescriptionReference._hash)) return DescriptionReferenceEntity._updatedAt;
else if (item.match(DescriptionReference._isActive)) return DescriptionReferenceEntity._isActive;
else return null;
}

View File

@ -234,6 +234,7 @@ public class DescriptionTagQuery extends QueryBase<DescriptionTagEntity> {
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;
}

View File

@ -225,6 +225,7 @@ public class DmpDescriptionTemplateQuery extends QueryBase<DmpDescriptionTemplat
else if (item.prefix(DmpDescriptionTemplate._dmp) || item.prefix(PublicDmpDescriptionTemplate._dmp)) return DmpDescriptionTemplateEntity._dmpId;
else if (item.prefix(DmpDescriptionTemplate._descriptionTemplate) || item.prefix(PublicDmpDescriptionTemplate._descriptionTemplate)) return DmpDescriptionTemplateEntity._descriptionTemplateId;
else if (item.match(DmpDescriptionTemplate._sectionId)) return DmpDescriptionTemplateEntity._sectionId;
else if (item.match(DmpDescriptionTemplate._hash)) return DmpDescriptionTemplateEntity._updatedAt;
else if (item.match(DmpDescriptionTemplate._createdAt)) return DmpDescriptionTemplateEntity._createdAt;
else if (item.match(DmpDescriptionTemplate._updatedAt)) return DmpDescriptionTemplateEntity._updatedAt;
else return null;

View File

@ -7,22 +7,15 @@ import eu.eudat.commons.enums.DmpStatus;
import eu.eudat.commons.enums.DmpVersionStatus;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.DmpEntity;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.model.DescriptionTemplate;
import eu.eudat.model.Dmp;
import eu.eudat.model.PublicDmp;
import eu.eudat.query.utils.BuildSubQueryInput;
import eu.eudat.query.utils.QueryUtilsService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.query.*;
import jakarta.persistence.AccessType;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@ -306,8 +299,10 @@ public class DmpQuery extends QueryBase<DmpEntity> {
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<DmpEntity> {
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;

View File

@ -206,6 +206,7 @@ public class DmpReferenceQuery extends QueryBase<DmpReferenceEntity> {
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;
}

View File

@ -156,7 +156,7 @@ public class DmpUserQuery extends QueryBase<DmpUserEntity> {
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<DmpUserEntity> {
predicates.add(inClause);
}
if (this.userIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._user));
CriteriaBuilder.In<UUID> 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> {
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<DmpUserEntity> {
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;
}

View File

@ -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<ReferenceEntity> {
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<ReferenceEntity> {
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<ReferenceEntity> {
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;
}

View File

@ -106,16 +106,9 @@ public class ReferenceTypeQuery extends QueryBase<ReferenceTypeEntity> {
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<ReferenceTypeEntity> {
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;

View File

@ -123,16 +123,8 @@ public class SupportiveMaterialQuery extends QueryBase<SupportiveMaterialEntity>
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<SupportiveMaterialEntity>
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;
}

View File

@ -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<TagEntity> {
predicates.add(inClause);
}
if (this.createdByIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TagEntity._createdBy));
CriteriaBuilder.In<UUID> 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<TagEntity> {
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> {
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));

View File

@ -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<UserDescriptionTempl
predicates.add(inClause);
}
if (this.userIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._user));
CriteriaBuilder.In<UUID> 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<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._descriptionTemplate));
CriteriaBuilder.In<UUID> 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<UserDescriptionTempl
protected UserDescriptionTemplateEntity convert(Tuple tuple, Set<String> 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<UserDescriptionTempl
@Override
protected String fieldNameOf(FieldResolver item) {
if (item.match(UserDescriptionTemplateEntity._id)) return UserDescriptionTemplateEntity._id;
else if (item.prefix(UserDescriptionTemplateEntity._user)) return UserDescriptionTemplateEntity._user;
else if (item.prefix(UserDescriptionTemplateEntity._descriptionTemplate)) return UserDescriptionTemplateEntity._descriptionTemplate;
else if (item.match(UserDescriptionTemplateEntity._role)) return UserDescriptionTemplateEntity._role;
else if (item.match(UserDescriptionTemplateEntity._createdAt)) return UserDescriptionTemplateEntity._createdAt;
else if (item.match(UserDescriptionTemplateEntity._updatedAt)) return UserDescriptionTemplateEntity._updatedAt;
else if (item.match(UserDescriptionTemplateEntity._isActive)) return UserDescriptionTemplateEntity._isActive;
if (item.match(UserDescriptionTemplate._id)) return UserDescriptionTemplateEntity._id;
else if (item.prefix(UserDescriptionTemplate._user)) return UserDescriptionTemplateEntity._userId;
else if (item.match(UserDescriptionTemplate._user)) return UserDescriptionTemplateEntity._userId;
else if (item.prefix(UserDescriptionTemplate._descriptionTemplate)) return UserDescriptionTemplateEntity._descriptionTemplateId;
else if (item.match(UserDescriptionTemplate._descriptionTemplate)) return UserDescriptionTemplateEntity._descriptionTemplateId;
else if (item.match(UserDescriptionTemplate._role)) return UserDescriptionTemplateEntity._role;
else if (item.match(UserDescriptionTemplate._createdAt)) return UserDescriptionTemplateEntity._createdAt;
else if (item.match(UserDescriptionTemplate._updatedAt)) return UserDescriptionTemplateEntity._updatedAt;
else if (item.match(UserDescriptionTemplate._hash)) return UserDescriptionTemplateEntity._updatedAt;
else if (item.match(UserDescriptionTemplate._isActive)) return UserDescriptionTemplateEntity._isActive;
else return null;
}

View File

@ -4,10 +4,14 @@ import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DescriptionEntity;
import eu.eudat.data.DescriptionReferenceEntity;
import eu.eudat.data.UserContactInfoEntity;
import eu.eudat.data.UserEntity;
import eu.eudat.data.DmpEntity;
import eu.eudat.model.User;
import eu.eudat.model.PublicUser;
import eu.eudat.model.UserContactInfo;
import eu.eudat.query.utils.BuildSubQueryInput;
import eu.eudat.query.utils.QueryUtilsService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.query.FieldResolver;
@ -29,6 +33,7 @@ import java.util.*;
public class UserQuery extends QueryBase<UserEntity> {
private String like;
private Collection<UUID> ids;
private Collection<String> emails;
private Collection<UUID> excludedIds;
private Collection<IsActive> isActives;
@ -36,9 +41,11 @@ public class UserQuery extends QueryBase<UserEntity> {
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) {
@ -61,6 +68,21 @@ public class UserQuery extends QueryBase<UserEntity> {
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<String> values) {
this.emails = values;
return this;
}
public UserQuery excludedIds(Collection<UUID> values) {
this.excludedIds = values;
return this;
@ -101,6 +123,7 @@ public class UserQuery extends QueryBase<UserEntity> {
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<UserEntity> {
inClause.value(item);
predicates.add(inClause);
}
if (this.emails != null) {
Subquery<UUID> userContactInfoSubquery = queryUtilsService.buildSubQuery(new BuildSubQueryInput<>(
new BuildSubQueryInput.Builder<>(UserContactInfoQuery.class, UUID.class, queryContext)
.keyPathFunc((subQueryRoot) -> subQueryRoot.get(UserContactInfoEntity._id))
.filterFunc((subQueryRoot, cb) -> {
CriteriaBuilder.In<String> 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);

View File

@ -18,6 +18,7 @@ public class UserLookup extends Lookup {
private String like;
private List<UUID> ids;
private List<String> emails;
private List<UUID> excludedIds;
private List<IsActive> 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);

View File

@ -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
)

View File

@ -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<UserDescriptionTemplateEntity> items = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(id).collect();
List<UUID> updatedCreatedIds = new ArrayList<>();
for (UserDescriptionTemplatePersist user : users) {
UserDescriptionTemplateEntity data = items.stream().filter(x -> x.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);
}

View File

@ -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<DmpUserEntity> 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<DmpUserEntity> 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<DmpUserEntity> 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;
};

View File

@ -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;
}

View File

@ -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));
//region persist
this.authorizationService.authorizeForce(Permission.EditDescriptionTemplateType);
@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<User> 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<UserRoleEntity> existingItems = this.queryFactory.query(UserRoleQuery.class).userIds(data.getId()).collect();
List<UUID> 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<UserRoleEntity> 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);
}
}

View File

@ -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<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole);
userManager.editRoles(userListingModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> 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<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
List<UserCredential> user = userManager.getCredentials(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserCredential>>().payload(user).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings) throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
userManager.updateSettings(settings);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().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<ResponseItem<UserProfile>> 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<UserProfile>().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<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
//// this.authorizationService.authorizeForce(Permission.AdminRole);
////
//// DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
//// }
//
// @Transactional
// @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
// public @ResponseBody
// ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel) throws InvalidApplicationException {
// this.authorizationService.authorizeForce(Permission.AdminRole);
//
// userManager.editRoles(userListingModel);
// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
// }
//
//// @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
//// public @ResponseBody
//// ResponseEntity<ResponseItem<UserProfile>> 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<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE));
//// }
//
//// @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json")
//// public @ResponseBody
//// ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id) throws Exception {
//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
////
//// UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
//// List<UserCredential> user = userManager.getCredentials(userId);
//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserCredential>>().payload(user).status(ApiMessageCode.NO_MESSAGE));
//// }
//
//// @Transactional
//// @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
//// public @ResponseBody
//// ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings) throws IOException, InvalidApplicationException {
//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
////
//// userManager.updateSettings(settings);
//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
//// }
//
//// @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
//// public @ResponseBody
//// ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
//// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
////
//// DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem);
//// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().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<ResponseItem<UserProfile>> 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<UserProfile>().payload(userProfile).status(ApiMessageCode.NO_MESSAGE));
//// }
//
//}
//
//
//
//
//
//
//
//
//
//
//

View File

@ -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<DescriptionTemplate> query(@RequestBody DescriptionTemplateLookup lookup) throws MyApplicationException, MyForbiddenException {
logger.debug("querying {}", DescriptionTemplate.class.getSimpleName());
public QueryResult<User> 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<DescriptionTemplateEntity> data = query.collectAs(lookup.getProject());
List<DescriptionTemplate> models = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), data);
List<UserEntity> data = query.collectAs(lookup.getProject());
List<User> 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<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("email", email),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return model;
}
@GetMapping("/export/csv")
public ResponseEntity<byte[]> 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<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("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<String, Object>("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<String, Object>("file", file),
new AbstractMap.SimpleEntry<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return model;
}
@RequestMapping(method = RequestMethod.GET, value = {"/get-semantics"}, produces = "application/json")
public List<String> getSemantics(@RequestParam(value = "query", required = false) String query) throws IOException {
logger.debug(new MapLogEntry("import" + DescriptionTemplate.class.getSimpleName()).And("query", query));
List<String> semantics = this.descriptionTemplateTypeService.getSemantics(query);
this.auditService.track(AuditableAction.DescriptionTemplate_GetSemantics, Map.ofEntries(
new AbstractMap.SimpleEntry<String, Object>("query", query)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return semantics;
}
}

View File

@ -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);
}

View File

@ -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<DmpUserEntity> 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<DmpUserEntity> users = new ArrayList<DmpUserEntity>().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<String, Object> dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference<Map<String, Object>>() {});
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<String, String> 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<DmpUserEntity> 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);

View File

@ -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<DmpUserEntity> 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);
}
}

View File

@ -54,7 +54,7 @@ public class InvitationsManager {
List<DmpUserEntity> 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)) {

View File

@ -90,7 +90,7 @@ public class MergeEmailConfirmationManager {
databaseRepository.getCredentialDao().createOrUpdate(credential);
List<DmpUserEntity> 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

View File

@ -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);
}

View File

@ -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
);
}
}
}

View File

@ -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()

View File

@ -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<DmpUserEntity> 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);

View File

@ -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");
// }

View File

@ -7,4 +7,4 @@ spring:
show-sql: true
properties:
hibernate:
format_sql: true
format_sql: false

View File

@ -174,6 +174,13 @@ permissions:
clients: [ ]
allowAnonymous: false
allowAuthenticated: false
ExportUsers:
roles:
- Admin
claims: [ ]
clients: [ ]
allowAnonymous: false
allowAuthenticated: false
# DescriptionTemplateType
BrowseDescriptionTemplateType:
roles: