diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDao.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDao.java index a6f3e7b8e..4abb033f5 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDao.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDao.java @@ -11,4 +11,5 @@ public interface UserInfoDao extends DatabaseAccessLayer { QueryableList getWithCriteria(UserInfoCriteria criteria); + QueryableList getAuthenticated(QueryableList users, UUID principalId); } \ No newline at end of file diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDaoImpl.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDaoImpl.java index 584516d3c..93fb0321d 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDaoImpl.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/UserInfoDaoImpl.java @@ -5,61 +5,75 @@ import eu.eudat.data.dao.criteria.UserInfoCriteria; import eu.eudat.data.dao.databaselayer.service.DatabaseService; import eu.eudat.data.entities.UserInfo; import eu.eudat.queryable.QueryableList; +import eu.eudat.queryable.types.FieldSelectionType; +import eu.eudat.queryable.types.SelectionField; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; +import java.util.Arrays; import java.util.UUID; import java.util.concurrent.CompletableFuture; @Component("userInfoDao") public class UserInfoDaoImpl extends DatabaseAccess implements UserInfoDao { - @Autowired - public UserInfoDaoImpl(DatabaseService databaseService) { - super(databaseService); - } + @Autowired + public UserInfoDaoImpl(DatabaseService databaseService) { + super(databaseService); + } - @Override - public QueryableList getWithCriteria(UserInfoCriteria criteria) { - QueryableList users = this.getDatabaseService().getQueryable(UserInfo.class); - if (criteria.getAppRoles() != null && !criteria.getAppRoles().isEmpty()) - users.where((builder, root) -> root.join("userRoles").get("role").in(criteria.getAppRoles())); - if (criteria.getLike() != null) - users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + criteria.getLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + criteria.getLike() + "%"))); - if (criteria.getEmail() != null) - users.where((builder, root) -> builder.equal(root.get("email"), criteria.getEmail())); - return users; - } + @Override + public QueryableList getWithCriteria(UserInfoCriteria criteria) { + QueryableList users = this.getDatabaseService().getQueryable(UserInfo.class); + if (criteria.getAppRoles() != null && !criteria.getAppRoles().isEmpty()) + users.where((builder, root) -> root.join("userRoles").get("role").in(criteria.getAppRoles())); + if (criteria.getLike() != null) + users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + criteria.getLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + criteria.getLike() + "%"))); + if (criteria.getEmail() != null) + users.where((builder, root) -> builder.equal(root.get("email"), criteria.getEmail())); + return users; + } - @Override - public UserInfo createOrUpdate(UserInfo item) { - return this.getDatabaseService().createOrUpdate(item, UserInfo.class); - } + @Override + public QueryableList getAuthenticated(QueryableList users, UUID principalId) { + users.initSubQuery(UUID.class).where((builder, root) -> + builder.and(builder.equal(root.join("dmps").get("id"), + users.subQuery((builder1, root1) -> builder1.equal(root1.join("dmps").get("id"), principalId), + Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmps:id")))), + builder.notEqual(root.get("id"), principalId))); - @Override - public UserInfo find(UUID id) { - return this.getDatabaseService().getQueryable(UserInfo.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); - } + return users; + } - @Override - public void delete(UserInfo item) { - this.getDatabaseService().delete(item); - } + @Override + public UserInfo createOrUpdate(UserInfo item) { + return this.getDatabaseService().createOrUpdate(item, UserInfo.class); + } - @Override - public QueryableList asQueryable() { - return this.getDatabaseService().getQueryable(UserInfo.class); - } + @Override + public UserInfo find(UUID id) { + return this.getDatabaseService().getQueryable(UserInfo.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } - @Async - @Override - public CompletableFuture createOrUpdateAsync(UserInfo item) { - return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); - } + @Override + public void delete(UserInfo item) { + this.getDatabaseService().delete(item); + } - @Override - public UserInfo find(UUID id, String hint) { - throw new UnsupportedOperationException(); - } + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserInfo.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(UserInfo item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserInfo find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } } \ No newline at end of file diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/entities/UserInfo.java b/dmp-backend/data/src/main/java/eu/eudat/data/entities/UserInfo.java index 2d69f5083..cd45762a9 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/entities/UserInfo.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/entities/UserInfo.java @@ -14,7 +14,7 @@ import java.util.*; @NamedEntityGraphs({ @NamedEntityGraph( name = "userInfo", - attributeNodes = {@NamedAttributeNode("userRoles"), @NamedAttributeNode("credentials")}) + attributeNodes = {@NamedAttributeNode("userRoles"), @NamedAttributeNode("credentials"),@NamedAttributeNode("dmps")}), }) public class UserInfo implements DataEntity { diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java index 71e1331dd..eed0bba6b 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java +++ b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java @@ -18,405 +18,415 @@ import java.util.stream.Collectors; public class QueryableHibernateList implements QueryableList { - private EntityManager manager; - private CriteriaQuery query; - private Class tClass; - private Root root; - private Root nestedQueryRoot; - private Subquery subquery; - private List> singlePredicates = new LinkedList<>(); - private List> nestedPredicates = new LinkedList<>(); - private boolean distinct = false; - private List> orderings = new LinkedList<>(); - private List fields = new LinkedList<>(); - private Integer length; - private Integer offset; - private Set hints; - private String hint; + private EntityManager manager; + private CriteriaQuery query; + private Class tClass; + private Root root; + private Root nestedQueryRoot; + private Subquery subquery; + private List> singlePredicates = new LinkedList<>(); + private List> nestedPredicates = new LinkedList<>(); + private boolean distinct = false; + private List> orderings = new LinkedList<>(); + private List fields = new LinkedList<>(); + private Integer length; + private Integer offset; + private Set hints; + private String hint; - public QueryableHibernateList(EntityManager manager, Class tClass) { - this.manager = manager; - this.tClass = tClass; - } + public QueryableHibernateList(EntityManager manager, Class tClass) { + this.manager = manager; + this.tClass = tClass; + } - public QueryableHibernateList setManager(EntityManager manager) { - this.manager = manager; - return this; - } + public QueryableHibernateList setManager(EntityManager manager) { + this.manager = manager; + return this; + } - public QueryableList withHint(String hint) { - this.hint = hint; - return this; - } + public QueryableList withHint(String hint) { + this.hint = hint; + return this; + } - @Override - public QueryableList withFields(List fields) { - this.fields = fields; - return this; - } + @Override + public QueryableList withFields(List fields) { + this.fields = fields; + return this; + } - private QueryableList selectFields() { - List rootFields = fields.stream().map(field -> this.convertFieldToPath(field)).collect(Collectors.toList()); - this.query.select(this.manager.getCriteriaBuilder().tuple(rootFields.toArray(new Selection[rootFields.size()]))); - return this; - } + private QueryableList selectFields() { + List rootFields = fields.stream().map(field -> this.convertFieldToPath(field)).collect(Collectors.toList()); + this.query.select(this.manager.getCriteriaBuilder().tuple(rootFields.toArray(new Selection[rootFields.size()]))); + return this; + } - private Path convertFieldToPath(String field) { - if (!field.contains(".")) { - Path path = this.root.get(field); - path.alias(field); - return path; - } else { - String[] fields = field.split("\\."); - Path path = this.root.get(fields[0]); - Join join = null; - path.alias(fields[0]); - for (int i = 1; i < fields.length; i++) { - join = join != null ? join.join(fields[i - 1], JoinType.LEFT) : this.root.join(fields[i - 1], JoinType.LEFT) ; - path = join.get(fields[i]); - path.alias(String.join(".", Arrays.asList(fields).subList(0, i + 1))); - } - return path; - } - } + private Path convertFieldToPath(String field) { + if (!field.contains(".")) { + Path path = this.root.get(field); + path.alias(field); + return path; + } else { + String[] fields = field.split("\\."); + Path path = this.root.get(fields[0]); + Join join = null; + path.alias(fields[0]); + for (int i = 1; i < fields.length; i++) { + join = join != null ? join.join(fields[i - 1], JoinType.LEFT) : this.root.join(fields[i - 1], JoinType.LEFT); + path = join.get(fields[i]); + path.alias(String.join(".", Arrays.asList(fields).subList(0, i + 1))); + } + return path; + } + } - public QueryableHibernateList setEntity(Class type) { + public QueryableHibernateList setEntity(Class type) { - return this; - } + return this; + } - public void initiateQueryableList(Class type) { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - this.query = builder.createQuery(type); - } + public void initiateQueryableList(Class type) { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + this.query = builder.createQuery(type); + } - @Override - public QueryableList skip(Integer offset) { - this.offset = offset; - return this; - } + @Override + public QueryableList skip(Integer offset) { + this.offset = offset; + return this; + } - @Override - public QueryableList take(Integer length) { - this.length = length; - return this; - } + @Override + public QueryableList take(Integer length) { + this.length = length; + return this; + } - public QueryableList where(SinglePredicate predicate) { - this.singlePredicates.add(predicate); - return this; - } + public QueryableList where(SinglePredicate predicate) { + this.singlePredicates.add(predicate); + return this; + } - public QueryableList where(NestedQuerySinglePredicate predicate) { - this.nestedPredicates.add(predicate); - return this; - } + public QueryableList where(NestedQuerySinglePredicate predicate) { + this.nestedPredicates.add(predicate); + return this; + } - public List select(SelectPredicate predicate) { - return this.toList().stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList()); - } + public List select(SelectPredicate predicate) { + return this.toList().stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList()); + } - public CompletableFuture> selectAsync(SelectPredicate predicate) { - return this.toListAsync().thenApplyAsync(items -> items.stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList())); - } + public CompletableFuture> selectAsync(SelectPredicate predicate) { + return this.toListAsync().thenApplyAsync(items -> items.stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList())); + } - public QueryableList distinct() { - this.distinct = true; - return this; - } + public QueryableList distinct() { + this.distinct = true; + return this; + } - public QueryableList orderBy(OrderByPredicate predicate) { - this.orderings.add(predicate); - return this; - } + public QueryableList orderBy(OrderByPredicate predicate) { + this.orderings.add(predicate); + return this; + } - public Long count() { - CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); - this.root = criteriaQuery.from(tClass); - if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); - else criteriaQuery.select(criteriaBuilder.count(this.root)); - criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - //if (distinct) criteriaQuery.distinct(true); - return this.manager.createQuery(criteriaQuery).getSingleResult(); - } + public Long count() { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); + this.root = criteriaQuery.from(tClass); + if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); + else criteriaQuery.select(criteriaBuilder.count(this.root)); + criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + //if (distinct) criteriaQuery.distinct(true); + return this.manager.createQuery(criteriaQuery).getSingleResult(); + } - @Async - public CompletableFuture countAsync() { - CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); - this.root = criteriaQuery.from(tClass); - if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); - else criteriaQuery.select(criteriaBuilder.count(this.root)); - criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - //if (distinct) criteriaQuery.distinct(true); - return CompletableFuture.supplyAsync(() -> this.manager.createQuery(criteriaQuery).getSingleResult()); - } + @Async + public CompletableFuture countAsync() { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); + this.root = criteriaQuery.from(tClass); + if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); + else criteriaQuery.select(criteriaBuilder.count(this.root)); + criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + //if (distinct) criteriaQuery.distinct(true); + return CompletableFuture.supplyAsync(() -> this.manager.createQuery(criteriaQuery).getSingleResult()); + } - private Predicate[] generateWherePredicates(List> singlePredicates, Root root, List> nestedPredicates, Root nestedQueryRoot) { - List predicates = new LinkedList<>(); - predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root))); - predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot))); - return predicates.toArray(new Predicate[predicates.size()]); - } + private Predicate[] generateWherePredicates(List> singlePredicates, Root root, List> nestedPredicates, Root nestedQueryRoot) { + List predicates = new LinkedList<>(); + predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root))); + predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot))); + return predicates.toArray(new Predicate[predicates.size()]); + } - private Predicate[] generateSingleWherePredicates(List> singlePredicates, Root root) { - List predicates = new LinkedList<>(); - for (SinglePredicate singlePredicate : singlePredicates) { - predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); - } - return predicates.toArray(new Predicate[predicates.size()]); - } + private Predicate[] generateSingleWherePredicates(List> singlePredicates, Root root) { + List predicates = new LinkedList<>(); + for (SinglePredicate singlePredicate : singlePredicates) { + predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); + } + return predicates.toArray(new Predicate[predicates.size()]); + } - private Predicate[] generateNestedWherePredicates(List> nestedPredicates, Root root, Root nestedQueryRoot) { - List predicates = new LinkedList<>(); - for (NestedQuerySinglePredicate singlePredicate : nestedPredicates) { - predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root, nestedQueryRoot)); - } - return predicates.toArray(new Predicate[predicates.size()]); - } + private Predicate[] generateNestedWherePredicates(List> nestedPredicates, Root root, Root nestedQueryRoot) { + List predicates = new LinkedList<>(); + for (NestedQuerySinglePredicate singlePredicate : nestedPredicates) { + predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root, nestedQueryRoot)); + } + return predicates.toArray(new Predicate[predicates.size()]); + } - private Order[] generateOrderPredicates(List> orderByPredicates, Root root) { - List predicates = new LinkedList<>(); - for (OrderByPredicate orderPredicate : orderByPredicates) { - predicates.add(orderPredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); - } - return predicates.toArray(new Order[predicates.size()]); - } + private Order[] generateOrderPredicates(List> orderByPredicates, Root root) { + List predicates = new LinkedList<>(); + for (OrderByPredicate orderPredicate : orderByPredicates) { + predicates.add(orderPredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); + } + return predicates.toArray(new Order[predicates.size()]); + } - public List toList() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); - if (!this.fields.isEmpty()) this.selectFields(); - if (distinct) this.query.distinct(true); - if (!this.fields.isEmpty()) return this.toListWithFields(); - else return this.toListWithOutFields(); - } + public List toList() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); + if (!this.fields.isEmpty()) this.selectFields(); + if (distinct) this.query.distinct(true); + if (!this.fields.isEmpty()) return this.toListWithFields(); + else return this.toListWithOutFields(); + } - private List toListWithFields() { - List results = this.manager.createQuery(query).getResultList(); - Map> groupedResults = results.stream() - .collect(Collectors.groupingBy(x -> x.get("id"))); - return results.stream().map(x -> { - try { - return (T) this.tClass.newInstance().buildFromTuple(groupedResults.get(x.get("id")), ""); - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - }).collect(Collectors.toList()); - } + private List toListWithFields() { + List results = this.manager.createQuery(query).getResultList(); + Map> groupedResults = results.stream() + .collect(Collectors.groupingBy(x -> x.get("id"))); + return results.stream().map(x -> { + try { + return (T) this.tClass.newInstance().buildFromTuple(groupedResults.get(x.get("id")), ""); + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + }).collect(Collectors.toList()); + } - private List toListWithOutFields() { - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.offset != null) typedQuery.setFirstResult(this.offset); - if (this.length != null) typedQuery.setMaxResults(this.length); - if (this.hint != null) { - List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); - if (ids != null && !ids.isEmpty()) typedQuery = queryWithHint(ids); - } - return typedQuery.getResultList(); - } + private List toListWithOutFields() { + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.offset != null) typedQuery.setFirstResult(this.offset); + if (this.length != null) typedQuery.setMaxResults(this.length); + if (this.hint != null) { + List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); + if (ids != null && !ids.isEmpty()) typedQuery = queryWithHint(ids); + } + return typedQuery.getResultList(); + } - @Async - public CompletableFuture> toListAsync() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); - if (!this.fields.isEmpty()) this.selectFields(); - if (distinct) this.query.distinct(true); - if (!this.fields.isEmpty()) return this.toListAsyncWithFields(); - else return this.toListAsyncWithOutFields(); - } + @Async + public CompletableFuture> toListAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); + if (!this.fields.isEmpty()) this.selectFields(); + if (distinct) this.query.distinct(true); + if (!this.fields.isEmpty()) return this.toListAsyncWithFields(); + else return this.toListAsyncWithOutFields(); + } - private CompletableFuture> toListAsyncWithFields() { - List results = this.manager.createQuery(query).getResultList(); - Map> groupedResults = results.stream() - .collect(Collectors.groupingBy(x -> x.get("id"))); - return CompletableFuture.supplyAsync(() -> results.stream().map(x -> { - try { - return (T) this.tClass.newInstance().buildFromTuple(groupedResults.get(x.get("id")), ""); - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - }).collect(Collectors.toList())); - } + private CompletableFuture> toListAsyncWithFields() { + List results = this.manager.createQuery(query).getResultList(); + Map> groupedResults = results.stream() + .collect(Collectors.groupingBy(x -> x.get("id"))); + return CompletableFuture.supplyAsync(() -> results.stream().map(x -> { + try { + return (T) this.tClass.newInstance().buildFromTuple(groupedResults.get(x.get("id")), ""); + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + }).collect(Collectors.toList())); + } - private CompletableFuture> toListAsyncWithOutFields() { - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.offset != null) typedQuery.setFirstResult(this.offset); - if (this.length != null) typedQuery.setMaxResults(this.length); - return CompletableFuture.supplyAsync(() -> { - if (this.hint != null) { - List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); - if (ids != null && !ids.isEmpty()) return queryWithHint(ids).getResultList(); - } - return typedQuery.getResultList(); - }); - } + private CompletableFuture> toListAsyncWithOutFields() { + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.offset != null) typedQuery.setFirstResult(this.offset); + if (this.length != null) typedQuery.setMaxResults(this.length); + return CompletableFuture.supplyAsync(() -> { + if (this.hint != null) { + List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); + if (ids != null && !ids.isEmpty()) return queryWithHint(ids).getResultList(); + } + return typedQuery.getResultList(); + }); + } - public T getSingle() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.fields.isEmpty()) this.selectFields(); - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.hint != null) - typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); - return typedQuery.getSingleResult(); - } + public T getSingle() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return typedQuery.getSingleResult(); + } - @Async - public CompletableFuture getSingleAsync() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.fields.isEmpty()) this.selectFields(); - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.hint != null) - typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); - return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult()); - } + @Async + public CompletableFuture getSingleAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult()); + } - public T getSingleOrDefault() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.fields.isEmpty()) this.selectFields(); - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.hint != null) - typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); - List results = typedQuery.getResultList(); - if (results.size() == 0) return null; - if (results.size() == 1) return results.get(0); - else throw new NotSingleResultException("Query returned more than one items"); - } + public T getSingleOrDefault() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + List results = typedQuery.getResultList(); + if (results.size() == 0) return null; + if (results.size() == 1) return results.get(0); + else throw new NotSingleResultException("Query returned more than one items"); + } - @Async - public CompletableFuture getSingleOrDefaultAsync() { - CriteriaBuilder builder = this.manager.getCriteriaBuilder(); - if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); - else this.query = builder.createQuery(this.tClass); - this.root = this.query.from(this.tClass); - this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - if (!this.fields.isEmpty()) this.selectFields(); - TypedQuery typedQuery = this.manager.createQuery(this.query); - if (this.hint != null) - typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); - return CompletableFuture.supplyAsync(() -> typedQuery.getResultList()).thenApply(list -> { - if (list.size() == 0) return null; - if (list.size() == 1) return list.get(0); - else throw new NotSingleResultException("Query returned more than one items"); - }); - } + @Async + public CompletableFuture getSingleOrDefaultAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return CompletableFuture.supplyAsync(() -> typedQuery.getResultList()).thenApply(list -> { + if (list.size() == 0) return null; + if (list.size() == 1) return list.get(0); + else throw new NotSingleResultException("Query returned more than one items"); + }); + } - private TypedQuery queryWithHint(List ids) { - CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(tClass); - Root criteriaRoot = criteriaQuery.from(this.tClass); - criteriaQuery.where(criteriaRoot.get("id").in(ids)); - if (!this.orderings.isEmpty()) - criteriaQuery.orderBy(this.generateOrderPredicates(this.orderings, criteriaRoot)); + private TypedQuery queryWithHint(List ids) { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(tClass); + Root criteriaRoot = criteriaQuery.from(this.tClass); + criteriaQuery.where(criteriaRoot.get("id").in(ids)); + if (!this.orderings.isEmpty()) + criteriaQuery.orderBy(this.generateOrderPredicates(this.orderings, criteriaRoot)); - TypedQuery typedQuery = this.manager.createQuery(criteriaQuery); - typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); - return typedQuery; - } + TypedQuery typedQuery = this.manager.createQuery(criteriaQuery); + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return typedQuery; + } - @Override - public Subquery subQuery(SinglePredicate predicate, List fields) { - Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); - this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); - subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); - return subquery; - } + @Override + public Subquery subQuery(SinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.nestedQueryRoot.join(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1])); + } + return subquery; + } - @Override - public Subquery subQuery(NestedQuerySinglePredicate predicate, List fields) { - Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); - this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); - subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); - return subquery; - } + @Override + public Subquery subQuery(NestedQuerySinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1])); + } + return subquery; + } - @Override - public Subquery subQueryCount(SinglePredicate predicate, List fields) { - Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); - this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); - subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); - return subquery; - } + @Override + public Subquery subQueryCount(SinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); + return subquery; + } - @Override - public Subquery subQueryCount(NestedQuerySinglePredicate predicate, List fields) { - Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); - this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); - subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); - return subquery; - } + @Override + public Subquery subQueryCount(NestedQuerySinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); + return subquery; + } - @Override - public Subquery subQueryMax(SinglePredicate predicate, List fields, Class uClass) { - Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); - this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); - if (fields.get(0).getType() == FieldSelectionType.FIELD) - subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); - else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { - subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); - } - return subquery; - } + @Override + public Subquery subQueryMax(SinglePredicate predicate, List fields, Class uClass) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); + } + return subquery; + } - @Override - public Subquery subQueryMax(NestedQuerySinglePredicate predicate, List fields, Class uClass) { - //Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); - //this.nestedQueryRoot = subquery.from(this.tClass); - subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); - if (fields.get(0).getType() == FieldSelectionType.FIELD) - subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); - else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { - subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); - } - return subquery; - } + @Override + public Subquery subQueryMax(NestedQuerySinglePredicate predicate, List fields, Class uClass) { + //Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + //this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); + } + return subquery; + } - public QueryableList initSubQuery(Class uClass) { - this.subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); - this.nestedQueryRoot = subquery.from(this.tClass); - return this; - } + public QueryableList initSubQuery(Class uClass) { + this.subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + this.nestedQueryRoot = subquery.from(this.tClass); + return this; + } - @Override - public void update(EntitySelectPredicate selectPredicate, V value) { - CriteriaBuilder builder = this.manager - .getCriteriaBuilder(); - CriteriaUpdate update = builder - .createCriteriaUpdate(tClass); - this.root = update.from(tClass); - update.set(selectPredicate.applyPredicate(root), value) - .where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); - this.manager - .createQuery(update) - .executeUpdate(); - } + @Override + public void update(EntitySelectPredicate selectPredicate, V value) { + CriteriaBuilder builder = this.manager + .getCriteriaBuilder(); + CriteriaUpdate update = builder + .createCriteriaUpdate(tClass); + this.root = update.from(tClass); + update.set(selectPredicate.applyPredicate(root), value) + .where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + this.manager + .createQuery(update) + .executeUpdate(); + } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java index 820f94cee..5d7f48319 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/Users.java @@ -69,7 +69,7 @@ public class Users extends BaseController { @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json") public @ResponseBody - ResponseEntity>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + ResponseEntity>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { DataTableData dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UserManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UserManager.java index 6a227eab5..352af13a0 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UserManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UserManager.java @@ -1,11 +1,9 @@ package eu.eudat.logic.managers; import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.data.dao.entities.DMPDao; import eu.eudat.data.dao.entities.UserInfoDao; import eu.eudat.data.entities.DMP; -import eu.eudat.data.entities.UserDMP; +import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserRole; import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem; import eu.eudat.exceptions.security.UnauthorisedException; @@ -19,7 +17,6 @@ import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.login.Credentials; import eu.eudat.models.data.security.Principal; -import eu.eudat.models.data.userinfo.UserInfo; import eu.eudat.models.data.userinfo.UserListingModel; import eu.eudat.models.data.userinfo.UserProfile; import eu.eudat.queryable.QueryableList; @@ -30,114 +27,87 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; @Component public class UserManager { - private ApiContext apiContext; + private ApiContext apiContext; - @Autowired - public UserManager(ApiContext apiContext) { - this.apiContext = apiContext; - } + @Autowired + public UserManager(ApiContext apiContext) { + this.apiContext = apiContext; + } - public eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.data.entities.DatasetProfile profile) { - Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); - Element root = (Element) viewStyleDoc.getDocumentElement(); - eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel viewstyle = new eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel().fromXml(root); + public eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.data.entities.DatasetProfile profile) { + Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); + Element root = (Element) viewStyleDoc.getDocumentElement(); + eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel viewstyle = new eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel().fromXml(root); - eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = new eu.eudat.models.data.user.composite.DatasetProfile(); - datasetprofile.buildProfile(viewstyle); + eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = new eu.eudat.models.data.user.composite.DatasetProfile(); + datasetprofile.buildProfile(viewstyle); - return datasetprofile; - } + return datasetprofile; + } - public DataTableData getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { - QueryableList users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class)); - QueryableList pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem); + public DataTableData getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { + QueryableList users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class)); + QueryableList pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem); - List modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item)); - return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build(); - } + List modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item)); + return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build(); + } - public UserProfile getSingle(UUID userId) throws Exception { - eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); - UserProfile profile = new UserProfile().fromDataModel(user); - List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable(), userId).take(5).toList(); - profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList())); - return profile; - } + public UserProfile getSingle(UUID userId) throws Exception { + eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); + UserProfile profile = new UserProfile().fromDataModel(user); + List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable(), userId).take(5).toList(); + profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList())); + return profile; + } - public void editRoles(UserListingModel user) { - eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId()); - userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item)); - for (Integer role : user.getAppRoles()) { - UserRole userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build(); - apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole); - } - } + public void editRoles(UserListingModel user) { + eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId()); + userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item)); + for (Integer role : user.getAppRoles()) { + UserRole userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build(); + apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole); + } + } - public void updateSettings(Map settings, Principal principal) throws IOException { - eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); - apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo); - HashMap result = - new ObjectMapper().readValue(userInfo.getAdditionalinfo(), HashMap.class); - result.putAll(settings); - userInfo.setAdditionalinfo(new JSONObject(result).toString()); - apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao() - .createOrUpdate(userInfo); - } + public void updateSettings(Map settings, Principal principal) throws IOException { + eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo); + HashMap result = + new ObjectMapper().readValue(userInfo.getAdditionalinfo(), HashMap.class); + result.putAll(settings); + userInfo.setAdditionalinfo(new JSONObject(result).toString()); + apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao() + .createOrUpdate(userInfo); + } - public Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) { - Principal principal = authenticationServiceImpl.Touch(credentials); - if (principal == null) throw new UnauthorisedException("Could not Sign In User"); - return principal; - } + public Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) { + Principal principal = authenticationServiceImpl.Touch(credentials); + if (principal == null) throw new UnauthorisedException("Could not Sign In User"); + return principal; + } - public DataTableData getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { - //UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao(); - DMPDao dmpDao = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(); + public DataTableData getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { + UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao(); - // Gets all the DMPs the user is associated. - DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); - QueryableList dmpItmes = dmpDao.getWithCriteria(dataManagementPlanCriteria); - QueryableList dmpAuthItems = dmpDao.getAuthenticated(dmpItmes, principal.getId()); - List dmpList = dmpAuthItems.toList(); + QueryableList users = userInfoDao.asQueryable(); - // List to place the associated users. - List associatedUsersList = new LinkedList<>(); + List colaborators = userInfoDao.getAuthenticated(users, principal.getId()) + .withHint(HintedModelFactory.getHint(UserListingModel.class)) + .select(colaborator -> new UserListingModel().fromDataModel(colaborator)); - // Iterate through the DMP list and get the users associated. - for (DMP dmp : dmpList) { - for (UserDMP userDMP : dmp.getUsers()) { - if (userDMP.getUser().getId() != principal.getId()) { - associatedUsersList.add(new UserListingModel().fromDataModel(userDMP.getUser())); - } - } - } - - // Remove duplicates from the associated users list. - associatedUsersList = associatedUsersList.stream().distinct().collect(Collectors.toList()); - - // Filter using the criteria. - List associatedUsersListFiltered = new LinkedList<>(); - associatedUsersList.stream() - .filter(item -> item.getName().toLowerCase().contains(userInfoTableRequestItem.getCriteria().getCollaboratorLike().toLowerCase())).forEach( - o -> { - associatedUsersListFiltered.add(o); - } - ); - - /*QueryableList users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class)); - QueryableList pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);*/ - - //List modelUsers = pagedUsers.select(item -> new listing model().fromDataModel(item)); - - DataTableData dataTableData = new DataTableData<>(); - dataTableData.setData(associatedUsersListFiltered); - dataTableData.setTotalCount((long)associatedUsersListFiltered.size()); - return dataTableData; - } + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setData(colaborators); + dataTableData.setTotalCount((long) colaborators.size()); + return dataTableData; + } }