diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java index 7780de09d..d58dd1ce5 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/DmpEntity.java @@ -18,7 +18,7 @@ import java.util.UUID; @Entity @Table(name = "\"Dmp\"") -public class DmpEntity extends TenantScopedBaseEntity implements DataEntity { +public class DmpEntity extends TenantScopedBaseEntity { @Id @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") @@ -246,20 +246,4 @@ public class DmpEntity extends TenantScopedBaseEntity implements DataEntity tuple, List fields, String base) { - return null; - } } diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDao.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDao.java deleted file mode 100644 index f565b96ad..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDao.java +++ /dev/null @@ -1,21 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.DatabaseAccessLayer; -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.data.dao.criteria.DatasetWizardUserDmpCriteria; -import eu.eudat.data.UserEntity; -import eu.eudat.queryable.QueryableList; - -import java.util.List; -import java.util.UUID; - -public interface DMPDao extends DatabaseAccessLayer { - - QueryableList getWithCriteria(DataManagementPlanCriteria criteria); - - QueryableList getUserDmps(DatasetWizardUserDmpCriteria datasetWizardAutocompleteRequest, UserEntity userInfo); - - QueryableList getAuthenticated(QueryableList query, UUID principalId, List roles); - -} \ No newline at end of file diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDaoImpl.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDaoImpl.java deleted file mode 100644 index dd7dd104e..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DMPDaoImpl.java +++ /dev/null @@ -1,154 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.commons.enums.DmpStatus; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.DatabaseAccess; -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.data.dao.criteria.DatasetWizardUserDmpCriteria; -import eu.eudat.data.dao.databaselayer.service.DatabaseService; -import eu.eudat.data.UserEntity; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; -import eu.eudat.types.grant.GrantStateType; -import jakarta.persistence.criteria.Join; -import jakarta.persistence.criteria.JoinType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -import javax.management.InvalidApplicationException; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - -@Component("dMPDao") -public class DMPDaoImpl extends DatabaseAccess implements DMPDao { - - @Autowired - public DMPDaoImpl(DatabaseService databaseService) { - super(databaseService); - } - - @Override - public QueryableList getWithCriteria(DataManagementPlanCriteria criteria) { - QueryableList query = getDatabaseService().getQueryable(DmpEntity.class); - if (criteria.getLike() != null && !criteria.getLike().isEmpty()) - query.where((builder, root) -> builder.or( - builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), - builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))); - if (criteria.getPeriodEnd() != null) - query.where((builder, root) -> builder.lessThan(root.get("created"), criteria.getPeriodEnd())); - if (criteria.getPeriodStart() != null) - query.where((builder, root) -> builder.greaterThan(root.get("created"), criteria.getPeriodStart())); - if (criteria.getProfile() != null) - query.where((builder, root) -> builder.equal(root.get("profile"), criteria.getProfile())); -// if (criteria.getGrants() != null && !criteria.getGrants().isEmpty()) //TODO -// query.where(((builder, root) -> root.get("grant").in(criteria.getGrants()))); - if (!criteria.getAllVersions()) - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), - query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and( - builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), - builder1.notEqual(nestedRoot.get("isActive"), IsActive.Inactive.getValue())), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), Integer.class))); - if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty()) - query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds())); - if (criteria.getStatus() != null) { - if (criteria.getStatus() == DmpStatus.Finalized.getValue().intValue()) { - query.where((builder, root) -> builder.equal(root.get("status"), DmpStatus.Finalized.getValue())); - } else if (criteria.getStatus() == DmpStatus.Draft.getValue().intValue()) { - query.where((builder, root) -> builder.equal(root.get("status"), DmpStatus.Draft.getValue())); - } - } - if (criteria.getIsPublic()) { - query.where(((builder, root) -> builder.equal(root.get("isPublic"), criteria.getIsPublic()))); - } - /*if (criteria.getRole() != null) { - if (criteria.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())) { - query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.OWNER.getValue())); - } else if (criteria.getRole().equals(UserDMP.UserDMPRoles.USER.getValue())) { - query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.USER.getValue())); - } - }*/ - if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) { - query.where((builder, root) -> root.join("organisations").get("reference").in(criteria.getOrganisations())); - } - if (criteria.getCollaborators() != null && !criteria.getCollaborators().isEmpty()) { - query.where((builder, root) -> root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id").in(criteria.getCollaborators())); - } - if (criteria.getDatasetTemplates() != null && !criteria.getDatasetTemplates().isEmpty()) { - query.where((builder, root) -> root.join("associatedDmps", JoinType.LEFT).get("id").in(criteria.getDatasetTemplates())); - } - if (criteria.getGrantStatus() != null) { - if (criteria.getGrantStatus().equals(GrantStateType.FINISHED.getValue().shortValue())) - query.where((builder, root) -> builder.lessThan(root.get("grant").get("enddate"), new Date())); - if (criteria.getGrantStatus().equals(GrantStateType.ONGOING.getValue().shortValue())) - query.where((builder, root) -> - builder.or(builder.greaterThan(root.get("grant").get("enddate"), new Date()) - , builder.isNull(root.get("grant").get("enddate")))); - } - - if (criteria.hasDoi()) { - query.where((builder, root) -> builder.not(builder.isNull(root.join("dois").get("id")))); - } - query.where((builder, root) -> builder.notEqual(root.get("isActive"), IsActive.Inactive)); - return query; - } - - public QueryableList getAuthenticated(QueryableList query, UUID principal, List roles) { - if (roles != null && !roles.isEmpty()) { - query.where((builder, root) -> { - Join userJoin = root.join("users", JoinType.LEFT); - return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal), userJoin.get("role").in(roles)); - }); - } else { - query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal)); - } - - return query; - } - - @Override - @Transactional - public DmpEntity createOrUpdate(DmpEntity item) { - return this.getDatabaseService().createOrUpdate(item, DmpEntity.class); - } - - @Override - public DmpEntity find(UUID id) throws InvalidApplicationException { - return getDatabaseService().getQueryable(DmpEntity.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); - } - - @Override - public QueryableList getUserDmps(DatasetWizardUserDmpCriteria datasetWizardUserDmpCriteria, UserEntity userInfo) { - QueryableList query = getDatabaseService().getQueryable(DmpEntity.class).where((builder, root) -> builder.or(builder.equal(root.get("creator"), userInfo), builder.isMember(userInfo, root.get("users")))); - if (datasetWizardUserDmpCriteria.getLike() != null && !datasetWizardUserDmpCriteria.getLike().isEmpty()) { - query.where((builder, root) -> builder.like(root.get("label"), "%" + datasetWizardUserDmpCriteria.getLike() + "%")); - } - return query; - } - - @Override - public void delete(DmpEntity item) { - this.getDatabaseService().delete(item); - } - - @Override - public QueryableList asQueryable() { - return this.getDatabaseService().getQueryable(DmpEntity.class); - } - - @Async - @Override - public CompletableFuture createOrUpdateAsync(DmpEntity item) { - return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); - } - - @Override - public DmpEntity find(UUID id, String hint) { - throw new UnsupportedOperationException(); - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java index c3cd862dd..572cec66a 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java @@ -13,7 +13,7 @@ import java.util.Collection; * Created by ikalyvas on 3/21/2018. */ public class PaginationService { - public static QueryableList applyPaging(QueryableList items, TableQuery tableRequest) { + public static QueryableList applyPaging(QueryableList items, TableQuery tableRequest) { if (tableRequest.getOrderings() != null) applyOrder(items, tableRequest); if (tableRequest.getLength() != null) items.take(tableRequest.getLength()); if (tableRequest.getOffset() != null) items.skip(tableRequest.getOffset()); @@ -21,12 +21,12 @@ public class PaginationService { items.withFields(Arrays.asList(tableRequest.getSelection().getFields())); return items; } - public static void applyOrder(QueryableList items, TableQuery tableRequest) { + public static void applyOrder(QueryableList items, TableQuery tableRequest) { applyOrder(items, tableRequest.getOrderings()); } - public static void applyOrder(QueryableList items, ColumnOrderings columnOrderings) { + public static void applyOrder(QueryableList items, ColumnOrderings columnOrderings) { for (Ordering ordering : columnOrderings.getFieldOrderings()) { if (ordering.getOrderByType() == Ordering.OrderByType.ASC) applyAscOrder(items, ordering); @@ -37,7 +37,7 @@ public class PaginationService { return; } - private static void applyAscOrder(QueryableList items, Ordering ordering) { + private static void applyAscOrder(QueryableList items, Ordering ordering) { if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { items.orderBy((builder, root) -> builder.asc(builder.size(root.get(ordering.getFieldName())))); } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { @@ -48,7 +48,7 @@ public class PaginationService { } } - private static void applyDescOrder(QueryableList items, Ordering ordering) { + private static void applyDescOrder(QueryableList items, Ordering ordering) { if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { items.orderBy((builder, root) -> builder.desc(builder.size(root.get(ordering.getFieldName())))); } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java index a7ec74232..e3ede8472 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java @@ -6,7 +6,7 @@ import eu.eudat.data.old.queryableentity.DataEntity; /** * Created by ikalyvas on 3/21/2018. */ -public interface Collector { +public interface Collector { QueryableList collect() throws Exception; QueryableList collect(QueryableList repo) throws Exception; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java index 271f67b18..48a4cb983 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java @@ -7,7 +7,7 @@ import eu.eudat.data.old.queryableentity.DataEntity; /** * Created by ikalyvas on 3/21/2018. */ -public interface CriteriaQuery, T extends DataEntity> extends Collector { +public interface CriteriaQuery, T> extends Collector { QueryableList applyCriteria(); } diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java index 4360b6d15..bde1e6fe0 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java @@ -7,7 +7,7 @@ import io.swagger.annotations.ApiModelProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public abstract class Query, T extends DataEntity> implements CriteriaQuery { +public abstract class Query, T> implements CriteriaQuery { private static final Logger logger = LoggerFactory.getLogger(Query.class); private C criteria; @ApiModelProperty(value = "query", name = "query", dataType = "String", hidden = true) diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java index 3243a91c0..eb3baa75b 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java @@ -7,6 +7,6 @@ import eu.eudat.data.old.queryableentity.DataEntity; /** * Created by ikalyvas on 3/21/2018. */ -public interface TableCriteriaQuery, T extends DataEntity> extends CriteriaQuery { +public interface TableCriteriaQuery, T> extends CriteriaQuery { QueryableList applyPaging(QueryableList items) ; } diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java index 6349a0f03..f3a3de05a 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java @@ -9,7 +9,7 @@ import eu.eudat.data.old.queryableentity.DataEntity; import io.swagger.annotations.ApiModelProperty; -public abstract class TableQuery, T extends DataEntity, K> extends Query implements TableCriteriaQuery { +public abstract class TableQuery, T, K> extends Query implements TableCriteriaQuery { private ColumnOrderings orderings; @ApiModelProperty(hidden = true) private SelectionFields selection; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java deleted file mode 100644 index 9cb1687db..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java +++ /dev/null @@ -1,17 +0,0 @@ -package eu.eudat.data.query.items.item.dataset; - -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.criteria.DatasetWizardUserDmpCriteria; -import eu.eudat.data.query.definition.Query; -import eu.eudat.queryable.QueryableList; - -public class DatasetWizardAutocompleteRequest extends Query { - @Override - public QueryableList applyCriteria() { - QueryableList query = this.getQuery().where((builder, root) -> builder.or(builder.equal(root.get("creator"), this.getCriteria().getUserInfo()), builder.isMember(this.getCriteria().getUserInfo(), root.get("users")))); - if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) { - query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%")); - } - return query; - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagementPlanTableRequest.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagementPlanTableRequest.java deleted file mode 100644 index 513df940b..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagementPlanTableRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package eu.eudat.data.query.items.table.dmp; - -import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.data.query.PaginationService; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; - -import java.util.Arrays; -import java.util.UUID; - -public class DataManagementPlanTableRequest extends TableQuery { - @Override - public QueryableList applyCriteria() { - QueryableList query = this.getQuery(); - if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) - query.where((builder, root) -> builder.or( - builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), - builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); - if (this.getCriteria().getPeriodEnd() != null) - query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd())); - if (this.getCriteria().getPeriodStart() != null) - query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart())); -// if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) -// query.where(((builder, root) -> root.get("grant").in(this.getCriteria().getGrants()))); //TODO - if (!this.getCriteria().getAllVersions()) - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class))); - if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty()) - query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds())); - query.where((builder, root) -> builder.notEqual(root.get("isActive"), IsActive.Inactive.getValue())); - return query; - } - - @Override - public QueryableList applyPaging(QueryableList items) { - return PaginationService.applyPaging(items, this); - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java deleted file mode 100644 index a585af283..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java +++ /dev/null @@ -1,54 +0,0 @@ -package eu.eudat.data.query.items.table.dmp; - -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.criteria.DataManagementPlanPublicCriteria; -import eu.eudat.data.query.PaginationService; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; -import eu.eudat.types.grant.GrantStateType; - -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; - -public class DataManagmentPlanPublicTableRequest extends TableQuery { - - public QueryableList applyCriteria() { - QueryableList query = this.getQuery(); - query.where((builder, root) -> builder.equal(root.get("isPublic"), true)); - if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) - query.where((builder, root) -> builder.or( - builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), - builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); - if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) - query.where(((builder, root) -> root.get("grant").get("id").in(this.getCriteria().getGrants()))); - if (this.getCriteria().getGrantStatus() != null) { - if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.FINISHED.getValue())) - query.where((builder, root) -> builder.lessThan(root.get("grant").get("enddate"), new Date())); - if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.ONGOING.getValue())) - query.where((builder, root) -> - builder.or(builder.greaterThan(root.get("grant").get("enddate"), new Date()) - , builder.isNull(root.get("grant").get("enddate")))); - } - if (this.getCriteria().datasetProfile != null && !this.getCriteria().datasetProfile.isEmpty()) - query.where((builder, root) -> root.join("associatedDmps").get("id").in(this.getCriteria().datasetProfile)); - if (this.getCriteria().getDmpOrganisations() != null && !this.getCriteria().getDmpOrganisations().isEmpty()) - query.where(((builder, root) -> root.join("organisations").get("reference").in(this.getCriteria().getDmpOrganisations()))); - if (!this.getCriteria().getAllVersions()) { - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), - query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("groupId"), - nestedRoot.get("groupId")), builder1.equal(nestedRoot.get("isPublic"), true)), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class))); - } - if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty()) { - query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds())); - } - return query; - } - - @Override - public QueryableList applyPaging(QueryableList items) { - return PaginationService.applyPaging(items, this); - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/query/DMPQuery.java b/dmp-backend/data/src/main/java/eu/eudat/query/DMPQuery.java deleted file mode 100644 index 6eb14bda5..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/query/DMPQuery.java +++ /dev/null @@ -1,135 +0,0 @@ -package eu.eudat.query; - -import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.DatabaseAccessLayer; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; - -import jakarta.persistence.criteria.Subquery; - -import javax.management.InvalidApplicationException; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -public class DMPQuery extends Query { - private UUID id; - private UUID groupId; - private String label; - private int version; -// private UserQueryOld userQuery; - private DatasetQuery datasetQuery; - private List statuses; - private Date created; - private Date modified; - - public DMPQuery(DatabaseAccessLayer databaseAccessLayer) { - super(databaseAccessLayer); - } - - public DMPQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { - super(databaseAccessLayer, selectionFields); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getGroupId() { - return groupId; - } - - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public int getVersion() { - return version; - } - - public void setVersion(int version) { - this.version = version; - } - - - public List getStatuses() { - return statuses; - } - - public void setStatuses(List statuses) { - statuses = statuses; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getModified() { - return modified; - } - - public void setModified(Date modified) { - this.modified = modified; - } - -// public UserQueryOld getUserQuery() { -// return userQuery; -// } -// -// public void setUserQuery(UserQueryOld userQuery) { -// this.userQuery = userQuery; -// } - - public DatasetQuery getDatasetQuery() { - return datasetQuery; - } - - public void setDatasetQuery(DatasetQuery datasetQuery) { - this.datasetQuery = datasetQuery; - } - - public QueryableList getQuery() throws InvalidApplicationException { - QueryableList query = this.databaseAccessLayer.asQueryable(); - if (this.id != null) { - query.where((builder, root) -> builder.equal(root.get("id"), this.id)); - } -// if (this.grantQuery != null) { //TODO -// Subquery grantQuery = this.grantQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); -// query.where((builder, root) -> root.get("grant").get("id").in(grantQuery)); -// } - if (this.getStatuses() != null && !this.getStatuses().isEmpty()) { - query.where((builder, root) -> root.get("status").in(this.getStatuses())); - } -// if (this.userQuery != null) { -// Subquery userInfoSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); -// query.where((builder, root) -> root.get("creator").get("id").in(userInfoSubQuery)); -// } - if(this.datasetQuery != null){ - Subquery datasetSubQuery = this.datasetQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:id"))); - query.where((builder, root) -> root.get("id").in(datasetSubQuery )); - } - if (!this.getSelectionFields().isEmpty() && this.getSelectionFields() != null) { - query.withFields(this.getSelectionFields()); - } - return query; - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/query/DatasetQuery.java b/dmp-backend/data/src/main/java/eu/eudat/query/DatasetQuery.java index 8775eb676..8be2668be 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/query/DatasetQuery.java +++ b/dmp-backend/data/src/main/java/eu/eudat/query/DatasetQuery.java @@ -18,7 +18,6 @@ public class DatasetQuery extends Query { private UUID id; private String label; - private DMPQuery dmpQuery; public DatasetQuery(DatabaseAccessLayer databaseAccessLayer) { super(databaseAccessLayer); @@ -44,13 +43,6 @@ public class DatasetQuery extends Query { this.label = label; } - public DMPQuery getDmpQuery() { - return dmpQuery; - } - - public void setDmpQuery(DMPQuery dmpQuery) { - this.dmpQuery = dmpQuery; - } @Override public QueryableList getQuery() throws InvalidApplicationException { @@ -58,10 +50,6 @@ public class DatasetQuery extends Query { if (this.id != null) { query.where((builder, root) -> builder.equal(root.get("id"), this.id)); } - if (this.dmpQuery != null) { - Subquery dmpSubQuery = this.dmpQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); - query.where((builder, root) -> root.get("dmp").get("id").in(dmpSubQuery)); - } return query; } } diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java index e928330d5..9f2063e04 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java +++ b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java @@ -13,7 +13,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; -public interface QueryableList { +public interface QueryableList { QueryableList where(SinglePredicate predicate); List select(SelectPredicate predicate) throws InvalidApplicationException; diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/BaseController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/BaseController.java index bf6249f18..9eb9e0401 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/BaseController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/BaseController.java @@ -1,9 +1,6 @@ package eu.eudat.controllers; import eu.eudat.logic.services.ApiContext; -import eu.eudat.models.validators.*; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; public abstract class BaseController { @@ -18,12 +15,4 @@ public abstract class BaseController { this.apiContext = apiContext; } - - @InitBinder() - protected void initBinder(WebDataBinder binder) { - if (binder.getTarget() != null && DataManagementPlanTableRequestValidator.supportsType((binder.getTarget().getClass()))) - binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("dataManagementPlanTableRequestValidator", DataManagementPlanTableRequestValidator.class)); - if (binder.getTarget() != null && DataManagementPlanNewVersionValidator.supportsType((binder.getTarget().getClass()))) - binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("dataManagementPlanNewVersionValidator", DataManagementPlanNewVersionValidator.class)); - } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/DMPs.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/DMPs.java deleted file mode 100644 index d442a67a2..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/DMPs.java +++ /dev/null @@ -1,417 +0,0 @@ -package eu.eudat.controllers; - - -import eu.eudat.authorization.Permission; -import eu.eudat.criteria.DMPCriteria; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.DmpEntity; -import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest; -import eu.eudat.exceptions.datamanagementplan.DMPNewVersionException; -import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException; -import eu.eudat.exceptions.security.UnauthorisedException; -import eu.eudat.logic.managers.DataManagementPlanManager; -import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; -import eu.eudat.logic.services.ApiContext; -import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.model.DmpUser; -import eu.eudat.model.file.FileEnvelope; -import eu.eudat.models.data.datasetwizard.DatasetsToBeFinalized; -import eu.eudat.models.data.dmp.DataManagementPlan; -import eu.eudat.models.data.helpers.common.DataTableData; -import eu.eudat.models.data.helpers.responses.ResponseItem; -import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel; -import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel; -import eu.eudat.models.data.listingmodels.VersionListingModel; -import eu.eudat.query.DMPQuery; -import eu.eudat.types.ApiMessageCode; -import gr.cite.commons.web.authz.service.AuthorizationService; -import jakarta.activation.MimetypesFileTypeMap; -import jakarta.validation.Valid; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import javax.management.InvalidApplicationException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import static org.springframework.http.MediaType.*; - - -@RestController -@CrossOrigin -@RequestMapping(value = {"/api/dmps/"}) -public class DMPs extends BaseController { - private static final Logger logger = LoggerFactory.getLogger(DMPs.class); - - private Environment environment; - private DataManagementPlanManager dataManagementPlanManager; - private ConfigLoader configLoader; - private final AuthorizationService authorizationService; - - @Autowired - public DMPs(ApiContext apiContext, Environment environment, - DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader, AuthorizationService authorizationService) { - super(apiContext); - this.environment = environment; - this.dataManagementPlanManager = dataManagementPlanManager; - this.configLoader = configLoader; - this.authorizationService = authorizationService; - } - - /* - * Data Retrieval - * */ - - @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest, - @RequestParam String fieldsGroup) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - - DataTableData dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, fieldsGroup); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); - } - - @RequestMapping(method = RequestMethod.GET, value = {"{id}"}) - public @ResponseBody - ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - - if (contentType.equals("application/xml") || contentType.equals("application/msword")) { - return this.dataManagementPlanManager.getDocument(id, contentType, this.configLoader); - } else { - eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, false, true); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); - } - } - - @RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"}) - public @ResponseBody - ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - - eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, false, false); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); - - } - -// @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDmps/paged"}, produces = "application/json") -// public @ResponseBody -// ResponseEntity>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException { -// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); -// -// DataTableData datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem); -// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); -// } - - @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"}) - public @ResponseBody - ResponseEntity getOverviewSingle(@PathVariable String id) { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - try { - DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, false); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); - } catch (Exception e) { - if (e instanceof UnauthorisedException) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); - } - } - } - - @RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}) - public @ResponseBody - ResponseEntity getSinglePublic(@PathVariable String id) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - // try { - eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, true, true); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); -// } catch (Exception ex) { -// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); -// } - } - - @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"}) - public @ResponseBody - ResponseEntity> getOverviewSinglePublic(@PathVariable String id) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); -// try { - DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, true); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); -// } catch (Exception ex) { -// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); -// } - } - -// @RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json") -// public @ResponseBody -// ResponseEntity>>> getWithCriteria(@RequestBody RequestItem criteriaRequestItem) throws InstantiationException, IllegalAccessException { -// this.authorizationService.authorizeForce(Permission.AuthenticatedRole); -// -// List> dataTable = this.dataManagementPlanManager.getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicGrantConfiguration, criteriaRequestItem.getCriteria()); -// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); -// } - - @RequestMapping(method = RequestMethod.GET, value = {"/versions/{id}"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic) throws Exception { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - List versions = this.dataManagementPlanManager.getAllVersions(groupId, isPublic); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(versions)); - } - - /* - * Data Export - * */ - - @RequestMapping(method = RequestMethod.GET, value = {"rda/{id}"}) - public @ResponseBody - ResponseEntity getRDAJsonDocument(@PathVariable String id) { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - try { - FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id); - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentLength(rdaJsonDocument.getFile().length()); - responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); - responseHeaders.set("Content-Disposition", "attachment;filename=" + rdaJsonDocument.getFilename()); - responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); - responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); - - InputStream resource = new FileInputStream(rdaJsonDocument.getFile()); - byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); - resource.close(); - Files.deleteIfExists(rdaJsonDocument.getFile().toPath()); - - return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseItem<>().message(e.getMessage()).status(ApiMessageCode.ERROR_MESSAGE)); - } - } - - @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) - public @ResponseBody - ResponseEntity getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InterruptedException, InvalidApplicationException { - this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole); - FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, configLoader); - String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_"); - File pdffile = null; //PDFUtils.convertToPDF(file, environment); //TODO - InputStream resource = new FileInputStream(pdffile); - logger.info("Mime Type of " + name + " is " + - new MimetypesFileTypeMap().getContentType(file.getFile())); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentLength(pdffile.length()); - responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); - responseHeaders.set("Content-Disposition", "attachment;filename=" + name + ".pdf"); - responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); - responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); - - byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); - resource.close(); - Files.deleteIfExists(file.getFile().toPath()); - Files.deleteIfExists(pdffile.toPath()); - return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); - } - - /* - * Data Management - * */ - - @Transactional - @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - DmpEntity dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(new eu.eudat.models.data.dmp.DataManagementPlan().fromDataModel(dmp))); - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - DmpEntity dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dmp.getId())); - } - - @RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> newVersion(@PathVariable UUID id, @Valid @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - try { - UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(result)); - } catch (DMPNewVersionException exception) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); - } - } - - @RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - UUID cloneId = this.dataManagementPlanManager.clone(id, dataManagementPlan); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).payload(cloneId)); - } - - @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> delete(@PathVariable UUID id) { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - try { - this.dataManagementPlanManager.delete(id); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan")); - } catch (DMPWithDatasetsDeleteException | IOException | InvalidApplicationException exception) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); - } - } - - @RequestMapping(method = RequestMethod.POST, value = {"/upload"}) - public ResponseEntity dmpUpload(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "profiles", required = false)String[] profiles) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - if (files[0].getContentType().equals(APPLICATION_JSON.toString())) { - this.dataManagementPlanManager.createFromRDA(files, profiles); - } else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString()) || files[0].getContentType().equals(TEXT_XML.toString())) { - this.dataManagementPlanManager.createDmpFromXml(files, profiles); - } else { - return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported")); - } - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem() - .status(ApiMessageCode.SUCCESS_MESSAGE)); - } - - @RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}) - public ResponseEntity> makePublic(@PathVariable String id) { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - try { - this.dataManagementPlanManager.makePublic(UUID.fromString(id)); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made public.")); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to make Data Management Plan public.")); - } - } - - @RequestMapping(method = RequestMethod.POST, value = {"/finalize/{id}"}) - public ResponseEntity> makeFinalize(@PathVariable String id, @RequestBody DatasetsToBeFinalized datasetsToBeFinalized) { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - try { - this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), datasetsToBeFinalized); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made finalized.")); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to finalize Data Management Plan.")); - } - } - - @RequestMapping(method = RequestMethod.POST, value = {"/unfinalize/{id}"}) - public ResponseEntity> undoFinalize(@PathVariable String id) { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - try { - this.dataManagementPlanManager.undoFinalize(UUID.fromString(id)); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made active.")); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to unfinalize the Data Management Plan.")); - } - } - - - @RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"}) - public ResponseEntity> updateUsers(@PathVariable String id, @RequestBody List users) { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - try { - this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan.")); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to update the users of Data Management Plan.")); - } - } - - /* - * Data Index - * */ - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = {"/index"}) - public @ResponseBody - ResponseEntity> generateIndex() throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - //this.dataManagementPlanManager.generateIndex(); //TODO - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null)); - } - - @Transactional - @RequestMapping(method = RequestMethod.DELETE, value = {"/index"}) - public @ResponseBody - ResponseEntity> clearIndex() throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - //this.dataManagementPlanManager.clearIndex(); //TODO - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null)); - } - - /* - * Misc - * */ - - @RequestMapping(method = RequestMethod.POST, value = {"/test"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> test(@RequestBody DMPCriteria criteria) throws Exception { - this.authorizationService.authorizeForce(Permission.AnonymousRole); - - DatabaseRepository dbRepo = this.getApiContext().getOperationsContext().getDatabaseRepository(); - - DMPQuery query = criteria.buildQuery(dbRepo); - - List models = query.getQuery().toListWithFields(); - DataTableData dmp = new DataTableData<>(); - dmp.setData(models); - dmp.setTotalCount(query.getQuery().count()); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dmp)); - } - - /*@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity>> getPublicPaged(@RequestBody DataManagmentPlanPublicTableRequest dmpTableRequest, - @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal, - @RequestParam String fieldsGroup) throws Exception { - DataTableData dmp = this.dataManagementPlanManager.getPublicPaged(dmpTableRequest, fieldsGroup, principal); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dmp)); - }*/ - /*@Transactional - @RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json") - public @ResponseBody - ResponseEntity> unlock(@PathVariable(value = "id") UUID id) throws Exception { - this.dataManagementPlanManager.unlock(id); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked")); - }*/ -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/FileController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/FileController.java index 15b72c118..06f131fbf 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/FileController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/FileController.java @@ -24,6 +24,7 @@ import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpDescriptionTemplateQuery; +import eu.eudat.query.DmpQuery; import eu.eudat.types.ApiMessageCode; import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.tools.data.query.QueryFactory; @@ -145,7 +146,7 @@ public class FileController { throw new NoSuchElementException("No dataset with id " + fileUpload.getEntityId() + " found. This dataset was related to the file with id " + id); } - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (!dmp.getAccessType().equals(DmpAccessType.Public) //TODO diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/QuickWizardController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/QuickWizardController.java index 151efae87..11faa168b 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/QuickWizardController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/QuickWizardController.java @@ -4,12 +4,9 @@ package eu.eudat.controllers; import eu.eudat.authorization.Permission; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.data.DmpEntity; import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.QuickWizardManager; import eu.eudat.logic.services.ApiContext; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.quickwizard.DatasetCreateWizardModel; import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel; @@ -86,17 +83,17 @@ public class QuickWizardController extends BaseController { // } //Create Dmp - DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(/*grantEntity,*/ userScope); - DmpEntity dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan/*, funderEntity*/); - - //Create Datasets - quickWizard.getDmp().setId(dmpEntity.getId()); - for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) { - DataManagementPlan dmp = quickWizard.getDmp().toDataDmp(/*grantEntity , projectEntity, */ userScope); - DescriptionTemplateEntity profile = quickWizard.getDmp().getDatasetProfile(); - DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile); - this.datasetManager.createOrUpdate(datasetWizardModel); - } +// DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(/*grantEntity,*/ userScope); +// DmpEntity dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan/*, funderEntity*/); +// +// //Create Datasets +// quickWizard.getDmp().setId(dmpEntity.getId()); +// for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) { +// DataManagementPlan dmp = quickWizard.getDmp().toDataDmp(/*grantEntity , projectEntity, */ userScope); +// DescriptionTemplateEntity profile = quickWizard.getDmp().getDatasetProfile(); +// DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile); +// this.datasetManager.createOrUpdate(datasetWizardModel); +// } return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); } @@ -108,9 +105,9 @@ public class QuickWizardController extends BaseController { for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){ DescriptionTemplateEntity profile = new DescriptionTemplateEntity(); - profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()); - profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel()); - this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), profile)); +// profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()); +// profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel()); + this.datasetManager.createOrUpdate(dataset.toDataModel(profile)); } return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Dataset added!")); diff --git a/dmp-backend/web/src/main/java/eu/eudat/criteria/DMPCriteria.java b/dmp-backend/web/src/main/java/eu/eudat/criteria/DMPCriteria.java deleted file mode 100644 index a9c850b56..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/criteria/DMPCriteria.java +++ /dev/null @@ -1,141 +0,0 @@ -package eu.eudat.criteria; - -import eu.eudat.criteria.entities.Criteria; -import eu.eudat.criteria.entities.DateCriteria; -import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.query.DMPQuery; - -import java.util.*; - -public class DMPCriteria { - private Criteria id; - private Criteria groupId; - private Criteria label; - private Criteria version; - private DateCriteria created; - private DateCriteria modified; - private UserCriteria creator; - private DatasetCriteria dataset; - - public Criteria getId() { - return id; - } - - public void setId(Criteria id) { - this.id = id; - } - - public void setId(String id) { - Criteria criteria = new Criteria<>(); - criteria.setAs(id); - this.id = criteria; - } - - public Criteria getGroupId() { - return groupId; - } - - public void setGroupId(Criteria groupId) { - this.groupId = groupId; - } - - public void setGroupId(String groupId) { - Criteria criteria = new Criteria<>(); - criteria.setAs(groupId); - this.groupId = criteria; - } - - public Criteria getLabel() { - return label; - } - - public void setLabel(Criteria label) { - this.label = label; - } - - public void setLabel(String label) { - Criteria criteria = new Criteria<>(); - criteria.setAs(label); - this.label = criteria; - } - - public Criteria getVersion() { - return version; - } - - public void setVersion(Criteria version) { - this.version = version; - } - - public void setVersion(String version) { - Criteria criteria = new Criteria<>(); - criteria.setAs(version); - this.version = criteria; - } - - public DateCriteria getCreated() { - return created; - } - - public void setCreated(DateCriteria created) { - this.created = created; - } - - public void setCreated(String created) { - DateCriteria criteria = new DateCriteria(); - criteria.setAs(created); - this.created = criteria; - } - - public DateCriteria getModified() { - return modified; - } - - public void setModified(DateCriteria modified) { - this.modified = modified; - } - - public void setModified(String modified) { - DateCriteria criteria = new DateCriteria(); - criteria.setAs(modified); - this.modified = criteria; - } - - public UserCriteria getCreator() { - return creator; - } - - public void setCreator(UserCriteria creator) { - this.creator = creator; - } - - public DatasetCriteria getDataset() { - return dataset; - } - - public void setDataset(DatasetCriteria dataset) { - this.dataset = dataset; - } - - protected List buildFields(String path) { - Set fields = new LinkedHashSet<>(); - path = path != null && !path.isEmpty() ? path + "." : ""; - if (this.id != null) fields.add(path + this.id.getAs()); - if (this.label != null) fields.add(path + this.label.getAs()); -// if (this.grant != null) fields.addAll(this.grant.buildFields(path + "grant")); - if (this.creator != null) fields.addAll(this.creator.buildFields(path + "creator")); - if (this.dataset != null) fields.addAll(this.dataset.buildFields(path + "dataset")); - if (!fields.contains(path + "id")) fields.add(path + "id"); - return new LinkedList<>(fields); - } - - public DMPQuery buildQuery(DatabaseRepository dao) { - List fields = this.buildFields(""); - DMPQuery dmpQuery = new DMPQuery(dao.getDmpDao(), fields); - if (this.id != null) dmpQuery.setId(this.id.getValue()); -// if (this.grant != null) dmpQuery.setGrantQuery(this.grant.buildQuery(dao)); -// if (this.creator != null) dmpQuery.setUserQuery(this.creator.buildQuery(dao)); - if (this.dataset != null) dmpQuery.setDatasetQuery(this.dataset.buildQuery(dao)); - return dmpQuery; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/criteria/DatasetCriteria.java b/dmp-backend/web/src/main/java/eu/eudat/criteria/DatasetCriteria.java index f65f69028..a198473a2 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/criteria/DatasetCriteria.java +++ b/dmp-backend/web/src/main/java/eu/eudat/criteria/DatasetCriteria.java @@ -15,7 +15,6 @@ import java.util.*; public class DatasetCriteria { private Criteria id; private Criteria label; - private DMPCriteria dmp; public Criteria getId() { return id; @@ -49,20 +48,12 @@ public class DatasetCriteria { } } - public DMPCriteria getDmp() { - return dmp; - } - - public void setDmp(DMPCriteria dmp) { - this.dmp = dmp; - } protected List buildFields(String path) { Set fields = new HashSet<>(); path = path != null && !path.isEmpty() ? path + "." : ""; if (this.id != null) fields.add(path + this.id.getAs()); if (this.label != null) fields.add(path + this.label.getAs()); - if (this.dmp != null) fields.addAll(this.dmp.buildFields(path + "dmp")); if (!fields.contains(path + "id")) fields.add(path + "id"); return new LinkedList<>(fields); } @@ -71,7 +62,6 @@ public class DatasetCriteria { List fields = this.buildFields(""); DatasetQuery datasetQuery = new DatasetQuery(dao.getDatasetDao(), fields); if (this.id != null) datasetQuery.setId(this.id.getValue()); - if (this.dmp != null) datasetQuery.setDmpQuery(this.dmp.buildQuery(dao)); return datasetQuery; } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java deleted file mode 100644 index 633dc642c..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DataManagementPlanManager.java +++ /dev/null @@ -1,2789 +0,0 @@ -package eu.eudat.logic.managers; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.commons.XmlHandlingService; -import eu.eudat.commons.enums.*; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.commons.types.dmpblueprint.*; -import eu.eudat.logic.xml.XmlBuilder; -import eu.eudat.data.*; -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.data.dao.criteria.DatasetCriteria; -import eu.eudat.data.dao.entities.DatasetDao; -import eu.eudat.data.old.FileUpload; -import eu.eudat.data.query.items.table.dataset.DatasetTableRequest; -import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest; -import eu.eudat.exceptions.datamanagementplan.DMPNewVersionException; -import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException; -import eu.eudat.exceptions.security.ForbiddenException; -import eu.eudat.exceptions.security.UnauthorisedException; -import eu.eudat.logic.builders.entity.UserInfoBuilder; -import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; -import eu.eudat.logic.services.ApiContext; -import eu.eudat.logic.services.forms.VisibilityRuleService; -import eu.eudat.logic.services.forms.VisibilityRuleServiceImpl; -import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.logic.utilities.documents.types.ParagraphStyle; -import eu.eudat.logic.utilities.documents.word.WordBuilder; -import eu.eudat.logic.utilities.documents.xml.ExportXmlBuilder; -import eu.eudat.model.DmpUser; -import eu.eudat.model.EntityDoi; -import eu.eudat.model.file.FileEnvelope; -import eu.eudat.model.persist.deposit.DepositRequest; -import eu.eudat.models.HintedModelFactory; -import eu.eudat.models.data.dataset.DatasetOverviewModel; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.models.data.datasetwizard.DatasetsToBeFinalized; -import eu.eudat.models.data.dmp.*; -import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue; -import eu.eudat.models.data.helpermodels.Tuple; -import eu.eudat.models.data.helpers.common.DataTableData; -import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel; -import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel; -import eu.eudat.models.data.listingmodels.DatasetListingModel; -import eu.eudat.models.data.listingmodels.VersionListingModel; -import eu.eudat.models.data.user.composite.PagedDatasetProfile; -import eu.eudat.query.*; -import eu.eudat.queryable.QueryableList; -import eu.eudat.service.deposit.DepositService; -import eu.eudat.service.dmpblueprint.DmpBlueprintService; -import eu.eudat.types.MetricNames; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.QueryFactory; -import jakarta.transaction.Transactional; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Unmarshaller; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.multipart.MultipartFile; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.management.InvalidApplicationException; -import java.io.*; -import java.math.BigInteger; -import java.nio.file.Files; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -@Component -public class DataManagementPlanManager { - private static final Logger logger = LoggerFactory.getLogger(DataManagementPlanManager.class); - private final ObjectMapper objectMapper; - -// private final Map notificationPaths = Stream.of(new Object[][] { -// {NotificationType.DMP_MODIFIED, "/plans/edit"}, -// {NotificationType.DMP_PUBLISH, "/plans/publicEdit"}, -// {NotificationType.DMP_FINALISED, "/plans/edit"}, -// {NotificationType.DMP_MODIFIED_FINALISED, "/plans/edit"} -// }).collect(Collectors.toMap(data -> (NotificationType) data[0], data -> (String) data[1])); - - private ApiContext apiContext; - private DatasetManager datasetManager; - private DatabaseRepository databaseRepository; - private Environment environment; - private RDAManager rdaManager; - private final MetricsManager metricsManager; - private final ConfigLoader configLoader; - private DepositService repositoriesDeposit; - private final UserScope userScope; - private final AuthorizationService authorizationService; - private final DmpBlueprintService dmpBlueprintService; - private final QueryFactory queryFactory; - private final XmlHandlingService xmlHandlingService; - - @Autowired - public DataManagementPlanManager(XmlHandlingService xmlHandlingService, ApiContext apiContext, DatasetManager datasetManager, Environment environment, RDAManager rdaManager, - MetricsManager metricsManager, ConfigLoader configLoader, DepositService repositoriesDeposit, UserScope userScope, AuthorizationService authorizationService, DmpBlueprintService dmpBlueprintService, QueryFactory queryFactory) { - this.xmlHandlingService = xmlHandlingService; - this.apiContext = apiContext; - this.datasetManager = datasetManager; - this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); - this.environment = environment; - this.rdaManager = rdaManager; - this.metricsManager = metricsManager; - this.configLoader = configLoader; - this.userScope = userScope; - this.authorizationService = authorizationService; - this.dmpBlueprintService = dmpBlueprintService; - this.queryFactory = queryFactory; - this.objectMapper = new ObjectMapper(); - this.repositoriesDeposit = repositoriesDeposit; - } - - /* - * Data Retrieval - * */ - - public DataTableData getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, String fieldsGroup) throws Exception { - UUID principalID = userScope.getUserIdSafe(); -// List dmps = null; - QueryableList items = null; - QueryableList authItems = null; - Long totalData = 0L; -// if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository() != null) { //TODO -// try { -// DmpCriteria criteria = DmpCriteriaMapper.toElasticCriteria(dataManagementPlanTableRequest.getCriteria(), principalID); -// criteria.setOffset(dataManagementPlanTableRequest.getOffset()); -// criteria.setSize(dataManagementPlanTableRequest.getLength()); -// criteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(dataManagementPlanTableRequest.getOrderings())); -// -// dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().query(criteria); -// if (dmps != null && !dmps.isEmpty()) { -// List finalDmps = dmps; -// items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().where((builder, root) -> root.get("id").in(finalDmps.stream().map(Dmp::getId).collect(Collectors.toList()))); -// PaginationManager.applyOrder(items, dataManagementPlanTableRequest); -// totalData = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(criteria); -// } -// } catch (Exception ex) { -// logger.warn(ex.getMessage(), ex); -// items = null; -// } -// } - - if (items == null) { - items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dataManagementPlanTableRequest.getCriteria()); - } - List roles = new LinkedList<>(); - if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) { - if (dataManagementPlanTableRequest.getCriteria().getRole() != null) - roles.add(dataManagementPlanTableRequest.getCriteria().getRole()); - authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalID, roles); - } else { - authItems = items; - } -// if (dmps == null) { - totalData = authItems.count(); - items = PaginationManager.applyPaging(authItems, dataManagementPlanTableRequest); -// } else { -// items = authItems; -// } - - - - DataTableData dataTable = new DataTableData<>(); - - if (fieldsGroup.equals("listing")) { - if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) { - List dmps1 = items.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) - .distinct().toList(); - dataTable.setData(dmps1.stream().map(dmp -> { - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(Collections.singletonList(dmp.getId())); - datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); - datasetCriteria.setIsPublic(dataManagementPlanTableRequest.getCriteria().getIsPublic()); - datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); -// try { //TODO -// dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID)); -// } catch (InvalidApplicationException e) { -// throw new RuntimeException(e); -// } - - - return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); - }).collect(Collectors.toList())); - /*.selectAsync(item -> { - item.setDataset( - item.getDataset().stream() - .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())).collect(Collectors.toList()).stream() - *//*.filter(dataset -> dataset.getDmp().getUsers().stream() - .filter(x -> x.getUser().getId().equals(principalID)) - .collect(Collectors.toList()).size() > 0)*//* - .collect(Collectors.toSet())); - return new DataManagementPlanListingModel().fromDataModelDatasets(item); - }) - .whenComplete((resultList, throwable) -> dataTable.setData(resultList));*/ - } else { - List dmps1 = items.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) - .distinct().toList(); - dataTable.setData(dmps1.stream().map(dmp -> { - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(Collections.singletonList(dmp.getId())); - datasetCriteria.setIsPublic(true); - datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); - datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); -// try { //TODO -// dmp.setDataset(retrieveRelevantDatasets(datasetCriteria)); -// } catch (InvalidApplicationException e) { -// throw new RuntimeException(e); -// } - - - return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); - }).collect(Collectors.toList())); - /*.selectAsync(item -> { - item.setDataset( - item.getDataset().stream() - .filter(dataset -> dataset.getStatus().equals(Dataset.Status.FINALISED.getValue())).collect(Collectors.toSet())); - return new DataManagementPlanListingModel().fromDataModelDatasets(item); - }) - .whenComplete((resultList, throwable) -> dataTable.setData(resultList));*/ - } - } else if (fieldsGroup.equals("autocomplete")) { - dataTable.setData(items - .distinct() - .select(item -> new DataManagementPlanListingModel().fromDataModelAutoComplete(item))); - } else { - dataTable.setData(items - .distinct() - .select(item -> new DataManagementPlanListingModel().fromDataModelAssociatedProfiles(item))); - } - - //CompletableFuture countFuture = authItems.distinct().countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count)); - dataTable.setTotalCount(totalData); - //CompletableFuture.allOf(itemsFuture).join(); - return dataTable; - } - - private Set retrieveRelevantDatasets(DatasetCriteria datasetCriteria) throws InvalidApplicationException { - return retrieveRelevantDatasets(datasetCriteria, null); - } - - private Set retrieveRelevantDatasets (DatasetCriteria datasetCriteria, UUID principal) throws InvalidApplicationException { - QueryableList datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetCriteria) - .orderBy((builder, root) -> builder.desc(root.get("modified"))); - if (principal != null) { - UserEntity userInfo = this.queryFactory.query(UserQuery.class).ids(principal).first(); - List roles = new ArrayList<>(); - roles.add(0); - roles.add(1); - datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getAuthenticated(datasetItems, userInfo, roles); - } - Long maxDatasets = datasetItems.distinct().count(); - DatasetTableRequest datasetTableRequest = new DatasetTableRequest(); - datasetTableRequest.setOffset(0); - datasetTableRequest.setLength(3); - Set datasetsSet = new LinkedHashSet<>(); - try { - datasetItems = PaginationManager.applyPaging(datasetItems, datasetTableRequest); - List descriptionEntities = datasetItems.distinct().toList(); - datasetsSet.addAll(descriptionEntities); - for (int i = 0; i < maxDatasets - descriptionEntities.size(); i++) { - DescriptionEntity fakedataset = new DescriptionEntity(); - fakedataset.setId(UUID.randomUUID()); - datasetsSet.add(fakedataset); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - - return datasetsSet; - } - - public eu.eudat.models.data.dmp.DataManagementPlan getSingle(String id, boolean isPublic, boolean includeDatasets) throws Exception { - eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan(); - DmpEntity dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (!isPublic && !this.userScope.isSet()) { - throw new UnauthorisedException(); - //TODO - } else if (!isPublic /*&& (dataManagementPlanEntity.getUsers().stream().noneMatch(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())))*/ ) { - if (!dataManagementPlanEntity.getAccessType().equals(DmpAccessType.Public)) { - throw new UnauthorisedException(); - } - } else if (isPublic && !dataManagementPlanEntity.getAccessType().equals(DmpAccessType.Public)) { - throw new ForbiddenException("Selected DMP is not public"); - } - if (includeDatasets) { - dataManagementPlan.fromDataModel(dataManagementPlanEntity); - dataManagementPlan.getDatasets().forEach(datasetWizardModel -> datasetWizardModel.setDescription(null)); - dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().sorted(Comparator.comparing(DatasetWizardModel::getCreated).reversed()).collect(Collectors.toList())); - //List datasetEnities = new ArrayList<>(dataManagementPlanEntity.getDataset()); - /*for (int i = 0; i < datasetEnities.size(); i++) { - for (int j = i; j < dataManagementPlan.getDatasets().size(); j++) { - if (dataManagementPlan.getDatasets().get(j).getId().equals(datasetEnities.get(i).getId())) { - dataManagementPlan.getDatasets().get(j).setDatasetProfileDefinition(datasetManager.getPagedProfile(dataManagementPlan.getDatasets().get(j), datasetEnities.get(i))); - break; - } - } - }*/ - /*datasetEnities.stream() - .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED) && !dataset.getStatus().equals(Dataset.Status.CANCELED)) - .forEach(dataset -> { - dataManagementPlan.getDatasets().stream().filter(datasetWizardModel -> datasetWizardModel.getId().equals(dataset.getId())).forEach(datasetWizardModel -> { - DatasetWizardModel wizardModel = datasetManager.getSingle(datasetWizardModel.getId().toString(), principal); - datasetWizardModel.setDatasetProfileDefinition(wizardModel.getDatasetProfileDefinition()); - datasetWizardModel.setTags(wizardModel.getTags()); - }); - });*/ - if (isPublic) { - dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == DescriptionStatus.Finalized).collect(Collectors.toList())); - } - } else { - dataManagementPlan.fromDataModelNoDatasets(dataManagementPlanEntity); - } - Map dmpProperties = new HashMap();//TODO dataManagementPlanEntity.getDmpProperties() != null ? new org.json.JSONObject(dataManagementPlanEntity.getDmpProperties()).toMap() : null; - - if (dmpProperties != null && dataManagementPlan.getDynamicFields() != null) - dataManagementPlan.getDynamicFields().forEach(item -> { - Map properties = (Map) dmpProperties.get(item.getId()); - if (properties != null) - item.setValue(new Tuple<>(properties.get("id"), properties.get("label"))); - }); - return dataManagementPlan; - } - - public DataManagementPlanOverviewModel getOverviewSingle(String id, boolean isPublic) throws Exception { - DmpEntity dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (dataManagementPlanEntity.getIsActive().equals(IsActive.Inactive)) { - throw new Exception("DMP is deleted."); - } - if (!isPublic && !this.userScope.isSet()) { - throw new UnauthorisedException(); - } else - if (!isPublic //&& dataManagementPlanEntity.getUsers() //TODO - // .stream().noneMatch(userInfo -> userInfo.getUser().getId().equals(this.userScope.getUserIdSafe())) - ) { - throw new UnauthorisedException(); - } else if (isPublic && !dataManagementPlanEntity.getAccessType().equals(DmpAccessType.Public)) { - throw new ForbiddenException("Selected DMP is not public"); - } - DataManagementPlanOverviewModel datamanagementPlan = new DataManagementPlanOverviewModel(); - datamanagementPlan.fromDataModelDatasets(dataManagementPlanEntity); - datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().sorted(Comparator.comparing(DatasetOverviewModel::getCreated).reversed()).collect(Collectors.toList())); - if (isPublic) { - datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == DescriptionStatus.Finalized).collect(Collectors.toList())); - } - - return datamanagementPlan; - } - -// public List> getDynamicFields(String id, DynamicGrantConfiguration dynamicGrantConfiguration, DynamicFieldsCriteria criteria) throws IllegalAccessException, InstantiationException { -// List> result = new LinkedList<>(); -// RestTemplate restTemplate = new RestTemplate(); -// HttpHeaders headers = new HttpHeaders(); -// headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); -// headers.setContentType(MediaType.APPLICATION_JSON); -// HttpEntity entity = new HttpEntity<>("parameters", headers); -// -// Property property = dynamicGrantConfiguration.getConfiguration().getConfigurationProperties().stream() -// .filter(item -> item.getId().equals(id)).findFirst().orElse(null); -// StringBuilder stringBuilder = new StringBuilder(); -// if (criteria.getLike() != null) stringBuilder.append("?search=" + criteria.getLike()); -// if (property.getDependencies() != null && !property.getDependencies().isEmpty() && criteria.getDynamicFields() != null && !criteria.getDynamicFields().isEmpty()) { -// property.getDependencies().stream().forEach(item -> { -// DynamicFieldsCriteria.DynamicFieldDependencyCriteria dependencyCriteria = criteria.getDynamicFields().stream().filter(dfield -> dfield.getProperty().equals(item.getId())) -// .findFirst().orElse(null); -// if (dependencyCriteria != null) { -// if (criteria.getLike() != null || property.getDependencies().indexOf(item) > 0) -// stringBuilder.append("&"); -// stringBuilder.append(item.getQueryProperty() + "=" + dependencyCriteria.getValue()); -// } -// }); -// -// ResponseEntity response = restTemplate.exchange(property.getSourceUrl() + stringBuilder.toString(), HttpMethod.GET, entity, ArrayList.class); -// response.getBody().forEach(item -> { -// Tuple tuple = new Tuple<>(); -// tuple.setId((String) (((Map) item).get(property.getExternalFieldId()))); -// tuple.setLabel((String) (((Map) item).get(property.getExternalFieldLabel()))); -// result.add(tuple); -// }); -// -// } else { -// ResponseEntity response = restTemplate.exchange(property.getSourceUrl() + stringBuilder.toString(), HttpMethod.GET, entity, ArrayList.class); -// response.getBody().forEach(item -> { -// Tuple tuple = new Tuple<>(); -// tuple.setId((String) (((Map) item).get(property.getExternalFieldId()))); -// tuple.setLabel((String) (((Map) item).get(property.getExternalFieldLabel()))); -// result.add(tuple); -// }); -// } -// return result; -// } - -// public DataTableData getDatasetProfilesUsedByDMP(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException { -// datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.DMPs.getValue()); -// datasetProfileTableRequestItem.getCriteria().setUserId(this.userScope.getUserId()); -// -// QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria()); -// List listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); -// -// DataTableData data = new DataTableData<>(); -// data.setData(listingModels); -// data.setTotalCount((long) listingModels.size()); -// -// return data; -// } - - public List getAllVersions(String groupId, Boolean isPublic) throws InvalidApplicationException { - UUID principalId = this.userScope.getUserIdSafe(); - List versions = new ArrayList<>(); - QueryableList items = null; - QueryableList authItems = null; - List roles = new LinkedList<>(); - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - criteria.setGroupIds(Collections.singletonList(UUID.fromString(groupId))); - criteria.setAllVersions(true); - criteria.setIsPublic(isPublic); - criteria.setOnlyPublic(isPublic); - items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria); - if (!isPublic) { - authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalId, roles); - } else { - authItems = items; - } - CompletableFuture> versionFuture = authItems.withHint(HintedModelFactory.getHint(VersionListingModel.class)) - .orderBy(((builder, root) -> builder.desc(root.get("version")))) - .selectAsync(item -> new VersionListingModel().fromDataModel(item)) - .whenComplete(((versionListingModels, throwable) -> versions.addAll(versionListingModels))); - - CompletableFuture.allOf(versionFuture).join(); - - return versions; - } - - /* - * Data Management - * */ - - @Transactional - public DmpEntity createOrUpdate(DataManagementPlanEditorModel dataManagementPlan) throws Exception { - boolean setNotification = false; - if (dataManagementPlan.getId() != null) { - DmpEntity dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); - - Instant dbTime = dmp1.getUpdatedAt().truncatedTo(ChronoUnit.SECONDS); - Instant modelTime = dmp1.getUpdatedAt().truncatedTo(ChronoUnit.SECONDS); - - if (!isUserOwnerOfDmp(dmp1)) { - throw new Exception("User not being the creator is not authorized to edit this DMP."); - } - if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { - throw new Exception("Another user have already edit that DMP."); - } - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(List.of(dmp1.getId())); - - List descriptionEntityList = this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList().stream().filter(dataset -> dataset.getIsActive() != IsActive.Inactive).collect(Collectors.toList()); - for (DescriptionEntity descriptionEntity : descriptionEntityList) { - if (dataManagementPlan.getProfiles().stream().filter(associatedProfile -> descriptionEntity.getDescriptionTemplateId().equals(associatedProfile.getDescriptionTemplateId())).findAny().orElse(null) == null) - throw new Exception("Dataset Template for Dataset Description is missing from the DMP."); - } - if (dataManagementPlan.getStatus() == DmpStatus.Finalized.getValue() && dmp1.getStatus().equals(DmpStatus.Finalized.getValue() )) - throw new Exception("DMP is finalized, therefore cannot be edited."); - - setNotification = true; - } else { - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - } - - DmpEntity newDmp = dataManagementPlan.toDataModel(); - if(dataManagementPlan.getProfile() != null){ - newDmp.setBlueprintId(dataManagementPlan.getProfile().getId()); - } - if (newDmp.getStatus().equals(DmpStatus.Finalized)) { - checkDmpValidationRules(newDmp); - } - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - newDmp.setCreatorId(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); - -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { -// createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Researchers)) { -// createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user); -// } //TODO -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { -// createFunderIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao()); -// }/TODO -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// createGrantIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao()); -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Project)) { -//// if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { //TODO -//// newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); -//// } -//// createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao()); //TODO -// } -// } - - DmpEntity dmp; - if (dataManagementPlan.getId() != null) { - dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); - } else dmp = new DmpEntity(); - - newDmp.setCreatedAt(dmp.getCreatedAt() == null ? Instant.now() : dmp.getCreatedAt()); - DmpEntity finalNewDmp = newDmp; - if (this.queryFactory.query(DmpUserQuery.class).dmpIds(finalNewDmp.getId()).collect() != null && - this.queryFactory.query(DmpUserQuery.class).dmpIds(finalNewDmp.getId()).collect().stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUserId())) - .collect(Collectors.toList()).size() == 0) { - List userDMPList = new ArrayList<>(this.queryFactory.query(DmpUserQuery.class).dmpIds(finalNewDmp.getId()).collect()); - for (DmpUser userInfoListingModel : dataManagementPlan.getUsers()) { - for (DmpUserEntity userDMP : userDMPList) { - if (!(userDMP.getUserId().equals(userInfoListingModel.getId()))) { -// apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP); - } - } - } - } - - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) { -// checkIfUserCanEditGrant(newDmp, user); -// }//TODO - assignGrandUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { - assignFunderUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Project)) { - assignProjectUserIfInternal(newDmp, user); - } - - if(newDmp.getId() != null){ -// for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ //TODO -// apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); -// } - } - - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// if (newDmp.getGrant() != null) { //TODO -// apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); -// } - } - newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp); - -// for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ //TODO -// apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); -// } - - if (dataManagementPlan.getUsers() != null && !dataManagementPlan.getUsers().isEmpty()) { - clearUsers(newDmp); - for (DmpUser userListing : dataManagementPlan.getUsers()) { - UserEntity tempUser = this.queryFactory.query(UserQuery.class).ids(userListing.getId()).first(); - assignUser(dmp, tempUser, userListing.getRole()); - } - } - - // Dataset manipulation for when the DMP is set to be finalized. - if (dataManagementPlan.getStatus() == DmpStatus.Finalized.getValue()) { - if (dataManagementPlan.getDatasetsToBeFinalized() != null && !dataManagementPlan.getDatasetsToBeFinalized().isEmpty()) { - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized())) - .update(root -> root.get("status"), DescriptionStatus.Finalized); - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized())) - .update(root -> root.get("finalizedat"), new Date()); - - List datasetsToBeCanceled = new LinkedList<>(); - for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { - if (!(dataset.getStatus() == DescriptionStatus.Finalized) && !dataManagementPlan.getDatasetsToBeFinalized().contains(dataset.getId())) { - datasetsToBeCanceled.add(UUID.fromString(dataset.getId().toString())); - } - } - if (!datasetsToBeCanceled.isEmpty()) - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) - .update(root -> root.get("status"), DescriptionStatus.Canceled); - } else { - List datasetsToBeCanceled = new LinkedList<>(); - for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { - if (!(dataset.getStatus() == DescriptionStatus.Finalized)) { - datasetsToBeCanceled.add(dataset.getId()); - } - } - if (!datasetsToBeCanceled.isEmpty()) - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) - .update(root -> root.get("status"), DescriptionStatus.Canceled); - } - } - -// if (dataManagementPlan.getAssociatedUsers().size() == 0) -// assignUser(newDmp, user); - - UUID dmpId = newDmp.getId(); - //TODO -// newDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); - - //this.updateIndex(newDmp); //TODO - - if (setNotification) { - if (newDmp.getStatus().equals(DmpStatus.Finalized.getValue())) { - this.sendNotification(newDmp, user/*, NotificationType.DMP_MODIFIED*/); - } else { - this.sendNotification(newDmp, user/*, , NotificationType.DMP_MODIFIED_FINALISED*/); - } - } - - return newDmp; - } - - public DmpEntity createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan) throws Exception { - if (dataManagementPlan.getId() != null) { - DmpEntity dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); - - Instant dbTime = dmp1.getUpdatedAt().truncatedTo(ChronoUnit.SECONDS); - Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); - - if (!isUserOwnerOfDmp(dmp1)) { - throw new Exception("User not being the creator is not authorized to edit this DMP."); - } - if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { - throw new Exception("Another user have already edit that DMP."); - } - for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { -// if (dataManagementPlan.getProfiles().stream().filter(associatedProfile -> dataset.getProfile().getId().equals(associatedProfile.getDescriptionTemplateId())).findAny().orElse(null) == null) //TODO -// throw new Exception("Dataset Template for Dataset Description is missing from the DMP."); - } - if (dataManagementPlan.getStatus() == (int) DmpStatus.Finalized.getValue() && dmp1.getStatus().equals(DmpStatus.Finalized.getValue())) - throw new Exception("DMP is finalized, therefore cannot be edited."); - } else { - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - } - List descriptionEntities = new ArrayList<>(); - DmpEntity tempDMP = dataManagementPlan.toDataModel(); - if (tempDMP.getStatus().equals(DmpStatus.Finalized)) { - checkDmpValidationRules(tempDMP); - } - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(tempDMP.getBlueprintId()).first(); - -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { -// createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Researchers)) { -// createResearchersIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { -// createFunderIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// createGrantIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao()); -// }//TODO - - DmpEntity result = createOrUpdate(dataManagementPlan); - - for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) { - datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result)); - DescriptionEntity descriptionEntity = datasetManager.createOrUpdate(datasetWizardModel); - descriptionEntities.add(descriptionEntity); - } - - UUID dmpId = result.getId(); - //result.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO - - //this.updateIndex(result); //TODO - - return result; - } - - public UUID newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan) throws Exception { - DmpEntity oldDmp = databaseRepository.getDmpDao().find(uuid); - if (!isUserOwnerOfDmp(oldDmp)) { - throw new Exception("User not being the creator is not authorized to perform this action."); - } - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - LinkedList list = new LinkedList<>(); - list.push(oldDmp.getGroupId()); - criteria.setGroupIds(list); - criteria.setAllVersions(false); - QueryableList dataManagementPlanQueryableList = databaseRepository.getDmpDao().getWithCriteria(criteria); - List latestVersionDMP = dataManagementPlanQueryableList.toList(); - - if (latestVersionDMP.get(0).getVersion().equals(oldDmp.getVersion())) { - DmpEntity newDmp = dataManagementPlan.toDataModel(); - newDmp.setBlueprintId(oldDmp.getBlueprintId()); - newDmp.setProperties(oldDmp.getProperties()); - newDmp.setProperties(oldDmp.getProperties()); - UserEntity user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - newDmp.setCreatorId(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { -// createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Researchers)) { -// createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user); -// }//TODO -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { -// createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao()); -// }//TODO -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao()); -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Project)) { -// //TODO -//// if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { -//// newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); -//// } -//// createProjectIfItDoesntExist(newDmp, databaseRepository.getProjectDao()); //TODO -// } -// }//TODO - - newDmp.setGroupId(oldDmp.getGroupId()); - newDmp.setVersion((short)(oldDmp.getVersion() + 1)); - newDmp.setId(null); - - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { - //TODO -// if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) { -// checkIfUserCanEditGrant(newDmp, user); -// } - assignGrandUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { - assignFunderUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Project)) { - assignProjectUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { - //TODO -// if (newDmp.getGrant() != null) { -// if (newDmp.getGrant().getStartdate() == null) { -// newDmp.getGrant().setStartdate(new Date()); -// } -// if (newDmp.getGrant().getEnddate() == null) { -// newDmp.getGrant().setEnddate(Date.from(Instant.now().plus(365, ChronoUnit.DAYS))); -// } -// databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant()); -// } - } - DmpEntity tempDmp = databaseRepository.getDmpDao().createOrUpdate(newDmp); - newDmp.setId(tempDmp.getId()); - //TODO -// for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ -// apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); -// } - - // Assign creator. - //assignUser(newDmp, user); - - copyDatasets(newDmp, databaseRepository.getDatasetDao()); - - this.queryFactory.query(DmpUserQuery.class).dmpIds(oldDmp.getId()).collect() - .stream().forEach(userDMP -> { - DmpUserEntity temp = new DmpUserEntity(); - temp.setUserId(userDMP.getUserId()); - temp.setRole(userDMP.getRole()); - temp.setDmpId(newDmp.getId()); -// apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(temp); - }); - - //TODO - //newDmp.setUsers(new HashSet<>(databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), newDmp.getId())).toList())); - - DatasetCriteria criteria1 = new DatasetCriteria(); - criteria1.setDmpIds(Collections.singletonList(newDmp.getId())); - //TODO - //newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); - - this.updateGroupIndex(newDmp.getGroupId()); - return newDmp.getId(); - } else { - throw new DMPNewVersionException("Version to update not the latest."); - } - } - - public UUID clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan) throws Exception { - DmpEntity oldDmp = databaseRepository.getDmpDao().find(uuid); - DmpEntity newDmp = dataManagementPlan.toDataModel(); - newDmp.setBlueprintId(oldDmp.getBlueprintId()); - newDmp.setProperties(oldDmp.getProperties()); - newDmp.setProperties(oldDmp.getProperties()); - - UserEntity user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - newDmp.setCreatorId(user.getId()); - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(newDmp.getBlueprintId()).first(); -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Organizations)) { -// createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Researchers)) { -// createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { -// createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao()); -// } -// if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { -// createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao()); -// //TODO -//// if(this.dmpBlueprintService.fieldInBlueprint(newDmp.getProfile(), DmpBlueprintSystemFieldType.Project)) { -//// if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { -//// newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); -//// } -//// createProjectIfItDoesntExist(newDmp, databaseRepository.getProjectDao()); -//// } -// }//TODO - - newDmp.setGroupId(UUID.randomUUID()); - newDmp.setVersion((short)0); - newDmp.setId(null); - - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { - //TODO -// if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) { -// checkIfUserCanEditGrant(newDmp, user); -// } - assignGrandUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Funder)) { - assignFunderUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Project)) { - assignProjectUserIfInternal(newDmp, user); - } - if(this.dmpBlueprintService.fieldInBlueprint(dmpBlueprint, DmpBlueprintSystemFieldType.Grant)) { - //TODO -// if (newDmp.getGrant() != null) { -// databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant()); -// } - } - DmpEntity tempDmp = databaseRepository.getDmpDao().createOrUpdate(newDmp); - newDmp.setId(tempDmp.getId()); - //TODO -// for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ -// apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); -// } - - assignUser(newDmp, user); - copyDatasets(newDmp, databaseRepository.getDatasetDao()); - - //TODO -// newDmp.setUsers(new HashSet<>(databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), newDmp.getId())).toList())); - - DatasetCriteria criteria1 = new DatasetCriteria(); - criteria1.setDmpIds(Collections.singletonList(newDmp.getId())); - //TODO -// newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); - UUID dmpId = newDmp.getId(); - //TODO -// newDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); - - //this.updateIndex(newDmp); //TODO - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - - return newDmp.getId(); - } - - public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException, InvalidApplicationException { - DatasetCriteria criteria = new DatasetCriteria(); - List dmpIds = Collections.singletonList(uuid); - criteria.setDmpIds(dmpIds); - if (apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).toList().size() > 0) - throw new DMPWithDatasetsDeleteException("You cannot Remove Datamanagement Plan with Datasets"); - DmpEntity oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid); - switch (oldDmp.getStatus()) { - case Draft: - metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - break; - case Finalized: - //TODO -// if (oldDmp.getDois() != null && !oldDmp.getDois().isEmpty()) { -// metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DOIED); -// } -// if (oldDmp.isPublic()) { -// metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.PUBLISHED); -// } - metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); - break; - } - oldDmp.setIsActive(IsActive.Inactive); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(oldDmp); - UUID dmpId = oldDmp.getId(); -// oldDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO -// this.updateIndex(oldDmp); //TODO - DataManagementPlanCriteria criteria1 = new DataManagementPlanCriteria(); - criteria1.setAllVersions(true); - criteria1.setGroupIds(Collections.singletonList(oldDmp.getGroupId())); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria1).toList().forEach(dmp -> { - //TODO -// try { -// UUID tdmpId = dmp.getId(); -// //TODO -// //dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tdmpId)).toList())); -// //this.updateIndex(dmp); //TODO -// } catch (InvalidApplicationException e) { -// logger.error(e.getMessage(), e); -// } -// for (DescriptionEntity descriptionEntity : dmp.getDataset()) { -// -// try { -// List tags = new ArrayList<>(); -// eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(descriptionEntity.getId().toString()); -// if (elastic != null) { -// tags = elastic.getTags(); -// } -// //descriptionEntity.setDmpId(dmp.getId()); //TODO -// this.datasetManager.updateTags(descriptionEntity, tags); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } -// } - }); - } - -// private void createResearchersIfTheyDontExist(DmpEntity newDmp, ResearcherDao researcherRepository, UserEntity user) throws InvalidApplicationException { -// if (newDmp.getResearchers() != null && !newDmp.getResearchers().isEmpty()) { //TODO -// for (eu.eudat.data.old.Researcher researcher : newDmp.getResearchers()) { -// ResearcherCriteria criteria = new ResearcherCriteria(); -// criteria.setReference(researcher.getReference()); -// List entries = researcherRepository.getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) researcher.setId(entries.get(0).getId()); -// else { -// researcher.setCreationUser(user); -// researcherRepository.createOrUpdate(researcher); -// metricsManager.increaseValue(MetricNames.RESEARCHER, 1, null); -// } -// } -// } -// } - -// private void createOrganisationsIfTheyDontExist(DmpEntity newDmp, OrganisationDao organisationRepository) throws InvalidApplicationException { -// if (newDmp.getOrganisations() != null && !newDmp.getOrganisations().isEmpty()) { //TODO -// for (Organisation organisation : newDmp.getOrganisations()) { -// boolean createNew = false; -// if (organisation.getReference() != null) { -// OrganisationCriteria criteria = new OrganisationCriteria(); -// criteria.setLike(organisation.getReference()); -// List entries = organisationRepository.getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) organisation.setId(entries.get(0).getId()); -// else createNew = true; -// } else { -// createNew = true; -// } -// -// if (createNew) { -// if (organisation.getReference() == null) { -// organisation.setReference("Internal:" + UUID.randomUUID().toString()); -// } -// organisationRepository.createOrUpdate(organisation); -// } -// } -// } -// } - -// private void createGrantIfItDoesntExist(DmpEntity newDmp, GrantDao grantDao) throws InvalidApplicationException { -// if (newDmp.getGrant() != null) { //TODO -// Grant grant = newDmp.getGrant(); -// GrantCriteria criteria = new GrantCriteria(); -// if (grant.getReference() != null) { -// criteria.setReference(grant.getReference()); -// Grant grantEntity = grantDao.getWithCriteria(criteria).toList().stream().max(Comparator.comparing(grant1 -> grant1.getModified().getTime())).orElse(null); -// if (grantEntity != null) grant.setId(grantEntity.getId()); -// else { -// grant.setType(Grant.GrantType.EXTERNAL.getValue()); -// grant.setCreationUser(null); -// if (grant.getStartdate() == null) { -// grant.setStartdate(new Date()); -// } -// if (grant.getEnddate() == null) { -// grant.setEnddate(Date.from(Instant.now().plus(365, ChronoUnit.DAYS))); -// } -// grantDao.createOrUpdate(grant); -// } -// } -// else { -// grant.setType(Grant.GrantType.EXTERNAL.getValue()); -// grant.setCreationUser(null); -// grantDao.createOrUpdate(grant); -// } -// } -// } - -// private void createFunderIfItDoesntExist(DmpEntity newDmp, FunderDao funderDao) throws InvalidApplicationException { -// if (newDmp.getGrant() != null && newDmp.getGrant().getFunder() != null) { //TODO -// Funder funder = newDmp.getGrant().getFunder(); -// FunderCriteria criteria = new FunderCriteria(); -// if (funder.getReference() != null) { -// criteria.setReference(funder.getReference()); -// Funder funderEntity = funderDao.getWithCritetia(criteria).toList().stream().max(Comparator.comparing(funder1 -> funder1.getModified().getTime())).orElse(null); -// if (funderEntity != null) funder.setId(funderEntity.getId()); -// else { -// funderDao.createOrUpdate(funder); -// } -// } -// else { -// funderDao.createOrUpdate(funder); -// } -// } -// } - -// private void createProjectIfItDoesntExist(DmpEntity newDmp, ProjectDao projectDao) throws InvalidApplicationException { //TODO -// if (newDmp.getProject() != null) { -// Project project = newDmp.getProject(); -// ProjectCriteria criteria = new ProjectCriteria(); -// if (project.getReference() != null) { -// criteria.setReference(project.getReference()); -// Project projectEntity = projectDao.getWithCritetia(criteria).toList().stream().max(Comparator.comparing(project1 -> project1.getModified().getTime())).orElse(null); -// if (projectEntity != null) project.setId(projectEntity.getId()); -// else { -// createExternalProject(project, projectDao); -// } -// } -// else { -// createExternalProject(project, projectDao); -// } -// } -// } -// -// private void createExternalProject(Project project, ProjectDao projectDao) { -// if (project.getStartdate() == null) project.setStartdate(new Date()); -// if (project.getEnddate() == null) project.setEnddate(new Date()); -// project.setType(Project.ProjectType.EXTERNAL.getValue()); -// if (project.getId() == null) project.setId(UUID.randomUUID()); -// projectDao.createOrUpdate(project); -// metricsManager.increaseValue(MetricNames.PROJECT, 1, null); -// } - - private void copyDatasets(DmpEntity newDmp, DatasetDao datasetDao) throws InvalidApplicationException { - List> futures = new LinkedList<>(); - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(List.of(newDmp.getId())); - for (DescriptionEntity descriptionEntity : this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList()) { - DescriptionEntity tempDescriptionEntity = datasetDao.find(descriptionEntity.getId()); - //TODO -// try { -// List tags = new ArrayList<>(); -// eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(descriptionEntity.getId().toString()); -// if (elastic != null) { -// tags = elastic.getTags(); -// } -// //TODO -// //UUID dmpId = tempDescriptionEntity.getDmpId(); -// //tempDescriptionEntity.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); -// this.datasetManager.updateTags(tempDescriptionEntity, tags); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } - datasetDao.asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)).where((builder, root) -> builder.equal(root.get("id"), descriptionEntity.getId())).getSingleAsync() - .thenApplyAsync(entityDataset -> { - DescriptionEntity newDescriptionEntity = new DescriptionEntity(); - newDescriptionEntity.update(entityDataset); - newDescriptionEntity.setStatus(DescriptionStatus.Draft); - //TODO - //newDescriptionEntity.setDmpId(newDmp.getId()); - -// if (newDescriptionEntity.getDatasetDataRepositories() != null) { -// newDescriptionEntity.setDatasetDataRepositories(newDescriptionEntity.getDatasetDataRepositories().stream().map(item -> { -// DataRepository dataRepository = new DataRepository(); -// dataRepository.setId(item.getDataRepository().getId()); -// -// DatasetDataRepository datasetDataRepository = new DatasetDataRepository(); -// datasetDataRepository.setDataRepository(dataRepository); -// datasetDataRepository.setDataset(newDescriptionEntity); -// datasetDataRepository.setData(item.getData()); -// return datasetDataRepository; -// }).collect(Collectors.toSet())); -// } -// -// if (newDescriptionEntity.getDatasetExternalDatasets() != null) { -// newDescriptionEntity.setDatasetExternalDatasets(newDescriptionEntity.getDatasetExternalDatasets().stream().map(item -> { -// ExternalDataset externalDataset = new ExternalDataset(); -// externalDataset.setId(item.getExternalDataset().getId()); -// DatasetExternalDataset datasetExternalDataset = new DatasetExternalDataset(); -// datasetExternalDataset.setExternalDataset(externalDataset); -// datasetExternalDataset.setDataset(newDescriptionEntity); -// datasetExternalDataset.setData(item.getData()); -// return datasetExternalDataset; -// }).collect(Collectors.toSet())); -// } -// -// if (newDescriptionEntity.getRegistries() != null) { -// newDescriptionEntity.setRegistries(newDescriptionEntity.getRegistries().stream().map(item -> { -// Registry registry = new Registry(); -// registry.setId(item.getId()); -// return registry; -// }).collect(Collectors.toSet())); -// } -// -// if (newDescriptionEntity.getServices() != null) { -// newDescriptionEntity.setServices(newDescriptionEntity.getServices().stream().map(item -> { -// Service service = new Service(); -// service.setId(item.getId()); -// DatasetService datasetService = new DatasetService(); -// datasetService.setService(service); -// datasetService.setDataset(newDescriptionEntity); -// datasetService.setData(item.getData()); -// return datasetService; -// }).collect(Collectors.toSet())); -// } - newDescriptionEntity.setCreatedAt(Instant.now()); - return newDescriptionEntity; - }).thenApplyAsync(item -> { - futures.add(datasetDao.createOrUpdateAsync(item).whenComplete(((dataset1, throwable) -> { - DmpEntity dmp = null; - try { - dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(dataset1.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); - //TODO -// eu.eudat.elastic.entities.Dataset datasetElastic = new eu.eudat.elastic.entities.Dataset(); -// datasetElastic.setId(dataset1.getId().toString()); -// datasetElastic.setLabel(dataset1.getLabel()); -// datasetElastic.setDescription(dataset1.getDescription()); -// datasetElastic.setTemplate(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(dataset1.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDescriptionTemplateId()); -// datasetElastic.setDmp(dmp.getId()); -// datasetElastic.setStatus(dataset1.getStatus().getValue()); -// datasetElastic.setGroup(dmp.getGroupId()); -// if(this.dmpBlueprintService.fieldInBlueprint(dmp.getProfile(), DmpBlueprintSystemFieldType.Grant)) { -// datasetElastic.setGrant(dmp.getGrant().getId()); -// } -// if (dmp.getUsers() != null) { -// datasetElastic.setCollaborators(dmp.getUsers().stream().map(user -> { -// Collaborator collaborator = new Collaborator(); -// collaborator.setId(user.getId().toString()); -// collaborator.setRole(user.getRole()); -// // collaborator.setName(user.getUser().getName()); -// return collaborator; -// }).collect(Collectors.toList())); -// } -// datasetElastic.setLastVersion(true); -// datasetElastic.setLastPublicVersion(false); -// if (dmp.getOrganisations() != null) { -// datasetElastic.setOrganizations(dmp.getOrganisations().stream().map(org -> { -// Organization organization = new Organization(); -// organization.setId(org.getId().toString()); -// organization.setName(org.getLabel()); -// return organization; -// }).collect(Collectors.toList())); -// } -// datasetElastic.setPublic(dmp.isPublic()); -// if(this.dmpBlueprintService.fieldInBlueprint(dmp.getProfile(), DmpBlueprintSystemFieldType.Grant)) { -// datasetElastic.setGrantStatus(dmp.getGrant().getStatus()); -// } -// -// try { -// eu.eudat.elastic.entities.Dataset oldDatasetElastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(descriptionEntity.getId().toString()); -// if (oldDatasetElastic != null) { -// datasetElastic.setTags(oldDatasetElastic.getTags()); -// } -// datasetElastic.setFormData(this.datasetManager.getWordDocumentText(dataset1)); -// apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(datasetElastic); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } - }))); - return futures; - }).join(); - - } - } - - public void makePublic(UUID id) throws Exception { - DmpEntity dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); - // Check if dmp is finalized and if user is owner. - if (!isUserOwnerOfDmp(dmp)) - throw new Exception("User does not have the privilege to do this action."); - if (!dmp.getStatus().equals(DmpStatus.Finalized)) - throw new Exception("DMP is not finalized"); - dmp.setAccessType(DmpAccessType.Public); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); - UUID dmpId = dmp.getId(); - -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO - //this.updateIndex(dmp); //TODO - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.PUBLISHED); - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - criteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); - criteria.setAllVersions(true); - - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).toList().stream().forEach(dmp1 -> { -// dmp1.getDataset().forEach(dataset -> { - //TODO -// try { -// List tags = new ArrayList<>(); -// eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); -// if (elastic != null) { -// tags = elastic.getTags(); -// } -// //TODO -// //UUID tmdmpId = dataset.getDmpId(); -// //dataset.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tmdmpId)).toList())); -// this.datasetManager.updateTags(dataset, tags); -// metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } -// }); - }); - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - sendNotification(dmp, user/*, , NotificationType.DMP_PUBLISH*/); - } - - @Transactional - public void makeFinalize(UUID id, DatasetsToBeFinalized datasetsToBeFinalized) throws Exception { - DmpEntity dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); - if (!isUserOwnerOfDmp(dmp)) - throw new Exception("User does not have the privilege to do this action."); - if (dmp.getStatus().equals(DmpStatus.Finalized)) - throw new Exception("DMP is already finalized"); - List indexDescriptionEntities = new ArrayList<>(); - if (datasetsToBeFinalized != null && datasetsToBeFinalized.getUuids() != null && !datasetsToBeFinalized.getUuids().isEmpty()) { - List finalizedDescriptionEntities = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids())) - .toList(); - for (DescriptionEntity descriptionEntity : finalizedDescriptionEntities) { - DescriptionStatus status = descriptionEntity.getStatus(); - Instant finalizedDate = descriptionEntity.getFinalizedAt(); - descriptionEntity.setStatus(DescriptionStatus.Finalized); - descriptionEntity.setFinalizedAt(Instant.now()); - DatasetWizardModel wizardModel = new DatasetWizardModel(); - wizardModel = wizardModel.fromDataModel(descriptionEntity); - wizardModel.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(wizardModel, descriptionEntity)); - try { - datasetManager.createOrUpdate(wizardModel); - } catch (Exception e) { - descriptionEntity.setStatus(status); - descriptionEntity.setFinalizedAt(finalizedDate); - throw e; - } - descriptionEntity.setUpdatedAt(Instant.now()); - } - /*apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids())) - .update(root -> root.get("finalizedAt"), new Date());*/ - //List finalizedDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeFinalized.getUuids().contains(dataset.getId())).collect(Collectors.toList()); -/* finalizedDatasets.forEach(dataset ->{ - dataset.setStatus(Dataset.Status.FINALISED.getValue()); - dataset.setFinalizedAt(new Date()); - dataset.setModified(new Date()); - } );*/ - indexDescriptionEntities.addAll(finalizedDescriptionEntities); - List datasetsToBeCanceled = new LinkedList<>(); - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(List.of(dmp.getId())); - - List descriptionEntityList = this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList().stream().collect(Collectors.toList()); - - for (DescriptionEntity descriptionEntity : descriptionEntityList) { - if (!descriptionEntity.getStatus().equals(DescriptionStatus.Finalized) && !datasetsToBeFinalized.getUuids().contains(descriptionEntity.getId())) { - datasetsToBeCanceled.add(descriptionEntity.getId()); - } - } - if (!datasetsToBeCanceled.isEmpty()) { - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) - .update(root -> root.get("status"), DescriptionStatus.Canceled); - List cancelledDescriptionEntities = descriptionEntityList.stream().filter(dataset -> datasetsToBeCanceled.contains(dataset.getId())).collect(Collectors.toList()); - cancelledDescriptionEntities.forEach(dataset -> dataset.setStatus(DescriptionStatus.Canceled)); - indexDescriptionEntities.addAll(cancelledDescriptionEntities); - } - } else { - List datasetsToBeCanceled = new LinkedList<>(); - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(List.of(dmp.getId())); - List descriptionEntityList = this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList().stream().collect(Collectors.toList()); - for (DescriptionEntity descriptionEntity : descriptionEntityList) { - if (!descriptionEntity.getStatus().equals(DescriptionStatus.Finalized)) { - datasetsToBeCanceled.add(descriptionEntity.getId()); - } - } - if (!datasetsToBeCanceled.isEmpty()) { - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() - .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) - .update(root -> root.get("status"), DescriptionStatus.Canceled); - List cancelledDescriptionEntities = descriptionEntityList.stream().filter(dataset -> datasetsToBeCanceled.contains(dataset.getId())).collect(Collectors.toList()); - cancelledDescriptionEntities.forEach(dataset -> dataset.setStatus(DescriptionStatus.Canceled)); - indexDescriptionEntities.addAll(cancelledDescriptionEntities); - } - } - dmp.setStatus(DmpStatus.Finalized); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); - UUID dmpId = dmp.getId(); -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO - //this.updateIndex(dmp); //TODO - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - sendNotification(dmp, user/*, , NotificationType.DMP_FINALISED*/); - metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); - //this.updateDatasetsIndex(indexDescriptionEntities); //TODO - metricsManager.decreaseValue(MetricNames.DATASET, indexDescriptionEntities.size(), MetricNames.DRAFT); - metricsManager.increaseValue(MetricNames.DATASET, indexDescriptionEntities.size(), MetricNames.FINALIZED); - } - - public void undoFinalize(UUID id) throws Exception { - DmpEntity dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); - if (!isUserOwnerOfDmp(dmp)) - throw new Exception("User does not have the privilege to do this action."); - if (dmp.getIsActive().equals(IsActive.Inactive)) - throw new Exception("DMP is already Active"); - if (dmp.getAccessType().equals(DmpAccessType.Public)) - throw new Exception("DMP is publicly available"); -// if (!dmp.getDois().isEmpty())//TODO -// throw new Exception("DMP is deposited"); - dmp.setStatus(DmpStatus.Draft); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); - UUID dmpId = dmp.getId(); -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO - //this.updateIndex(dmp); //TODO - metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); - metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); - } - - public void updateUsers(UUID id, List users) throws Exception { - DmpEntity dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); - if (!isUserOwnerOfDmp(dmp)) - throw new Exception("User does not have the privilege to do this action."); - clearUsers(dmp); - for (DmpUser userListing : users) { - UserEntity tempUser = this.queryFactory.query(UserQuery.class).ids(userListing.getId()).first(); - assignUser(dmp, tempUser, userListing.getRole()); - } - - } - - /* - * Export Data - * */ - - public FileEnvelope getWordDocument(String id, ConfigLoader configLoader) throws IOException, InvalidApplicationException { - return this.getWordDocument(id, configLoader, true); - } - - public FileEnvelope getWordDocument(String id, ConfigLoader configLoader, Boolean versioned) throws IOException, InvalidApplicationException { - WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); - VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); - DatasetWizardModel dataset = new DatasetWizardModel(); - XWPFDocument document = configLoader.getDocument(); - - DmpEntity dmpEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (!dmpEntity.getAccessType().equals(DmpAccessType.Public) - //TODO && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId().equals(this.userScope.getUserIdSafe())).collect(Collectors.toList()).size() == 0 - ) - throw new UnauthorisedException(); - - wordBuilder.fillFirstPage(dmpEntity, null, document, false); - -// int powered_pos = document.getParagraphs().size() - 3; - int powered_pos = wordBuilder.findPosOfPoweredBy(document); - XWPFParagraph powered_par = null; - XWPFParagraph argos_img_par = null; - if(powered_pos != -1) { - powered_par = document.getParagraphArray(powered_pos); - argos_img_par = document.getParagraphArray(powered_pos + 1); - } - - -// // DMP info on top of the document. -// wordBuilder.addParagraphContent("Data Management Plan Information", document, ParagraphStyle.HEADER1, BigInteger.ZERO); -// // DMP title custom style. -// wordBuilder.addParagraphContent(dmpEntity.getLabel(), document, ParagraphStyle.HEADER2, BigInteger.ZERO); -// wordBuilder.addParagraphContent(dmpEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Funder", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getGrant().getFunder() != null) -// wordBuilder.addParagraphContent(dmpEntity.getGrant().getFunder().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Grant", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// wordBuilder.addParagraphContent(dmpEntity.getGrant().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Organisations", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getOrganisations().size() > 0) { -// wordBuilder.addParagraphContent(dmpEntity.getOrganisations().stream().map(Organisation::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// -// wordBuilder.addParagraphContent("Researchers", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getResearchers().size() > 0) { -// wordBuilder.addParagraphContent(dmpEntity.getResearchers().stream().map(Researcher::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// -// /*wordBuilder.addParagraphContent("DMP Profile", document, ParagraphStyle.HEADER2, BigInteger.ZERO); -// if (dmpEntity.getProfile() != null){ -// wordBuilder.addParagraphContent(dmpEntity.getProfile().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// }*/ -// -// // Page break at the end of the DMP title. -// XWPFParagraph parBreakDMP = document.createParagraph(); -// parBreakDMP.setPageBreak(true); -// -// wordBuilder.addParagraphContent("Datasets", document, ParagraphStyle.HEADER1, BigInteger.ZERO); -// // Space below Datasets. -// XWPFParagraph parBreakDatasets = document.createParagraph(); - - DefinitionEntity dmpBlueprint = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, this.queryFactory.query(DmpBlueprintQuery.class).ids(dmpEntity.getBlueprintId()).first().getDefinition()); - for(SectionEntity section: dmpBlueprint.getSections()){ - wordBuilder.addParagraphContent("Section " + section.getOrdinal(), document, ParagraphStyle.HEADER1, BigInteger.ZERO, 0); - XWPFParagraph sectionInfoParagraph = document.createParagraph(); - sectionInfoParagraph.setSpacingBetween(1.0); - XWPFRun runSectionTitle = sectionInfoParagraph.createRun(); - runSectionTitle.setText("Title: "); - runSectionTitle.setColor("000000"); - XWPFRun runSectionTitleText = sectionInfoParagraph.createRun(); - runSectionTitleText.setText(section.getLabel()); - runSectionTitleText.setColor("116a78"); - XWPFParagraph sectionDescriptionParagraph = document.createParagraph(); - XWPFRun runSectionDescription = sectionDescriptionParagraph.createRun(); - runSectionDescription.setText("Description: "); - runSectionDescription.setColor("000000"); - XWPFRun runSectionDescriptionText = sectionDescriptionParagraph.createRun(); - runSectionDescriptionText.setText(section.getDescription()); - runSectionDescriptionText.setColor("116a78"); - - wordBuilder.addParagraphContent("Section Fields", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); - section.getFields().sort(Comparator.comparingInt(FieldEntity::getOrdinal)); - for(FieldEntity field: section.getFields()){ - if(field.getCategory() == DmpBlueprintFieldCategory.System){ - SystemFieldEntity systemField = (SystemFieldEntity) field; - XWPFParagraph systemFieldParagraph = document.createParagraph(); - systemFieldParagraph.setSpacingBetween(1.0); - XWPFRun runSyStemFieldTitle = systemFieldParagraph.createRun(); - runSyStemFieldTitle.setText("Title: "); - runSyStemFieldTitle.setColor("000000"); - XWPFRun runSystemFieldTitleText = systemFieldParagraph.createRun(); - runSystemFieldTitleText.setText(systemField.getLabel()); - runSystemFieldTitleText.setColor("116a78"); - if(systemField.getDescription() != null && !systemField.getDescription().isEmpty()){ - XWPFParagraph systemFieldDescription = document.createParagraph(); - systemFieldDescription.setSpacingBetween(1.0); - XWPFRun runSyStemFieldDescription = systemFieldDescription.createRun(); - runSyStemFieldDescription.setText("Description: "); - runSyStemFieldDescription.setColor("000000"); - XWPFRun runSystemFieldDescriptionText = systemFieldDescription.createRun(); - runSystemFieldDescriptionText.setText(systemField.getDescription()); - runSystemFieldDescriptionText.setColor("116a78"); - } - XWPFParagraph systemFieldInput = document.createParagraph(); - systemFieldInput.setSpacingBetween(1.0); - XWPFRun runInput = systemFieldInput.createRun(); - runInput.setText("Input: "); - runInput.setColor("000000"); - switch (systemField.getType()) { - case Text: - XWPFRun runTitle = systemFieldInput.createRun(); - runTitle.setText(dmpEntity.getLabel()); - runTitle.setColor("116a78"); - break; - case HtmlText: - XWPFRun runDescription = systemFieldInput.createRun(); - runDescription.setText(dmpEntity.getDescription()); - runDescription.setColor("116a78"); - break; - case Researchers: - //TODO -// for(Researcher researcher: dmpEntity.getResearchers()){ -// XWPFRun runResearcher = systemFieldInput.createRun(); -// runResearcher.setText("• " + researcher.getLabel()); -// runResearcher.setColor("116a78"); -// } - break; - //TODO -// case Organizations: -// -// for(Organisation organisation: dmpEntity.getOrganisations()){ -// XWPFRun runOrganisation = systemFieldInput.createRun(); -// runOrganisation.setText("• " + organisation.getLabel()); -// runOrganisation.setColor("116a78"); -// } -// break; -// case Language: -// XWPFRun runLanguage = systemFieldInput.createRun(); -// runLanguage.setText(objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class).get("language").toString()); -// runLanguage.setColor("116a78"); -// break; -// case Contact: -// XWPFRun runContact = systemFieldInput.createRun(); -// runContact.setText(dmpEntity.getCreator().getName()); -// runContact.setColor("116a78"); -// break; -// case Funder: -// if (dmpEntity.getGrant() != null && dmpEntity.getGrant().getFunder() != null) { -// XWPFRun runFunder = systemFieldInput.createRun(); -// runFunder.setText(dmpEntity.getGrant().getFunder().getLabel()); -// runFunder.setColor("116a78"); -// } -// break; -// case Grant: -// if (dmpEntity.getGrant() != null) { -// XWPFRun runGrant = systemFieldInput.createRun(); -// runGrant.setText(dmpEntity.getGrant().getLabel()); -// runGrant.setColor("116a78"); -// } -// break; -// case Project: -// if (dmpEntity.getProject() != null ) { -// XWPFRun runProject = systemFieldInput.createRun(); -// runProject.setText(dmpEntity.getProject().getLabel()); -// runProject.setColor("116a78"); -// } -// break; -// case License: -// Map extraProperties = objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class); -// if (extraProperties.containsKey("license")) { -// XWPFRun runLicense = systemFieldInput.createRun(); -// runLicense.setText(extraProperties.get("license").toString()); -// runLicense.setColor("116a78"); -// } -// break; -// case AccessRights: -// Map extraPropertiesMap = objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class); -// if (extraPropertiesMap.containsKey("visible")) { -// XWPFRun runAccessRights = systemFieldInput.createRun(); -// runAccessRights.setText(extraPropertiesMap.get("visible").toString()); -// runAccessRights.setColor("116a78"); -// } -// break; - } - document.createParagraph(); - } - else if(field.getCategory() == DmpBlueprintFieldCategory.Extra){ - ExtraFieldEntity extraField = (ExtraFieldEntity)field; - XWPFParagraph extraFieldParagraph = document.createParagraph(); - extraFieldParagraph.setSpacingBetween(1.0); - XWPFRun runExtraFieldLabel = extraFieldParagraph.createRun(); - runExtraFieldLabel.setText(extraField.getLabel()); - runExtraFieldLabel.setColor("116a78"); - if(extraField.getDescription() != null && !extraField.getDescription().isEmpty()){ - XWPFRun runExtraFieldDescription = extraFieldParagraph.createRun(); - runExtraFieldDescription.setText(extraField.getDescription()); - runExtraFieldDescription.setColor("116a78"); - } - XWPFRun runExtraFieldInput = extraFieldParagraph.createRun(); - Map dmpProperties = objectMapper.readValue(dmpEntity.getProperties(), HashMap.class); - if (dmpProperties.containsKey(field.getId()) && dmpProperties.get(field.getId()) != null) { - runExtraFieldInput.setText((String) dmpProperties.get(field.getId())); - } - runExtraFieldInput.setColor("116a78"); - } - } - - if(!section.getDescriptionTemplates().isEmpty()){ - wordBuilder.addParagraphContent("Section descriptions", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); - wordBuilder.addParagraphContent("Description Templates", document, ParagraphStyle.HEADER4, BigInteger.ZERO, 0); - for(eu.eudat.commons.types.dmpblueprint.DescriptionTemplateEntity descriptionTemplateEntity : section.getDescriptionTemplates()){ - XWPFParagraph templateParagraph = document.createParagraph(); - XWPFRun runTemplateLabel = templateParagraph.createRun(); - runTemplateLabel.setText("• " + descriptionTemplateEntity.getLabel()); - runTemplateLabel.setColor("116a78"); - } - - final Boolean isFinalized = dmpEntity.getStatus().equals(DmpStatus.Finalized); - final Boolean isPublic = dmpEntity.getAccessType().equals(DmpAccessType.Public); - - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(Collections.singletonList(dmpEntity.getId())); - List descriptionEntityList = this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList().stream().collect(Collectors.toList()); - descriptionEntityList.stream() - .filter(item -> item.getStatus() != DescriptionStatus.Canceled) - .filter(item -> item.getIsActive() != IsActive.Inactive) - .filter(item -> !isPublic && !isFinalized || item.getStatus() == DescriptionStatus.Finalized) - //.filter(item -> item.getDmpSectionIndex().equals(section.getOrdinal() - 1)) //TODO - .sorted(Comparator.comparing(DescriptionEntity::getCreatedAt)) - .forEach(datasetEntity -> { - Map properties = new HashMap<>(); - if (datasetEntity.getProperties() != null) { - //ObjectMapper objectMapper = new ObjectMapper(); - try { - properties = objectMapper.readValue(datasetEntity.getProperties(), LinkedHashMap.class); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - /*JSONObject jObject = new JSONObject(datasetEntity.getProperties()); - properties = jObject.toMap();*/ - } - - - // Dataset Description custom style. - XWPFParagraph datasetDescriptionParagraph = document.createParagraph(); - datasetDescriptionParagraph.setStyle("Heading4"); - datasetDescriptionParagraph.setSpacingBetween(1.5); - XWPFRun datasetDescriptionRun = datasetDescriptionParagraph.createRun(); - datasetDescriptionRun.setText("Dataset Description"); - //datasetDescriptionRun.setColor("2E75B6"); - //datasetDescriptionRun.setBold(true); - datasetDescriptionRun.setFontSize(15); - - - // Custom style for the Dataset title. - //wordBuilder.addParagraphContent("Title: " + datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); - XWPFParagraph datasetLabelParagraph = document.createParagraph(); -// datasetLabelParagraph.setStyle("Heading2"); - datasetLabelParagraph.setSpacingBetween(1.0); - XWPFRun runDatasetTitle1 = datasetLabelParagraph.createRun(); - runDatasetTitle1.setText("Title: "); - runDatasetTitle1.setColor("000000"); - //runDatasetTitle1.setBold(true); - //runDatasetTitle1.setFontSize(12); - XWPFRun runDatasetTitle = datasetLabelParagraph.createRun(); - runDatasetTitle.setText(datasetEntity.getLabel()); - runDatasetTitle.setColor("116a78"); - //runDatasetTitle.setBold(true); - //runDatasetTitle.setFontSize(12); - - XWPFParagraph datasetTemplateParagraph = document.createParagraph(); -// datasetTemplateParagraph.setStyle("Heading3"); - XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); - runDatasetTemplate1.setText("Template: "); - runDatasetTemplate1.setColor("000000"); - //runDatasetTemplate1.setBold(true); - //runDatasetTemplate1.setFontSize(12); - XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); - runDatasetTemplate.setText(this.queryFactory.query(DescriptionTemplateQuery.class).ids(datasetEntity.getDescriptionTemplateId()).first().getLabel()); - runDatasetTemplate.setColor("116a78"); - //runDatasetTemplate.setBold(true); - //runDatasetTemplate.setFontSize(12); - -// /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); -// externalReferencesParagraph.setStyle("Heading3"); -// XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); -// externalReferencesRun.setText("External References"); -// externalReferencesRun.setColor("2E75B6"); -// externalReferencesRun.setBold(true); -// externalReferencesRun.setFontSize(12); -// -// wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getDatasetDataRepositories().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getDatasetDataRepositories().stream().map(DatasetDataRepository::getDataRepository).map(DataRepository::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("External Datasets", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getDatasetExternalDatasets().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getDatasetExternalDatasets().stream().map(DatasetExternalDataset::getExternalDataset).map(ExternalDataset::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("Registries", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getRegistries().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getRegistries().stream().map(Registry::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("Services", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getServices().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// *//*wordBuilder.addParagraphContent("Tags", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (datasetEntity.().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// }*/ -// -// - - XWPFParagraph datasetDescParagraph = document.createParagraph(); - XWPFRun runDatasetDescription1 = datasetDescParagraph.createRun(); - runDatasetDescription1.setText("Description: "); - runDatasetDescription1.setColor("000000"); - XWPFRun runDatasetDescription = datasetDescParagraph.createRun(); - runDatasetDescription.setText(this.queryFactory.query(DescriptionTemplateQuery.class).ids(datasetEntity.getDescriptionTemplateId()).first().getLabel()); - runDatasetDescription.setColor("116a78"); - //wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO, 0); - - document.createParagraph(); - - PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity); - visibilityRuleService.setProperties(properties); - visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); - try { - wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - // Page break at the end of the Dataset. - XWPFParagraph parBreakDataset = document.createParagraph(); - parBreakDataset.setPageBreak(true); - }); - } - } - -// // Removes the top empty headings. -// for (int i = 0; i < 6; i++) { -// document.removeBodyElement(0); -// } - - - if(powered_pos != -1) { - document.getLastParagraph().setPageBreak(false); - document.createParagraph(); - document.setParagraph(powered_par, document.getParagraphs().size() - 1); - - document.createParagraph(); - document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); - - document.removeBodyElement(powered_pos + 1); - document.removeBodyElement(powered_pos + 1); - } - - wordBuilder.fillFooter(dmpEntity, null, document, false); - - String fileName =""; - //TODO -// if (dmpEntity.getGrant() != null && dmpEntity.getGrant().getLabel() != null) { -// fileName = "DMP_" + dmpEntity.getGrant().getLabel(); -// } -// else { -// fileName = "DMP_" + dmpEntity.getLabel(); -// } -// if (versioned) { -// fileName += "_" + dmpEntity.getVersion(); -// } - // fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); - FileEnvelope exportEnvelope = new FileEnvelope(); - exportEnvelope.setFilename(fileName + ".docx"); - String uuid = UUID.randomUUID().toString(); - File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx"); - FileOutputStream out = new FileOutputStream(exportFile); - document.write(out); - out.close(); - exportEnvelope.setFile(exportFile); - - return exportEnvelope; - } - - private FileEnvelope getXmlDocument(String id) throws IOException, InvalidApplicationException { - ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); - VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); - DmpEntity dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (!dmp.getAccessType().equals(DmpAccessType.Public) - //TODO && dmp.getUsers().stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())).collect(Collectors.toList()).size() == 0 - ) - throw new UnauthorisedException(); - final Boolean isFinalized = dmp.getStatus().equals(DmpStatus.Finalized); - final Boolean isPublic = dmp.getAccessType().equals(DmpAccessType.Public); - DatasetCriteria datasetCriteria = new DatasetCriteria(); - datasetCriteria.setDmpIds(List.of(dmp.getId())); - - List descriptionEntityList = this.databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).toList().stream().filter(dataset -> dataset.getIsActive() != IsActive.Inactive).collect(Collectors.toList()); - - List descriptionEntities = descriptionEntityList.stream() - .filter(dataset -> dataset.getIsActive() != IsActive.Inactive && - dataset.getStatus() != DescriptionStatus.Canceled) - .filter(dataset -> !isPublic && !isFinalized || dataset.getStatus() == DescriptionStatus.Finalized) - .collect(Collectors.toList()); - /*String fileName = dmp.getLabel(); - fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");*/ - String uuid = UUID.randomUUID().toString(); - File xmlFile = new File(this.environment.getProperty("temp.temp") + uuid + ".xml"); - BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true)); - Document xmlDoc = XmlBuilder.getDocument(); - Element dmpElement = xmlDoc.createElement("dmp"); - Element dmpDescription = xmlDoc.createElement("description"); - dmpDescription.setTextContent(dmp.getDescription()); - dmpElement.appendChild(dmpDescription); - Element dmpName = xmlDoc.createElement("dmpName"); - dmpName.setTextContent(dmp.getLabel()); - dmpElement.appendChild(dmpName); - - //TODO -// if (dmp.getExtraProperties() != null && !dmp.getExtraProperties().isEmpty()) { -// Map extraProperties = new ObjectMapper().readValue(dmp.getExtraProperties(), HashMap.class); -// Element language = xmlDoc.createElement("language"); -// language.setTextContent(extraProperties.get("language") != null ? extraProperties.get("language").toString() : null); -// dmpElement.appendChild(language); -// Element visibility = xmlDoc.createElement("visibility"); -// visibility.setTextContent(extraProperties.get("visible") != null ? extraProperties.get("visible").toString() : null); -// dmpElement.appendChild(visibility); -// Element publicDate = xmlDoc.createElement("publicDate"); -// publicDate.setTextContent(extraProperties.get("publicDate") != null ? extraProperties.get("publicDate").toString() : null); -// dmpElement.appendChild(publicDate); -// Element costs = xmlDoc.createElement("costs"); -// costs.setTextContent(extraProperties.get("costs") != null ? extraProperties.get("costs").toString() : null); -// dmpElement.appendChild(costs); -// } - - DmpBlueprintEntity dmpBlueprint = this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(); - Element dmpProfileElement = xmlDoc.createElement("dmpProfile"); - Element dmpProfileName = xmlDoc.createElement("dmpProfileName"); - if (!(dmpBlueprint == null)) { - dmpProfileName.setTextContent(dmpBlueprint.getLabel()); - dmpProfileElement.appendChild(dmpProfileName); - Element dmpProfileId = xmlDoc.createElement("dmpProfileId"); - dmpProfileId.setTextContent(dmpBlueprint.getId().toString()); - dmpProfileElement.appendChild(dmpProfileId); -// Element values = xmlDoc.createElement("values"); -// values.setTextContent(dmpProfile.getDefinition()); -// dmpProfileElement.appendChild(values); - } - dmpElement.appendChild(dmpProfileElement); - - Element dmpContactElement = xmlDoc.createElement("contact"); - Element dmpContactName = xmlDoc.createElement("name"); - Element dmpContactEmail = xmlDoc.createElement("email"); - if(dmp.getCreatorId() != null){ - dmpContactName.setTextContent(this.queryFactory.query(UserQuery.class).ids(dmp.getCreatorId()).first().getName()); - //TODO dmpContactEmail.setTextContent(this.databaseRepository.getUserInfoDao().find(dmp.getCreator()).getEmail()); - } - else{ - Iterator users = new ArrayList().iterator(); //TODO dmp.getUsers().iterator(); - if(users.hasNext()){ - DmpUserEntity creator = users.next(); - dmpContactName.setTextContent(this.queryFactory.query(UserQuery.class).ids(creator.getUserId()).first().getName()); -//TODO .setTextContent(this.databaseRepository.getUserInfoDao().find(creator.getUser()).getEmail()); - } - } - dmpContactElement.appendChild(dmpContactName); - dmpContactElement.appendChild(dmpContactEmail); - dmpElement.appendChild(dmpContactElement); - - Element dmpContributorsElement = xmlDoc.createElement("contributors"); - Iterator users = new ArrayList().iterator(); //TODO dmp.getUsers().iterator(); - while(users.hasNext()){ - Element dmpContributorElement = xmlDoc.createElement("contributor"); - Element dmpContributorName = xmlDoc.createElement("name"); - Element dmpContributorEmail= xmlDoc.createElement("email"); - DmpUserEntity contributor = users.next(); - dmpContributorName.setTextContent(this.queryFactory.query(UserQuery.class).ids(contributor.getUserId()).first().getName()); - //TODO dmpContributorEmail.setTextContent(this.databaseRepository.getUserInfoDao().find(contributor.getUser()).getEmail()); - dmpContributorElement.appendChild(dmpContributorName); - dmpContributorElement.appendChild(dmpContributorEmail); - dmpContributorsElement.appendChild(dmpContributorElement); - } - dmpElement.appendChild(dmpContributorsElement); - - // Funder. - Element funder = xmlDoc.createElement("funder"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Grant) && this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Funder)) { - Element funderLabel = xmlDoc.createElement("label"); - Element funderId = xmlDoc.createElement("id"); - //TODO -// funderLabel.setTextContent(dmp.getGrant().getFunder().getLabel()); -// funderId.setTextContent(dmp.getGrant().getFunder().getId().toString()); -// funder.appendChild(funderLabel); -// funder.appendChild(funderId); -// if (dmp.getGrant().getFunder().getReference() != null) { -// String referencePrefix = dmp.getGrant().getFunder().getReference().split(":")[0]; -// String shortReference = dmp.getGrant().getFunder().getReference().substring(referencePrefix.length() + 1); -// Element funderReference = xmlDoc.createElement("reference"); -// funderReference.setTextContent(shortReference); -// funder.appendChild(funderReference); -// } - } - dmpElement.appendChild(funder); - // Grant. - Element grant = xmlDoc.createElement("grant"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Grant)) { - Element grantLabel = xmlDoc.createElement("label"); - Element grantId = xmlDoc.createElement("id"); - //TODO -// grantLabel.setTextContent(dmp.getGrant().getLabel()); -// grantId.setTextContent(dmp.getGrant().getId().toString()); -// grant.appendChild(grantLabel); -// grant.appendChild(grantId); -// if (dmp.getGrant().getReference() != null) { -// String referencePrefix = dmp.getGrant().getReference().split(":")[0]; -// String shortReference = dmp.getGrant().getReference().substring(referencePrefix.length() + 1); -// Element grantReference = xmlDoc.createElement("reference"); -// grantReference.setTextContent(shortReference); -// grant.appendChild(grantReference); -// } - } - dmpElement.appendChild(grant); - // Project. - Element project = xmlDoc.createElement("project"); - if (this.dmpBlueprintService.fieldInBlueprint(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first(), DmpBlueprintSystemFieldType.Project)) { - Element projectId = xmlDoc.createElement("id"); - Element projectLabel = xmlDoc.createElement("label"); - Element projectDescription = xmlDoc.createElement("description"); - Element projectStartDate = xmlDoc.createElement("start"); - Element projectEndDate = xmlDoc.createElement("end"); - - //TODO -// projectId.setTextContent(dmp.getProject().getId().toString()); -// projectLabel.setTextContent(dmp.getProject().getLabel()); -// projectDescription.setTextContent(dmp.getProject().getDescription()); -// projectStartDate.setTextContent(dmp.getProject().getStartdate().toString()); -// projectEndDate.setTextContent(dmp.getProject().getEnddate().toString()); - project.appendChild(projectId); - project.appendChild(projectLabel); - project.appendChild(projectDescription); - project.appendChild(projectStartDate); - project.appendChild(projectEndDate); - } - dmpElement.appendChild(project); - - //TODO -// Element organisationsElement = xmlDoc.createElement("organisations"); -// for (Organisation organisation : dmp.getOrganisations()) { -// Element organisationElement = xmlDoc.createElement("organisation"); -// Element organisationNameElement = xmlDoc.createElement("name"); -// organisationNameElement.setTextContent(organisation.getLabel()); -// Element organisationReferenceElement = xmlDoc.createElement("reference"); -// organisationReferenceElement.setTextContent(organisation.getReference()); -// organisationElement.appendChild(organisationNameElement); -// organisationElement.appendChild(organisationReferenceElement); -// organisationsElement.appendChild(organisationElement); -// } -// dmpElement.appendChild(organisationsElement); -// -// Element researchersElement = xmlDoc.createElement("researchers"); -// for (Researcher researcher : dmp.getResearchers()) { -// Element researcherElement = xmlDoc.createElement("researcher"); -// Element researcherNameElement = xmlDoc.createElement("name"); -// researcherNameElement.setTextContent(researcher.getLabel()); -// Element researcherReferenceElement = xmlDoc.createElement("reference"); -// researcherReferenceElement.setTextContent(researcher.getReference()); -// researcherElement.appendChild(researcherNameElement); -// researcherElement.appendChild(researcherReferenceElement); -// researchersElement.appendChild(researcherElement); -// } -// dmpElement.appendChild(researchersElement); - - Element extraFields = xmlDoc.createElement("extraFields"); - Map dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference>() {}); - - DefinitionEntity blueprint = new DefinitionEntity(); //new DefinitionEntity().fromXml(XmlBuilder.fromXml(this.queryFactory.query(DmpBlueprintQuery.class).ids(dmp.getBlueprintId()).first().getDefinition()).getDocumentElement()); - - blueprint.getSections().forEach(section -> { - section.getFields().forEach(fieldModel -> { - if (fieldModel.getCategory() == DmpBlueprintFieldCategory.Extra) { - Element extraField = xmlDoc.createElement("extraField"); - Element extraFieldId = xmlDoc.createElement("id"); - extraFieldId.setTextContent(fieldModel.getId().toString()); - Element extraFieldLabel = xmlDoc.createElement("label"); - extraFieldLabel.setTextContent(fieldModel.getLabel()); - Element extraFieldValue = xmlDoc.createElement("value"); - Object value = dmpProperties.get(fieldModel.getId().toString()); - if (value != null) { - extraFieldValue.setTextContent((String) value); - } - extraField.appendChild(extraFieldId); - extraField.appendChild(extraFieldLabel); - extraField.appendChild(extraFieldValue); - extraFields.appendChild(extraField); - } - }); - }); - dmpElement.appendChild(extraFields); - - Element datasetsElement = xmlDoc.createElement("datasets"); - for (DescriptionEntity descriptionEntity : descriptionEntities) { - Element datasetElement = xmlDoc.createElement("dataset"); - datasetElement.setAttribute("name", descriptionEntity.getLabel()); - - Element datasetDescriptionElement = xmlDoc.createElement("description"); - datasetElement.appendChild(datasetDescriptionElement); - datasetDescriptionElement.setTextContent(descriptionEntity.getDescription()); - - //TODO -// Element datasetDmpSectionIndex = xmlDoc.createElement("dmpSectionIndex"); -// datasetElement.appendChild(datasetDmpSectionIndex); -// datasetDmpSectionIndex.setTextContent(String.valueOf(descriptionEntity.getDmpSectionIndex())); - - Element datsetProfileElement = xmlDoc.createElement("profile-id"); - datasetElement.appendChild(datsetProfileElement); - datsetProfileElement.setTextContent(descriptionEntity.getDescriptionTemplateId().toString()); - - Element datsetProfileLabelElement = xmlDoc.createElement("profile-label"); - datasetElement.appendChild(datsetProfileLabelElement); - datsetProfileLabelElement.setTextContent(this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntity.getDescriptionTemplateId()).first().getLabel()); - - DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); - Map properties = new HashMap<>(); - if (descriptionEntity.getProperties() != null) { - JSONObject jobject = new JSONObject(descriptionEntity.getProperties()); - properties = jobject.toMap(); - } - PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(datasetWizardModel, descriptionEntity); - visibilityRuleService.setProperties(properties); - visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); - datasetElement.appendChild(xmlBuilder.createPages(pagedDatasetProfile.getPages(), visibilityRuleService, xmlDoc)); - datasetsElement.appendChild(datasetElement); - } - - Element profiles = xmlDoc.createElement("profiles"); - // Get DatasetProfiles from DMP to add to XML. - //TODO -// for (DMPDatasetProfile dmpDescriptionProfile : dmp.getAssociatedDmps()) { -// DescriptionTemplateEntity descriptionTemplateEntity = dmpDescriptionProfile.getDatasetprofile(); -// Element profile = xmlDoc.createElement("profile"); -// Element profileId = xmlDoc.createElement("profileId"); -// profileId.setTextContent(descriptionTemplateEntity.getId().toString()); -// profile.appendChild(profileId); -// Element profileGroupId = xmlDoc.createElement("profileGroupId"); -// profileGroupId.setTextContent(descriptionTemplateEntity.getGroupId().toString()); -// profile.appendChild(profileGroupId); -// Element profileLabel = xmlDoc.createElement("profileLabel"); -// profileLabel.setTextContent(descriptionTemplateEntity.getLabel()); -// profile.appendChild(profileLabel); -// Element profileVersion = xmlDoc.createElement("profileVersion"); -// profileVersion.setTextContent(String.valueOf(descriptionTemplateEntity.getVersion())); -// profile.appendChild(profileVersion); -// Element profileInSections = xmlDoc.createElement("profileInSections"); -// Map data = new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {}); -// List sections = (List) data.get("dmpSectionIndex"); -// for(int section: sections) { -// Element profileInSection = xmlDoc.createElement("section"); -// profileInSection.setTextContent(String.valueOf(section)); -// profileInSections.appendChild(profileInSection); -// } -// profile.appendChild(profileInSections); -// profiles.appendChild(profile); -// } - dmpElement.appendChild(profiles); - dmpElement.appendChild(datasetsElement); - xmlDoc.appendChild(dmpElement); - String xml = XmlBuilder.generateXml(xmlDoc); - writer.write(xml); - writer.close(); - FileEnvelope fileEnvelope = new FileEnvelope(); - fileEnvelope.setFile(xmlFile); - //TODO -// if (dmp.getGrant() != null && dmp.getGrant().getLabel() != null) { -// fileEnvelope.setFilename("DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion() + ".xml"); -// } -// else { -// fileEnvelope.setFilename("DMP_" + dmp.getLabel() + "_" + dmp.getVersion() + ".xml"); -// } - - return fileEnvelope; - } - - @Transactional - public FileEnvelope getRDAJsonDocument(String id) throws Exception { - DmpEntity dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (!dmp.getAccessType().equals(DmpAccessType.Public) - //TODO && dmp.getUsers().stream().noneMatch(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())) - ) - throw new UnauthorisedException(); - final boolean isFinalized = dmp.getStatus() == DmpStatus.Finalized; - final boolean isPublic = dmp.getAccessType().equals(DmpAccessType.Public); - //TODO -// dmp.setDataset(dmp.getDataset().stream() -// .filter(dataset -> dataset.getIsActive() != IsActive.Inactive && -// dataset.getStatus() != DescriptionStatus.Canceled) -// .filter(dataset -> !isPublic && !isFinalized || dataset.getStatus() == DescriptionStatus.Finalized) -// .collect(Collectors.toSet())); - String result = rdaManager.convertToRDA(dmp); - - String fileName = ""; - //TODO -// if (dmp.getGrant() != null && dmp.getGrant().getLabel() != null) { -// fileName = "DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion(); -// } -// else { -// fileName = "DMP_" + dmp.getLabel() + "_" + dmp.getVersion(); -// } - fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "").replace(" ", "_").replace(",", "_"); - String uuid = UUID.randomUUID().toString(); - File file = new File(this.environment.getProperty("temp.temp") + uuid + ".json"); - OutputStream output = new FileOutputStream(file); - try { - output.write(result.getBytes()); - output.flush(); - output.close(); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - - FileEnvelope rdaJsonDocument = new FileEnvelope(); - rdaJsonDocument.setFilename(fileName + ".json"); - rdaJsonDocument.setFile(file); - return rdaJsonDocument; - } - - public ResponseEntity getDocument(String id, String contentType, ConfigLoader configLoader) throws InstantiationException, IllegalAccessException, IOException, InvalidApplicationException { - FileEnvelope file; - switch (contentType) { - case "application/xml": - file = getXmlDocument(id); - break; - case "application/msword": - file = getWordDocument(id, configLoader); - break; - default: - file = getXmlDocument(id); - } - String fileName = file.getFilename().replace(" ", "_").replace(",", "_"); - InputStream resource = new FileInputStream(file.getFile()); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentLength(file.getFile().length()); - responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); - responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName); - responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); - responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); - - byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); - resource.close(); - Files.deleteIfExists(file.getFile().toPath()); - return new ResponseEntity<>(content, - responseHeaders, - HttpStatus.OK); - } - - /* - * Data Import - * */ - - public List createDmpFromXml(MultipartFile[] files, String[] profiles) throws IOException, JAXBException, Exception { - List dataManagementPlans = new ArrayList<>(); - // Jaxb approach. - JAXBContext jaxbContext; - - for (MultipartFile multipartFile : Arrays.asList(files)) { // Gets one item from the array. - try { - InputStream in = multipartFile.getInputStream(); // Transforms item to InputStream. - jaxbContext = JAXBContext.newInstance(DmpImportModel.class); - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - DmpImportModel dmpImportModel = (DmpImportModel) jaxbUnmarshaller.unmarshal(in); - dataManagementPlans.add(dmpImportModel); - } catch (IOException | JAXBException ex) { - logger.error(ex.getMessage(), ex); - } - // TODO Iterate through the list of dataManagementPlans. - // Creates new dataManagementPlan to fill it with the data model that was parsed from the xml. - // Creates properties. - DataManagementPlanEditorModel dm = new DataManagementPlanEditorModel(); - - DmpProfileImportModel dmpProfileImportModel = dataManagementPlans.get(0).getDmpProfile(); - Tuple tupleProfile = new Tuple<>(); - if (dmpProfileImportModel != null) { - tupleProfile.setId(dmpProfileImportModel.getDmpProfileId()); - tupleProfile.setLabel(dmpProfileImportModel.getDmpProfileName()); - } - else { - tupleProfile.setId(UUID.fromString("86635178-36a6-484f-9057-a934e4eeecd5")); - tupleProfile.setLabel("Dmp Default Blueprint"); - } - dm.setProfile(tupleProfile); - - - Map dmpPropertiesMap = new HashMap<>(); - if (dataManagementPlans.get(0).getExtraFieldsImportModels() != null) { - for (ExtraFieldsImportModels extraField: dataManagementPlans.get(0).getExtraFieldsImportModels()) { - dmpPropertiesMap.put(extraField.getId(), extraField.getValue()); - } - } - dm.setProperties(dmpPropertiesMap); -//TODO -// if (this.dmpBlueprintService.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId(), DmpBlueprintSystemFieldType.Funder)) { -// eu.eudat.models.data.funder.Funder funder = new eu.eudat.models.data.funder.Funder(); -// FunderImportModels funderImport = dataManagementPlans.get(0).getFunderImportModels(); -// funder.setId(funderImport.getId()); -// funder.setLabel(funderImport.getLabel()); -// FunderDMPEditorModel funderEditor = new FunderDMPEditorModel(); -// funderEditor.setExistFunder(funder); -// -// dm.setFunder(funderEditor); -// } - //TODO -// if (this.dmpBlueprintService.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId(), DmpBlueprintSystemFieldType.Grant)) { -// eu.eudat.models.data.grant.Grant grant = new eu.eudat.models.data.grant.Grant(); -// GrantImportModels grantImport = dataManagementPlans.get(0).getGrantImport(); -// grant.setId(grantImport.getId()); -// grant.setLabel(grantImport.getLabel()); -// grant.setAbbreviation(grantImport.getAbbreviation()); -// grant.setDescription(grantImport.getDescription()); -// GrantDMPEditorModel grantEditor = new GrantDMPEditorModel(); -// grantEditor.setExistGrant(grant); -// -// dm.setGrant(grantEditor); -// } - - //TODO -// if (this.dmpBlueprintService.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId(), DmpBlueprintSystemFieldType.Project)) { -// eu.eudat.models.data.project.Project project = new eu.eudat.models.data.project.Project(); -// ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImportModels(); -// project.setId(projectImport.getId()); -// project.setLabel(projectImport.getLabel()); -// ProjectDMPEditorModel projectEditor = new ProjectDMPEditorModel(); -// projectEditor.setExistProject(project); -// -// dm.setProject(projectEditor); -// } - - List associatedProfiles = new LinkedList<>(); -// if (profiles != null && profiles.length > 0) { -// for (String profile : profiles) { -// DescriptionTemplate exProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(profile)); -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(exProfile); -// associatedProfiles.add(associatedProfile); -// } -// } - -// for (AssociatedProfileImportModels a : dataManagementPlans.get(0).getProfilesImportModels()) { -// try { -// eu.eudat.data.DescriptionTemplateEntity exProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(a.getId()); -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(exProfile); -// Map data = new HashMap<>(); -// List sections = new ArrayList<>(a.getSection()); -// data.put("dmpSectionIndex", sections); -// associatedProfile.setData(data); -// associatedProfiles.add(associatedProfile); -// } catch (Exception ignored) { -// } -// } - -// List organisations = new ArrayList<>(); -// for (OrganisationImportModel org : dataManagementPlans.get(0).getOrganisationImportModels()) { -// eu.eudat.models.data.dmp.Organisation organisation = new eu.eudat.models.data.dmp.Organisation(); -// organisation.setName(org.getOrganaisationNameImport()); -// organisation.setReference(org.getOrganaisationReferenceImport()); -// organisation.setKey(organisation.getReference().split(":")[0]); -// organisations.add(organisation); -// }//TODO - -// List researchers = new LinkedList<>(); -// for (ResearcherImportModels res : dataManagementPlans.get(0).getResearchersImportModels()) { -// eu.eudat.models.data.dmp.Researcher researcher = new eu.eudat.models.data.dmp.Researcher(); -// researcher.setLabel(res.getResearcherImportName()); -// researcher.setName(res.getResearcherImportName()); -// researcher.setReference(res.getResearcherImportReference()); -// researcher.setKey(researcher.getReference().split(":")[0]); -// researchers.add(researcher); -// } //TODO - - //List associatedUsers = new LinkedList<>(); - List dynamicFields = new LinkedList<>(); - - // Sets properties. - dm.setLabel(files[0].getOriginalFilename()); // Sets label. - dm.setDescription(dataManagementPlans.get(0).getDescriptionImport()); // Sets description property. - dm.setProfiles(associatedProfiles); -// dm.setOrganisations(organisations); // Sets organisations property. -// dm.setResearchers(researchers); // Sets researchers property. - //dm.setAssociatedUsers(associatedUsers); // Sets associatedUsers property. - dm.setDynamicFields(dynamicFields); // Sets dynamicFields property. - //dm.setDefinition(dmpProfile); - //ObjectMapper mapper = new ObjectMapper(); - Map extraPropertiesMap = new HashMap<>(); - if (dataManagementPlans.get(0).getLanguage() != null) { - extraPropertiesMap.put("language", dataManagementPlans.get(0).getLanguage()); - } - if (dataManagementPlans.get(0).getVisibility() != null) { - extraPropertiesMap.put("visible", dataManagementPlans.get(0).getVisibility()); - } - if (dataManagementPlans.get(0).getPublicDate() != null) { - extraPropertiesMap.put("publicDate", dataManagementPlans.get(0).getPublicDate()); - } - if (dataManagementPlans.get(0).getCosts() != null && !dataManagementPlans.get(0).getCosts().isEmpty()) { - extraPropertiesMap.put("costs", objectMapper.readValue(dataManagementPlans.get(0).getCosts(), ArrayList.class)); - } - dm.setExtraProperties(extraPropertiesMap); - - //createOrUpdate(apiContext, dm, principal); - DmpEntity dmp = this.createOrUpdate(dm); -// if (dmp.getOrganisations() == null) { //TODO -// dmp.setOrganisations(new HashSet<>()); -// } -// if (dmp.getResearchers() == null) { -// dmp.setResearchers(new HashSet<>()); -// } -// if (dmp.getDataset() == null) { -// dmp.setDataset(new HashSet<>()); -// } -// if (dmp.getUsers() == null) { -// dmp.setUsers(new HashSet<>()); -// } -// if (dmp.getAssociatedDmps() == null) { -// dmp.setAssociatedDmps(new HashSet<>()); -// } - - List datasets = new LinkedList<>(); - for (DatasetImportModels das: dataManagementPlans.get(0).getDatasetImportModels()) { - DescriptionEntity descriptionEntity = new DescriptionEntity(); - descriptionEntity.setLabel(das.getName()); - //TODO -// descriptionEntity.setDmpSectionIndex(das.getDmpSectionIndex()); -// try { -// descriptionEntity.setDescriptionTemplateId(das.getProfile()); -// } catch (Exception ignored) { -// descriptionEntity.setDescriptionTemplateId(associatedProfiles.get(0).getDescriptionTemplateId()); -// } -// descriptionEntity.setDmpId(dmp.getId()); - descriptionEntity.setProperties(objectMapper.writeValueAsString(das.getFieldImportModels())); - descriptionEntity.setStatus(DescriptionStatus.Draft); -// descriptionEntity.setRegistries(new HashSet<>()); -// descriptionEntity.setDatasetDataRepositories(new HashSet<>()); -// descriptionEntity.setServices(new HashSet<>()); -// descriptionEntity.setDatasetExternalDatasets(new HashSet<>()); - DatasetWizardModel datasetWizard = new DatasetWizardModel(); - datasetWizard.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(datasetWizard, descriptionEntity)); - datasetWizard.fromDataModel(descriptionEntity); - this.datasetManager.createOrUpdate(datasetWizard); - // datasets.add(new DatasetListingModel().fromDataModel(dataset)); - } - } - - return dataManagementPlans; - } - - public List createFromRDA(MultipartFile[] files, String[] profiles) throws IOException, InvalidApplicationException { - if (!this.userScope.isSet()) { - throw new UnauthorisedException("No user is logged in"); - } - List result = new ArrayList<>(); - for (MultipartFile file: files) { - DmpEntity dmp = rdaManager.convertToEntity(new String(file.getBytes(), "UTF-8"), profiles); - dmp.setLabel(file.getOriginalFilename()); - UserEntity me = this.queryFactory.query(UserQuery.class).ids(dmp.getCreatorId()).first(); - dmp.setUpdatedAt(Instant.now()); - dmp.setCreatorId(me.getId()); - //TODO -// Map extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class); -// extraProperties.put("contact", me.getId().toString()); -// dmp.setExtraProperties(objectMapper.writeValueAsString(extraProperties)); -// dmp.setVersion(0); -// dmp.setStatus((short)0); -// dmp.setGroupId(UUID.randomUUID()); -// if (dmp.getResearchers() != null && !dmp.getResearchers().isEmpty()) { -// dmp.getResearchers().stream().filter(Objects::nonNull).forEach(researcher -> { -// researcher.setId(UUID.randomUUID()); -// researcher.setCreated(new Date()); -// researcher.setModified(new Date()); -// researcher.setStatus((short) 0); -// apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcher); -// }); -// } -// databaseRepository.getDmpDao().createOrUpdate(dmp); -// assignUser(dmp, me); -// //TODO -//// if (this.apiContext.getOperationsContext().getElasticRepository().getDmpRepository().getClient() != null) { -//// UUID dmpId = dmp.getId(); -//// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); -//// this.updateIndex(dmp); -//// } -// dmp.getDataset().forEach(dataset -> { -// dataset.setStatus(DescriptionStatus.Draft); -// dataset.setCreatedAt(Instant.now()); -// dataset.setUpdatedAt(Instant.now()); -// //dataset.setDmpId(dmp.getId()); //TODO -// dataset = databaseRepository.getDatasetDao().createOrUpdate(dataset); -//// dataset.setRegistries(new HashSet<>()); -//// dataset.setDatasetDataRepositories(new HashSet<>()); -//// dataset.setDatasetExternalDatasets(new HashSet<>()); -//// dataset.setServices(new HashSet<>()); -// if (dmp.getOrganisations() == null) { -// dmp.setOrganisations(new HashSet<>()); -// } -// if (dmp.getResearchers() == null) { -// dmp.setResearchers(new HashSet<>()); -// } -// try { -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId())).toList())); -// } catch (InvalidApplicationException e) { -// throw new RuntimeException(e); -// } - //TODO -// try { -// List tags = new ArrayList<>(); -// eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); -// DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(dataset); -// if (elastic != null) { -// tags = elastic.getTags(); -// datasetWizardModel.setTags(tags); -// } -// datasetManager.getTagsFromProfile(datasetWizardModel, dataset); -// datasetManager.updateTags(dataset, datasetWizardModel.getTags()); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } -// }); - result.add(dmp); - } - - return result; - } - - /* - * Data assignments - * */ - - private void assignUser(DmpEntity dmp, UserEntity userInfo) { - this.assignUser(dmp, userInfo, DmpUserRole.Owner); - } - - private void assignUser(DmpEntity dmp, UserEntity userInfo, DmpUserRole role) { - DmpUserEntity userDMP = new DmpUserEntity(); - userDMP.setDmpId(dmp.getId()); - userDMP.setUserId(userInfo.getId()); - userDMP.setRole(role); -// databaseRepository.getUserDmpDao().createOrUpdate(userDMP); - } - - private void clearUsers(DmpEntity dmp) throws InvalidApplicationException { - List userDMPs = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmp.getId()).collect(); -// userDMPs.forEach(userDMP -> apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP)); - } - - private void assignGrandUserIfInternal(DmpEntity dmp, UserEntity user) { - //TODO -// if (dmp.getGrant() != null && dmp.getGrant().getCreationUser() == null && (dmp.getGrant().getReference() != null && dmp.getGrant().getReference().startsWith("dmp:"))) { -// dmp.getGrant().setCreationUser(user); -// } - } - - private void assignFunderUserIfInternal(DmpEntity dmp, UserEntity user) { - //TODO -// if (dmp.getGrant() != null && dmp.getGrant().getFunder() != null && dmp.getGrant().getFunder().getCreationUser() == null && ( dmp.getGrant().getFunder().getReference() != null && dmp.getGrant().getFunder().getReference().startsWith("dmp:"))) { -// dmp.getGrant().getFunder().setCreationUser(user); -// } - } - - private void assignProjectUserIfInternal(DmpEntity dmp, UserEntity user) { - //TODO -// if (dmp.getProject() != null && dmp.getProject().getCreationUser() == null && (dmp.getProject().getReference() != null && dmp.getProject().getReference().startsWith("dmp:"))) { -// dmp.getProject().setCreationUser(user); -// } - } - - /* - * Data Index - * */ - - private void updateGroupIndex(UUID groupId) throws InvalidApplicationException { - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - criteria.setGroupIds(Collections.singletonList(groupId)); - criteria.setAllVersions(true); - List dmps = databaseRepository.getDmpDao().getWithCriteria(criteria).toList(); - for (DmpEntity dmp: dmps) { -// try { //TODO -// if (dmp.getUsers() == null) { -// UUID dmpId = dmp.getId(); -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); -// } -//// this.updateIndex(dmp); //TODO -// } catch (InvalidApplicationException e) { -// logger.error(e.getMessage(), e); -// } - } - } - -// private void updateDatasetsIndex(List descriptionEntities) { -// descriptionEntities.forEach(dataset -> { -// List tags = new ArrayList<>(); -// eu.eudat.elastic.entities.Dataset elastic = null; -// try { -// elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); -// if (elastic != null) { -// tags = elastic.getTags(); -// } -// //TODO -// //UUID dmpId = dataset.getDmpId(); -// //dataset.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); -// this.datasetManager.updateTags(dataset, tags); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// } -// -// }); -// } - -// public void updateIndex(DMP dmp) throws IOException, InvalidApplicationException { -// DmpMapper mapper = new DmpMapper(apiContext, datasetManager); -// Dmp elastic = mapper.toElastic(dmp); -// apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic); -// } -// -// public void generateIndex() throws InvalidApplicationException { -// if (this.authorizationService.authorize(Permission.AdminRole)) { -// if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createIndex()) { -// List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); -// dmps.forEach(dmp -> { -// try { -// UUID dmpId = dmp.getId(); -// dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); -// this.updateIndex(dmp); -// } catch (IOException | InvalidApplicationException e) { -// logger.error(e.getMessage(), e); -// } -// }); -// } -// } -// } - -// public void clearIndex() throws IOException { -// if (this.authorizationService.authorize(Permission.AdminRole)) { -// apiContext.getOperationsContext().getElasticRepository().getDmpRepository().clear(); -// } -// } - - /* - * Data Checkup - * */ - - private void checkIfUserCanEditGrant(DmpEntity dmp, UserEntity user) throws Exception{ -// if (dmp.getGrant() != null && dmp.getGrant().getId() != null) { //TODO -// Grant grant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().find(dmp.getGrant().getId()); -// if (grant.getFunder() != null && dmp.getGrant().getFunder() != null -// && !grant.getFunder().getId().equals(dmp.getGrant().getFunder().getId())) { -// if (grant.getCreationUser() == null) { -// throw new Exception("Grant has no user, therefore, cannot be edited."); -// } -// if (!grant.getCreationUser().getId().equals(user.getId())) { -// throw new Exception("User is not the owner of the Grant, therefore, cannot edit it."); -// } -// } -// } - } - - private void checkDmpValidationRules(DmpEntity dmp) throws Exception { - if (dmp.getLabel() == null || dmp.getLabel().trim().isEmpty()) { - throw new Exception("DMP has no label."); - } - //TODO -// if (dmp.getAssociatedDmps().size() == 0) { -// throw new Exception("DMP does not contain Dataset Templates."); -// } -// if (dmp.getGrant() == null) { -// throw new Exception("DMP has no Grant assigned."); -// } - } - - private boolean isUserOwnerOfDmp(DmpEntity dmp) throws InvalidApplicationException { - return this.userScope.isSet() ; - //TODO && (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).map(userDMP -> userDMP.getUser().getId())).collect(Collectors.toList()).contains(this.userScope.getUserId(); - } - - /* - * DOI Generation - * */ - - private String getPreviousDOI(UUID groupId, UUID selfId, String repositoryId) throws InvalidApplicationException { - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - List groupIds = new ArrayList<>(); - groupIds.add(groupId); - criteria.setGroupIds(groupIds); - criteria.setAllVersions(true); - List dmps = this.databaseRepository.getDmpDao().getWithCriteria(criteria).toList(); - dmps.sort((DmpEntity d1, DmpEntity d2) -> d2.getVersion() - d1.getVersion()); - for (DmpEntity dmp: dmps) { - if (!dmp.getId().equals(selfId)) { -// if (dmp.getDois() != null && !dmp.getDois().isEmpty()) { //TODO -// for (Iterator it = dmp.getDois().iterator(); it.hasNext(); ) { -// EntityDoiEntity entityDoi = it.next(); -// if(entityDoi.getRepositoryId().equals(repositoryId)){ -// return entityDoi.getDoi(); -// } -// } -// } - } - } - - return null; - } - - - @Transactional - public EntityDoi createDoi(DepositRequest depositRequest) throws Exception { - DmpEntity dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(depositRequest.getDmpId()); - if (!isUserOwnerOfDmp(dmp)) - throw new Exception("User is not authorized to invoke this action"); - if (!dmp.getStatus().equals(DmpStatus.Finalized)) - throw new Exception("DMP is not finalized"); - /*if (dmp.getDoi() != null) - throw new Exception("DMP already has a DOI");*/ - - FileEnvelope file = getWordDocument(depositRequest.getDmpId().toString(), configLoader); - String name = file.getFilename().substring(0, file.getFilename().length() - 5).replaceAll("[^a-zA-Z0-9_+ ]", "").replace(" ", "_").replace(",", "_"); - byte[] pdfFile = null; //PDFUtils.convertToPDF(file, environment); //TODO -// eu.eudat.depositinterface.models.FileEnvelope pdfEnvelope = new eu.eudat.depositinterface.models.FileEnvelope(); -// pdfEnvelope.setFile(pdfFile); -// pdfEnvelope.setFilename(name + ".pdf"); -// eu.eudat.depositinterface.models.FileEnvelope rdaJsonFile = new eu.eudat.depositinterface.models.FileEnvelope(); - try { - FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId().toString()); - //rdaJsonFile.setFile(rdaJsonDocument.getFile()); //TODO -// rdaJsonFile.setFilename(rdaJsonDocument.getFilename()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - String previousDOI = this.getPreviousDOI(dmp.getGroupId(), dmp.getId(), depositRequest.getRepositoryId()); - - File supportingFilesZip = this.createSupportingFilesZip(dmp); - -// DmpDepositModel dmpDepositModel = new DmpDepositModel(); // DMPToDepositMapper.fromDMP(dmp, pdfEnvelope, rdaJsonFile, supportingFilesZip, previousDOI);//TODO - - String finalDoi = null; - try { - finalDoi = this.repositoriesDeposit.deposit(depositRequest).getDoi(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return null; - } - EntityDoi doiModel = null; - if (finalDoi != null) { - - EntityDoiEntity doiEntity = new EntityDoiEntity(); - doiEntity.setId(UUID.randomUUID()); - doiEntity.setEntityType(EntityType.DMP); - doiEntity.setDoi(finalDoi); - doiEntity.setRepositoryId(depositRequest.getRepositoryId()); - doiEntity.setCreatedAt(Instant.now()); - doiEntity.setUpdatedAt(Instant.now()); - doiEntity.setEntityId(dmp.getId()); - //TODO: Save doi -// apiContext.getOperationsContext().getDatabaseRepository().getEntityDoiDao().createOrUpdate(doiEntity); - -// dmp.getDois().add(doiEntity); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); - - doiModel = new EntityDoi();//.fromDataModel(doiEntity); //TODO - - } - if(supportingFilesZip != null) { - Files.deleteIfExists(supportingFilesZip.toPath()); - } -// Files.deleteIfExists(rdaJsonFile.getFile().toPath()); //TODO -// Files.deleteIfExists(pdfFile.toPath()); -// Files.deleteIfExists(file.getFile().toPath()); - - return doiModel; - - } - - private File createSupportingFilesZip(DmpEntity dmp) throws IOException, InvalidApplicationException { - FileOutputStream fout = new FileOutputStream(this.environment.getProperty("temp.temp") + "supportingFiles.zip"); - ZipOutputStream zout = new ZipOutputStream(fout); - - boolean hasFileUploaded = false; - Set descriptionEntities = new HashSet<>(); //TODO dmp.getDataset(); - for (DescriptionEntity descriptionEntity : descriptionEntities) { - List files = this.apiContext.getOperationsContext().getDatabaseRepository().getFileUploadDao().getFileUploads(descriptionEntity.getId()); - for (FileUpload f : files) { - if(!f.getIsDeleted()){ - File exportFile = new File(this.environment.getProperty("file.storage") + f.getId()); - String filename = f.getName().replace(" ", "_").replace(",", "_"); - byte[] content = Files.readAllBytes(exportFile.toPath()); - ZipEntry ze = new ZipEntry(filename); - zout.putNextEntry(ze); - zout.write(content, 0, content.length); - zout.closeEntry(); - hasFileUploaded = true; - } - } - } - zout.close(); - if(!hasFileUploaded){ - Files.deleteIfExists(new File(this.environment.getProperty("temp.temp") + "supportingFiles.zip").toPath()); - } - return hasFileUploaded ? new File(this.environment.getProperty("temp.temp") + "supportingFiles.zip") : null; - } - - /* - * Misc - * */ - - private void sendNotification(DmpEntity dmp, UserEntity user/*, NotificationType notificationType*/) throws InvalidApplicationException { - List userDMPS = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmp.getId()).collect(); - for (DmpUserEntity userDMP : userDMPS) { - if (!userDMP.getUserId().equals(user.getId())) { -// Notification notification = new Notification(); //TODO -// notification.setUserId(user); -// notification.setType(notificationType); -// notification.setNotifyState(NotifyState.PENDING); -// notification.setIsActive(ActiveStatus.ACTIVE); -// notification.setData("{" + -// "\"userId\": \"" + userDMP.getId() + "\"" + -//// ", \"id\": \"" + userDMP.getDmp().getId() + "\"" + //TODO -//// ", \"name\": \"" + userDMP.getDmp().getLabel() + "\"" + -// ", \"path\": \"" + notificationPaths.get(notificationType) +"\"" + -// "}"); -// notification.setCreatedAt(new Date()); -// notification.setUpdatedAt(notification.getCreatedAt()); -// notification.setContactTypeHint(ContactType.EMAIL); -// //notification.setContactHint(userDMP.getUser().getEmail()); //TODO -// databaseRepository.getNotificationDao().createOrUpdate(notification); - } - } - - } - - /*public DataTableData getPublicPaged(DataManagmentPlanPublicTableRequest dataManagementPlanPublicTableRequest, String fieldsGroup, Principal principal) throws Exception { - dataManagementPlanPublicTableRequest.setQuery(databaseRepository.getDmpDao().asQueryable().withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))); - QueryableList items = dataManagementPlanPublicTableRequest.applyCriteria(); - - if (principal.getId() != null && dataManagementPlanPublicTableRequest.getCriteria().getRole() != null) { - items.where((builder, root) -> { - Join userJoin = root.join("users", JoinType.LEFT); - return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), dataManagementPlanPublicTableRequest.getCriteria().getRole())); - }); - } - QueryableList pagedItems = PaginationManager.applyPaging(items, dataManagementPlanPublicTableRequest); - - DataTableData dataTable = new DataTableData<>(); - - CompletableFuture itemsFuture; - if (fieldsGroup.equals("listing")) { - itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) - .selectAsync(item -> { - item.setDataset( - item.getDataset().stream() - .filter(dataset -> dataset.getStatus().equals(Dataset.Status.FINALISED.getValue())).collect(Collectors.toSet())); - return new DataManagementPlanListingModel().fromDataModelDatasets(item); - }) - .whenComplete((resultList, throwable) -> dataTable.setData(resultList)); - } else { - itemsFuture = pagedItems - .selectAsync(item -> new DataManagementPlanListingModel().fromDataModel(item)) - .whenComplete((resultList, throwable) -> dataTable.setData(resultList)); - } - - CompletableFuture countFuture = items.countAsync().whenComplete((count, throwable) -> { - dataTable.setTotalCount(count); - }); - CompletableFuture.allOf(itemsFuture, countFuture).join(); - return dataTable; - } -*/ - /*public void unlock(UUID uuid) throws Exception { - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao() - .asQueryable().where((builder, root) -> builder.equal(root.get("id"), uuid)) - .update(root -> root.get("status"), DMP.DMPStatus.ACTIVE.getValue()); - return; - }*/ - /*public File getPdfDocument(String id) throws InstantiationException, IllegalAccessException, InterruptedException, IOException { - File file = this.getWordDocument(id); - String fileName = file.getName(); - if (fileName.endsWith(".docx")){ - fileName = fileName.substring(0, fileName.length() - 5); - } - return this.datasetManager.convertToPDF(file, environment, fileName); - }*/ - /*public eu.eudat.models.data.dmp.DataManagementPlan getSinglePublic(String id, DynamicGrantConfiguration dynamicGrantConfiguration) throws Exception { - DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); - - if (dataManagementPlanEntity != null && dataManagementPlanEntity.getStatus() == 1) { - eu.eudat.models.data.dmp.DataManagementPlan datamanagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan(); - datamanagementPlan.fromDataModel(dataManagementPlanEntity); - datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); - Map dmpProperties = dataManagementPlanEntity.getDmpProperties() != null ? new org.json.JSONObject(dataManagementPlanEntity.getDmpProperties()).toMap() : null; -// datamanagementPlan.setDynamicFields(dynamicGrantConfiguration.getFields().stream().map(item -> { -// DynamicFieldWithValue fieldWithValue = new DynamicFieldWithValue(); -// fieldWithValue.setId(item.getId()); -// fieldWithValue.setDependencies(item.getDependencies()); -// fieldWithValue.setName(item.getName()); -// fieldWithValue.setQueryProperty(item.getQueryProperty()); -// fieldWithValue.setRequired(item.getRequired()); -// return fieldWithValue; -// }).collect(Collectors.toList())); - - if (dmpProperties != null && datamanagementPlan.getDynamicFields() != null) - datamanagementPlan.getDynamicFields().forEach(item -> { - Map properties = (Map) dmpProperties.get(item.getId()); - if (properties != null) - item.setValue(new Tuple<>(properties.get("id"), properties.get("label"))); - }); - return datamanagementPlan; - } else { - throw new Exception("Selected DMP is not public"); - } - } - - public DataManagementPlanOverviewModel getOverviewSinglePublic(String id) throws Exception { - DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); - if (dataManagementPlanEntity != null && dataManagementPlanEntity.getStatus() == 1) { - DataManagementPlanOverviewModel datamanagementPlan = new DataManagementPlanOverviewModel(); - datamanagementPlan.fromDataModelDatasets(dataManagementPlanEntity); - datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); - return datamanagementPlan; - } else { - throw new Exception("Selected DMP is not public"); - } - }*/ - /*public List getWithCriteria(DMPDao dmpsRepository, DataManagementPlanCriteriaRequest dataManagementPlanCriteria, Principal principal) throws IllegalAccessException, InstantiationException { - UUID principalID = principal.getId(); - QueryableList items = dmpsRepository.getWithCriteria(dataManagementPlanCriteria.getCriteria()).withHint(HintedModelFactory.getHint(DataManagementPlan.class)); - List roles = new LinkedList<>(); - QueryableList authenticatedItems = dmpsRepository.getAuthenticated(items, principalID, roles); - List datamanagementPlans = authenticatedItems.select(item -> new DataManagementPlan().fromDataModel(item)); - return datamanagementPlans; - }*/ -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java index 46757d9ee..2068e8d38 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java @@ -41,6 +41,7 @@ import eu.eudat.models.data.listingmodels.DatasetListingModel; import eu.eudat.models.data.user.composite.PagedDatasetProfile; import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpDescriptionTemplateQuery; +import eu.eudat.query.DmpQuery; import eu.eudat.query.DmpUserQuery; import eu.eudat.queryable.QueryableList; import eu.eudat.types.MetricNames; @@ -288,7 +289,7 @@ public class DatasetManager { DatasetWizardModel dataset = new DatasetWizardModel(); DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); ; - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if ( //TODO // dmp.getUsers() @@ -314,11 +315,11 @@ public class DatasetManager { // Iterate through the versions and remove those that are not included in the DMP of the dataset in question. for (DescriptionTemplateEntity version : profileVersions) { - for (AssociatedProfile p : dataset.getDmp().getProfiles()) { - if (version.getId().toString().equals(p.getDescriptionTemplateId().toString())) { - profileVersionsIncluded.add(version); - } - } +// for (AssociatedProfile p : dataset.getDmp().getProfiles()) { +// if (version.getId().toString().equals(p.getDescriptionTemplateId().toString())) { +// profileVersionsIncluded.add(version); +// } +// } } // Sort the list with the included Versions. @@ -356,7 +357,7 @@ public class DatasetManager { public DatasetWizardModel getSinglePublic(String id) throws Exception { DatasetWizardModel dataset = new DatasetWizardModel(); DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().isPublicDataset(UUID.fromString(id)); - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (descriptionEntityEntity != null && descriptionEntityEntity.getStatus() == DescriptionStatus.Finalized && dmp.getStatus().getValue() == 1) { dataset.setDatasetProfileDefinition(getPagedProfile(dataset, descriptionEntityEntity)); dataset.fromDataModel(descriptionEntityEntity); @@ -371,7 +372,7 @@ public class DatasetManager { if (descriptionEntityEntity.getIsActive() == IsActive.Inactive) { throw new Exception("Dataset is deleted."); } - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (!isPublic && !this.userScope.isSet()) { throw new UnauthorisedException(); } else @@ -412,7 +413,7 @@ public class DatasetManager { DatasetWizardModel dataset = new DatasetWizardModel(); XWPFDocument document = configLoader.getDatasetDocument(); - DmpEntity dmpEntity = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmpEntity = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (!dmpEntity.getAccessType().equals(DmpAccessType.Public) //TODO // && dmpEntity.getUsers().stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())).collect(Collectors.toList()).size() == 0 @@ -553,7 +554,7 @@ public class DatasetManager { public FileEnvelope getWordDocumentFile(ConfigLoader configLoader, String id, VisibilityRuleService visibilityRuleService) throws IOException, InvalidApplicationException { DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (!dmp.getAccessType().equals(DmpAccessType.Public) //TODO // && dmp.getUsers() @@ -586,7 +587,7 @@ public class DatasetManager { ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); DatasetWizardModel dataset = new DatasetWizardModel(); DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); - DmpEntity dmp = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()).first(); if (!dmp.getAccessType().equals(DmpAccessType.Public) //TODO // && dmp.getUsers() @@ -613,7 +614,7 @@ public class DatasetManager { public DescriptionEntity createOrUpdate(DatasetWizardModel datasetWizardModel) throws Exception { Boolean sendNotification = false; DescriptionEntity tempDescriptionEntity = null; - DmpEntity dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(datasetWizardModel.getDmp().getId()); + DmpEntity dmp = null; //apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(datasetWizardModel.getDmp().getId()); if (datasetWizardModel.getId() != null) { tempDescriptionEntity = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(datasetWizardModel.getId()); if (tempDescriptionEntity != null) { @@ -659,7 +660,7 @@ public class DatasetManager { // descriptionEntity1.setDescriptionTemplateId(datasetWizardModel.getProfile().getId()); //TODO // datasetWizardModel.setDatasetProfileDefinition(getPagedProfile(datasetWizardModel, dataset1)); UUID dmpId = this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntity1.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId(); - DmpEntity dmp1 = databaseRepository.getDmpDao().find(dmpId); + DmpEntity dmp1 = this.queryFactory.query(DmpQuery.class).ids(dmpId).first(); // dmp1.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));//TODO //updateTags(descriptionEntity1, datasetWizardModel.getTags()); //TODO if (sendNotification) { @@ -1096,12 +1097,11 @@ public class DatasetManager { public void generateIndex() throws InvalidApplicationException { if (this.authorizationService.authorize(Permission.AdminRole)) { - this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); List descriptionEntityEntities = new ArrayList<>(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().toList()); descriptionEntityEntities.forEach(datasetEntity -> { try { UUID dmpId = this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(datasetEntity.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId(); - DmpEntity dmp = databaseRepository.getDmpDao().find(dmpId); + DmpEntity dmp = this.queryFactory.query(DmpQuery.class).ids(dmpId).first(); //dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); //TODO // eu.eudat.elastic.entities.Dataset dataset = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(datasetEntity.getId().toString()); //TODO // updateTags(datasetEntity, dataset != null ? dataset.getTags() : null); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetWizardManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetWizardManager.java index bbd1eb986..c7c0d7a80 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetWizardManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetWizardManager.java @@ -7,11 +7,8 @@ import eu.eudat.commons.scope.user.UserScope; import eu.eudat.data.DescriptionEntity; import eu.eudat.data.DmpEntity; import eu.eudat.data.UserEntity; -import eu.eudat.data.dao.entities.DMPDao; -import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest; import eu.eudat.exceptions.datasetwizard.DatasetWizardCannotUnlockException; import eu.eudat.logic.services.ApiContext; -import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel; import eu.eudat.queryable.QueryableList; import gr.cite.tools.data.query.QueryFactory; @@ -23,13 +20,13 @@ import java.util.UUID; public class DatasetWizardManager { - public static List getUserDmps(DMPDao dmpRepository, DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, UserScope userScope) throws InstantiationException, IllegalAccessException, InvalidApplicationException { - UserEntity userInfo = new UserEntity(); - userInfo.setId(userScope.getUserId()); - QueryableList items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo); - List dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item)); - return dataManagementPlans; - } +// public static List getUserDmps(DMPDao dmpRepository, DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, UserScope userScope) throws InstantiationException, IllegalAccessException, InvalidApplicationException { +// UserEntity userInfo = new UserEntity(); +// userInfo.setId(userScope.getUserId()); +// QueryableList items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo); +// List dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item)); +// return dataManagementPlans; +// } // public static List getAvailableProfiles(DMPDao dmpRepository, DatasetProfileDao profileDao, DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws InstantiationException, IllegalAccessException, InvalidApplicationException { // DataManagementPlan dataManagementPlan = new DataManagementPlan().fromDataModel(dmpRepository.find(datasetProfileWizardAutocompleteRequest.getCriteria().getId())); @@ -46,14 +43,14 @@ public class DatasetWizardManager { // return profiles; // } - public void unlock(ApiContext apiContext, QueryFactory queryFactory, UUID uuid) throws DatasetWizardCannotUnlockException, InvalidApplicationException { - DescriptionEntity descriptionEntity = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); - DmpEntity dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(descriptionEntity.getDescriptionTemplateId()); - if(dmp.getStatus().equals(DmpStatus.Finalized)) throw new DatasetWizardCannotUnlockException("To perform this action you will need to revert DMP's finalisation"); - descriptionEntity.setStatus(DescriptionStatus.Draft); - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(descriptionEntity); - return; - } +// public void unlock(ApiContext apiContext, QueryFactory queryFactory, UUID uuid) throws DatasetWizardCannotUnlockException, InvalidApplicationException { +// DescriptionEntity descriptionEntity = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); +// DmpEntity dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(descriptionEntity.getDescriptionTemplateId()); +// if(dmp.getStatus().equals(DmpStatus.Finalized)) throw new DatasetWizardCannotUnlockException("To perform this action you will need to revert DMP's finalisation"); +// descriptionEntity.setStatus(DescriptionStatus.Draft); +// apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(descriptionEntity); +// return; +// } public void delete(ApiContext apiContext, UUID uuid) throws IOException, InvalidApplicationException { DescriptionEntity oldDescriptionEntity = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MetricsManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MetricsManager.java index 09f3eb684..71a2a3297 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MetricsManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/MetricsManager.java @@ -210,7 +210,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setStatus(0); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + return 0; } private long countAllFinalizedDMPs() throws InvalidApplicationException { @@ -221,7 +222,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setStatus(1); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + return 0; } private long countAllPublishedDMPs() throws InvalidApplicationException { @@ -233,7 +235,8 @@ public class MetricsManager { criteria.setIsPublic(true); criteria.setOnlyPublic(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + return 0; } private long countAllDoiedDMPs() throws InvalidApplicationException { @@ -244,7 +247,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setHasDoi(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + return 0; } private long countAllDraftDMPsWithGrantId() throws InvalidApplicationException { @@ -255,7 +259,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setStatus(0); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + return 0; } private long countAllFinalizedDMPsWithGrantId() throws InvalidApplicationException { @@ -266,7 +271,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setStatus(1); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + return 0; } private long countAllPublishedDMPsWithGrantId() throws InvalidApplicationException { @@ -278,7 +284,8 @@ public class MetricsManager { criteria.setIsPublic(true); criteria.setOnlyPublic(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + return 0; } private long countAllDoiedDMPsWithGrantId() throws InvalidApplicationException { @@ -289,7 +296,8 @@ public class MetricsManager { DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); criteria.setHasDoi(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + return 0; } private long countAllResearchers() throws InvalidApplicationException { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java index 3d64abe32..2fdba27d4 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java @@ -8,7 +8,6 @@ import eu.eudat.data.UserEntity; import eu.eudat.data.old.*; import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.query.UserQuery; import gr.cite.tools.data.query.QueryFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -55,32 +54,32 @@ public class QuickWizardManager { // return databaseRepository.getProjectDao().createOrUpdate(projectEntity); // } - public DmpEntity createOrUpdate(DataManagementPlan dataManagementPlan/*, Funder funderEntity*/) throws Exception { - DmpEntity newDmp = dataManagementPlan.toDataModel(); -// if (funderEntity != null) { -// //TODO -// //newDmp.getGrant().setFunder(funderEntity); -// } - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - createFunderIfItDoesntExist(newDmp, user); - createGrantIfItDoesntExist(newDmp, user); - //TODO -// if (newDmp.getProject() == null) { -// newDmp.setProject(new Project()); -// newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); -// } - createProjectIfItDoesntExist(newDmp, user); - - //TODO - //apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); - DmpEntity dmpret = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp); -// if (dataManagementPlan.getAssociatedUsers().size() == 0) -// assignUser(newDmp, user, apiContext); - -// this.updateIndex(dmpret); - - return dmpret; - } +// public DmpEntity createOrUpdate(DataManagementPlan dataManagementPlan/*, Funder funderEntity*/) throws Exception { +// DmpEntity newDmp = dataManagementPlan.toDataModel(); +//// if (funderEntity != null) { +//// //TODO +//// //newDmp.getGrant().setFunder(funderEntity); +//// } +// UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); +// createFunderIfItDoesntExist(newDmp, user); +// createGrantIfItDoesntExist(newDmp, user); +// //TODO +//// if (newDmp.getProject() == null) { +//// newDmp.setProject(new Project()); +//// newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); +//// } +// createProjectIfItDoesntExist(newDmp, user); +// +// //TODO +// //apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); +// DmpEntity dmpret = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp); +//// if (dataManagementPlan.getAssociatedUsers().size() == 0) +//// assignUser(newDmp, user, apiContext); +// +//// this.updateIndex(dmpret); +// +// return dmpret; +// } // private void updateIndex(DMP dmp) throws IOException, InvalidApplicationException { // DmpMapper mapper = new DmpMapper(apiContext, datasetManager); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java index b7aaab44e..1fed11fe0 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepository.java @@ -8,7 +8,6 @@ public interface DatabaseRepository { DatasetDao getDatasetDao(); - DMPDao getDmpDao(); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java index b184a85aa..a4ab22cb5 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/operations/DatabaseRepositoryImpl.java @@ -11,8 +11,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository { private DatasetDao datasetDao; - private DMPDao dmpDao; - private FileUploadDao fileUploadDao; @@ -25,10 +23,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository { this.datasetDao = datasetDao; } - @Autowired - private void setDmpDao(DMPDao dmpDao) { - this.dmpDao = dmpDao; - } @Autowired @@ -37,11 +31,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository { return datasetDao; } - @Override - public DMPDao getDmpDao() { - return dmpDao; - } - @Autowired public void setEntityManager(EntityManager entityManager) { diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDmpModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDmpModel.java deleted file mode 100644 index 91bbb67b7..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDmpModel.java +++ /dev/null @@ -1,76 +0,0 @@ -package eu.eudat.models.data.dashboard.recent.model; - -import eu.eudat.data.DmpEntity; -import eu.eudat.models.data.urls.DatasetUrlListing; - -import jakarta.transaction.Transactional; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class RecentDmpModel extends RecentActivityModel { - private Map extraProperties; - private List datasets; - private UUID groupId; - - public Map getExtraProperties() { - return extraProperties; - } - - public void setExtraProperties(Map extraProperties) { - this.extraProperties = extraProperties; - } - - public List getDatasets() { - return datasets; - } - - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public UUID getGroupId() { - return groupId; - } - - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - @Override - @Transactional - public RecentActivityModel fromEntity(DmpEntity entity) { - this.setType(RecentActivityType.DMP.getIndex()); - this.setId(entity.getId().toString()); - this.setTitle(entity.getLabel()); //TODO -// this.setCreated(entity.getCreated()); -// this.setModified(entity.getModified()); -// this.setStatus(entity.getStatus()); -// this.setVersion(entity.getVersion()); -// this.datasets = entity.getDataset().stream().map(dataset -> new DatasetUrlListing().fromDataModel(dataset)).collect(Collectors.toList()); -// this.setFinalizedAt(entity.getFinalizedAt()); -// if (entity.getGrant() != null) { -// this.setGrant(entity.getGrant().getLabel()); -// } -// this.groupId = entity.getGroupId(); -// this.setPublic(entity.isPublic()); -// this.setPublishedAt(entity.getPublishedAt()); -// this.setUsers(entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList())); - return this; - } - - @Override - public RecentDmpModel fromDataModel(DmpEntity entity) { - return (RecentDmpModel) this.fromEntity(entity); - } - - @Override - public DmpEntity toDataModel() throws Exception { - return null; - } - - @Override - public String getHint() { - return "recentDmpModel"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/Dataset.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/Dataset.java index 8dd65940b..f844cdf12 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/Dataset.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/Dataset.java @@ -2,7 +2,6 @@ package eu.eudat.models.data.dataset; import eu.eudat.data.DescriptionEntity; import eu.eudat.models.DataModel; -import eu.eudat.models.data.dmp.DataManagementPlan; import java.util.Date; import java.util.UUID; @@ -16,7 +15,6 @@ public class Dataset implements DataModel { private short status; private String properties; private Date created; - private DataManagementPlan dmp; public UUID getId() { return id; @@ -83,13 +81,13 @@ public class Dataset implements DataModel { this.description = description; } - public DataManagementPlan getDmp() { - return dmp; - } - - public void setDmp(DataManagementPlan dmp) { - this.dmp = dmp; - } +// public DataManagementPlan getDmp() { +// return dmp; +// } +// +// public void setDmp(DataManagementPlan dmp) { +// this.dmp = dmp; +// } public Dataset fromDataModel(DescriptionEntity entity) { //TODO diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/DatasetOverviewModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/DatasetOverviewModel.java index 08f79bfb9..729a2f6ce 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/DatasetOverviewModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/DatasetOverviewModel.java @@ -4,7 +4,6 @@ import eu.eudat.commons.enums.DescriptionStatus; import eu.eudat.data.DescriptionEntity; import eu.eudat.model.DmpUser; import eu.eudat.models.DataModel; -import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel; import java.time.Instant; import java.util.List; @@ -16,7 +15,7 @@ public class DatasetOverviewModel implements DataModel users; - private DataManagementPlanOverviewModel dmp; +// private DataManagementPlanOverviewModel dmp; private String description; private Boolean isPublic; private Instant modified; @@ -51,13 +50,13 @@ public class DatasetOverviewModel implements DataModel { - - private String id; - private String label; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - @Override - public DataManagentPlanListingModel fromDataModel(DmpEntity entity) { - this.id = entity.getId().toString(); - this.label = entity.getLabel(); - return this; - } - - @Override - public DmpEntity toDataModel() { - return null; - } - - @Override - public String getHint() { - return null; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetWizardModel.java index d7eaa85e4..582dfa5d7 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetWizardModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetWizardModel.java @@ -3,7 +3,6 @@ package eu.eudat.models.data.datasetwizard; import eu.eudat.commons.enums.DescriptionStatus; import eu.eudat.data.DescriptionEntity; import eu.eudat.models.DataModel; -import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.user.composite.PagedDatasetProfile; import java.time.Instant; @@ -20,7 +19,7 @@ public class DatasetWizardModel implements DataModel tags; //TODO @@ -76,12 +75,12 @@ public class DatasetWizardModel implements DataModel { - private UUID id; - private String label; - private UUID groupId; - private Tuple profile; - private int version; - private int status; - private boolean lockable; - private String description; - private List datasets; - private List profiles; - private List extraFields; - private Date modified; - private Date created; - private List dynamicFields; - private Map properties; - private List users; - private List dois; - private Boolean isPublic; - private Map extraProperties; - - public UUID getId() { - return id; - } - public void setId(UUID id) { - this.id = id; - } - - public Tuple getProfile() { - return profile; - } - public void setProfile(Tuple profile) { - this.profile = profile; - } - - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - - public UUID getGroupId() { - return groupId; - } - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public int getVersion() { - return version; - } - public void setVersion(int version) { - this.version = version; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } - - public List getProfiles() { - return profiles; - } - public void setProfiles(List profiles) { - this.profiles = profiles; - } - - public Date getModified() { - return modified; - } - public void setModified(Date modified) { - this.modified = modified; - } - - public Date getCreated() { - return created; - } - public void setCreated(Date created) { - this.created = created; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - public List getExtraFields() { - return extraFields; - } - public void setExtraFields(List extraFields) { - this.extraFields = extraFields; - } - - public Map getProperties() { - return properties; - } - public void setProperties(Map properties) { - this.properties = properties; - } - - public List getDynamicFields() { - return dynamicFields; - } - public void setDynamicFields(List dynamicFields) { - this.dynamicFields = dynamicFields; - } - - public boolean getLockable() { - return lockable; - } - public void setLockable(boolean lockable) { - this.lockable = lockable; - } - - public List getDatasets() { - return datasets; - } - - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public List getUsers() { - return users; - } - public void setUsers(List users) { - this.users = users; - } - - public List getDois() { - return dois; - } - public void setDois(List dois) { - this.dois = dois; - } - - public Boolean getPublic() { - return isPublic; - } - - public void setPublic(Boolean aPublic) { - isPublic = aPublic; - } - - public Map getExtraProperties() { - return extraProperties; - } - - public void setExtraProperties(Map extraProperties) { - this.extraProperties = extraProperties; - } - - @Override - public DataManagementPlan fromDataModel(DmpEntity entity) { - this.id = entity.getId(); - //TODO -// this.profile = entity.getProfile() != null ? new Tuple(entity.getProfile().getId(), entity.getProfile().getLabel()) : null; -// this.organisations = entity.getOrganisations() != null ? entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.researchers = entity.getResearchers() != null ? entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()): new ArrayList<>(); -// this.version = entity.getVersion(); -// this.groupId = this.groupId == null ? null : entity.getGroupId(); -// this.label = entity.getLabel(); -// this.properties = entity.getProperties() != null ? new org.json.JSONObject(entity.getProperties()).toMap() : null; -// if(entity.getGrant() != null) { -// this.grant = new Grant(); -// this.grant.fromDataModel(entity.getGrant()); -// } -// else { -// this.grant = null; -// } -// this.creator = new eu.eudat.models.data.userinfo.UserInfo(); -// this.groupId = entity.getGroupId(); -// this.lockable = entity.getDataset() != null && entity.getDataset().stream().findAny().isPresent(); -// if (this.properties != null) { -// this.extraFields = new ArrayList<>(); -// this.properties.forEach((id, value) -> { -// if (value != null) { -// ExtraFieldModel extraField = new ExtraFieldModel(); -// extraField.setId(id); -// extraField.setValue(value.toString()); -// this.extraFields.add(extraField); -// } -// }); -// } -// if (entity.getUsers() != null && entity.getUsers().stream().anyMatch(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue()))) -// this.creator.fromDataModel(entity.getUsers().stream().filter(user -> user.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser()); -// -// if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { -// this.profiles = new LinkedList<>(); -// for (DMPDatasetProfile dmpDescriptionProfile : entity.getAssociatedDmps()) { -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(dmpDescriptionProfile.getDatasetprofile()); -// associatedProfile.setId(dmpDescriptionProfile.getId()); -// try { -// associatedProfile.setData(new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {})); -// } -// catch (Exception e) { -// associatedProfile.setData(null); -// } -// this.profiles.add(associatedProfile); -// } -// } -// if (entity.getDataset() != null) { -// if (entity.isPublic()) { -// this.datasets = entity.getDataset().stream() -// .filter(dataset -> !dataset.getIsActive().equals(IsActive.Inactive) && !dataset.getStatus().equals(DescriptionStatus.Canceled) && !dataset.getStatus().equals(DescriptionStatus.Draft)) -// .map(x -> new DatasetWizardModel().fromDataModelNoDmp(x)).collect(Collectors.toList()); -// } else { -// this.datasets = entity.getDataset().stream() -// .filter(dataset -> !dataset.getIsActive().equals(IsActive.Inactive) && !dataset.getStatus().equals(DescriptionStatus.Draft)) -// .map(x -> new DatasetWizardModel().fromDataModelNoDmp(x)).collect(Collectors.toList()); -// } -// } -// this.modified = entity.getModified(); -// this.created = entity.getCreated(); -// this.description = entity.getDescription(); -// this.status = entity.getStatus(); -// this.associatedUsers = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList()) : new ArrayList<>(); -// this.users = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.dois = entity.getDois() != null ? entity.getDois().stream().map(item -> new Doi().fromDataModel(item)).collect(Collectors.toList()): new ArrayList<>(); -// -// if (entity.getProject() != null) { -// this.project = new Project(); -// this.project = new Project().fromDataModel(entity.getProject()); -// } -// -// if (entity.getGrant() != null && entity.getGrant().getFunder() != null) { -// this.funder = new Funder(); -// this.funder.fromDataModel(entity.getGrant().getFunder()); -// } -// this.isPublic = entity.isPublic(); -// -// this.extraProperties = entity.getExtraProperties() != null ? new org.json.JSONObject(entity.getExtraProperties()).toMap() : null; - - return this; - } - - @Override - public DmpEntity toDataModel() throws Exception { - DmpEntity dataManagementPlanEntity = new DmpEntity(); //TODO -// if (this.profile != null) { -// DmpBlueprintEntity dmpBlueprint = new DmpBlueprintEntity(); -// dmpBlueprint.setId(this.profile.getId()); -// dataManagementPlanEntity.setProfile(dmpBlueprint); -// } -// dataManagementPlanEntity.setId(this.id); -// if (this.organisations != null && !this.organisations.isEmpty()) -// dataManagementPlanEntity.setOrganisations(new HashSet<>(this.organisations.stream().map(item -> item.toDataModel()).collect(Collectors.toList()))); -// if (this.researchers != null && !this.researchers.isEmpty()) -// dataManagementPlanEntity.setResearchers(new HashSet<>(this.researchers.stream().map(item -> item.toDataModel()).collect(Collectors.toList()))); -// dataManagementPlanEntity.setVersion(this.version); -// dataManagementPlanEntity.setLabel(this.label); -// if (this.grant != null) dataManagementPlanEntity.setGrant(this.grant.toDataModel()); -// dataManagementPlanEntity.setStatus((short) this.status); -// dataManagementPlanEntity.setDescription(this.description); -// if (this.project != null) { -// dataManagementPlanEntity.setProject(this.project.toDataModel()); -// } -// if (this.profiles != null) { -// Set dmpDatasetProfiles = new HashSet<>(); -// for (AssociatedProfile profile : this.profiles) { -// DMPDatasetProfile dmpDatasetProfile = new DMPDatasetProfile(); -// dmpDatasetProfile.setId(profile.getId()); -// dmpDatasetProfile.setDmp(dataManagementPlanEntity); -// dmpDatasetProfile.setDatasetprofile(profile.toData()); -// dmpDatasetProfile.setData(new ObjectMapper().writeValueAsString(profile.getData())); -// dmpDatasetProfiles.add(dmpDatasetProfile); -// } -// dataManagementPlanEntity.setAssociatedDmps(dmpDatasetProfiles); -// } -// if(this.extraFields != null) { -// this.properties = this.extraFields.stream().collect(Collectors.toMap(ExtraFieldModel::getId, ExtraFieldModel::getValue)); -// } -// dataManagementPlanEntity.setProperties(this.properties != null ? JSONObject.toJSONString(this.properties) : null); -// dataManagementPlanEntity.setGroupId(this.groupId != null ? this.groupId : UUID.randomUUID()); -// dataManagementPlanEntity.setModified(this.modified != null ? this.modified : new Date()); -// dataManagementPlanEntity.setCreated(this.created != null ? this.created : new Date()); -// if (this.dynamicFields != null) -// dataManagementPlanEntity.setDmpProperties(JSONObject.toJSONString(this.dynamicFields.stream().filter(item -> item.getValue() != null).collect(Collectors.toMap(DynamicFieldWithValue::getId, DynamicFieldWithValue::getValue)))); -// -// if (this.isPublic != null) { -// dataManagementPlanEntity.setPublic(this.isPublic); -// } -// -// dataManagementPlanEntity.setExtraProperties(this.extraProperties != null ? JSONObject.toJSONString(this.extraProperties) : null); - return dataManagementPlanEntity; - } - - public DataManagementPlan fromDataModelNoDatasets(DmpEntity entity) { - this.id = entity.getId(); //TODO -// this.profile = entity.getProfile() != null ? new Tuple(entity.getProfile().getId(), entity.getProfile().getLabel()) : null; -// this.organisations = entity.getOrganisations() != null ? entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.researchers = entity.getResearchers() != null ? entity.getResearchers().stream().filter(Objects::nonNull).map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.version = entity.getVersion(); -// this.label = entity.getLabel(); -// this.properties = entity.getProperties() != null ? new org.json.JSONObject(entity.getProperties()).toMap() : null; -// this.creator = new eu.eudat.models.data.userinfo.UserInfo(); -// this.groupId = entity.getGroupId(); -// this.lockable = entity.getDataset() != null && entity.getDataset().stream().findAny().isPresent(); -// if (this.properties != null) { -// this.extraFields = new ArrayList<>(); -// this.properties.forEach((id, value) -> { -// if (value != null) { -// ExtraFieldModel extraField = new ExtraFieldModel(); -// extraField.setId(id); -// extraField.setValue(value.toString()); -// this.extraFields.add(extraField); -// } -// }); -// } -// if (entity.getUsers() != null && entity.getUsers().stream().anyMatch(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue()))) -// this.creator.fromDataModel(entity.getUsers().stream().filter(user -> user.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser()); -// -// if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { -// this.profiles = new LinkedList<>(); -// for (DMPDatasetProfile dmpDescriptionProfile : entity.getAssociatedDmps()) { -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(dmpDescriptionProfile.getDatasetprofile()); -// associatedProfile.setId(dmpDescriptionProfile.getId()); -// try { -// associatedProfile.setData(new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {})); -// } -// catch (Exception e) { -// associatedProfile.setData(null); -// } -// this.profiles.add(associatedProfile); -// } -// } -// this.modified = entity.getModified(); -// this.created = entity.getCreated(); -// this.description = entity.getDescription(); -// this.status = entity.getStatus(); -// this.associatedUsers = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList()) : new ArrayList<>(); -// this.users = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.dois = entity.getDois() != null ? entity.getDois().stream().map(item -> new Doi().fromDataModel(item)).collect(Collectors.toList()): new ArrayList<>(); -// if(entity.getGrant() != null) { -// this.grant = new Grant(); -// this.grant.fromDataModel(entity.getGrant()); -// } -// else { -// this.grant = null; -// } -// -// if (entity.getProject() != null) { -// this.project = new Project(); -// this.project = new Project().fromDataModel(entity.getProject()); -// } -// if (entity.getGrant() != null && entity.getGrant().getFunder() != null) { -// this.funder = new Funder(); -// this.funder.fromDataModel(entity.getGrant().getFunder()); -// } -// this.isPublic = entity.isPublic(); -// -// this.extraProperties = entity.getExtraProperties() != null ? new org.json.JSONObject(entity.getExtraProperties()).toMap() : null; - - return this; - } - - @Override - public String getHint() { - return "fullyDetailed"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanEditorModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanEditorModel.java deleted file mode 100644 index d74d25c1d..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanEditorModel.java +++ /dev/null @@ -1,343 +0,0 @@ -package eu.eudat.models.data.dmp; - -import eu.eudat.data.DmpEntity; -import eu.eudat.model.DmpUser; -import eu.eudat.models.DataModel; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue; -import eu.eudat.models.data.helpermodels.Tuple; -import eu.eudat.models.data.project.ProjectDMPEditorModel; - -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class DataManagementPlanEditorModel implements DataModel { - private UUID id; - private String label; - private UUID groupId; - private Tuple profile; - private int version; - private int status; - private boolean lockable; - private String description; - private List datasets; - private List profiles; - private List extraFields; - private Date modified; - private Date created; - private List dynamicFields; - private Map properties; - private List users; - private List datasetsToBeFinalized; - private ProjectDMPEditorModel project; - private Map extraProperties; - - public UUID getId() { - return id; - } - public void setId(UUID id) { - this.id = id; - } - - public Tuple getProfile() { - return profile; - } - public void setProfile(Tuple profile) { - this.profile = profile; - } - - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - - public UUID getGroupId() { - return groupId; - } - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public void setVersion(int version) { - this.version = version; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } - - public List getProfiles() { - return profiles; - } - public void setProfiles(List profiles) { - this.profiles = profiles; - } - - public Date getModified() { - return modified; - } - public void setModified(Date modified) { - this.modified = modified; - } - - public Date getCreated() { - return created; - } - public void setCreated(Date created) { - this.created = created; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - public List getExtraFields() { - return extraFields; - } - public void setExtraFields(List extraFields) { - this.extraFields = extraFields; - } - - public Map getProperties() { - return properties; - } - public void setProperties(Map properties) { - this.properties = properties; - } - - public List getDynamicFields() { - return dynamicFields; - } - public void setDynamicFields(List dynamicFields) { - this.dynamicFields = dynamicFields; - } - - public boolean getLockable() { - return lockable; - } - public void setLockable(boolean lockable) { - this.lockable = lockable; - } - - public List getDatasets() { - return datasets; - } - - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public List getUsers() { - return users; - } - public void setUsers(List users) { - this.users = users; - } - - public List getDatasetsToBeFinalized() { - return datasetsToBeFinalized; - } - public void setDatasetsToBeFinalized(List datasetsToBeFinalized) { - this.datasetsToBeFinalized = datasetsToBeFinalized; - } - - public ProjectDMPEditorModel getProject() { - return project; - } - public void setProject(ProjectDMPEditorModel project) { - this.project = project; - } - - public Map getExtraProperties() { - return extraProperties; - } - - public void setExtraProperties(Map extraProperties) { - this.extraProperties = extraProperties; - } - - @Override - public DataManagementPlanEditorModel fromDataModel(DmpEntity entity) { - this.id = entity.getId(); -// this.profile = entity.getProfile() != null ? new Tuple(entity.getProfile().getId(), entity.getProfile().getLabel()) : null; //TODO -// this.organisations = entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); -// this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()); -// this.version = entity.getVersion(); -// this.groupId = this.groupId == null ? null : entity.getGroupId(); -// this.label = entity.getLabel(); -// this.properties = entity.getProperties() != null ? new org.json.JSONObject(entity.getProperties()).toMap() : null; -// if (entity.getGrant() != null) { -// this.grant = new GrantDMPEditorModel(); -// this.grant.getExistGrant().fromDataModel(entity.getGrant()); -// this.grant.getExistGrant().setSource(""); -// } -// this.creator = new eu.eudat.models.data.userinfo.UserInfo(); -// this.groupId = entity.getGroupId(); -// this.lockable = entity.getDataset().stream().findAny().isPresent(); -// if (this.properties != null) { -// this.extraFields = new ArrayList<>(); -// this.properties.forEach((id, value) -> { -// ExtraFieldModel extraField = new ExtraFieldModel(); -// extraField.setId(id); -// extraField.setValue(value.toString()); -// this.extraFields.add(extraField); -// }); -// } -// if (entity.getUsers().stream().anyMatch(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue()))) -// this.creator.fromDataModel(entity.getUsers().stream().filter(user -> user.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser()); -// -// if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { -// this.profiles = new LinkedList<>(); -// for (DMPDatasetProfile dmpDescriptionProfile : entity.getAssociatedDmps()) { -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(dmpDescriptionProfile.getDatasetprofile()); -// try { -// associatedProfile.setData(new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {})); -// } -// catch (Exception e) { -// associatedProfile.setData(null); -// } -// this.profiles.add(associatedProfile); -// } -// } -// this.datasets = entity.getDataset().stream().map(item -> new DatasetWizardModel().fromDataModelNoDmp(item)).collect(Collectors.toList()); -// this.modified = entity.getModified(); -// this.created = entity.getCreated(); -// this.description = entity.getDescription(); -// this.status = entity.getStatus(); -// this.project = new ProjectDMPEditorModel(); -// this.project.getExistProject().fromDataModel(entity.getProject()); -// this.associatedUsers = entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList()); -// this.users = entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList()); -// if (entity.getGrant() != null) { -// this.funder = new FunderDMPEditorModel(); -// this.funder.getExistFunder().fromDataModel(entity.getGrant().getFunder()); -// } -// this.extraProperties = entity.getExtraProperties() != null ? new org.json.JSONObject(entity.getExtraProperties()).toMap() : null; - - return this; - } - - @Override - public DmpEntity toDataModel() throws Exception { - DmpEntity dataManagementPlanEntity = new DmpEntity();//TODO -// if (this.profile != null) { -// DmpBlueprintEntity dmpBlueprint = new DmpBlueprintEntity(); -// dmpBlueprint.setId(this.profile.getId()); -// dataManagementPlanEntity.setProfile(dmpBlueprint); -// } -// dataManagementPlanEntity.setId(this.id); -// if (this.organisations != null && !this.organisations.isEmpty()) -// dataManagementPlanEntity.setOrganisations(new HashSet<>(this.organisations.stream().map(Organisation::toDataModel).collect(Collectors.toList()))); -// if (this.researchers != null && !this.researchers.isEmpty()) -// dataManagementPlanEntity.setResearchers(new HashSet<>(this.researchers.stream().map(Researcher::toDataModel).collect(Collectors.toList()))); -// dataManagementPlanEntity.setVersion(this.version); -// dataManagementPlanEntity.setLabel(this.label); -// if (this.grant != null) { -// if (this.grant.getExistGrant() != null && this.grant.getLabel() == null && this.grant.getDescription() == null) -// dataManagementPlanEntity.setGrant(this.grant.getExistGrant().toDataModel()); -// else if (this.grant.getLabel() != null) { -// Grant grant = new Grant(); -// grant.setId(UUID.randomUUID()); -// grant.setAbbreviation(""); -// grant.setLabel(this.grant.getLabel()); -// grant.setType(Grant.GrantType.INTERNAL.getValue()); -// grant.setReference("dmp:" + (this.grant.getReference() != null ? this.grant.getReference() : grant.getId())); -// grant.setUri(""); -// grant.setDefinition(""); -// grant.setCreated(new Date()); -// grant.setStatus(Grant.Status.ACTIVE.getValue()); -// grant.setModified(new Date()); -// grant.setDescription(this.grant.getDescription()); -// -// dataManagementPlanEntity.setGrant(grant); -// } -// } -// -// if (this.funder != null) { -// if (this.funder.getLabel() != null) { -// Funder funder = new Funder(); -// funder.setId(UUID.randomUUID()); -// funder.setLabel(this.funder.getLabel()); -// funder.setType(Funder.FunderType.INTERNAL.getValue()); -// funder.setReference("dmp:" + (this.funder.getReference() != null ? this.funder.getReference() : funder.getId())); -// funder.setDefinition(""); -// funder.setCreated(new Date()); -// funder.setStatus(Funder.Status.ACTIVE.getValue()); -// funder.setModified(new Date()); -// -// dataManagementPlanEntity.getGrant().setFunder(funder); -// } else if (this.funder.getExistFunder() != null && this.funder.getLabel() == null){ -// dataManagementPlanEntity.getGrant().setFunder(this.funder.getExistFunder().toDataModel()); -// dataManagementPlanEntity.getGrant().getFunder().setType(Funder.FunderType.EXTERNAL.getValue()); -// } -// } -// -// if (this.project != null) { -// if (this.project.getExistProject() != null && this.project.getLabel() == null && this.project.getDescription() == null) -// dataManagementPlanEntity.setProject(this.project.getExistProject().toDataModel()); -// else if (this.project.getLabel() != null) { -// Project project = new Project(); -// project.setId(UUID.randomUUID()); -// project.setAbbreviation(""); -// project.setLabel(this.project.getLabel()); -// project.setType(Project.ProjectType.INTERNAL.getValue()); -// project.setReference("dmp:" + (this.project.getReference() != null ? this.project.getReference() : project.getId())); -// project.setUri(""); -// project.setDefinition(""); -// project.setCreated(new Date()); -// project.setStatus(Project.Status.ACTIVE.getValue()); -// project.setModified(new Date()); -// project.setDescription(this.project.getDescription()); -// -// dataManagementPlanEntity.setProject(project); -// } -// } -// -// dataManagementPlanEntity.setStatus((short) this.status); -// if (this.status == (int) DMP.DMPStatus.FINALISED.getValue()) { -// dataManagementPlanEntity.setFinalizedAt(new Date()); -// } -// dataManagementPlanEntity.setDescription(this.description); -// if (this.profiles != null) { -// Set dmpDatasetProfiles = new HashSet<>(); -// for (AssociatedProfile profile : this.profiles) { -// DMPDatasetProfile dmpDatasetProfile = new DMPDatasetProfile(); -// dmpDatasetProfile.setId(profile.getId()); -// dmpDatasetProfile.setDmp(dataManagementPlanEntity); -// dmpDatasetProfile.setDatasetprofile(profile.toData()); -// dmpDatasetProfile.setData(new ObjectMapper().writeValueAsString(profile.getData())); -// dmpDatasetProfiles.add(dmpDatasetProfile); -// } -// dataManagementPlanEntity.setAssociatedDmps(dmpDatasetProfiles); -// } -// if(this.extraFields != null) { -// this.properties = new HashMap<>(); -// this.extraFields.forEach((extraField) -> this.properties.put(extraField.getId(), extraField.getValue())); -// } -// dataManagementPlanEntity.setProperties(this.properties != null ? JSONObject.toJSONString(this.properties) : null); -// dataManagementPlanEntity.setGroupId(this.groupId != null ? this.groupId : UUID.randomUUID()); -// dataManagementPlanEntity.setModified(this.modified != null ? this.modified : new Date()); -// dataManagementPlanEntity.setCreated(this.created != null ? this.created : new Date()); -// if (this.dynamicFields != null) -// dataManagementPlanEntity.setDmpProperties(JSONObject.toJSONString(this.dynamicFields.stream().filter(item -> item.getValue() != null).collect(Collectors.toMap(DynamicFieldWithValue::getId, DynamicFieldWithValue::getValue)))); -// -// dataManagementPlanEntity.setExtraProperties(this.extraProperties != null ? JSONObject.toJSONString(this.extraProperties) : null); - - return dataManagementPlanEntity; - } - - @Override - public String getHint() { - return "fullyDetailed"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanNewVersionModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanNewVersionModel.java deleted file mode 100644 index 53024ec49..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dmp/DataManagementPlanNewVersionModel.java +++ /dev/null @@ -1,222 +0,0 @@ -package eu.eudat.models.data.dmp; - -import eu.eudat.commons.enums.DmpStatus; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.DmpEntity; -import eu.eudat.models.DataModel; -import eu.eudat.models.data.dataset.Dataset; -import eu.eudat.models.data.project.ProjectDMPEditorModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.time.Instant; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Created by ikalyvas on 2/5/2018. - */ -public class DataManagementPlanNewVersionModel implements DataModel { - private static final Logger logger = LoggerFactory.getLogger(DataManagementPlanNewVersionModel.class); - - private UUID id; - private String label; - private UUID groupId; - private int version; - private int status; - private String description; - private List profiles; - private List datasets; - private ProjectDMPEditorModel project; - private Map extraProperties; - - public UUID getId() { - return id; - } - public void setId(UUID id) { - this.id = id; - } - - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - - public UUID getGroupId() { - return groupId; - } - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public int getVersion() { - return version; - } - public void setVersion(int version) { - this.version = version; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - public List getProfiles() { - return profiles; - } - public void setProfiles(List profiles) { - this.profiles = profiles; - } - - - public List getDatasets() { - return datasets; - } - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public ProjectDMPEditorModel getProject() { - return project; - } - public void setProject(ProjectDMPEditorModel project) { - this.project = project; - } - - - public Map getExtraProperties() { - return extraProperties; - } - - public void setExtraProperties(Map extraProperties) { - this.extraProperties = extraProperties; - } - - @Override - public DataManagementPlanNewVersionModel fromDataModel(DmpEntity entity) { - return null; - } - - @Override - public DmpEntity toDataModel() throws Exception { - DmpEntity entity = new DmpEntity(); - entity.setId(this.id); - // entity.setUsers(new HashSet<>(new ArrayList<>(this.associatedUsers))); - entity.setDescription(this.description); - entity.setStatus(DmpStatus.of((short)this.status)); - entity.setGroupId(this.groupId == null ? UUID.randomUUID() : this.groupId); - entity.setCreatedAt(Instant.now()); - entity.setUpdatedAt(Instant.now()); - entity.setLabel(this.label); - List descriptionEntities = new LinkedList<>();//TODO -// if (this.datasets != null) { -// for (Dataset dataset : this.datasets) { -// DescriptionEntity entityDescriptionEntity = new DescriptionEntity(); -// entityDescriptionEntity.setId(dataset.getId()); -// descriptionEntities.add(entityDescriptionEntity); -// } -// entity.setDataset(new HashSet<>(descriptionEntities)); -// } -// if (this.organisations != null && !this.organisations.isEmpty()) -// entity.setOrganisations(new HashSet<>(this.organisations.stream().map(item -> item.toDataModel()).collect(Collectors.toList()))); -// if (this.researchers != null && !this.researchers.isEmpty()) -// entity.setResearchers(new HashSet<>(this.researchers.stream().map(item -> item.toDataModel()).collect(Collectors.toList()))); -// /*if (this.grant != null) { -// entity.setGrant(this.grant.toDataModel()); -// }*/ -// -// if (this.grant != null) { -// if (this.grant.getExistGrant() != null && this.grant.getLabel() == null && this.grant.getDescription() == null) -// entity.setGrant(this.grant.getExistGrant().toDataModel()); -// else if (this.grant.getLabel() != null) { -// Grant grant = new Grant(); -// grant.setId(UUID.randomUUID()); -// grant.setAbbreviation(""); -// grant.setLabel(this.grant.getLabel()); -// grant.setType(Grant.GrantType.INTERNAL.getValue()); -// grant.setReference("dmp:" + (this.grant.getReference() != null ? this.grant.getReference() : grant.getId())); -// grant.setUri(""); -// grant.setDefinition(""); -// grant.setCreated(new Date()); -// grant.setStatus(Grant.Status.ACTIVE.getValue()); -// grant.setModified(new Date()); -// grant.setDescription(this.grant.getDescription()); -// -// entity.setGrant(grant); -// } -// } -// -// if (this.funder != null) { -// if (this.funder.getLabel() != null) { -// Funder funder = new Funder(); -// funder.setId(UUID.randomUUID()); -// funder.setLabel(this.funder.getLabel()); -// funder.setType(Funder.FunderType.INTERNAL.getValue()); -// funder.setReference("dmp:" + (this.funder.getReference() != null ? this.funder.getReference() : funder.getId())); -// funder.setDefinition(""); -// funder.setCreated(new Date()); -// funder.setStatus(Funder.Status.ACTIVE.getValue()); -// funder.setModified(new Date()); -// -// entity.getGrant().setFunder(funder); -// } else if (this.funder.getExistFunder() != null && this.funder.getLabel() == null) { -// entity.getGrant().setFunder(this.funder.getExistFunder().toDataModel()); -// entity.getGrant().getFunder().setType(Funder.FunderType.EXTERNAL.getValue()); -// } -// } - -// if (this.project != null) { -// if (this.project.getExistProject() != null && this.project.getLabel() == null && this.project.getDescription() == null) -// entity.setProject(this.project.getExistProject().toDataModel()); -// else if (this.project.getLabel() != null) { -// Project project = new Project(); -// project.setId(UUID.randomUUID()); -// project.setAbbreviation(""); -// project.setLabel(this.project.getLabel()); -// project.setType(Project.ProjectType.INTERNAL.getValue()); -// project.setReference("dmp:" + (this.project.getReference() != null ? this.project.getReference() : project.getId())); -// project.setUri(""); -// project.setDefinition(""); -// project.setCreated(new Date()); -// project.setStatus(Project.Status.ACTIVE.getValue()); -// project.setModified(new Date()); -// project.setDescription(this.project.getDescription()); -// -// entity.setProject(project); -// } -// } -// -// entity.setExtraProperties(this.extraProperties != null ? JSONObject.toJSONString(this.extraProperties) : null); -// if (this.profiles != null) { -// Set dmpDatasetProfiles = new HashSet<>(); -// for (AssociatedProfile profile : this.profiles) { -// DMPDatasetProfile dmpDatasetProfile = new DMPDatasetProfile(); -// dmpDatasetProfile.setId(null); -// dmpDatasetProfile.setDmp(entity); -// dmpDatasetProfile.setDatasetprofile(profile.toData()); -// dmpDatasetProfile.setData(new ObjectMapper().writeValueAsString(profile.getData())); -// dmpDatasetProfiles.add(dmpDatasetProfile); -// } -// entity.setAssociatedDmps(dmpDatasetProfiles); -// } - return entity; - } - - @Override - public String getHint() { - return null; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanListingModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanListingModel.java deleted file mode 100644 index cc412a201..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanListingModel.java +++ /dev/null @@ -1,190 +0,0 @@ -package eu.eudat.models.data.listingmodels; - -import eu.eudat.data.DmpEntity; -import eu.eudat.model.DmpUser; -import eu.eudat.models.DataModel; -import eu.eudat.models.data.urls.DatasetUrlListing; - -import java.util.Date; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - - -public class DataManagementPlanListingModel implements DataModel { - private String id; - private String label; - private String grant; - private Date creationTime; - private Date modifiedTime; - private int version; - private int status; - private UUID groupId; - private List datasets; - private List users; - private Date finalizedAt; - private Boolean isPublic; - private Date publishedAt; - - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - - public String getGrant() { - return grant; - } - public void setGrant(String grant) { - this.grant = grant; - } - - public Date getCreationTime() { - return creationTime; - } - public void setCreationTime(Date creationTime) { - this.creationTime = creationTime; - } - - public Date getModifiedTime() { - return modifiedTime; - } - public void setModifiedTime(Date modifiedTime) { - this.modifiedTime = modifiedTime; - } - - public int getVersion() { - return version; - } - public void setVersion(int version) { - this.version = version; - } - - public UUID getGroupId() { - return groupId; - } - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public List getDatasets() { - return datasets; - } - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } - - public List getUsers() { - return users; - } - public void setUsers(List users) { - this.users = users; - } - - public Date getFinalizedAt() { - return finalizedAt; - } - public void setFinalizedAt(Date finalizedAt) { - this.finalizedAt = finalizedAt; - } - - public Boolean getPublic() { - return isPublic; - } - public void setPublic(Boolean aPublic) { - isPublic = aPublic; - } - - public Date getPublishedAt() { - return publishedAt; - } - public void setPublishedAt(Date publishedAt) { - this.publishedAt = publishedAt; - } - - @Override - public DataManagementPlanListingModel fromDataModel(DmpEntity entity) { - this.id = entity.getId().toString(); - this.label = entity.getLabel(); - this.groupId = entity.getGroupId(); - return this; - } - - public DataManagementPlanListingModel fromDataModelAssociatedProfiles(DmpEntity entity) { - this.id = entity.getId().toString(); - this.label = entity.getLabel(); - this.groupId = entity.getGroupId(); - this.creationTime = Date.from(entity.getCreatedAt()); - return this; - } - - public DataManagementPlanListingModel fromDataModelAutoComplete(DmpEntity entity) { - this.id = entity.getId().toString(); - this.label = entity.getLabel(); - this.groupId = entity.getGroupId(); - this.creationTime = Date.from(entity.getCreatedAt()); - return this; - } - - public DataManagementPlanListingModel fromDataModelDatasets(DmpEntity entity) { - this.fromDataModel(entity); - this.status = entity.getStatus().getValue(); - this.version = entity.getVersion(); - this.creationTime = Date.from(entity.getCreatedAt()); - this.modifiedTime = Date.from(entity.getUpdatedAt()); - this.finalizedAt = Date.from(entity.getFinalizedAt()); -// this.grant = (entity.getGrant() != null) ? entity.getGrant().getLabel() : null; //TODO -// this.datasets = entity.getDataset().stream().map(x-> new DatasetUrlListing().fromDataModel(x)).collect(Collectors.toList()); -// this.users = entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()); -// this.isPublic = entity.isPublic(); -// this.publishedAt = entity.getPublishedAt(); - - return this; - } - - @Override - public DmpEntity toDataModel() { - DmpEntity entity = new DmpEntity(); - entity.setId(UUID.fromString(this.getId())); - entity.setLabel(this.getLabel()); - entity.setGroupId(this.getGroupId()); -// entity.setStatus(Integer.valueOf(this.getStatus()).shortValue()); //TODO -// entity.setCreated(this.getCreationTime()); -// entity.setFinalizedAt(this.getFinalizedAt()); -// entity.setModified(this.getModifiedTime()); -// entity.setPublic(this.getPublic()); -// entity.setPublishedAt(this.getPublishedAt()); -// entity.setVersion(this.getVersion()); -// -// entity.setDataset(this.getDatasets().stream().map(DatasetUrlListing::toDataModel).collect(Collectors.toCollection(LinkedHashSet::new))); -// if (this.getGrant() != null && !this.getGrant().isEmpty()) { -// Grant grant = new Grant(); -// grant.setLabel(this.getGrant()); -// entity.setGrant(grant); -// } -// entity.setUsers(this.getUsers().stream().map(UserInfoListingModel::toDataModel).collect(Collectors.toSet())); - return entity; - } - - @Override - public String getHint() { - return "dataManagementPlanListingModel"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanOverviewModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanOverviewModel.java deleted file mode 100644 index ec3346b41..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanOverviewModel.java +++ /dev/null @@ -1,210 +0,0 @@ -package eu.eudat.models.data.listingmodels; - -import eu.eudat.data.DmpEntity; -import eu.eudat.model.DmpUser; -import eu.eudat.model.EntityDoi; -import eu.eudat.models.DataModel; -import eu.eudat.models.data.dataset.DatasetOverviewModel; -import eu.eudat.models.data.dmp.AssociatedProfile; - -import java.util.Date; -import java.util.List; -import java.util.UUID; - -public class DataManagementPlanOverviewModel implements DataModel { - private String id; - private String label; - private String profile; - private Date creationTime; - private Date modifiedTime; - private Date finalizedAt; - private int version; - private int status; - private UUID groupId; - private List datasets; - private List associatedProfiles; - private List users; - private String description; - private boolean isPublic; - private Date publishedAt; - private List dois; - - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - - public String getProfile() { - return profile; - } - public void setProfile(String profile) { - this.profile = profile; - } - - public Date getCreationTime() { - return creationTime; - } - public void setCreationTime(Date creationTime) { - this.creationTime = creationTime; - } - - public Date getModifiedTime() { - return modifiedTime; - } - public void setModifiedTime(Date modifiedTime) { - this.modifiedTime = modifiedTime; - } - - public Date getFinalizedAt() { - return finalizedAt; - } - public void setFinalizedAt(Date finalizedAt) { - this.finalizedAt = finalizedAt; - } - - public int getVersion() { - return version; - } - public void setVersion(int version) { - this.version = version; - } - - public UUID getGroupId() { - return groupId; - } - public void setGroupId(UUID groupId) { - this.groupId = groupId; - } - - public List getDatasets() { - return datasets; - } - public void setDatasets(List datasets) { - this.datasets = datasets; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } - - public List getAssociatedProfiles() { - return associatedProfiles; - } - public void setAssociatedProfiles(List associatedProfiles) { - this.associatedProfiles = associatedProfiles; - } - - public List getUsers() { - return users; - } - public void setUsers(List users) { - this.users = users; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - - public boolean getIsPublic() { - return isPublic; - } - public void setIsPublic(boolean aPublic) { - isPublic = aPublic; - } - - public Date getPublishedAt() { - return publishedAt; - } - public void setPublishedAt(Date publishedAt) { - this.publishedAt = publishedAt; - } - - public List getDois() { - return dois; - } - public void setDois(List dois) { - this.dois = dois; - } - - @Override - public DataManagementPlanOverviewModel fromDataModel(DmpEntity entity) { - this.id = entity.getId().toString(); - this.label = entity.getLabel(); - this.groupId = entity.getGroupId(); - this.status = entity.getStatus().getValue(); -// if (entity.getResearchers() != null) { //TODO -// this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()); -// } -// if(entity.getDois() != null){ -// this.dois = entity.getDois().stream().map(item -> new Doi().fromDataModel(item)).collect(Collectors.toList()); -// } - return this; - } - - public DataManagementPlanOverviewModel fromDataModelDatasets(DmpEntity entity) { - this.fromDataModel(entity); - this.version = entity.getVersion(); -// if (entity.getGrant() != null) this.grant = new GrantOverviewModel().fromDataModel(entity.getGrant()); -// if (entity.getProfile() != null) this.profile = entity.getProfile().getLabel(); - this.creationTime = Date.from(entity.getCreatedAt()); - this.modifiedTime = Date.from(entity.getUpdatedAt()); - this.finalizedAt = Date.from(entity.getFinalizedAt()); -// this.organisations = entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); -// this.datasets = entity.getDataset().stream().filter(dataset -> !dataset.getIsActive().equals(IsActive.Inactive) && !dataset.getStatus().equals(DescriptionStatus.Canceled)).map(x-> new DatasetOverviewModel().fromDataModel(x)).collect(Collectors.toList()); -// this.users = entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()); -// this.description = entity.getDescription(); -// if (entity.getResearchers() != null) { -// this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()); -// } -// -// if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { -// this.associatedProfiles = new LinkedList<>(); -// for (DMPDatasetProfile dmpDescriptionProfile : entity.getAssociatedDmps()) { -// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(dmpDescriptionProfile.getDatasetprofile()); -// try { -// associatedProfile.setData(new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {})); -// } -// catch (Exception e) { -// associatedProfile.setData(null); -// } -// this.associatedProfiles.add(associatedProfile); -// } -// } -// this.isPublic = entity.isPublic(); -// this.publishedAt = entity.getPublishedAt(); -// if (entity.getDois() != null) { -// this.dois = entity.getDois().stream().map(item -> new Doi().fromDataModel(item)).collect(Collectors.toList()); -// } else { -// this.dois = new ArrayList<>(); -// } - - return this; - } - - @Override - public DmpEntity toDataModel() { - return null; - } - - @Override - public String getHint() { - return "dataManagementPlanOverviewModel"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanProfileListingModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanProfileListingModel.java deleted file mode 100644 index 59734eb23..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DataManagementPlanProfileListingModel.java +++ /dev/null @@ -1,107 +0,0 @@ -//package eu.eudat.models.data.listingmodels; -// -//import eu.eudat.commons.enums.DmpBlueprintStatus; -//import eu.eudat.commons.types.dmpblueprint.DefinitionEntity; -//import eu.eudat.data.DmpBlueprintEntity; -//import eu.eudat.models.DataModel; -//import eu.eudat.commons.types.xml.XmlBuilder; -//import org.w3c.dom.Document; -// -//import java.time.Instant; -//import java.util.UUID; -// -///** -// * Created by ikalyvas on 3/21/2018. -// */ -//public class DataManagementPlanProfileListingModel implements DataModel { -// -// private UUID id; -// -// private String label; -// -// private DefinitionEntity definitionEntity; -// -// private DmpBlueprintStatus status; -// -// private Instant created = null; -// -// private Instant modified = Instant.now(); -// -// public UUID getId() { -// return id; -// } -// -// public void setId(UUID id) { -// this.id = id; -// } -// -// public String getLabel() { -// return label; -// } -// -// public void setLabel(String label) { -// this.label = label; -// } -// -// public DefinitionEntity getDefinition() { -// return definitionEntity; -// } -// -// public void setDefinition(DefinitionEntity definitionEntity) { -// this.definitionEntity = definitionEntity; -// } -// -// public DmpBlueprintStatus getStatus() { -// return status; -// } -// -// public void setStatus(DmpBlueprintStatus status) { -// this.status = status; -// } -// -// public Instant getCreated() { -// return created; -// } -// -// public void setCreated(Instant created) { -// this.created = created; -// } -// -// public Instant getModified() { -// return modified; -// } -// -// public void setModified(Instant modified) { -// this.modified = modified; -// } -// -// @Override -// public DataManagementPlanProfileListingModel fromDataModel(DmpBlueprintEntity entity) { -// this.id = entity.getId(); -// this.created = entity.getCreatedAt(); -// this.definitionEntity = new DefinitionEntity().fromXml(XmlBuilder.fromXml(entity.getDefinition()).getDocumentElement()); -// this.modified = entity.getUpdatedAt(); -// this.label = entity.getLabel(); -// this.status = entity.getStatus(); -// return this; -// } -// -// @Override -// public DmpBlueprintEntity toDataModel() throws Exception { -// Document document = XmlBuilder.getDocument(); -// document.appendChild(this.definitionEntity.toXml(document)); -// DmpBlueprintEntity dmpBlueprint = new DmpBlueprintEntity(); -// dmpBlueprint.setCreatedAt(this.created == null ? Instant.now() : this.created); -// dmpBlueprint.setDefinition(XmlBuilder.generateXml(document)); -// dmpBlueprint.setId(this.id); -// dmpBlueprint.setLabel(this.label); -// dmpBlueprint.setStatus(this.status); -// dmpBlueprint.setUpdatedAt(this.modified == null ? Instant.now() : this.modified); -// return dmpBlueprint; -// } -// -// @Override -// public String getHint() { -// return null; -// } -//} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/VersionListingModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/VersionListingModel.java deleted file mode 100644 index 6093adf36..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/VersionListingModel.java +++ /dev/null @@ -1,53 +0,0 @@ -package eu.eudat.models.data.listingmodels; - -import eu.eudat.data.DmpEntity; -import eu.eudat.models.DataModel; - -public class VersionListingModel implements DataModel { - private String id; - private String groupId; - private Integer version; - - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public Integer getVersion() { - return version; - } - - public void setVersion(Integer version) { - this.version = version; - } - - @Override - public VersionListingModel fromDataModel(DmpEntity entity) { - this.id = entity.getId().toString(); - this.groupId = entity.getGroupId().toString(); - this.version = entity.getVersion().intValue(); - return this; - } - - @Override - public DmpEntity toDataModel() throws Exception { - return null; - } - - @Override - public String getHint() { - return "versionListingModel"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetCreateWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetCreateWizardModel.java index f8a3b486e..072e894f5 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetCreateWizardModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetCreateWizardModel.java @@ -2,11 +2,8 @@ package eu.eudat.models.data.quickwizard; public class DatasetCreateWizardModel { - private DmpCreateWizardModel dmpMeta; private DatasetQuickWizardModel datasets; - public DmpCreateWizardModel getDmpMeta() { return dmpMeta; } - public void setDmpMeta(DmpCreateWizardModel dmpMeta) { this.dmpMeta = dmpMeta; } public DatasetQuickWizardModel getDatasets() { return datasets; diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetDescriptionQuickWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetDescriptionQuickWizardModel.java index 466bec4dd..21930b7f5 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetDescriptionQuickWizardModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetDescriptionQuickWizardModel.java @@ -3,7 +3,6 @@ package eu.eudat.models.data.quickwizard; import eu.eudat.commons.enums.DescriptionStatus; import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.user.composite.PagedDatasetProfile; @@ -23,12 +22,12 @@ public class DatasetDescriptionQuickWizardModel extends PagedDatasetProfile { } - public DatasetWizardModel toDataModel(DataManagementPlan dmp, DescriptionTemplateEntity profile){ + public DatasetWizardModel toDataModel(DescriptionTemplateEntity profile){ DatasetWizardModel newDataset = new DatasetWizardModel(); newDataset.setLabel(datasetLabel); newDataset.setCreated(Instant.now()); // newDataset.setProfile(new DatasetProfileOverviewModel().fromDataModel(profile)); - newDataset.setDmp(dmp); +// newDataset.setDmp(dmp); newDataset.setStatus(DescriptionStatus.of((short)this.getStatus())); //newDataset.setStatus(Dataset.Status.SAVED.getValue()); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpCreateWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpCreateWizardModel.java deleted file mode 100644 index dcad10f59..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpCreateWizardModel.java +++ /dev/null @@ -1,16 +0,0 @@ -package eu.eudat.models.data.quickwizard; - -import eu.eudat.models.data.dmp.DataManagementPlan; - -public class DmpCreateWizardModel { - private DatasetProfileCreateWizardModel datasetProfile; - private DataManagementPlan dmp; - - public DatasetProfileCreateWizardModel getDatasetProfile() {return datasetProfile; } - public void setDatasetProfile(DatasetProfileCreateWizardModel datasetProfileCreateWizardModel) { - this.datasetProfile = datasetProfileCreateWizardModel; - } - - public DataManagementPlan getDmp() { return dmp; } - public void setDmp(DataManagementPlan dmp) { this.dmp = dmp; } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpQuickWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpQuickWizardModel.java deleted file mode 100644 index 3a24bfa30..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DmpQuickWizardModel.java +++ /dev/null @@ -1,112 +0,0 @@ -package eu.eudat.models.data.quickwizard; - -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.model.User; -import eu.eudat.models.data.dmp.AssociatedProfile; - -import javax.management.InvalidApplicationException; -import java.util.*; - - -public class DmpQuickWizardModel { - private UUID id; - private String label; - private int status; - private AssociatedProfile datasetProfile; - private String description; - private String language; - - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public void setDatasetProfile(AssociatedProfile datasetProfile) { - this.datasetProfile = datasetProfile; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public eu.eudat.models.data.dmp.DataManagementPlan toDataDmp(/*Grant grant, Project project,*/ UserScope userScope) throws InvalidApplicationException { - eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlanEntity = new eu.eudat.models.data.dmp.DataManagementPlan(); - - dataManagementPlanEntity.setId(this.id); - dataManagementPlanEntity.setVersion(0); - - dataManagementPlanEntity.setLabel(this.label); - //TODO -// if (grant != null) { -// eu.eudat.models.data.grant.Grant importGrant = new eu.eudat.models.data.grant.Grant(); -// dataManagementPlanEntity.setGrant(importGrant.fromDataModel(grant)); -// } -// if (project != null) { -// eu.eudat.models.data.project.Project importProject = new eu.eudat.models.data.project.Project(); -// dataManagementPlanEntity.setProject(importProject.fromDataModel(project)); -// } - if (this.datasetProfile != null) { - List assProfile = new LinkedList<>(); - assProfile.add(this.datasetProfile); - dataManagementPlanEntity.setProfiles(assProfile); - } - dataManagementPlanEntity.setStatus((short) this.status); - dataManagementPlanEntity.setDescription(this.description); - dataManagementPlanEntity.setProperties(null); - dataManagementPlanEntity.setCreated(new Date()); - List user = new LinkedList<>(); - User userInfo = new User(); - userInfo.setId(userScope.getUserId()); -// dataManagementPlanEntity.setAssociatedUsers(user); - dataManagementPlanEntity.setExtraProperties(new HashMap<>()); - dataManagementPlanEntity.getExtraProperties().put("language", this.language); - dataManagementPlanEntity.getExtraProperties().put("visible", false); - dataManagementPlanEntity.getExtraProperties().put("contact", userScope.getUserId().toString()); - return dataManagementPlanEntity; - } - - - public DescriptionTemplateEntity getDatasetProfile() { - DescriptionTemplateEntity descriptionTemplateEntity = new DescriptionTemplateEntity(); - descriptionTemplateEntity.setDefinition(this.datasetProfile.getLabel()); - descriptionTemplateEntity.setLabel(this.datasetProfile.getLabel()); - descriptionTemplateEntity.setId(this.datasetProfile.getDescriptionTemplateId()); - return descriptionTemplateEntity; - } - - -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/QuickWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/QuickWizardModel.java index 5a565dd00..8e57910c0 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/QuickWizardModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/QuickWizardModel.java @@ -3,17 +3,9 @@ package eu.eudat.models.data.quickwizard; public class QuickWizardModel { - private DmpQuickWizardModel dmp; private DatasetQuickWizardModel datasets; private int status; - public DmpQuickWizardModel getDmp() { - return dmp; - } - public void setDmp(DmpQuickWizardModel dmp) { - this.dmp = dmp; - } - public DatasetQuickWizardModel getDatasets() { return datasets; } diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DataManagementPlanUrlListing.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DataManagementPlanUrlListing.java deleted file mode 100644 index e79b201ad..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DataManagementPlanUrlListing.java +++ /dev/null @@ -1,26 +0,0 @@ -package eu.eudat.models.data.urls; - -import eu.eudat.data.DmpEntity; - -/** - * Created by ikalyvas on 3/19/2018. - */ -public class DataManagementPlanUrlListing extends UrlListing { - - @Override - public DataManagementPlanUrlListing fromDataModel(DmpEntity entity) { - this.setLabel(entity.getLabel()); - this.setUrl(entity.getId().toString()); - return this; - } - - @Override - public DmpEntity toDataModel() throws Exception { - return null; - } - - @Override - public String getHint() { - return null; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanNewVersionValidator.java b/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanNewVersionValidator.java deleted file mode 100644 index 725d70e44..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanNewVersionValidator.java +++ /dev/null @@ -1,54 +0,0 @@ -package eu.eudat.models.validators; - -import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; -import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel; -import eu.eudat.models.validators.fluentvalidator.FluentValidator; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.validation.Errors; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -/** - * Created by ikalyvas on 3/7/2018. - */ -@Component("dataManagementPlanNewVersionValidator") -public class DataManagementPlanNewVersionValidator extends FluentValidator { - - private DatabaseRepository databaseRepository; - - @Autowired - public DataManagementPlanNewVersionValidator(DatabaseRepository databaseRepository) { - this.databaseRepository = databaseRepository; - - ruleFor(x -> { - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - List groupIds = Arrays.asList(x.getGroupId()); - criteria.setGroupIds(groupIds); - return this.databaseRepository.getDmpDao().getWithCriteria(criteria).getSingleOrDefault().getVersion(); - }).compareAs(x -> x.getVersion(), ((leftItem, rightItem) -> leftItem > rightItem)) - .withName("version").withMessage("datamanagementplannewversion.version.notacceptable"); - - ruleFor(x -> { - DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); - List groupIds = Arrays.asList(x.getGroupId()); - criteria.setGroupIds(groupIds); - return this.databaseRepository.getDmpDao().getWithCriteria(criteria).getSingleOrDefault().getVersion() + 1; - }).compareAs(x -> x.getVersion(), ((leftItem, rightItem) -> !leftItem.equals(rightItem))) - .withName("version").withMessage("datamanagementplannewversion.version.notnext"); - } - - @Override - public boolean supports(Class aClass) { - return DataManagementPlanNewVersionModel.class.equals(aClass); - } - - - public static boolean supportsType(Class aClass) { - return DataManagementPlanNewVersionModel.class.equals(aClass); - } - -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanTableRequestValidator.java b/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanTableRequestValidator.java deleted file mode 100644 index 44fbbb74f..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/validators/DataManagementPlanTableRequestValidator.java +++ /dev/null @@ -1,26 +0,0 @@ -package eu.eudat.models.validators; - -import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest; -import eu.eudat.models.validators.fluentvalidator.FluentValidator; -import org.springframework.stereotype.Component; - - -@Component("dataManagementPlanTableRequestValidator") -public class DataManagementPlanTableRequestValidator extends FluentValidator { - - public DataManagementPlanTableRequestValidator() { - ruleFor(x -> x.getOffset()).compareAs((x -> 0), (leftItem, rightItem) -> leftItem < rightItem) - .withName("offset").withMessage("datamanagementplanrequest.offset.negative"); - ruleFor(x -> x.getLength()).compareAs((x -> 0), (leftItem, rightItem) -> leftItem < rightItem) - .withName("length").withMessage("datamanagementplanrequest.length.negative"); - } - - @Override - public boolean supports(Class clazz) { - return DataManagementPlanTableRequest.class.equals(clazz); - } - - public static boolean supportsType(Class clazz) { - return DataManagementPlanTableRequest.class.equals(clazz); - } -}