Added DmpUser table and stack

This commit is contained in:
Thomas Georgios Giannos 2023-11-07 12:12:14 +02:00
parent ea58ed2e44
commit ee68224f58
9 changed files with 682 additions and 1 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 DmpUserRole implements DatabaseEnum<Short> {
Owner((short) 0), User((short) 1);
private final Short value;
DmpUserRole(Short value) {
this.value = value;
}
@Override
@JsonValue
public Short getValue() {
return value;
}
private static final Map<Short, DmpUserRole> map = EnumUtils.getEnumValueMap(DmpUserRole.class);
public static DmpUserRole of(Short i) {
return map.get(i);
}
}

View File

@ -0,0 +1,108 @@
package eu.eudat.data;
import eu.eudat.commons.enums.DmpUserRole;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.converters.enums.IsActiveConverter;
import jakarta.persistence.*;
import java.time.Instant;
import java.util.UUID;
@Table(name = "\"DmpUser\"")
public class DmpUserEntity {
@Id
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID id;
public static final String _id = "id";
@Column(name = "dmp", columnDefinition = "uuid", nullable = false)
private UUID dmp;
public static final String _dmp = "dmp";
@Column(name = "user", columnDefinition = "uuid", nullable = false)
private UUID user;
public static final String _user = "user";
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
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;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getDmp() {
return dmp;
}
public void setDmp(UUID dmp) {
this.dmp = dmp;
}
public UUID getUser() {
return user;
}
public void setUser(UUID user) {
this.user = user;
}
public DmpUserRole getRole() {
return role;
}
public void setRole(DmpUserRole 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;
}
}

View File

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

View File

@ -0,0 +1,103 @@
package eu.eudat.model;
import eu.eudat.commons.enums.DmpUserRole;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.converters.enums.IsActiveConverter;
import eu.eudat.data.old.UserInfo;
import jakarta.persistence.*;
import java.time.Instant;
import java.util.UUID;
public class DmpUser {
private UUID id;
public static final String _id = "id";
private Dmp dmp;
public static final String _dmp = "dmp";
@Column(name = "user", columnDefinition = "uuid", nullable = false)
private UserInfo user;
public static final String _user = "user";
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
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 UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public Dmp getDmp() {
return dmp;
}
public void setDmp(Dmp dmp) {
this.dmp = dmp;
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
public DmpUserRole getRole() {
return role;
}
public void setRole(DmpUserRole 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;
}
}

View File

@ -0,0 +1,143 @@
package eu.eudat.model.builder;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.data.old.UserInfo;
import eu.eudat.model.Dmp;
import eu.eudat.model.DmpUser;
import eu.eudat.model.Reference;
import eu.eudat.query.DmpQuery;
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 DmpUserBuilder extends BaseBuilder<DmpUser, DmpUserEntity>{
private final BuilderFactory builderFactory;
private final QueryFactory queryFactory;
private EnumSet<AuthorizationFlags> authorize = EnumSet.of(AuthorizationFlags.None);
@Autowired
public DmpUserBuilder(
ConventionService conventionService,
BuilderFactory builderFactory, QueryFactory queryFactory) {
super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpUserBuilder.class)));
this.builderFactory = builderFactory;
this.queryFactory = queryFactory;
}
public DmpUserBuilder authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
@Override
public List<DmpUser> build(FieldSet fields, List<DmpUserEntity> 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(DmpUser._user));
Map<UUID, UserInfo> userItemsMap = this.collectUsers(userFields, data);
FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpUser._dmp));
Map<UUID, Dmp> dmpItemsMap = this.collectDmps(dmpFields, 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()));
}
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, UserInfo> collectUsers(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", UserInfo.class.getSimpleName());
Map<UUID, UserInfo> itemMap;
if (!fields.hasOtherField(this.asIndexer("id"))) {
itemMap = this.asEmpty(
data.stream().map(DmpUserEntity::getUser).distinct().collect(Collectors.toList()),
x -> {
UserInfo item = new UserInfo();
item.setId(x);
return item;
},
UserInfo::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);
}
if (!fields.hasField(Reference._id)) {
// itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList());
}
// return itemMap;
return new HashMap<>();
}
private Map<UUID, Dmp> collectDmps(FieldSet fields, List<DmpUserEntity> data) throws MyApplicationException {
if (fields.isEmpty() || data.isEmpty())
return null;
this.logger.debug("checking related - {}", Dmp.class.getSimpleName());
Map<UUID, Dmp> itemMap;
if (!fields.hasOtherField(this.asIndexer(Dmp._id))) {
itemMap = this.asEmpty(
data.stream().map(DmpUserEntity::getDmp).distinct().collect(Collectors.toList()),
x -> {
Dmp item = new Dmp();
item.setId(x);
return item;
},
Dmp::getId);
} else {
FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id);
DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getDmp).distinct().collect(Collectors.toList()));
itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId);
}
if (!fields.hasField(Dmp._id)) {
itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList());
}
return itemMap;
}
}

View File

@ -0,0 +1,76 @@
package eu.eudat.model.deleter;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.query.DmpUserQuery;
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 DmpUserDeleter implements Deleter {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpUserDeleter.class));
private final EntityManager entityManager;
protected final QueryFactory queryFactory;
protected final DeleterFactory deleterFactory;
@Autowired
public DmpUserDeleter(
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<DmpUserEntity> data = this.queryFactory.query(DmpUserQuery.class).ids(ids).collect();
logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0));
this.deleteAndSave(data);
}
public void deleteAndSave(List<DmpUserEntity> 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<DmpUserEntity> data) throws InvalidApplicationException {
logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0));
if (data == null || data.isEmpty())
return;
for (DmpUserEntity item : data) {
logger.trace("deleting item {}", item.getId());
logger.trace("updating item");
item.setUpdatedAt(Instant.now());
item.setIsActive(IsActive.Inactive);
this.entityManager.merge(item);
logger.trace("updated item");
}
}
}

View File

@ -0,0 +1,182 @@
package eu.eudat.query;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.enums.DmpUserRole;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.model.DmpUser;
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 DmpUserQuery extends QueryBase<DmpUserEntity> {
private Collection<UUID> ids;
private Collection<UUID> dmpIds;
private Collection<UUID> userIds;
private Collection<DmpUserRole> userRoles;
private EnumSet<AuthorizationFlags> authorize = EnumSet.of(AuthorizationFlags.None);
public DmpUserQuery ids(UUID value) {
this.ids = List.of(value);
return this;
}
public DmpUserQuery ids(UUID... value) {
this.ids = Arrays.asList(value);
return this;
}
public DmpUserQuery ids(Collection<UUID> values) {
this.ids = values;
return this;
}
public DmpUserQuery dmpIds(UUID value) {
this.dmpIds = List.of(value);
return this;
}
public DmpUserQuery dmpIds(UUID... value) {
this.dmpIds = Arrays.asList(value);
return this;
}
public DmpUserQuery dmpIds(Collection<UUID> values) {
this.dmpIds = values;
return this;
}
public DmpUserQuery userRoles(DmpUserRole value) {
this.userRoles = List.of(value);
return this;
}
public DmpUserQuery userRoles(DmpUserRole... value) {
this.userRoles = Arrays.asList(value);
return this;
}
public DmpUserQuery userRoles(Collection<DmpUserRole> values) {
this.userRoles = values;
return this;
}
public DmpUserQuery userIds(UUID value) {
this.userIds = List.of(value);
return this;
}
public DmpUserQuery userIds(UUID... value) {
this.userIds = Arrays.asList(value);
return this;
}
public DmpUserQuery userIds(Collection<UUID> values) {
this.userIds = values;
return this;
}
public DmpUserQuery authorize(EnumSet<AuthorizationFlags> values) {
this.authorize = values;
return this;
}
private final UserScope userScope;
private final AuthorizationService authService;
public DmpUserQuery(
UserScope userScope,
AuthorizationService authService
) {
this.userScope = userScope;
this.authService = authService;
}
@Override
protected Class<DmpUserEntity> entityClass() {
return DmpUserEntity.class;
}
@Override
protected Boolean isFalseQuery() {
return this.isEmpty(this.ids) || this.isEmpty(this.dmpIds) || this.isEmpty(this.userIds);
}
@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(DmpUserEntity._id));
for (UUID item : this.ids)
inClause.value(item);
predicates.add(inClause);
}
if (this.dmpIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._dmp));
for (UUID item : this.dmpIds)
inClause.value(item);
predicates.add(inClause);
}
if (this.userIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._user));
for (UUID item : this.userIds)
inClause.value(item);
predicates.add(inClause);
}
if (this.userRoles != null) {
CriteriaBuilder.In<DmpUserRole> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(DmpUserEntity._role));
for (DmpUserRole item : this.userRoles)
inClause.value(item);
predicates.add(inClause);
}
if (!predicates.isEmpty()) {
Predicate[] predicatesArray = predicates.toArray(new Predicate[0]);
return queryContext.CriteriaBuilder.and(predicatesArray);
} else {
return null;
}
}
@Override
protected DmpUserEntity convert(Tuple tuple, Set<String> columns) {
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.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));
return item;
}
@Override
protected String fieldNameOf(FieldResolver item) {
if (item.match(DmpUser._id)) return DmpUserEntity._id;
else if (item.prefix(DmpUser._dmp)) return DmpUserEntity._dmp;
else if (item.prefix(DmpUser._user)) return DmpUserEntity._user;
else if (item.match(DmpUser._role)) return DmpUserEntity._role;
else if (item.match(DmpUser._createdAt)) return DmpUserEntity._createdAt;
else if (item.match(DmpUser._updatedAt)) return DmpUserEntity._updatedAt;
else return null;
}
}

View File

@ -13,7 +13,7 @@ CREATE TABLE IF NOT EXISTS public."DmpDescriptionTemplate"
"created_at" timestamp without time zone NOT NULL DEFAULT now(),
"updated_at" timestamp without time zone NOT NULL DEFAULT now(),
"is_active" smallint NOT NULL DEFAULT 1,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT "DmpDescriptionTemplate_pkey" PRIMARY KEY (id),
CONSTRAINT "DmpDescriptionTemplate_dmp_fkey" FOREIGN KEY (dmp)
REFERENCES public."Dmp" (id),
CONSTRAINT "DmpDescriptionTemplate_description_template_fkey" FOREIGN KEY (description_template)

View File

@ -0,0 +1,25 @@
DO $$DECLARE
this_version CONSTANT varchar := '00.01.013';
BEGIN
PERFORM * FROM "DBVersion" WHERE version = this_version;
IF FOUND THEN RETURN; END IF;
CREATE TABLE IF NOT EXISTS public."DmpUser"
(
"id" uuid NOT NULL,
"dmp" uuid NOT NULL,
"user" uuid NOT NULL,
"role" smallint NOT NULL DEFAULT 0,
"created_at" timestamp without time zone NOT NULL DEFAULT now(),
"updated_at" timestamp without time zone NOT NULL DEFAULT now(),
"is_active" smallint NOT NULL DEFAULT 1,
CONSTRAINT "DmpUser_pkey" PRIMARY KEY (id),
CONSTRAINT "DmpUser_dmp_fkey" FOREIGN KEY ("dmp")
REFERENCES public."Dmp" (id),
CONSTRAINT "DmpUser_user_fkey" FOREIGN KEY ("user")
REFERENCES public."UserInfo" (id)
)
INSERT INTO public."DBVersion" VALUES ('DMPDB', '00.01.013', '2023-11-07 12:00:00.000000+02', now(), 'Add Dmp User table (former UserDMP).');
END$$;