User DescriptionTemplate refactor

This commit is contained in:
Efstratios Giannopoulos 2023-10-31 17:24:03 +02:00
parent c08f05bc04
commit 7e391582b5
23 changed files with 983 additions and 232 deletions

View File

@ -0,0 +1,30 @@
package eu.eudat.commons.enums;
import com.fasterxml.jackson.annotation.JsonValue;
import eu.eudat.data.converters.enums.DatabaseEnum;
import java.util.Map;
public enum UserDescriptionTemplateRole implements DatabaseEnum<Short> {
Owner((short) 0),
Member((short) 1);
private final Short value;
UserDescriptionTemplateRole(Short value) {
this.value = value;
}
@JsonValue
public Short getValue() {
return value;
}
private static final Map<Short, UserDescriptionTemplateRole> map = EnumUtils.getEnumValueMap(UserDescriptionTemplateRole.class);
public static UserDescriptionTemplateRole of(Short i) {
return map.get(i);
}
}

View File

@ -5,7 +5,6 @@ import eu.eudat.commons.enums.DescriptionTemplateStatus;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.converters.enums.DescriptionTemplateStatusConverter;
import eu.eudat.data.converters.enums.IsActiveConverter;
import eu.eudat.data.old.UserDatasetProfile;
import eu.eudat.queryable.queryableentity.DataEntity;
import jakarta.persistence.*;
import org.hibernate.annotations.Type;
@ -150,13 +149,6 @@ public class DescriptionTemplateEntity implements DataEntity<DescriptionTemplate
this.type = type;
}
public Set<UserDatasetProfile> getUsers() {
return new HashSet<>();
}
public void setUsers(Set<UserDatasetProfile> users) {
//this.users = users;
}
@Override
public void update(DescriptionTemplateEntity entity) {
}

View File

@ -1,80 +0,0 @@
package eu.eudat.data;
import eu.eudat.data.old.UserInfo;
import eu.eudat.data.old.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import jakarta.persistence.*;
import org.hibernate.annotations.GenericGenerator;
import java.util.List;
import java.util.UUID;
//@Entity
//@Table(name = "\"UserDatasetProfile\"")
public class UserDatasetProfile implements DataEntity<UserDatasetProfile, UUID> {
@Id
@GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usr")
private UserInfo user;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "\"descriptionTemplate\"")
private DescriptionTemplateEntity descriptionTemplate;
@Column(name = "role")
private Integer role;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
public DescriptionTemplateEntity getDatasetProfile() {
return descriptionTemplate;
}
public void setDatasetProfile(DescriptionTemplateEntity descriptionTemplateEntity) {
this.descriptionTemplate = descriptionTemplateEntity;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
@Override
public void update(UserDatasetProfile entity) {
this.role = entity.getRole();
}
@Override
public UUID getKeys() {
return this.id;
}
@Override
public UserDatasetProfile buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
String currentBase = base.isEmpty() ? "" : base + ".";
if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
return this;
}
}

View File

@ -0,0 +1,122 @@
package eu.eudat.data;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import eu.eudat.data.converters.enums.IsActiveConverter;
import eu.eudat.data.converters.enums.UserDescriptionTemplateRoleConverter;
import eu.eudat.data.old.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import jakarta.persistence.*;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "\"UserDescriptionTemplate\"")
public class UserDescriptionTemplateEntity implements DataEntity<UserDescriptionTemplateEntity, UUID> {
@Id
@Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false)
private UUID id;
public static final String _id = "id";
@Column(name = "\"user\"", nullable = false)
private UUID user;
public static final String _user = "user";
@Column(name = "is_active", nullable = false)
@Convert(converter = IsActiveConverter.class)
private IsActive isActive;
public static final String _isActive = "isActive";
@Column(name = "\"created_at\"", nullable = false)
private Instant createdAt = null;
public static final String _createdAt = "createdAt";
@Column(name = "\"updated_at\"", nullable = false)
private Instant updatedAt;
public static final String _updatedAt = "updatedAt";
@Column(name = "\"description_template\"", nullable = false)
private UUID descriptionTemplate;
public static final String _descriptionTemplate = "descriptionTemplate";
@Column(name = "role", nullable = false)
@Convert(converter = UserDescriptionTemplateRoleConverter.class)
private UserDescriptionTemplateRole role;
public static final String _role = "role";
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getUser() {
return user;
}
public void setUser(UUID user) {
this.user = user;
}
public IsActive getIsActive() {
return isActive;
}
public void setIsActive(IsActive isActive) {
this.isActive = isActive;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
public UUID getDescriptionTemplate() {
return descriptionTemplate;
}
public void setDescriptionTemplate(UUID descriptionTemplate) {
this.descriptionTemplate = descriptionTemplate;
}
public UserDescriptionTemplateRole getRole() {
return role;
}
public void setRole(UserDescriptionTemplateRole role) {
this.role = role;
}
@Override
public void update(UserDescriptionTemplateEntity entity) {
this.role = entity.getRole();
}
@Override
public UUID getKeys() {
return this.id;
}
@Override
public UserDescriptionTemplateEntity buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
String currentBase = base.isEmpty() ? "" : base + ".";
if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
return this;
}
}

View File

@ -0,0 +1,11 @@
package eu.eudat.data.converters.enums;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import jakarta.persistence.Converter;
@Converter
public class UserDescriptionTemplateRoleConverter extends DatabaseEnumConverter<UserDescriptionTemplateRole, Short>{
protected UserDescriptionTemplateRole of(Short i) {
return UserDescriptionTemplateRole.of(i);
}
}

View File

@ -1,80 +0,0 @@
package eu.eudat.data.old;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.old.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.hibernate.annotations.GenericGenerator;
import jakarta.persistence.*;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "\"UserDatasetProfile\"")
public class UserDatasetProfile implements DataEntity<UserDatasetProfile, UUID> {
@Id
@GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usr")
private UserInfo user;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "\"descriptionTemplate\"")
private DescriptionTemplateEntity descriptionTemplate;
@Column(name = "role")
private Integer role;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
public DescriptionTemplateEntity getDatasetProfile() {
return descriptionTemplate;
}
public void setDatasetProfile(DescriptionTemplateEntity descriptionTemplateEntity) {
this.descriptionTemplate = descriptionTemplateEntity;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
@Override
public void update(UserDatasetProfile entity) {
this.role = entity.getRole();
}
@Override
public UUID getKeys() {
return this.id;
}
@Override
public UserDatasetProfile buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
String currentBase = base.isEmpty() ? "" : base + ".";
if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
return this;
}
}

View File

@ -6,6 +6,7 @@ import eu.eudat.commons.enums.IsActive;
import eu.eudat.model.descriptiontemplatedefinition.Definition;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public class DescriptionTemplate {
@ -46,6 +47,9 @@ public class DescriptionTemplate {
public final static String _status = "status";
private DescriptionTemplateStatus status;
public final static String _users = "users";
private List<UserDescriptionTemplate> users;
public final static String _hash = "hash";
private String hash;
@ -145,6 +149,14 @@ public class DescriptionTemplate {
this.status = status;
}
public List<UserDescriptionTemplate> getUsers() {
return users;
}
public void setUsers(List<UserDescriptionTemplate> users) {
this.users = users;
}
public String getHash() {
return hash;
}

View File

@ -0,0 +1,88 @@
package eu.eudat.model;
import eu.eudat.commons.enums.DescriptionTemplateStatus;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import eu.eudat.model.descriptiontemplatedefinition.Definition;
import java.time.Instant;
import java.util.UUID;
public class UserDescriptionTemplate {
public final static String _id = "id";
private UUID id;
public final static String _descriptionTemplate = "descriptionTemplate";
private DescriptionTemplate descriptionTemplate;
public final static String _role = "role";
private UserDescriptionTemplateRole role;
public final static String _createdAt = "createdAt";
private Instant createdAt;
public final static String _updatedAt = "updatedAt";
private Instant updatedAt;
public final static String _isActive = "isActive";
private IsActive isActive;
public final static String _hash = "hash";
private String hash;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public DescriptionTemplate getDescriptionTemplate() {
return descriptionTemplate;
}
public void setDescriptionTemplate(DescriptionTemplate descriptionTemplate) {
this.descriptionTemplate = descriptionTemplate;
}
public UserDescriptionTemplateRole getRole() {
return role;
}
public void setRole(UserDescriptionTemplateRole role) {
this.role = role;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
public IsActive getIsActive() {
return isActive;
}
public void setIsActive(IsActive isActive) {
this.isActive = isActive;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}

View File

@ -7,8 +7,10 @@ import eu.eudat.convention.ConventionService;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.model.DescriptionTemplate;
import eu.eudat.model.DescriptionTemplateType;
import eu.eudat.model.UserDescriptionTemplate;
import eu.eudat.model.builder.descriptiontemplatedefinition.DefinitionBuilder;
import eu.eudat.query.DescriptionTemplateTypeQuery;
import eu.eudat.query.UserDescriptionTemplateQuery;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
@ -58,6 +60,8 @@ public class DescriptionTemplateBuilder extends BaseBuilder<DescriptionTemplate,
FieldSet descriptionTemplateTypeFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._type));
Map<UUID, DescriptionTemplateType> descriptionTemplateTypeMap = this.collectDescriptionTemplateTypes(descriptionTemplateTypeFields, datas);
FieldSet usersFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._users));
Map<UUID, List<UserDescriptionTemplate>> usersMap = this.collectUserDescriptionTemplates(usersFields, datas);
FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._definition));
List<DescriptionTemplate> models = new ArrayList<>();
@ -80,6 +84,7 @@ public class DescriptionTemplateBuilder extends BaseBuilder<DescriptionTemplate,
DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition());
m.setDefinition(this.builderFactory.builder(DefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition));
}
if (!usersFields.isEmpty() && usersMap != null && usersMap.containsKey(d.getId())) m.setUsers(usersMap.get(d.getId()));
if (!descriptionTemplateTypeFields.isEmpty() && descriptionTemplateTypeMap != null && descriptionTemplateTypeMap.containsKey(d.getType())) m.setType(descriptionTemplateTypeMap.get(d.getType()));
models.add(m);
}
@ -115,4 +120,22 @@ public class DescriptionTemplateBuilder extends BaseBuilder<DescriptionTemplate,
return itemMap;
}
private Map<UUID, List<UserDescriptionTemplate>> collectUserDescriptionTemplates(FieldSet fields, List<DescriptionTemplateEntity> datas) throws MyApplicationException {
if (fields.isEmpty() || datas.isEmpty()) return null;
this.logger.debug("checking related - {}", UserDescriptionTemplate.class.getSimpleName());
Map<UUID, List<UserDescriptionTemplate>> itemMap = null;
FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserDescriptionTemplate._descriptionTemplate, DescriptionTemplate._id));
UserDescriptionTemplateQuery query = this.queryFactory.query(UserDescriptionTemplateQuery.class).authorize(this.authorize).descriptionTemplateIds(datas.stream().map(DescriptionTemplateEntity::getId).distinct().collect(Collectors.toList()));
itemMap = this.builderFactory.builder(UserDescriptionTemplateBuilder.class).authorize(this.authorize).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDescriptionTemplate().getId());
if (!fields.hasField(this.asIndexer(UserDescriptionTemplate._descriptionTemplate, DescriptionTemplate._id))) {
itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDescriptionTemplate() != null).map(x -> {
x.getDescriptionTemplate().setId(null);
return x;
}).collect(Collectors.toList());
}
return itemMap;
}
}

View File

@ -0,0 +1,104 @@
package eu.eudat.model.builder;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.XmlHandlingService;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.model.DescriptionTemplate;
import eu.eudat.model.UserDescriptionTemplate;
import eu.eudat.query.DescriptionTemplateQuery;
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;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserDescriptionTemplateBuilder extends BaseBuilder<UserDescriptionTemplate, UserDescriptionTemplateEntity> {
private EnumSet<AuthorizationFlags> authorize = EnumSet.of(AuthorizationFlags.None);
private final QueryFactory queryFactory;
private final BuilderFactory builderFactory;
private final XmlHandlingService xmlHandlingService;
@Autowired
public UserDescriptionTemplateBuilder(
ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory, XmlHandlingService xmlHandlingService) {
super(conventionService, new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateBuilder.class)));
this.queryFactory = queryFactory;
this.builderFactory = builderFactory;
this.xmlHandlingService = xmlHandlingService;
}
public UserDescriptionTemplateBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<UserDescriptionTemplate> build(FieldSet fields, List<UserDescriptionTemplateEntity> datas) throws MyApplicationException {
this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(datas).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0));
this.logger.trace(new DataLogEntry("requested fields", fields));
if (fields == null || datas == null || fields.isEmpty())
return new ArrayList<>();
FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asPrefix(UserDescriptionTemplate._descriptionTemplate));
Map<UUID, DescriptionTemplate> descriptionTemplateMap = this.collectDescriptionTemplates(descriptionTemplateFields, datas);
List<UserDescriptionTemplate> models = new ArrayList<>();
for (UserDescriptionTemplateEntity d : datas) {
UserDescriptionTemplate m = new UserDescriptionTemplate();
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._id))) m.setId(d.getId());
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._createdAt))) m.setCreatedAt(d.getCreatedAt());
if (fields.hasField(this.asIndexer(UserDescriptionTemplate._updatedAt))) m.setUpdatedAt(d.getUpdatedAt());
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()));
models.add(m);
}
this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0));
return models;
}
private Map<UUID, DescriptionTemplate> collectDescriptionTemplates(FieldSet fields, List<UserDescriptionTemplateEntity> datas) throws MyApplicationException {
if (fields.isEmpty() || datas.isEmpty()) return null;
this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName());
Map<UUID, DescriptionTemplate> itemMap = null;
if (!fields.hasOtherField(this.asIndexer(DescriptionTemplate._id))) {
itemMap = this.asEmpty(
datas.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplate).distinct().collect(Collectors.toList()),
x -> {
DescriptionTemplate item = new DescriptionTemplate();
item.setId(x);
return item;
},
x -> x.getId());
} else {
FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._id);
DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).ids(datas.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplate).distinct().collect(Collectors.toList()));
itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).asForeignKey(q, clone, DescriptionTemplate::getId);
}
if (!fields.hasField(DescriptionTemplate._id)) {
itemMap.values().stream().filter(x -> x != null).map(x -> {
x.setId(null);
return x;
}).collect(Collectors.toList());
}
return itemMap;
}
}

View File

@ -41,6 +41,8 @@ public class DescriptionTemplateCensor extends BaseCensor {
this.censorFactory.censor(DescriptionTemplateTypeCensor.class).censor(definitionFields, userId);
FieldSet typeFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTemplate._type));
this.censorFactory.censor(DefinitionCensor.class).censor(typeFields, userId);
FieldSet _usersFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTemplate._users));
this.censorFactory.censor(UserDescriptionTemplateCensor.class).censor(_usersFields, userId);
}
}

View File

@ -0,0 +1,45 @@
package eu.eudat.model.censorship;
import eu.eudat.authorization.Permission;
import eu.eudat.convention.ConventionService;
import eu.eudat.model.DescriptionTemplate;
import eu.eudat.model.UserDescriptionTemplate;
import eu.eudat.model.censorship.descriptiontemplatedefinition.DefinitionCensor;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.censor.CensorFactory;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.DataLogEntry;
import gr.cite.tools.logging.LoggerService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserDescriptionTemplateCensor extends BaseCensor {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateCensor.class));
protected final AuthorizationService authService;
protected final CensorFactory censorFactory;
public UserDescriptionTemplateCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) {
super(conventionService);
this.authService = authService;
this.censorFactory = censorFactory;
}
public void censor(FieldSet fields, UUID userId) {
logger.debug(new DataLogEntry("censoring fields", fields));
if (fields == null || fields.isEmpty())
return;
this.authService.authorizeForce(Permission.BrowseDescriptionTemplate);
FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._descriptionTemplate));
this.censorFactory.censor(DescriptionTemplateCensor.class).censor(userFields, userId);
}
}

View File

@ -2,7 +2,9 @@ package eu.eudat.model.deleter;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.query.DescriptionTemplateQuery;
import eu.eudat.query.UserDescriptionTemplateQuery;
import gr.cite.tools.data.deleter.Deleter;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
@ -20,6 +22,7 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ -59,16 +62,24 @@ public class DescriptionTemplateDeleter implements Deleter {
logger.trace("changes saved");
}
public void delete(List<DescriptionTemplateEntity> data) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0));
if (data == null || data.isEmpty())
public void delete(List<DescriptionTemplateEntity> datas) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(datas).map(List::size).orElse(0));
if (datas == null || datas.isEmpty())
return;
List<UUID> ids = datas.stream().map(x -> x.getId()).distinct().collect(Collectors.toList());
{
logger.debug("checking related - {}", UserDescriptionTemplateEntity.class.getSimpleName());
List<UserDescriptionTemplateEntity> items = this.queryFactory.query(UserDescriptionTemplateQuery.class).descriptionTemplateIds(ids).collect();
UserDescriptionTemplateDeleter deleter = this.deleterFactory.deleter(UserDescriptionTemplateDeleter.class);
deleter.delete(items);
}
//TODO can not delete profile if has Datasets
Instant now = Instant.now();
for (DescriptionTemplateEntity item : data) {
for (DescriptionTemplateEntity item : datas) {
logger.trace("deleting item {}", item.getId());
item.setIsActive(IsActive.Inactive);
item.setUpdatedAt(now);

View File

@ -0,0 +1,80 @@
package eu.eudat.model.deleter;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.query.DescriptionTemplateQuery;
import eu.eudat.query.UserDescriptionTemplateQuery;
import gr.cite.tools.data.deleter.Deleter;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import jakarta.persistence.EntityManager;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserDescriptionTemplateDeleter implements Deleter {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateDeleter.class));
private final EntityManager entityManager;
protected final QueryFactory queryFactory;
protected final DeleterFactory deleterFactory;
@Autowired
public UserDescriptionTemplateDeleter(
EntityManager entityManager,
QueryFactory queryFactory,
DeleterFactory deleterFactory
) {
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<UserDescriptionTemplateEntity> data = this.queryFactory.query(UserDescriptionTemplateQuery.class).ids(ids).collect();
logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0));
this.deleteAndSave(data);
}
public void deleteAndSave(List<UserDescriptionTemplateEntity> 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<UserDescriptionTemplateEntity> data) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0));
if (data == null || data.isEmpty())
return;
Instant now = Instant.now();
for (UserDescriptionTemplateEntity 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");
}
}
}

View File

@ -212,6 +212,7 @@ public class DescriptionTemplateQuery extends QueryBase<DescriptionTemplateEntit
if (item.match(DescriptionTemplate._id)) return DescriptionTemplateEntity._id;
else if (item.match(DescriptionTemplate._label)) return DescriptionTemplateEntity._label;
else if (item.prefix(DescriptionTemplate._definition)) return DescriptionTemplateEntity._definition;
else if (item.prefix(DescriptionTemplate._users)) return DescriptionTemplateEntity._id;
else if (item.match(DescriptionTemplate._description)) return DescriptionTemplateEntity._description;
else if (item.match(DescriptionTemplate._groupId)) return DescriptionTemplateEntity._groupId;
else if (item.match(DescriptionTemplate._version)) return DescriptionTemplateEntity._version;

View File

@ -0,0 +1,221 @@
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 gr.cite.tools.data.query.FieldResolver;
import gr.cite.tools.data.query.QueryBase;
import gr.cite.tools.data.query.QueryContext;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.*;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserDescriptionTemplateQuery extends QueryBase<UserDescriptionTemplateEntity> {
private Collection<UUID> ids;
private Collection<IsActive> isActives;
private Collection<UserDescriptionTemplateRole> roles;
private Collection<UUID> excludedIds;
private Collection<UUID> userIds;
private Collection<UUID> descriptionTemplateIds;
private EnumSet<AuthorizationFlags> authorize = EnumSet.of(AuthorizationFlags.None);
public UserDescriptionTemplateQuery ids(UUID value) {
this.ids = List.of(value);
return this;
}
public UserDescriptionTemplateQuery ids(UUID... value) {
this.ids = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery ids(Collection<UUID> values) {
this.ids = values;
return this;
}
public UserDescriptionTemplateQuery userIds(UUID value) {
this.userIds = List.of(value);
return this;
}
public UserDescriptionTemplateQuery userIds(UUID... value) {
this.userIds = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery userIds(Collection<UUID> values) {
this.userIds = values;
return this;
}
public UserDescriptionTemplateQuery descriptionTemplateIds(UUID value) {
this.descriptionTemplateIds = List.of(value);
return this;
}
public UserDescriptionTemplateQuery descriptionTemplateIds(UUID... value) {
this.descriptionTemplateIds = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery descriptionTemplateIds(Collection<UUID> values) {
this.descriptionTemplateIds = values;
return this;
}
public UserDescriptionTemplateQuery isActive(IsActive value) {
this.isActives = List.of(value);
return this;
}
public UserDescriptionTemplateQuery isActive(IsActive... value) {
this.isActives = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery isActive(Collection<IsActive> values) {
this.isActives = values;
return this;
}
public UserDescriptionTemplateQuery roles(UserDescriptionTemplateRole value) {
this.roles = List.of(value);
return this;
}
public UserDescriptionTemplateQuery roles(UserDescriptionTemplateRole... value) {
this.roles = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery roles(Collection<UserDescriptionTemplateRole> values) {
this.roles = values;
return this;
}
public UserDescriptionTemplateQuery excludedIds(Collection<UUID> values) {
this.excludedIds = values;
return this;
}
public UserDescriptionTemplateQuery excludedIds(UUID value) {
this.excludedIds = List.of(value);
return this;
}
public UserDescriptionTemplateQuery excludedIds(UUID... value) {
this.excludedIds = Arrays.asList(value);
return this;
}
public UserDescriptionTemplateQuery authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
private final AuthorizationService authService;
public UserDescriptionTemplateQuery(
UserScope userScope,
AuthorizationService authService
) {
this.authService = authService;
}
@Override
protected Class<UserDescriptionTemplateEntity> entityClass() {
return UserDescriptionTemplateEntity.class;
}
@Override
protected Boolean isFalseQuery() {
return this.isEmpty(this.ids) || this.isEmpty(this.userIds) || this.isEmpty(this.descriptionTemplateIds) ||this.isEmpty(this.isActives) ||this.isEmpty(this.roles) || this.isEmpty(this.excludedIds);
}
@Override
protected <X, Y> Predicate applyFilters(QueryContext<X, Y> queryContext) {
List<Predicate> predicates = new ArrayList<>();
if (this.ids != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._id));
for (UUID item : this.ids)
inClause.value(item);
predicates.add(inClause);
}
if (this.userIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._user));
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));
for (UUID item : this.descriptionTemplateIds)
inClause.value(item);
predicates.add(inClause);
}
if (this.isActives != null) {
CriteriaBuilder.In<IsActive> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._isActive));
for (IsActive item : this.isActives)
inClause.value(item);
predicates.add(inClause);
}
if (this.roles != null) {
CriteriaBuilder.In<UserDescriptionTemplateRole> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._role));
for (UserDescriptionTemplateRole item : this.roles)
inClause.value(item);
predicates.add(inClause);
}
if (this.excludedIds != null) {
CriteriaBuilder.In<UUID> notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserDescriptionTemplateEntity._id));
for (UUID item : this.excludedIds)
notInClause.value(item);
predicates.add(notInClause.not());
}
if (!predicates.isEmpty()) {
Predicate[] predicatesArray = predicates.toArray(new Predicate[0]);
return queryContext.CriteriaBuilder.and(predicatesArray);
} else {
return null;
}
}
@Override
protected 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.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));
item.setIsActive(QueryBase.convertSafe(tuple, columns, UserDescriptionTemplateEntity._isActive, IsActive.class));
return item;
}
@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;
else return null;
}
}

View File

@ -0,0 +1,93 @@
package eu.eudat.query.lookup;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import eu.eudat.query.UserDescriptionTemplateQuery;
import gr.cite.tools.data.query.Lookup;
import gr.cite.tools.data.query.QueryFactory;
import java.util.List;
import java.util.UUID;
public class UserDescriptionTemplateLookup extends Lookup {
private List<IsActive> isActive;
private List<UserDescriptionTemplateRole> roles;
private List<UUID> ids;
private List<UUID> userIds;
private List<UUID> descriptionTemplateIds;
private List<UUID> excludedIds;
public List<IsActive> getIsActive() {
return isActive;
}
public void setIsActive(List<IsActive> isActive) {
this.isActive = isActive;
}
public List<UserDescriptionTemplateRole> getRoles() {
return roles;
}
public void setRoles(List<UserDescriptionTemplateRole> roles) {
this.roles = roles;
}
public List<UUID> getIds() {
return ids;
}
public void setIds(List<UUID> ids) {
this.ids = ids;
}
public List<UUID> getUserIds() {
return userIds;
}
public void setUserIds(List<UUID> userIds) {
this.userIds = userIds;
}
public List<UUID> getDescriptionTemplateIds() {
return descriptionTemplateIds;
}
public void setDescriptionTemplateIds(List<UUID> descriptionTemplateIds) {
this.descriptionTemplateIds = descriptionTemplateIds;
}
public List<UUID> getExcludedIds() {
return excludedIds;
}
public void setExcludedIds(List<UUID> excludedIds) {
this.excludedIds = excludedIds;
}
public UserDescriptionTemplateQuery enrich(QueryFactory queryFactory) {
UserDescriptionTemplateQuery query = queryFactory.query(UserDescriptionTemplateQuery.class);
if (this.isActive != null)
query.isActive(this.isActive);
if (this.roles != null)
query.roles(this.roles);
if (this.ids != null)
query.ids(this.ids);
if (this.excludedIds != null)
query.excludedIds(this.excludedIds);
if (this.userIds != null)
query.userIds(this.userIds);
if (this.descriptionTemplateIds != null)
query.userIds(this.descriptionTemplateIds);
this.enrichCommon(query);
return query;
}
}

View File

@ -5,10 +5,13 @@ import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.XmlHandlingService;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.types.descriptiontemplate.*;
import eu.eudat.commons.types.descriptiontemplate.fielddata.BaseFieldDataEntity;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.model.DescriptionTemplate;
import eu.eudat.model.builder.DescriptionTemplateBuilder;
import eu.eudat.model.deleter.DescriptionTemplateDeleter;
@ -50,6 +53,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateServiceImpl.class));
private final EntityManager entityManager;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@ -64,14 +68,15 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
@Autowired
public DescriptionTemplateServiceImpl(
EntityManager entityManager,
AuthorizationService authorizationService,
UserScope userScope, AuthorizationService authorizationService,
DeleterFactory deleterFactory,
BuilderFactory builderFactory,
ConventionService conventionService,
MessageSource messageSource,
XmlHandlingService xmlHandlingService,
XmlHandlingService xmlHandlingService,
FieldDataHelperServiceProvider fieldDataHelperServiceProvider) {
this.entityManager = entityManager;
this.userScope = userScope;
this.authorizationService = authorizationService;
this.deleterFactory = deleterFactory;
this.builderFactory = builderFactory;
@ -112,11 +117,24 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic
this.entityManager.merge(data);
else
this.entityManager.persist(data);
if (!isUpdate) this.addOwner(data);
this.entityManager.flush();
return this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, DescriptionTemplate._id), data);
}
private void addOwner(DescriptionTemplateEntity descriptionTemplateEntity) throws InvalidApplicationException {
UserDescriptionTemplateEntity data = new UserDescriptionTemplateEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now());
data.setRole(UserDescriptionTemplateRole.Owner);
data.setUser(userScope.getUserId());
data.setDescriptionTemplate(descriptionTemplateEntity.getId());
this.entityManager.persist(data);
}
private @NotNull DefinitionEntity buildDefinitionEntity(DefinitionPersist persist){
DefinitionEntity data = new DefinitionEntity();

View File

@ -1,12 +1,12 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.old.UserDatasetProfile;
import java.util.UUID;
/**
* Created by ikalyvas on 2/8/2018.
*/
public interface UserDatasetProfileDao extends DatabaseAccessLayer<UserDatasetProfile, UUID> {
public interface UserDatasetProfileDao extends DatabaseAccessLayer<UserDescriptionTemplateEntity, UUID> {
}

View File

@ -1,8 +1,8 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.old.UserDatasetProfile;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
@ -13,41 +13,41 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Component("userDatasetProfileDao")
public class UserDatasetProfileDaoImpl extends DatabaseAccess<UserDatasetProfile> implements UserDatasetProfileDao {
public class UserDatasetProfileDaoImpl extends DatabaseAccess<UserDescriptionTemplateEntity> implements UserDatasetProfileDao {
@Autowired
public UserDatasetProfileDaoImpl(DatabaseService<UserDatasetProfile> databaseService) {
public UserDatasetProfileDaoImpl(DatabaseService<UserDescriptionTemplateEntity> databaseService) {
super(databaseService);
}
@Override
public UserDatasetProfile createOrUpdate(UserDatasetProfile item) {
return this.getDatabaseService().createOrUpdate(item, UserDatasetProfile.class);
public UserDescriptionTemplateEntity createOrUpdate(UserDescriptionTemplateEntity item) {
return this.getDatabaseService().createOrUpdate(item, UserDescriptionTemplateEntity.class);
}
@Override
public UserDatasetProfile find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserDatasetProfile.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
public UserDescriptionTemplateEntity find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserDescriptionTemplateEntity.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
}
@Override
public void delete(UserDatasetProfile item) {
public void delete(UserDescriptionTemplateEntity item) {
this.getDatabaseService().delete(item);
}
@Override
public QueryableList<UserDatasetProfile> asQueryable() {
return this.getDatabaseService().getQueryable(UserDatasetProfile.class);
public QueryableList<UserDescriptionTemplateEntity> asQueryable() {
return this.getDatabaseService().getQueryable(UserDescriptionTemplateEntity.class);
}
@Async
@Override
public CompletableFuture<UserDatasetProfile> createOrUpdateAsync(UserDatasetProfile item) {
public CompletableFuture<UserDescriptionTemplateEntity> createOrUpdateAsync(UserDescriptionTemplateEntity item) {
return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
}
@Override
public UserDatasetProfile find(UUID id, String hint) {
public UserDescriptionTemplateEntity find(UUID id, String hint) {
throw new UnsupportedOperationException();
}
}

View File

@ -2,13 +2,13 @@ package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.DescriptionTemplateStatus;
import eu.eudat.commons.enums.UserDescriptionTemplateRole;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.old.UserDatasetProfile;
import eu.eudat.data.UserDescriptionTemplateEntity;
import eu.eudat.data.old.UserInfo;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
import eu.eudat.exceptions.datasetprofile.DatasetProfileNewVersionException;
import eu.eudat.exceptions.datasetprofile.DatasetProfileWithDatasetsExeption;
import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.managers.MetricsManager;
@ -82,11 +82,11 @@ public class Admin extends BaseController {
modelDefinition.setVersion((short) 0);
DescriptionTemplateEntity descriptionTemplateEntity = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
UserDatasetProfile userDatasetProfile = new UserDatasetProfile();
userDatasetProfile.setDatasetProfile(descriptionTemplateEntity);
UserDescriptionTemplateEntity userDatasetProfile = new UserDescriptionTemplateEntity();
userDatasetProfile.setDescriptionTemplate(descriptionTemplateEntity.getId());
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
userDatasetProfile.setUser(userInfo);
userDatasetProfile.setRole(0);
userDatasetProfile.setUser(userInfo.getId());
userDatasetProfile.setRole(UserDescriptionTemplateRole.Owner);
getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
datasetProfileManager.storeDatasetProfileUsers(descriptionTemplateEntity, profile);
@ -211,11 +211,11 @@ public class Admin extends BaseController {
if (id == null) {
modelDefinition = AdminManager.generateViewStyleDefinition(datasetProfileEntity, getApiContext(), descriptionTemplateTypeService);
DescriptionTemplateEntity descriptionTemplateEntity = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
UserDatasetProfile userDatasetProfile = new UserDatasetProfile();
userDatasetProfile.setDatasetProfile(descriptionTemplateEntity);
UserDescriptionTemplateEntity userDatasetProfile = new UserDescriptionTemplateEntity();
userDatasetProfile.setDescriptionTemplate(descriptionTemplateEntity.getId());
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userScope.getUserId());
userDatasetProfile.setUser(userInfo);
userDatasetProfile.setRole(0);
userDatasetProfile.setUser(userInfo.getId());
userDatasetProfile.setRole(UserDescriptionTemplateRole.Owner);
getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
} else {
modelDefinition = datasetProfileManager.createNewVersionDatasetProfile(id, datasetProfileEntity);

View File

@ -1,10 +1,12 @@
package eu.eudat.logic.managers;
import eu.eudat.authorization.Permission;
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 eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.old.UserDatasetProfile;
import eu.eudat.data.old.UserInfo;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileAutocompleteRequest;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
@ -21,6 +23,7 @@ import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.ExportXmlBuilderDatasetProfile;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.ImportXmlBuilderDatasetProfile;
import eu.eudat.commons.types.descriptiontemplate.fielddata.AutoCompleteDataEntity;
import eu.eudat.model.deleter.UserDescriptionTemplateDeleter;
import eu.eudat.models.data.datasetprofile.DatasetProfileAutocompleteItem;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.commons.types.descriptiontemplate.FieldEntity;
@ -28,11 +31,14 @@ import eu.eudat.models.data.externaldataset.ExternalAutocompleteFieldModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.mail.SimpleMail;
import eu.eudat.query.DescriptionTemplateQuery;
import eu.eudat.query.DescriptionTemplateTypeQuery;
import eu.eudat.query.UserDescriptionTemplateQuery;
import eu.eudat.queryable.QueryableList;
import eu.eudat.service.descriptiontemplatetype.DescriptionTemplateTypeService;
import eu.eudat.types.MetricNames;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -80,9 +86,10 @@ public class DatasetProfileManager {
private final AuthorizationService authorizationService;
private final UserScope userScope;
private final QueryFactory queryFactory;
private final DeleterFactory deleterFactory;
@Autowired
public DatasetProfileManager(ApiContext apiContext, Environment environment, ConfigLoader configLoader, MetricsManager metricsManager, RemoteFetcher remoteFetcher, DescriptionTemplateTypeService descriptionTemplateTypeService, AuthorizationService authorizationService, UserScope userScope, QueryFactory queryFactory) {
public DatasetProfileManager(ApiContext apiContext, Environment environment, ConfigLoader configLoader, MetricsManager metricsManager, RemoteFetcher remoteFetcher, DescriptionTemplateTypeService descriptionTemplateTypeService, AuthorizationService authorizationService, UserScope userScope, QueryFactory queryFactory, DeleterFactory deleterFactory) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.environment = environment;
@ -93,6 +100,7 @@ public class DatasetProfileManager {
this.authorizationService = authorizationService;
this.userScope = userScope;
this.queryFactory = queryFactory;
this.deleterFactory = deleterFactory;
}
@Transactional
@ -386,68 +394,89 @@ public class DatasetProfileManager {
}
public void storeDatasetProfileUsers(DescriptionTemplateEntity entity, eu.eudat.models.data.admin.composite.DatasetProfile model) {
final List<UserDescriptionTemplateEntity> userDescriptionTemplateEntities = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(entity.getId()).collect();
if (model.getUsers() != null && !model.getUsers().isEmpty()) {
if (entity.getUsers() == null) {
entity.setUsers(new HashSet<>());
}
model.getUsers().stream().filter(userInfoListingModel -> entity.getUsers().stream()
.filter(userDatasetProfile -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() == 0)
model.getUsers().stream().filter(userInfoListingModel -> userDescriptionTemplateEntities.stream()
.filter(userDatasetProfile -> userDatasetProfile.getUser().equals(userInfoListingModel.getId())).count() == 0)
.forEach(userInfoListingModel -> {
UserDatasetProfile userDatasetProfile1 = new UserDatasetProfile();
userDatasetProfile1.setDatasetProfile(entity);
UserDescriptionTemplateEntity userDatasetProfile1 = new UserDescriptionTemplateEntity();
userDatasetProfile1.setDescriptionTemplate(entity.getId());
UserInfo userInfo1 = null;
try {
userInfo1 = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userInfoListingModel.getId());
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
userDatasetProfile1.setUser(userInfo1);
userDatasetProfile1.setRole(1);
userDatasetProfile1.setUser(userInfo1.getId());
userDatasetProfile1.setRole(UserDescriptionTemplateRole.Member);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile1);
sendJoinMail(userDatasetProfile1);
});
entity.getUsers().stream().filter(userDatasetProfile -> model.getUsers().stream()
.filter(userInfoListingModel -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() > 0
&& userDatasetProfile.getRole() == 2).forEach(userDatasetProfile -> {
userDatasetProfile.setRole(1);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
sendJoinMail(userDatasetProfile);
});
// userDescriptionTemplateEntities.stream().filter(userDatasetProfile -> model.getUsers().stream()
// .filter(userInfoListingModel -> userDatasetProfile.getUser().equals(userInfoListingModel.getId())).count() > 0
// && userDatasetProfile.getRole() == UserDescriptionTemplateRole.Saved2).forEach(userDatasetProfile -> {
// userDatasetProfile.setRole(UserDescriptionTemplateRole.Member);
// apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
// sendJoinMail(userDatasetProfile);
// });
}
if (entity.getUsers() != null && !entity.getUsers().isEmpty()) {
entity.getUsers().stream().filter(userDatasetProfile -> model.getUsers().stream()
.filter(userInfoListingModel -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() == 0)
if (userDescriptionTemplateEntities != null && !userDescriptionTemplateEntities.isEmpty()) {
List<UserDescriptionTemplateEntity> toDelete = new ArrayList<>();
userDescriptionTemplateEntities.stream().filter(userDatasetProfile -> model.getUsers().stream()
.filter(userInfoListingModel -> userDatasetProfile.getUser().equals(userInfoListingModel.getId())).count() == 0)
.forEach(userDatasetProfile -> {
userDatasetProfile.setRole(2);
toDelete.add(userDatasetProfile);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
});
try {
this.deleterFactory.deleter(UserDescriptionTemplateDeleter.class).delete(toDelete);
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
}
}
@Transactional
public void retrieveUsers(DescriptionTemplateEntity entity, eu.eudat.models.data.admin.composite.DatasetProfile model) {
if (entity.getUsers() != null && !entity.getUsers().isEmpty()) {
model.setUsers(entity.getUsers().stream().filter(userDatasetProfile -> userDatasetProfile.getRole() < 2).map(userDatasetProfile -> {
final List<UserDescriptionTemplateEntity> userDescriptionTemplateEntities = this.queryFactory.query(UserDescriptionTemplateQuery.class).isActive(IsActive.Active).descriptionTemplateIds(entity.getId()).collect();
if (userDescriptionTemplateEntities != null && !userDescriptionTemplateEntities.isEmpty()) {
model.setUsers(userDescriptionTemplateEntities.stream().filter(userDatasetProfile -> userDatasetProfile.getRole().getValue() < 2).map(userDatasetProfile -> {
UserInfo user = null;
try {
user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userDatasetProfile.getUser());
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
UserInfoListingModel userInfoListingModel = new UserInfoListingModel();
userInfoListingModel.setId(userDatasetProfile.getUser().getId());
userInfoListingModel.setName(userDatasetProfile.getUser().getName());
userInfoListingModel.setEmail(userDatasetProfile.getUser().getEmail());
userInfoListingModel.setRole(userDatasetProfile.getRole());
userInfoListingModel.setId(user.getId());
userInfoListingModel.setName(user.getName());
userInfoListingModel.setEmail(user.getEmail());
userInfoListingModel.setRole(userDatasetProfile.getRole().getValue());
return userInfoListingModel;
}).collect(Collectors.toList()));
}
}
private void sendJoinMail(UserDatasetProfile userDatasetProfile) {
private void sendJoinMail(UserDescriptionTemplateEntity userDatasetProfile) {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", userDatasetProfile.getDatasetProfile().getLabel()));
UserInfo user = null;
try {
user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userDatasetProfile.getUser());
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(userDatasetProfile.getDescriptionTemplate()).first();
mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", descriptionTemplate.getLabel()));
String content = apiContext.getUtilitiesService().getMailService().getMailTemplateContent(environment.getProperty("email.dataset.template"));
content = content.replace("{recipient}", userDatasetProfile.getUser().getName());
content = content.replace("{templateName}", userDatasetProfile.getDatasetProfile().getLabel());
content = content.replace("{recipient}", user.getName());
content = content.replace("{templateName}", descriptionTemplate.getLabel());
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{templateID}", userDatasetProfile.getDatasetProfile().getId().toString());
content = content.replace("{templateID}", descriptionTemplate.getId().toString());
mail.setContent(content);
mail.setTo(userDatasetProfile.getUser().getEmail());
mail.setTo(user.getEmail());
try {
apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
} catch (Exception ex) {

View File

@ -0,0 +1,29 @@
ALTER TABLE public."UserDatasetProfile" RENAME TO "UserDescriptionTemplate";
ALTER TABLE public."UserDescriptionTemplate" RENAME usr TO "user";
ALTER TABLE public."UserDescriptionTemplate" RENAME "descriptionTemplate" TO description_template;
ALTER TABLE public."UserDescriptionTemplate" ALTER COLUMN "role" TYPE smallint;
ALTER TABLE public."UserDescriptionTemplate" ALTER COLUMN "role" SET NOT NULL;
ALTER TABLE public."UserDescriptionTemplate" ADD COLUMN updated_at timestamp without time zone;
ALTER TABLE public."UserDescriptionTemplate" ADD COLUMN created_at timestamp without time zone;
ALTER TABLE public."UserDescriptionTemplate" ADD COLUMN is_active smallint;
UPDATE public."UserDescriptionTemplate" SET is_active = 1;
UPDATE public."UserDescriptionTemplate" SET is_active = 0 where role = 2;
UPDATE public."UserDescriptionTemplate" SET role = 1 where is_active = 0;
ALTER TABLE public."UserDescriptionTemplate" ALTER COLUMN is_active SET NOT NULL;
UPDATE public."UserDescriptionTemplate" SET updated_at = now() at time zone 'utc';
ALTER TABLE public."UserDescriptionTemplate" ALTER COLUMN updated_at SET NOT NULL;
UPDATE public."UserDescriptionTemplate" SET created_at = now() at time zone 'utc';
ALTER TABLE public."UserDescriptionTemplate" ALTER COLUMN created_at SET NOT NULL;