diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionEntity.java index b97048998..bb2ac8eb0 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/DescriptionEntity.java @@ -17,7 +17,7 @@ import java.util.*; @Entity @Table(name = "\"Description\"") -public class DescriptionEntity extends TenantScopedBaseEntity implements DataEntity { +public class DescriptionEntity extends TenantScopedBaseEntity { @Id @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) @@ -190,22 +190,5 @@ public class DescriptionEntity extends TenantScopedBaseEntity implements DataEnt public void setDescriptionTemplateId(UUID descriptionTemplateId) { this.descriptionTemplateId = descriptionTemplateId; } - - @Override - public void update(DescriptionEntity entity) { - - } - - @Override - public UUID getKeys() { - return this.id; - } - - @Override - public DescriptionEntity buildFromTuple(List tuple, List fields, String base) { - String currentBase = base.isEmpty() ? "" : base + "."; - if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); - return this; - } } diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDao.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDao.java deleted file mode 100644 index f492b6733..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDao.java +++ /dev/null @@ -1,23 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.data.dao.DatabaseAccessLayer; -import eu.eudat.data.dao.criteria.DatasetCriteria; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.UserEntity; -import eu.eudat.queryable.QueryableList; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.UUID; - -public interface DatasetDao extends DatabaseAccessLayer { - - QueryableList getWithCriteria(DatasetCriteria criteria); - - QueryableList filterFromElastic(DatasetCriteria criteria, List ids); - - QueryableList getAuthenticated(QueryableList query, UserEntity principal, List roles); - - DescriptionEntity isPublicDataset(UUID id) throws InvalidApplicationException; - -} \ No newline at end of file diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDaoImpl.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDaoImpl.java deleted file mode 100644 index a0521ed48..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DatasetDaoImpl.java +++ /dev/null @@ -1,152 +0,0 @@ -package eu.eudat.data.dao.entities; - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.dao.DatabaseAccess; -import eu.eudat.data.dao.criteria.DatasetCriteria; -import eu.eudat.data.dao.databaselayer.service.DatabaseService; -import eu.eudat.data.DescriptionEntity; -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 org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; - -import jakarta.persistence.criteria.Join; -import jakarta.persistence.criteria.JoinType; - -import javax.management.InvalidApplicationException; -import java.util.*; -import java.util.concurrent.CompletableFuture; - -@Component("datasetDao") -public class DatasetDaoImpl extends DatabaseAccess implements DatasetDao { - - @Autowired - public DatasetDaoImpl(DatabaseService databaseService) { super(databaseService); } - - @Override - public QueryableList getWithCriteria(DatasetCriteria criteria) { - QueryableList query = getDatabaseService().getQueryable(new HashSet<>(Arrays.asList("datasetListingModel")), DescriptionEntity.class); - if (criteria.getIsPublic() != null && criteria.getIsPublic()) { - query.where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true)); - query.where((builder, root) -> builder.equal(root.get("status"), DescriptionStatus.Finalized)); - /*query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), - query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), - Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.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.getStatus() != null) - query.where((builder, root) -> builder.equal(root.get("status"), criteria.getStatus())); - if (criteria.getProfileDatasetId() != null) - query.where((builder, root) -> builder.equal(root.get("profile").get("id"), criteria.getProfileDatasetId())); - 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.getAllVersions()) - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), builder1.notEqual(nestedRoot.get("dmp").get("isActive"), IsActive.Inactive.getValue())), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), Integer.class))); - if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty()) - query.where((builder, root) -> root.get("dmp").get("groupId").in(criteria.getGroupIds())); - if (criteria.getDmpIds() != null && !criteria.getDmpIds().isEmpty()) - query.where((builder, root) -> root.get("dmp").get("id").in(criteria.getDmpIds())); - /*if (criteria.getRole() != null) { - query.where((builder, root) -> builder.equal(root.join("dmp").join("users").get("role"), criteria.getRole())); - } else { - query.where((builder, root) -> root.join("dmp").join("users").get("role").in(UserDMP.UserDMPRoles.getAllValues())); - }*/ - if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) - query.where((builder, root) -> root.join("dmp").join("organisations").get("reference").in(criteria.getOrganisations())); - if (criteria.getGrants() != null && !criteria.getGrants().isEmpty()) - query.where((builder, root) -> root.join("dmp").join("grant").get("id").in(criteria.getGrants())); - if (criteria.getGrantStatus() != null) { - if (criteria.getGrantStatus().equals(GrantStateType.FINISHED.getValue().shortValue())) - query.where((builder, root) -> builder.lessThan(root.get("dmp").get("grant").get("enddate"), new Date())); - if (criteria.getGrantStatus().equals(GrantStateType.ONGOING.getValue().shortValue())) - query.where((builder, root) -> - builder.or(builder.greaterThan(root.get("dmp").get("grant").get("enddate"), new Date()) - , builder.isNull(root.get("dmp").get("grant").get("enddate")))); - } - if (criteria.getCollaborators() != null && !criteria.getCollaborators().isEmpty()) - query.where((builder, root) -> root.join("dmp", JoinType.LEFT).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.get("profile").get("id").in(criteria.getDatasetTemplates())); - - if (criteria.hasDoi()) { - query.where((builder, root) -> builder.not(builder.isNull(root.join("dmp").join("dois").get("id")))); - } - query.where((builder, root) -> builder.notEqual(root.get(DescriptionEntity._isActive), IsActive.Inactive)); - query.where((builder, root) -> builder.notEqual(root.get("status"), DescriptionStatus.Canceled)); - return query; - } - - public QueryableList filterFromElastic(DatasetCriteria criteria, List ids) { - QueryableList query = getDatabaseService().getQueryable(new HashSet<>(Arrays.asList("datasetListingModel")), DescriptionEntity.class); - - query.where(((builder, root) -> root.get("id").in(ids))); - if (!criteria.getAllVersions()) - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), builder1.notEqual(nestedRoot.get("dmp").get("isActive"), IsActive.Inactive.getValue())), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); - - return query; - } - - @Override - public DescriptionEntity createOrUpdate(DescriptionEntity item) { - return getDatabaseService().createOrUpdate(item, DescriptionEntity.class); - } - - @Override - public DescriptionEntity find(UUID id) throws InvalidApplicationException { - return getDatabaseService().getQueryable(DescriptionEntity.class) - .where((builder, root) -> builder.and(builder.notEqual(root.get(DescriptionEntity._isActive), IsActive.Inactive), builder.notEqual(root.get("status"), DescriptionStatus.Canceled), builder.equal((root.get("id")), id))).getSingle(); - } - - @Override - public DescriptionEntity find(UUID id, String hint) throws InvalidApplicationException { - return getDatabaseService().getQueryable(new HashSet<>(Arrays.asList("datasetListingModel")), DescriptionEntity.class).withHint(hint) - .where((builder, root) -> builder.and(builder.notEqual(root.get(DescriptionEntity._isActive), IsActive.Inactive), builder.notEqual(root.get("status"), DescriptionStatus.Canceled), builder.equal((root.get("id")), id))).getSingle(); - } - - @Override - public DescriptionEntity isPublicDataset(UUID id) throws InvalidApplicationException { - QueryableList query = getDatabaseService().getQueryable(new HashSet<>(Arrays.asList("datasetListingModel")), DescriptionEntity.class); - query.where(((builder, root) -> builder.equal(root.get("id"), id))); - - return query.withHint("datasetListingModel").getSingle(); - } - - @Override - public QueryableList getAuthenticated(QueryableList query, UserEntity principal, List roles) { - if (roles != null && !roles.isEmpty()) { - query.where((builder, root) -> { - Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); - return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), userJoin.get("role").in(roles)); - }); - } else { - query.where((builder, root) -> builder.equal(root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal.getId())); - - } - return query; - } - - @Override - public void delete(DescriptionEntity item) { - this.getDatabaseService().delete(item); - } - - @Override - public QueryableList asQueryable() { - return this.getDatabaseService().getQueryable(DescriptionEntity.class); - } - - @Async - public CompletableFuture createOrUpdateAsync(DescriptionEntity item) { - return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); - } -} 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 deleted file mode 100644 index 8be2668be..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/query/DatasetQuery.java +++ /dev/null @@ -1,55 +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.List; -import java.util.UUID; - -public class DatasetQuery extends Query { - - private UUID id; - private String label; - - public DatasetQuery(DatabaseAccessLayer databaseAccessLayer) { - super(databaseAccessLayer); - } - - public DatasetQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { - super(databaseAccessLayer, selectionFields); - } - - 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; - } - - - @Override - 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)); - } - return query; - } -} 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 06f131fbf..f70912743 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 @@ -20,8 +20,8 @@ import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.operations.DatabaseRepository; import eu.eudat.model.file.FileEnvelope; import eu.eudat.models.HintedModelFactory; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.helpers.responses.ResponseItem; +import eu.eudat.query.DescriptionQuery; import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpDescriptionTemplateQuery; import eu.eudat.query.DmpQuery; @@ -141,7 +141,7 @@ public class FileController { } if(fileUpload.getEntityType().name().equals(FileUpload.EntityType.DATASET.name())) { - DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(fileUpload.getEntityId(), HintedModelFactory.getHint(DatasetWizardModel.class)); + DescriptionEntity descriptionEntityEntity = this.queryFactory.query(DescriptionQuery.class).ids(fileUpload.getEntityId()).first(); if (descriptionEntityEntity == null) { throw new NoSuchElementException("No dataset with id " + fileUpload.getEntityId() + " found. This dataset was related to the file with id " + id); } 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 deleted file mode 100644 index 11faa168b..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/QuickWizardController.java +++ /dev/null @@ -1,115 +0,0 @@ -package eu.eudat.controllers; - - -import eu.eudat.authorization.Permission; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.logic.managers.DatasetManager; -import eu.eudat.logic.managers.QuickWizardManager; -import eu.eudat.logic.services.ApiContext; -import eu.eudat.models.data.helpers.responses.ResponseItem; -import eu.eudat.models.data.quickwizard.DatasetCreateWizardModel; -import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel; -import eu.eudat.models.data.quickwizard.QuickWizardModel; -import eu.eudat.types.ApiMessageCode; -import gr.cite.commons.web.authz.service.AuthorizationService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import jakarta.transaction.Transactional; -import jakarta.validation.Valid; - -@RestController -@CrossOrigin -@RequestMapping(value = {"/api/quick-wizard/"}) -public class QuickWizardController extends BaseController { - - private QuickWizardManager quickWizardManager; - private DatasetManager datasetManager; - private final AuthorizationService authorizationService; - private final UserScope userScope; - - @Autowired - public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager, AuthorizationService authorizationService, UserScope userScope) { - super(apiContext); - this.quickWizardManager = quickWizardManager; - this.datasetManager = datasetManager; - this.authorizationService = authorizationService; - this.userScope = userScope; - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> addQuickWizardModel(@Valid @RequestBody QuickWizardModel quickWizard) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - -// Funder funderEntity;//TODO -// //Create Funder -// if (quickWizard.getFunder() == null) { -// funderEntity = null; -// } else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() == null) { -// funderEntity = null; -// } else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() != null) { -// funderEntity = this.quickWizardManager.createOrUpdate(quickWizard.getFunder().toDataFunder()); -// } else { -// funderEntity = quickWizard.getFunder().getExistFunder().toDataModel(); -// } - -// Grant grantEntity; //TODO -// //Create Grant -// if (quickWizard.getGrant() == null) { -// grantEntity = null; -// } else if (quickWizard.getGrant().getExistGrant() == null && quickWizard.getGrant().getLabel() == null) { -// grantEntity = null; -// } else if (quickWizard.getGrant().getExistGrant() == null) { -// grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant()); -// } else { -// grantEntity = quickWizard.getGrant().getExistGrant().toDataModel(); -// } - -// Project projectEntity; //TODO -// //Create Project -// if (quickWizard.getProject().getExistProject() == null -// && quickWizard.getProject().getLabel() == null) { -// projectEntity = null; -// } else if (quickWizard.getProject().getExistProject() == null && quickWizard.getProject().getLabel() != null) { -// projectEntity = this.quickWizardManager.createOrUpdate(quickWizard.getProject().toDataProject()); -// } else { -// projectEntity = quickWizard.getProject().getExistProject().toDataModel(); -// } - - //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); -// } - - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); - } - - @RequestMapping(method = RequestMethod.POST, value = {"/datasetcreate"}, consumes = "application/json", produces = "application/json") - public @ResponseBody - ResponseEntity> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel) throws Exception{ - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); - - 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(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/controllers/v2/PrincipalController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/PrincipalController.java index 158e3996b..7fbf9588f 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/PrincipalController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/PrincipalController.java @@ -1,10 +1,8 @@ package eu.eudat.controllers.v2; import eu.eudat.audit.AuditableAction; -import eu.eudat.models.data.dataset.DatasetOverviewModel; -import eu.eudat.models.data.helpers.responses.ResponseItem; +import eu.eudat.models.v2.Account; import eu.eudat.models.v2.AccountBuilder; -import eu.eudat.types.ApiMessageCode; import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; import gr.cite.commons.web.oidc.principal.MyPrincipal; import gr.cite.tools.auditing.AuditService; @@ -13,11 +11,9 @@ import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import eu.eudat.models.v2.Account; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; import javax.management.InvalidApplicationException; 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 a198473a2..ec591be19 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 @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.node.JsonNodeType; import eu.eudat.criteria.entities.Criteria; import eu.eudat.logic.services.operations.DatabaseRepository; -import eu.eudat.query.DatasetQuery; import java.io.IOException; import java.util.*; @@ -58,10 +57,4 @@ public class DatasetCriteria { return new LinkedList<>(fields); } - public DatasetQuery buildQuery(DatabaseRepository dao) { - List fields = this.buildFields(""); - DatasetQuery datasetQuery = new DatasetQuery(dao.getDatasetDao(), fields); - if (this.id != null) datasetQuery.setId(this.id.getValue()); - return datasetQuery; - } } 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 deleted file mode 100644 index 2068e8d38..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetManager.java +++ /dev/null @@ -1,1182 +0,0 @@ -package eu.eudat.logic.managers; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.authorization.Permission; -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.commons.enums.DmpAccessType; -import eu.eudat.commons.enums.DmpStatus; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.*; -import eu.eudat.data.dao.criteria.*; -import eu.eudat.data.dao.entities.DatasetDao; -import eu.eudat.data.old.*; -import eu.eudat.data.query.items.table.dataset.DatasetPublicTableRequest; -import eu.eudat.data.query.items.table.dataset.DatasetTableRequest; -import eu.eudat.exceptions.security.ForbiddenException; -import eu.eudat.exceptions.security.UnauthorisedException; -import eu.eudat.logic.builders.BuilderFactory; -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.model.file.FileEnvelope; -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.logic.utilities.json.JsonSearcher; -import eu.eudat.models.HintedModelFactory; -import eu.eudat.models.data.dataset.DatasetOverviewModel; -import eu.eudat.models.data.datasetImport.DatasetImportField; -import eu.eudat.models.data.datasetImport.DatasetImportPagedDatasetProfile; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.models.data.dmp.AssociatedProfile; -import eu.eudat.models.data.helpers.common.DataTableData; -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; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.QueryFactory; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -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 org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import jakarta.activation.MimetypesFileTypeMap; -import jakarta.persistence.criteria.Join; -import jakarta.persistence.criteria.JoinType; -import jakarta.transaction.Transactional; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Unmarshaller; - -import javax.management.InvalidApplicationException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathFactory; -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.stream.Collectors; -import java.util.stream.Stream; - -@Component -public class DatasetManager { - private static final Logger logger = LoggerFactory.getLogger(DatasetManager.class); - -// private final Map notificationPaths = Stream.of(new Object[][] { -// {NotificationType.DATASET_MODIFIED, "/datasets/edit"}, -// {NotificationType.DATASET_MODIFIED_FINALISED, "/datasets/edit"} -// }).collect(Collectors.toMap(data -> (NotificationType) data[0], data -> (String) data[1])); - - private ApiContext apiContext; - private DatabaseRepository databaseRepository; -// private DatasetRepository datasetRepository; - private BuilderFactory builderFactory; - private ConfigLoader configLoader; - private Environment environment; - private final MetricsManager metricsManager; - private final FileManager fileManager; - private final UserScope userScope; - private final AuthorizationService authorizationService; - private final QueryFactory queryFactory; - - @Autowired - public DatasetManager(ApiContext apiContext, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager, - FileManager fileManager, UserScope userScope, AuthorizationService authorizationService, QueryFactory queryFactory) { - this.apiContext = apiContext; - this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); -// this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(); - this.builderFactory = apiContext.getOperationsContext().getBuilderFactory(); - this.configLoader = configLoader; - this.environment = environment; - this.metricsManager = metricsManager; - this.fileManager = fileManager; - this.userScope = userScope; - this.authorizationService = authorizationService; - this.queryFactory = queryFactory; - } - - public DataTableData getPaged(DatasetTableRequest datasetTableRequest) throws Exception { - //TODO -// DatasetCriteria datasetCriteria = new DatasetCriteria(); -// datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); -// datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetTemplates()); -// if (datasetTableRequest.getCriteria().getStatus() != null) { -// datasetCriteria.setStatus(datasetTableRequest.getCriteria().getStatus().shortValue()); -// } -// datasetCriteria.setDmps(datasetTableRequest.getCriteria().getDmpIds()); -// datasetCriteria.setGroupIds(datasetTableRequest.getCriteria().getGroupIds()); -// datasetCriteria.setGrants(datasetTableRequest.getCriteria().getGrants()); -// datasetCriteria.setCollaborators(datasetTableRequest.getCriteria().getCollaborators()); -// datasetCriteria.setAllowAllVersions(datasetTableRequest.getCriteria().getAllVersions()); -// datasetCriteria.setOrganiztions(datasetTableRequest.getCriteria().getOrganisations()); -// datasetCriteria.setTags(datasetTableRequest.getCriteria().getTags()); -// if (datasetTableRequest.getCriteria().getIsPublic() != null) { -// datasetCriteria.setPublic(datasetTableRequest.getCriteria().getIsPublic()); -// } -// -// if (!datasetCriteria.isPublic()) { -// if (datasetCriteria.getCollaborators() == null) { -// datasetCriteria.setSortCriteria(new ArrayList<>()); -// } -// datasetCriteria.getCollaborators().add(this.userScope.getUserId()); -// } -// if (datasetTableRequest.getCriteria().getGrantStatus() != null) { -// datasetCriteria.setGrantStatus(datasetTableRequest.getCriteria().getGrantStatus()); -// } -// if (datasetTableRequest.getOrderings() != null) { -// datasetCriteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(datasetTableRequest.getOrderings())); -// } -// datasetCriteria.setOffset(datasetTableRequest.getOffset()); -// datasetCriteria.setSize(datasetTableRequest.getLength()); -// List datasets; -// try { -// datasets = datasetRepository.exists() ? -// datasetRepository.queryIds(datasetCriteria) : null; -// } catch (Exception ex) { -// logger.warn(ex.getMessage(), ex); -// datasets = null; -// } - - UserEntity userInfo = builderFactory.getBuilder(UserInfoBuilder.class).id(this.userScope.getUserIdSafe()).build(); -// QueryableList items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class)); - QueryableList items; - //TODO -// if (datasets != null) { -// -// if (!datasets.isEmpty()) { -// //items = databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)); -// final List datasetIds = datasets.stream().map(datasetE -> UUID.fromString(datasetE.getId())).distinct().collect(Collectors.toList()); -// items = databaseRepository.getDatasetDao().filterFromElastic(datasetTableRequest.getCriteria(), datasetIds).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); -// //items.where((builder, root) -> root.get("id").in(datasetIds)); -// } else { -// items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); -// //items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()})); -// } -// } else { - items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); -// } - List roles = new LinkedList<>(); - QueryableList pagedItems; - QueryableList authItems; - if (!datasetTableRequest.getCriteria().getIsPublic()) { - if (this.userScope.getUserIdSafe() == null) { - throw new UnauthorisedException("You are not allowed to access those datasets"); - } - if (datasetTableRequest.getCriteria().getRole() != null) { - roles.add(datasetTableRequest.getCriteria().getRole()); - } - authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo, roles).distinct(); - pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest); - } else { - if (this.userScope.getUserIdSafe() != null && datasetTableRequest.getCriteria().getRole() != null) { - items.where((builder, root) -> { - Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); - return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), this.userScope.getUserId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole())); - }); - } - String[] strings = new String[1]; - //strings[0] = "-dmp:publishedAt|join|"; - //datasetTableRequest.getOrderings().setFields(strings); - authItems = items; - pagedItems = PaginationManager.applyPaging(items, datasetTableRequest); - } - DataTableData dataTable = new DataTableData<>(); - - - dataTable.setData(pagedItems.select(this::mapModel).stream().filter(Objects::nonNull).collect(Collectors.toList())); - - dataTable.setTotalCount(authItems.count()); - - //CompletableFuture.allOf(itemsFuture, countFuture).join(); - return dataTable; - } - - public DataTableData getPaged(DatasetPublicTableRequest datasetTableRequest) throws Exception { - Long count = 0L; - //TODO -// DatasetCriteria datasetCriteria = new DatasetCriteria(); -// datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); -// datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetProfile()); -// datasetCriteria.setDmps(datasetTableRequest.getCriteria().getDmpIds()); -// datasetCriteria.setGrants(datasetTableRequest.getCriteria().getGrants()); -// if (datasetTableRequest.getOrderings() != null) { -// datasetCriteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(datasetTableRequest.getOrderings())); -// } -// datasetCriteria.setOffset(datasetTableRequest.getOffset()); -// datasetCriteria.setSize(datasetTableRequest.getLength()); -// List datasets; -// try { -// datasets = datasetRepository.exists() ? -// datasetRepository.queryIds(datasetCriteria) : new LinkedList<>(); -// count = datasetRepository.exists() ? datasetRepository.count(datasetCriteria) : 0L; -// } catch (Exception ex) { -// logger.warn(ex.getMessage()); -// datasets = null; -// } - /*datasetTableRequest.setQuery(databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class))); - QueryableList items = datasetTableRequest.applyCriteria();*/ - QueryableList items; - //TODO -// if (datasets != null) { -// if (!datasets.isEmpty()) { -// items = databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)); -// List finalDatasets = datasets; -// items.where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList()))); -// } else -// items = datasetTableRequest.applyCriteria(); -// items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()})); -// } else { - items = datasetTableRequest.applyCriteria(); -// } - - if (this.userScope.isSet() && datasetTableRequest.getCriteria().getRole() != null) { - items.where((builder, root) -> { - Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); - return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), this.userScope.getUserId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole())); - }); - } - List strings = new ArrayList<>(); - strings.add("-dmp:publishedAt|join|"); - datasetTableRequest.getOrderings().setFields(strings); - if (count == 0L) { - count = items.count(); - } - QueryableList pagedItems = PaginationManager.applyPaging(items, datasetTableRequest); - DataTableData dataTable = new DataTableData<>(); - - List datasetListis = pagedItems. - select(this::mapModel); - - dataTable.setData(datasetListis.stream().filter(Objects::nonNull).collect(Collectors.toList())); - - dataTable.setTotalCount(count); - //CompletableFuture.allOf(countFuture).join(); - return dataTable; - } - - public DatasetWizardModel getSingle(String id) throws InvalidApplicationException { - DatasetWizardModel dataset = new DatasetWizardModel(); - DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); - ; - 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() -// .stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())) -// .collect(Collectors.toList()).size() == 0 && - !dmp.getAccessType().equals(DmpAccessType.Public)) - throw new UnauthorisedException(); - dataset.setDatasetProfileDefinition(getPagedProfile(dataset, descriptionEntityEntity)); - dataset.fromDataModel(descriptionEntityEntity); - - // Creates the Criteria to get all version of DescriptionTemplate in question. - DatasetProfileCriteria profileCriteria = new DatasetProfileCriteria(); - UUID profileId = this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDescriptionTemplateId()).first().getGroupId(); - List uuidList = new LinkedList<>(); - uuidList.add(profileId); - profileCriteria.setGroupIds(uuidList); - profileCriteria.setAllVersions(true); - List profileVersions = null; -// List profileVersions = databaseRepository.getDatasetProfileDao().getWithCriteria(profileCriteria) -// .orderBy(((builder, root) -> builder.desc(root.get("version")))) -// .toList(); - List profileVersionsIncluded = new LinkedList<>(); - - // 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); -// } -// } - } - - // Sort the list with the included Versions. - Stream sorted = profileVersionsIncluded.stream().sorted(Comparator.comparing(DescriptionTemplateEntity::getVersion).reversed()); - - // Make the Stream into List and get the first item. - List profiles = sorted.collect(Collectors.toList()); - if (profiles.isEmpty()) - throw new NoSuchElementException("No profiles found for the specific Dataset"); - - DescriptionTemplateEntity profile = profiles.get(0); - - // Check if the dataset is on the latest Version. - boolean latestVersion = profile.getVersion().toString().equals(this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDescriptionTemplateId()).first().getVersion()); - dataset.setIsProfileLatestVersion(latestVersion); - -// eu.eudat.elastic.entities.Dataset datasetElastic; //TODO -// try { -// datasetElastic = datasetRepository.exists() ? -// datasetRepository.findDocument(id) : new eu.eudat.elastic.entities.Dataset(); -// } catch (Exception ex) { -// logger.warn(ex.getMessage()); -// datasetElastic = null; -// } -// if (datasetElastic != null && datasetElastic.getTags() != null && !datasetElastic.getTags().isEmpty()) { -// dataset.setTags(datasetElastic.getTags()); -// } - - /*if (datasetElastic != null && datasetElastic.getLabel() != null && !datasetElastic.getLabel().isEmpty()) { - dataset.setLabel(datasetElastic.getLabel()); - }*/ - return dataset; - } - - public DatasetWizardModel getSinglePublic(String id) throws Exception { - DatasetWizardModel dataset = new DatasetWizardModel(); - DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().isPublicDataset(UUID.fromString(id)); - 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); - return dataset; - } else { - throw new Exception("Selected dataset is not public"); - } - } - - public DatasetOverviewModel getOverviewSingle(String id, boolean isPublic) throws Exception { - DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id)); - if (descriptionEntityEntity.getIsActive() == IsActive.Inactive) { - throw new Exception("Dataset is deleted."); - } - 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 - if (!isPublic - //TODO -// && dmp.getUsers() -// .stream().noneMatch(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())) - ) { - throw new UnauthorisedException(); - } else if (isPublic && !dmp.getAccessType().equals(DmpAccessType.Public)) { - throw new ForbiddenException("Selected Dataset is not public"); - } - DatasetOverviewModel dataset = new DatasetOverviewModel(); - dataset.fromDataModel(descriptionEntityEntity); - - return dataset; - } - - public DescriptionEntity getEntitySingle(UUID id) throws InvalidApplicationException { - return databaseRepository.getDatasetDao().find(id); - } - - public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, DescriptionEntity descriptionEntityEntity) { -// eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDescriptionTemplateId()).first()); -// datasetprofile.setStatus(dataset.getStatus().getValue()); -// if (descriptionEntityEntity.getProperties() != null) { -// JSONObject jObject = new JSONObject(descriptionEntityEntity.getProperties()); -// Map properties = jObject.toMap(); -// datasetprofile.fromJsonObject(properties); -// } - PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); -// pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile); - return pagedDatasetProfile; - } - - private XWPFDocument getWordDocument(ConfigLoader configLoader, DescriptionEntity descriptionEntityEntity, VisibilityRuleService visibilityRuleService) throws IOException, InvalidApplicationException { - WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); - DatasetWizardModel dataset = new DatasetWizardModel(); - XWPFDocument document = configLoader.getDatasetDocument(); - - 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 - ) - throw new UnauthorisedException(); - - wordBuilder.fillFirstPage(dmpEntity, descriptionEntityEntity, document, true); - wordBuilder.fillFooter(dmpEntity, descriptionEntityEntity, document, true); - - 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); - } - -// wordBuilder.addParagraphContent(datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); - - // Space below Dataset title. -// XWPFParagraph parBreakDataset = document.createParagraph(); -// -// XWPFParagraph datasetTemplateParagraph = document.createParagraph(); -// datasetTemplateParagraph.setStyle("Heading2"); -// XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); -// runDatasetTemplate1.setText("Template: "); -// runDatasetTemplate1.setBold(true); -// runDatasetTemplate1.setFontSize(12); -// XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); -// runDatasetTemplate.setText(datasetEntity.getProfile().getLabel()); -// runDatasetTemplate.setColor("2E75B6"); -// runDatasetTemplate.setBold(true); -// runDatasetTemplate.setFontSize(12); -// -// wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); - - /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); - externalReferencesParagraph.setStyle("Heading2"); - XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); - externalReferencesRun.setText("External References"); - externalReferencesRun.setColor("2E75B6"); - externalReferencesRun.setBold(true); - externalReferencesRun.setFontSize(12); - - wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER3, 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.HEADER3, 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.HEADER3, 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.HEADER3, 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); - }*/ - - Map properties = new HashMap<>(); - if (descriptionEntityEntity.getProperties() != null) { - JSONObject jObject = new JSONObject(descriptionEntityEntity.getProperties()); - properties = jObject.toMap(); - } - -// wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER2, BigInteger.ZERO); - PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, descriptionEntityEntity); - visibilityRuleService.setProperties(properties); - visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); - wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService); - String label = descriptionEntityEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); -// File exportFile = new File(label + ".docx"); - - // 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); - } - - return document; - //FileOutputStream out = new FileOutputStream(exportFile); - // document.write(out); - // out.close(); - // return exportFile; - } - - private XWPFDocument getLightWordDocument(ConfigLoader configLoader, DatasetWizardModel dataset, VisibilityRuleService visibilityRuleService) throws IOException { - WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); - XWPFDocument document = configLoader.getDocument(); - - // Space below Dataset title. - XWPFParagraph parBreakDataset = document.createParagraph(); - - Map properties = new HashMap<>(); - if (dataset.getDatasetProfileDefinition() != null) { - JSONObject jObject = new JSONObject(propertiesModelToString(dataset.getDatasetProfileDefinition())); - properties = jObject.toMap(); - } - - wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); - visibilityRuleService.setProperties(properties); - visibilityRuleService.buildVisibilityContext(dataset.getDatasetProfileDefinition().getRules()); - wordBuilder.build(document, dataset.getDatasetProfileDefinition(), visibilityRuleService); - - // Removes the top empty headings. - for (int i = 0; i < 6; i++) { - document.removeBodyElement(0); - } - - return document; - //FileOutputStream out = new FileOutputStream(exportFile); - // document.write(out); - // out.close(); - // return exportFile; - } - - 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 = 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() -// .stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())) -// .collect(Collectors.toList()).size() == 0 - ) - throw new UnauthorisedException(); - String label = descriptionEntityEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); - FileEnvelope exportEnvelope = new FileEnvelope(); - exportEnvelope.setFilename(label + ".docx"); - String uuid = UUID.randomUUID().toString(); - File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx"); - XWPFDocument document = getWordDocument(configLoader, descriptionEntityEntity, visibilityRuleService); - FileOutputStream out = new FileOutputStream(exportFile); - document.write(out); - out.close(); - exportEnvelope.setFile(exportFile); - return exportEnvelope; - } - - public String getWordDocumentText (DescriptionEntity descriptionEntityEntity) throws Exception { - DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(descriptionEntityEntity); - datasetWizardModel.setDatasetProfileDefinition(this.getPagedProfile(datasetWizardModel, descriptionEntityEntity)); - XWPFDocument document = getLightWordDocument(this.configLoader, datasetWizardModel, new VisibilityRuleServiceImpl()); - XWPFWordExtractor extractor = new XWPFWordExtractor(document); - return extractor.getText();/*.replaceAll("\n\\s*", " ");*/ - } - - public FileEnvelope getXmlDocument(String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException, InvalidApplicationException { - ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); - DatasetWizardModel dataset = new DatasetWizardModel(); - DescriptionEntity descriptionEntityEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); - 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() -// .stream().filter(userInfo -> this.userScope.getUserIdSafe().equals(userInfo.getUser().getId())) -// .collect(Collectors.toList()).size() == 0 - ) - throw new UnauthorisedException(); - Map properties = new HashMap<>(); - if (descriptionEntityEntity.getProperties() != null) { - JSONObject jobject = new JSONObject(descriptionEntityEntity.getProperties()); - properties = jobject.toMap(); - } - PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, descriptionEntityEntity); - visibilityRuleService.setProperties(properties); - visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); - File file = xmlBuilder.build(pagedDatasetProfile, descriptionEntityEntity.getDescriptionTemplateId(), visibilityRuleService, environment); - FileEnvelope fileEnvelope = new FileEnvelope(); - fileEnvelope.setFile(file); - String label = descriptionEntityEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); - fileEnvelope.setFilename(label); - return fileEnvelope; - } - - public DescriptionEntity createOrUpdate(DatasetWizardModel datasetWizardModel) throws Exception { - Boolean sendNotification = false; - DescriptionEntity tempDescriptionEntity = null; - 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) { - - Instant dbTime = tempDescriptionEntity.getCreatedAt().truncatedTo(ChronoUnit.SECONDS); - Instant modelTime = datasetWizardModel.getModified().truncatedTo(ChronoUnit.SECONDS); - if (modelTime.toEpochMilli() != dbTime.toEpochMilli()) { - throw new Exception("Dataset has been modified already by another user."); - } - sendNotification = true; - } - } else { - metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); - } - if (dmp.getStatus().equals(DmpStatus.Finalized) && datasetWizardModel.getId() != null) - throw new Exception("DMP is finalized, therefore Dataset cannot be edited."); - DescriptionEntity descriptionEntity = datasetWizardModel.toDataModel(); -// descriptionEntity.setDmpId(dmp.getId()); //TODO - descriptionEntity.setProperties(propertiesModelToString(datasetWizardModel.getDatasetProfileDefinition())); -// if (this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().getClient() != null) { -// this.getTagsFromProfile(datasetWizardModel, descriptionEntity); -// } //TODO - if (datasetWizardModel.getStatus() == DescriptionStatus.Finalized) { - String failedField = checkDatasetValidation(descriptionEntity); - if (failedField != null) { - throw new Exception("Field value of " + failedField + " must be filled."); - } - } - UserEntity userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - descriptionEntity.setDmpDescriptionTemplateId(userInfo.getId()); - -// createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), descriptionEntity);//TODO - createExternalDatasetsIfTheyDontExist(descriptionEntity); -// createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), descriptionEntity); - createServicesIfTheyDontExist(descriptionEntity); - DescriptionEntity descriptionEntity1 = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(descriptionEntity); - datasetWizardModel.setId(descriptionEntity1.getId()); -// if (datasetWizardModel.getDmp().getGrant() == null) { //TODO -// DmpEntity dmp1 = databaseRepository.getDmpDao().find(this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntity1.getDmpDescriptionTemplateId()).isActive(IsActive.Active).first().getDmpId()); -// -// datasetWizardModel.setDmp(new DataManagementPlan().fromDataModelNoDatasets(dmp1)); -// } -// 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 = 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) { - if (descriptionEntity1.getStatus() != DescriptionStatus.Finalized) { - this.sendNotification(descriptionEntity1, dmp1, userInfo/*, NotificationType.DATASET_MODIFIED*/); - } else { - this.sendNotification(descriptionEntity1, dmp1, userInfo/*, NotificationType.DATASET_MODIFIED_FINALISED*/); - } - } - - this.deleteOldFilesAndAddNew(datasetWizardModel, userInfo); - - - return descriptionEntity1; - } - - private void deleteOldFilesAndAddNew(DatasetWizardModel datasetWizardModel, UserEntity userInfo) throws JsonProcessingException, InvalidApplicationException { - // Files in DB for this entityId which are NOT DELETED - List fileUploads = fileManager.getCurrentFileUploadsForEntityId(datasetWizardModel.getId()); - List fileUploadIds = fileUploads.stream().map(fileUpload -> fileUpload.getId().toString()).collect(Collectors.toList()); - - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - String json = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); - JsonNode propertiesJson = mapper.readTree(json); - - Set uploadNodes = new HashSet<>(); - uploadNodes.addAll(JsonSearcher.findNodes(propertiesJson, "renderStyle", "upload", true)); - - uploadNodes.forEach(node -> { - JsonNode value = node.get("value"); - if (value != null && !value.toString().equals("\"\"") && !value.toString().equals("null")) { - String stringValue = value.toString().replaceAll("=", ":"); - JSONObject values = new JSONObject(stringValue); - Map data = ((JSONObject) values).toMap(); - - int index = fileUploadIds.indexOf(data.get("id").toString()); - if(index != -1) { - // file in DB is the same as file in the Dataset - fileUploadIds.remove(index); - fileUploads.remove(index); - } else { - // new file - this.fileManager.createFile(data.get("id").toString(), data.get("name").toString(), data.get("type").toString(), datasetWizardModel.getId().toString(), FileUpload.EntityType.DATASET, userInfo); - } - } - }); - - // old files in DB that are not contained anymore in the Dataset -> mark them as Deleted - fileUploads.forEach(fileUpload -> { - fileManager.markOldFileAsDeleted(fileUpload); - }); - } - - private void sendNotification(DescriptionEntity descriptionEntity, 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.getUserId() + "\"" + -// ", \"id\": \"" + descriptionEntity.getId() + "\"" + -// ", \"name\": \"" + descriptionEntity.getLabel() + "\"" + -// ", \"path\": \"" + notificationPaths.get(notificationType) + "\"" + -// "}"); -// notification.setCreatedAt(new Date()); -// notification.setUpdatedAt(notification.getCreatedAt()); -// notification.setContactTypeHint(ContactType.EMAIL); -// -// UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(userDMP.getUserId()); -// query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); -// notification.setContactHint(query.first().getValue()); -// databaseRepository.getNotificationDao().createOrUpdate(notification); - } - } - - } - - public String checkDatasetValidation(DescriptionEntity descriptionEntity) throws Exception { - List datasetProfileValidators = new LinkedList<>(); - DescriptionTemplateEntity profile = null; -// DescriptionTemplateEntity profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(descriptionEntity.getDescriptionTemplateId()); - DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = builderFactory.newDocumentBuilder(); - Document xmlDocument = builder.parse(new ByteArrayInputStream(profile.getDefinition().getBytes())); - - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "//validation/@type[.=1]/ancestor::field/@id"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); - - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - datasetProfileValidators.add(node.getNodeValue()); - } - - expression = "//validation/@type[.=1]/ancestor::fieldSet"; - nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); - - - JSONObject obj = new JSONObject(descriptionEntity.getProperties()); - VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); - visibilityRuleService.setProperties(obj.toMap()); - - //descriptionEntity.setDescriptionTemplateId(profile.getId()); //TODO - PagedDatasetProfile pagedDatasetProfile = this.getPagedProfile(new DatasetWizardModel(), descriptionEntity); - visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); - - - String failedField = null; - - for (String validator : datasetProfileValidators) { - if (obj.has(validator) && isNullOrEmpty(obj.getString(validator)) && isElementVisible(nodeList, validator, visibilityRuleService)) { - //throw new Exception("Field value of " + validator + " must be filled."); - failedField = validator; - break; - } - } - - return failedField; - } - - private boolean isNullOrEmpty(String value) { - return value == null || value.trim().isEmpty(); - } - - private boolean isElementVisible(NodeList nodeList, String id, VisibilityRuleService visibilityRuleService) { - Element fieldSet = null; - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - for (int j = 0; j < node.getChildNodes().getLength(); j++) { - Node fcnode = node.getChildNodes().item(j); - if (fcnode.getNodeName().equals("fields")) { - for(int k = 0; k < fcnode.getChildNodes().getLength(); k++) { - Node scnode = fcnode.getChildNodes().item(k); - if (scnode.getNodeName().equals("field") && scnode.getAttributes().getNamedItem("id").getNodeValue().equals(id)) { - fieldSet = (Element) node; - } - } - } - } - } - if (fieldSet != null) { - return visibilityRuleService.isElementVisible(id) && visibilityRuleService.isElementVisible(fieldSet.getAttribute("id")); - } else { - return visibilityRuleService.isElementVisible(id); - } - } - - private String propertiesModelToString(PagedDatasetProfile pagedDatasetProfile) { - Map values = new LinkedHashMap<>(); - pagedDatasetProfile.toMap(values); - JSONObject jobject = new JSONObject(values); - return jobject.toString(); - } - - public void updateTags(DescriptionEntity descriptionEntityEntity, List tags) throws Exception { - // if (datasetWizardModel.getTags() != null && !datasetWizardModel.getTags().isEmpty()) { - /*eu.eudat.elastic.entities.Dataset dataset = new eu.eudat.elastic.entities.Dataset(); - dataset.setId(datasetWizardModel.getId().toString()); - if (datasetWizardModel.getTags() != null && !datasetWizardModel.getTags().isEmpty()) { - DatasetCriteria criteria = new DatasetCriteria(); - criteria.setTags(datasetWizardModel.getTags()); - List tags = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(eu.eudat.elastic.entities.Dataset::getTags).flatMap(Collection::stream) - .filter(StreamDistinctBy.distinctByKey(Tag::getId)).filter(tag -> datasetWizardModel.getTags().stream().anyMatch(tag1 -> tag1.getName().equals(tag.getName()))).collect(Collectors.toList()); - if (tags.isEmpty()) { - datasetWizardModel.getTags().forEach(tag -> tag.setId(UUID.randomUUID().toString())); - dataset.setTags(datasetWizardModel.getTags()); - } else { - dataset.setTags(tags); - } - } - dataset.setLabel(datasetWizardModel.getLabel()); - dataset.setDescription(datasetWizardModel.getDescription()); - dataset.setTemplate(datasetWizardModel.getProfile()); - dataset.setStatus(datasetWizardModel.getStatus()); - dataset.setDmp(datasetWizardModel.getDmp().getId()); - dataset.setGroup(datasetWizardModel.getDmp().getGroupId()); - dataset.setGrant(datasetWizardModel.getDmp().getGrant().getId()); - if (datasetWizardModel.getDmp().getUsers() != null) { - dataset.setCollaborators(datasetWizardModel.getDmp().getUsers().stream().map(user -> { - Collaborator collaborator = new Collaborator(); - collaborator.setId(user.getId().toString()); - collaborator.setName(user.getName()); - return collaborator; - }).collect(Collectors.toList())); - } - DataManagementPlanCriteria dmpCriteria = new DataManagementPlanCriteria(); - dmpCriteria.setAllVersions(true); - dmpCriteria.setGroupIds(Collections.singletonList(datasetWizardModel.getDmp().getGroupId())); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream() - .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> dataset.setLastVersion(dmp.getId().equals(datasetWizardModel.getDmp().getId()))); - apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream().filter(DMP::isPublic) - .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> dataset.setLastPublicVersion(dmp.getId().equals(datasetWizardModel.getDmp().getId()))); - if (dataset.getLastVersion() == null) { - dataset.setLastVersion(true); - } - if (dataset.getLastPublicVersion() == null) { - dataset.setLastPublicVersion(false); - } - if (datasetWizardModel.getDmp().getOrganisations() != null) { - dataset.setOrganizations(datasetWizardModel.getDmp().getOrganisations().stream().map(org -> { - Organization organization = new Organization(); - organization.setId(org.getId()); - organization.setName(org.getName()); - return organization; - }).collect(Collectors.toList())); - } - dataset.setPublic(datasetWizardModel.getDmp().getPublic()); - dataset.setGrantStatus(datasetWizardModel.getDmp().getGrant().getStatus()); - dataset.setFormData(this.getWordDocumentText(datasetWizardModel));*/ -// DatasetMapper mapper = new DatasetMapper(apiContext, this); //TODO -// eu.eudat.elastic.entities.Dataset dataset = mapper.toElastic(descriptionEntityEntity, tags); -// apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(dataset); - // } - } - - - //TODO implement it on create -// private void createRegistriesIfTheyDontExist(RegistryDao registryDao, DescriptionEntity descriptionEntity) throws InvalidApplicationException { -// -// if (descriptionEntity.getRegistries() != null && !descriptionEntity.getRegistries().isEmpty()) { -// for (Registry registry : descriptionEntity.getRegistries()) { -// RegistryCriteria criteria = new RegistryCriteria(); -// criteria.setLike(registry.getReference()); -// List entries = registryDao.getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) registry.setId(entries.get(0).getId()); -// else { -// registry.setCreated(new Date()); -// registryDao.createOrUpdate(registry); -// } -// } -// } -// } - - //TODO implement it on create -// private void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, DescriptionEntity descriptionEntity) throws InvalidApplicationException { -// -// if (descriptionEntity.getDatasetDataRepositories() != null && !descriptionEntity.getDatasetDataRepositories().isEmpty()) { -// for (DatasetDataRepository datasetDataRepository : descriptionEntity.getDatasetDataRepositories()) { -// DataRepositoryCriteria criteria = new DataRepositoryCriteria(); -// criteria.setLike(datasetDataRepository.getDataRepository().getReference()); -// List entries = dataRepositoryDao.getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) { -// datasetDataRepository.getDataRepository().setId(entries.get(0).getId()); -// datasetDataRepository.setDataset(descriptionEntity); -// descriptionEntity.getDatasetDataRepositories().add(datasetDataRepository); -// } else { -// datasetDataRepository.getDataRepository().setId(UUID.randomUUID()); -// DataRepository dataRepository = dataRepositoryDao.createOrUpdate(datasetDataRepository.getDataRepository()); -// datasetDataRepository.setDataset(descriptionEntity); -// datasetDataRepository.setDataRepository(dataRepository); -// descriptionEntity.getDatasetDataRepositories().add(datasetDataRepository); -// } -// } -// } -// } - - private void createServicesIfTheyDontExist(DescriptionEntity descriptionEntity) throws InvalidApplicationException { - //TODO implement it on create -// if (descriptionEntity.getServices() != null && !descriptionEntity.getServices().isEmpty()) { -// for (DatasetService service : descriptionEntity.getServices()) { -// ServiceCriteria criteria = new ServiceCriteria(); -// criteria.setLike(service.getService().getReference()); -// List entries = databaseRepository.getServiceDao().getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) { -// service.setDataset(descriptionEntity); -// service.getService().setCreated(new Date()); -// service.setService(service.getService()); -// this.databaseRepository.getServiceDao().createOrUpdate(service.getService()); -// descriptionEntity.getServices().add(service); -// } -// } -// } - } - - private void createExternalDatasetsIfTheyDontExist(DescriptionEntity descriptionEntity) throws InvalidApplicationException { - //TODO implement it on create -// if (descriptionEntity.getDatasetExternalDatasets() != null && !descriptionEntity.getDatasetExternalDatasets().isEmpty()) { -// for (DatasetExternalDataset datasetExternalDataset : descriptionEntity.getDatasetExternalDatasets()) { -// ExternalDatasetCriteria criteria = new ExternalDatasetCriteria(); -// criteria.setLike(datasetExternalDataset.getExternalDataset().getReference()); -// List entries = databaseRepository.getExternalDatasetDao().getWithCriteria(criteria).toList(); -// if (entries != null && !entries.isEmpty()) { -// datasetExternalDataset.getExternalDataset().setId(entries.get(0).getId()); -// datasetExternalDataset.setDataset(descriptionEntity); -// descriptionEntity.getDatasetExternalDatasets().add(datasetExternalDataset); -// } else { -// datasetExternalDataset.getExternalDataset().setId(UUID.randomUUID()); -// datasetExternalDataset.setDataset(descriptionEntity); -// ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().createOrUpdate(datasetExternalDataset.getExternalDataset()); -// datasetExternalDataset.setExternalDataset(externalDataset); -// descriptionEntity.getDatasetExternalDatasets().add(datasetExternalDataset); -// } -// } -// } - } - - public void makePublic(DatasetDao datasetDao, UUID id) throws Exception { - DescriptionEntity descriptionEntity = datasetDao.find(id); - if (descriptionEntity.getStatus() != DescriptionStatus.Finalized) - throw new Exception("You cannot make public a Dataset That Has not Been Finalised"); - datasetDao.createOrUpdate(descriptionEntity); - metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED); - } - - public ResponseEntity getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType) throws IllegalAccessException, IOException, InstantiationException, InvalidApplicationException { - FileEnvelope envelope = getXmlDocument(id, visibilityRuleService); - InputStream resource = new FileInputStream(envelope.getFile()); - logger.info("Mime Type of " + envelope.getFilename() + " is " + - new MimetypesFileTypeMap().getContentType(envelope.getFile())); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentLength(envelope.getFile().length()); - responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); - String fileName = envelope.getFilename().replace(" ", "_").replace(",", "_"); - responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".xml"); - 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(envelope.getFile().toPath()); - - return new ResponseEntity<>(content, - responseHeaders, - HttpStatus.OK); - } - - public DescriptionEntity createDatasetFromXml(MultipartFile importFile, String dmpId, String datasetProfileId) throws JAXBException, IOException, InvalidApplicationException { - DatasetImportPagedDatasetProfile importModel = new DatasetImportPagedDatasetProfile(); - JAXBContext jaxbContext; - - // Parses XML into DatasetImport Model. - try { - InputStream in = importFile.getInputStream(); - jaxbContext = JAXBContext.newInstance(DatasetImportPagedDatasetProfile.class); - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - DatasetImportPagedDatasetProfile datasetImport = (DatasetImportPagedDatasetProfile) jaxbUnmarshaller.unmarshal(in); - importModel = datasetImport; - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - - // Checks if XML datasetProfileId GroupId matches the one selected. - try { - DescriptionTemplateEntity importDescriptionTemplateEntity = null; - DescriptionTemplateEntity latestVersionDescriptionTemplateEntity = null; -// DescriptionTemplateEntity importDescriptionTemplateEntity = databaseRepository.getDatasetProfileDao().find(UUID.fromString(importModel.getDatasetProfileId())); -// DescriptionTemplateEntity latestVersionDescriptionTemplateEntity = databaseRepository.getDatasetProfileDao().find(UUID.fromString(datasetProfileId)); - if (latestVersionDescriptionTemplateEntity.getGroupId() != importDescriptionTemplateEntity.getGroupId()) { - throw new Exception(); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - return null; - } - - // Creates the Hash Map to place the values of the data set. - Map importMap = importModel.getPages().stream() - .flatMap(s -> s.getSections().getSection().stream() - .flatMap(cFields -> cFields.getCompositeFields().stream() - .flatMap(cField -> cField.getCompositeField().stream() - .filter(Objects::nonNull) - .flatMap(fields -> fields.getFields().stream() - .flatMap(field -> field.getField().stream() - .filter(f -> f.getValue() != null) - ))))) - .collect(Collectors.toMap(DatasetImportField::getId, DatasetImportField::getValue)); - - // Transforms map into json file. - JSONObject jsonDatasetProperties = new JSONObject(importMap); - - // Creates the entity data set to save. - DescriptionEntity entity = new DescriptionEntity(); - entity.setProperties(jsonDatasetProperties.toString()); - entity.setLabel(importFile.getOriginalFilename()); - DmpEntity dmp = new DmpEntity(); - dmp.setId(UUID.fromString(dmpId)); -// entity.setDmpId(dmp.getId()); //TODO - entity.setStatus(DescriptionStatus.Draft); - entity.setCreatedAt(Instant.now()); - entity.setUpdatedAt(Instant.now()); - DescriptionTemplateEntity profile = new DescriptionTemplateEntity(); - profile.setId(UUID.fromString(datasetProfileId)); -// entity.setDescriptionTemplateId(profile.getId());//TODO - - UserEntity userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build(); - entity.setDmpDescriptionTemplateId(userInfo.getId()); - - updateTagsXmlImportDataset(entity); -// createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), entity); -// createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), entity);//TODO - createServicesIfTheyDontExist(entity); - createExternalDatasetsIfTheyDontExist(entity); - - metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); - return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(entity); - } - - public void updateTagsXmlImportDataset(DescriptionEntity descriptionEntity) throws IOException { - // TODO: When tags functionality return. - } - - -// public PagedDatasetProfile getLatestDatasetProfile(DescriptionEntity descriptionEntityEntity, DescriptionTemplateEntity profile) { -// eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile); -// datasetprofile.setStatus(descriptionEntityEntity.getStatus().getValue()); -// if (descriptionEntityEntity.getProperties() != null) { -// JSONObject jobject = new JSONObject(descriptionEntityEntity.getProperties()); -// Map properties = jobject.toMap(); -// datasetprofile.fromJsonObject(properties); -// } -// PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); -// pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile); -// return pagedDatasetProfile; -// } - -// public DataTableData getDatasetProfilesUsedByDatasets(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException { -// datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.Datasets.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 void generateIndex() throws InvalidApplicationException { - if (this.authorizationService.authorize(Permission.AdminRole)) { - 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 = 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); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - }); - } - } -//TODO -// public void getTagsFromProfile(DatasetWizardModel wizardModel, DescriptionEntity descriptionEntity) throws IOException, InvalidApplicationException { -//// descriptionEntity.setDescriptionTemplateId(descriptionEntity.getDescriptionTemplateId()); //TODO -// wizardModel.setDatasetProfileDefinition(this.getPagedProfile(wizardModel, descriptionEntity)); -// ObjectMapper mapper = new ObjectMapper(); -// String json = mapper.writeValueAsString(wizardModel.getDatasetProfileDefinition()); -// JsonNode propertiesJson = mapper.readTree(json); -// DatasetCriteria criteria = new DatasetCriteria(); -// criteria.setHasTags(true); -// List tags = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(eu.eudat.elastic.entities.Dataset::getTags).flatMap(Collection::stream).filter(StreamDistinctBy.distinctByKey(Tag::getId)).collect(Collectors.toList()); -// Set tagNodes = new HashSet<>(); -// tagNodes.addAll(JsonSearcher.findNodes(propertiesJson, "renderStyle", "tags", true)); -// tagNodes.addAll(JsonSearcher.findNodes(propertiesJson, "schematics", "rda.dataset.keyword")); -// if(wizardModel.getTags() == null){ -// wizardModel.setTags(new ArrayList<>()); -// } -// if (!tagNodes.isEmpty()) { -// tagNodes.forEach(node -> { -// JsonNode value = node.get("value"); -// if (!value.toString().equals("\"\"") && !value.toString().equals("null")) { -// if (value.toString().startsWith("[")) { -// String stringValue = value.toString().replaceAll("=", ":"); -// JSONArray values = new JSONArray(stringValue); -// values.iterator().forEachRemaining(element -> { -// Map data = ((JSONObject) element).toMap(); -// this.addTag(tags, wizardModel.getTags(), data.get("id").toString(), data.get("name").toString()); -// }); -// } else { -// List values = Arrays.asList(value.textValue().split(", ")); -// List tagValues = values.stream().map(stringValue -> new Tag(stringValue, stringValue)).collect(Collectors.toList()); -// tagValues.iterator().forEachRemaining(tag -> { -// this.addTag(tags, wizardModel.getTags(), tag.getId(), tag.getName()); -// }); -// } -// } -// }); -// } -// } -// -// private void addTag(List srcTags, List dstTags, String id, String name) { -// Tag tag = new Tag(); -// if(srcTags.stream().anyMatch(intag -> intag.getName().equals(name))) { -// tag = srcTags.stream().filter(intag -> intag.getName().equals(name)).findFirst().get(); -// } else { -// tag.setName(name); -// tag.setId(id); -// } -// if (dstTags.stream().noneMatch(intag -> intag.getName().equals(name))) { -// dstTags.add(tag); -// } -// } - - @Transactional - private DatasetListingModel mapModel(DescriptionEntity item) { - /*if (item.getProfile() == null) - return null;*/ - DatasetListingModel listingModel = new DatasetListingModel().fromDataModel(item); - /*DatasetProfileCriteria criteria = new DatasetProfileCriteria(); - criteria.setGroupIds(Collections.singletonList(item.getProfile().getGroupId())); - List profiles = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).toList(); - boolean islast = false; - if (!profiles.isEmpty()) { - profiles = profiles.stream().sorted(Comparator.comparing(DescriptionTemplate::getVersion)).collect(Collectors.toList()); - islast = profiles.get(0).getId().equals(item.getProfile().getId()); - } - listingModel.setProfileLatestVersion(islast);*/ - return listingModel; - } -} 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 deleted file mode 100644 index c7c0d7a80..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetWizardManager.java +++ /dev/null @@ -1,65 +0,0 @@ -package eu.eudat.logic.managers; - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.commons.enums.DmpStatus; -import eu.eudat.commons.enums.IsActive; -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.exceptions.datasetwizard.DatasetWizardCannotUnlockException; -import eu.eudat.logic.services.ApiContext; -import eu.eudat.queryable.QueryableList; -import gr.cite.tools.data.query.QueryFactory; - -import javax.management.InvalidApplicationException; -import java.io.IOException; -import java.util.List; -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 getAvailableProfiles(DMPDao dmpRepository, DatasetProfileDao profileDao, DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws InstantiationException, IllegalAccessException, InvalidApplicationException { -// DataManagementPlan dataManagementPlan = new DataManagementPlan().fromDataModel(dmpRepository.find(datasetProfileWizardAutocompleteRequest.getCriteria().getId())); -// if (dataManagementPlan.getProfiles() == null || dataManagementPlan.getProfiles().isEmpty()) { -// return new LinkedList<>(); -// } -// DatasetProfileCriteria criteria = new DatasetProfileCriteria(); -// criteria.setIds(dataManagementPlan.getProfiles().stream().map(AssociatedProfile::getDescriptionTemplateId).collect(Collectors.toList())); -// List descriptionTemplateEntities = profileDao.getWithCriteria(criteria).toList(); -// criteria.setIds(null); -// criteria.setGroupIds(descriptionTemplateEntities.stream().map(DescriptionTemplateEntity::getGroupId).collect(Collectors.toList())); -// descriptionTemplateEntities = profileDao.getWithCriteria(criteria).toList(); -// List profiles = descriptionTemplateEntities.stream().map(profile -> new AssociatedProfile().fromData(profile)).collect(Collectors.toList()); -// 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 delete(ApiContext apiContext, UUID uuid) throws IOException, InvalidApplicationException { - DescriptionEntity oldDescriptionEntity = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); -// eu.eudat.elastic.entities.Dataset oldDatasetElasitc = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(uuid.toString()); //TODO - oldDescriptionEntity.setIsActive(IsActive.Inactive); - apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(oldDescriptionEntity); -// if (oldDatasetElasitc != null && uuid != null && oldDatasetElasitc.getId()!= null) { -// oldDatasetElasitc.setStatus(oldDescriptionEntity.getStatus().getValue()); -// apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(oldDatasetElasitc); -// } - } -} 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 71a2a3297..1939569a8 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 @@ -352,7 +352,8 @@ public class MetricsManager { eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); criteria.setStatus(0); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + return 0; } public long countAllFinalizedDatasets() throws InvalidApplicationException { @@ -363,7 +364,8 @@ public class MetricsManager { eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); criteria.setStatus(1); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + return 0; } public long countAllPublicDatasets() throws InvalidApplicationException { @@ -374,7 +376,8 @@ public class MetricsManager { eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); criteria.setIsPublic(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + return 0; } public long countAllDatasetsWithDoi() throws InvalidApplicationException { @@ -385,7 +388,8 @@ public class MetricsManager { eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); criteria.setHasDoi(true); if (countNexus) criteria.setPeriodStart(getNexusDate()); - return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); +// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + return 0; } public long countAllDraftTemplates() 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 deleted file mode 100644 index 2fdba27d4..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/QuickWizardManager.java +++ /dev/null @@ -1,140 +0,0 @@ -package eu.eudat.logic.managers; - -import eu.eudat.commons.enums.DmpUserRole; -import eu.eudat.commons.scope.user.UserScope; -import eu.eudat.data.DmpEntity; -import eu.eudat.data.DmpUserEntity; -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.query.UserQuery; -import gr.cite.tools.data.query.QueryFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.io.IOException; -import java.text.ParseException; - -@Component -public class QuickWizardManager { - - private ApiContext apiContext; - private DatabaseRepository databaseRepository; - private DatasetManager datasetManager; - - private final QueryFactory queryFactory; - - private final UserScope userScope; - @Autowired - public QuickWizardManager(ApiContext apiContext, DatasetManager datasetManager, QueryFactory queryFactory, UserScope userScope) { - this.apiContext = apiContext; - this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); - this.datasetManager = datasetManager; - this.queryFactory = queryFactory; - this.userScope = userScope; - } - //TODO -// public Funder createOrUpdate(eu.eudat.models.data.funder.Funder funder) { -// Funder funderEntity = funder.toDataModel(); -// return databaseRepository.getFunderDao().createOrUpdate(funderEntity); -// } - //TODO -// public Grant createOrUpdate(eu.eudat.models.data.grant.Grant grant) throws ParseException, IOException, InvalidApplicationException { -// Grant grantEntity = grant.toDataModel(); -// grantEntity.setType(Grant.GrantType.INTERNAL.getValue()); -// grantEntity.setCreationUser(this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first()); -// return databaseRepository.getGrantDao().createOrUpdate(grantEntity); -// } - //TODO -// public Project createOrUpdate(eu.eudat.models.data.project.Project project) throws InvalidApplicationException { -// Project projectEntity = project.toDataModel(); -// projectEntity.setCreationUser(this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first()); -// 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; -// } - -// private void updateIndex(DMP dmp) throws IOException, InvalidApplicationException { -// DmpMapper mapper = new DmpMapper(apiContext, datasetManager); -// Dmp elastic = mapper.toElastic(dmp); -// apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic); -// } - - private void assignUser(DmpEntity dmp, UserEntity userInfo, ApiContext apiContext) { - DmpUserEntity userDMP = new DmpUserEntity(); - userDMP.setDmpId(dmp.getId()); - userDMP.setUserId(userInfo.getId()); - userDMP.setRole(DmpUserRole.User); - //apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP); - } - - private void createGrantIfItDoesntExist(DmpEntity newDmp, UserEntity userInfo) throws InvalidApplicationException { -// if (newDmp.getGrant() != null) { -// Grant grant = newDmp.getGrant(); -// GrantCriteria criteria = new GrantCriteria(); -// criteria.setReference(grant.getReference()); -// Grant grantEntity = databaseRepository.getGrantDao().getWithCriteria(criteria).getSingleOrDefault(); -// if (grantEntity != null) grant.setId(grantEntity.getId()); -// else { -// grant.setType(Grant.GrantType.EXTERNAL.getValue()); -// databaseRepository.getGrantDao().createOrUpdate(grant); -// } -// } - } - - private void createFunderIfItDoesntExist(DmpEntity newDmp, UserEntity userInfo) throws InvalidApplicationException { -// if (newDmp.getGrant().getFunder() != null) { //TODO -// Funder funder = newDmp.getGrant().getFunder(); -// FunderCriteria criteria = new FunderCriteria(); -// criteria.setReference(funder.getReference()); -// Funder funderEntity = databaseRepository.getFunderDao().getWithCritetia(criteria).getSingleOrDefault(); -// if (funderEntity != null) funder.setId(funderEntity.getId()); -// else { -// funder.setType(Funder.FunderType.EXTERNAL.getValue()); -// databaseRepository.getFunderDao().createOrUpdate(funder); -// } -// } - } - - private void createProjectIfItDoesntExist(DmpEntity newDmp, UserEntity userInfo) throws InvalidApplicationException { -// if (newDmp.getProject() != null) { //TODO -// Project project = newDmp.getProject(); -// ProjectCriteria criteria = new ProjectCriteria(); -// criteria.setReference(project.getReference()); -// Project projectEntity = databaseRepository.getProjectDao().getWithCritetia(criteria).getSingleOrDefault(); -// if (projectEntity != null) project.setId(projectEntity.getId()); -// else { -// if (project.getId() == null) project.setId(UUID.randomUUID()); -// project.setType(Project.ProjectType.EXTERNAL.getValue()); -// databaseRepository.getProjectDao().createOrUpdate(project); -// } -// } - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/mapper/prefilling/PrefillingMapper.java b/dmp-backend/web/src/main/java/eu/eudat/logic/mapper/prefilling/PrefillingMapper.java deleted file mode 100644 index 7fc696885..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/mapper/prefilling/PrefillingMapper.java +++ /dev/null @@ -1,279 +0,0 @@ -package eu.eudat.logic.mapper.prefilling; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.data.TagEntity; -import eu.eudat.logic.managers.DatasetManager; -import eu.eudat.logic.managers.DatasetProfileManager; -import eu.eudat.service.remotefetcher.config.entities.DefaultPrefillingMapping; -import eu.eudat.service.remotefetcher.config.entities.PrefillingFixedMapping; -import eu.eudat.service.remotefetcher.config.entities.PrefillingGet; -import eu.eudat.service.remotefetcher.config.entities.PrefillingMapping; -import eu.eudat.utilities.helpers.StreamDistinctBy; -import eu.eudat.logic.utilities.json.JsonSearcher; -import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalSelectDataEntity; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.service.remotefetcher.models.ExternalAutocompleteFieldResult; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.stream.Collectors; -import eu.eudat.commons.enums.FieldType; - -@Component -public class PrefillingMapper { - private static final Logger logger = LoggerFactory.getLogger(PrefillingMapper.class); - private static final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - private final DatasetProfileManager datasetProfileManager; - - @Autowired - public PrefillingMapper(DatasetProfileManager datasetProfileManager) { - this.datasetProfileManager = datasetProfileManager; - } - - public DatasetWizardModel mapPrefilledEntityToDatasetWizard(Map prefilledEntity, PrefillingGet prefillingGet, String type, - DescriptionTemplateEntity profile, DatasetManager datasetManager /*, LicenseManager licenseManager*/) throws Exception { - DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); -// datasetWizardModel.setProfile(new DatasetProfileOverviewModel().fromDataModel(profile)); - DescriptionEntity descriptionEntity = new DescriptionEntity(); - //descriptionEntity.setDescriptionTemplateId(profile.getId()); //TODO - Map properties = new HashMap<>(); - JsonNode parentNode = mapper.readTree(mapper.writeValueAsString(datasetManager.getPagedProfile(datasetWizardModel, descriptionEntity))); - for (DefaultPrefillingMapping prefillingMapping: prefillingGet.getMappings()) { - List sourceKeys = Arrays.asList(prefillingMapping.getSource().split("\\.")); - Object sourceValue = null; - for (String sourceKey: sourceKeys) { - if (sourceValue == null) { - sourceValue = prefilledEntity.get(sourceKey); - } else if (sourceValue instanceof Map) { - sourceValue = ((Map)sourceValue).get(sourceKey); - } - } - try { - setValue(prefillingMapping, mapper.writeValueAsString(sourceValue), datasetWizardModel, parentNode, properties, type/*, licenseManager*/); - } - catch (Exception e) { - if (prefillingMapping.getSemanticTarget() != null && !prefillingMapping.getSemanticTarget().isEmpty()) { - logger.warn("Couldn't map " + prefillingMapping.getSemanticTarget()); - } - else if (prefillingMapping.getTarget() != null && !prefillingMapping.getTarget().isEmpty()) { - logger.warn("Couldn't map " + prefillingMapping.getTarget()); - } - } - } - for (PrefillingFixedMapping fixedMapping: prefillingGet.getFixedMappings()) { - setValue(fixedMapping, fixedMapping.getValue(), datasetWizardModel, parentNode, properties, type/*, licenseManager*/); - } - descriptionEntity.setProperties(mapper.writeValueAsString(properties)); - datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, descriptionEntity)); - return datasetWizardModel; - } - - private void setValue(PrefillingMapping prefillingMapping, String value, DatasetWizardModel datasetWizardModel, JsonNode parentNode, Map properties, String type/*, LicenseManager licenseManager*/) throws InvocationTargetException, IllegalAccessException, JsonProcessingException { - String trimRegex = prefillingMapping.getTrimRegex() != null ? prefillingMapping.getTrimRegex() : ""; - if (!value.startsWith("\"") && !value.startsWith("[") && !value.equals("null")) { - value = "\"" + value + "\""; - } - JsonNode valueNode = mapper.readTree(value); - List parsedValues = new ArrayList<>(); - if (valueNode.isArray() && (valueNode.get(0) != null && !valueNode.get(0).isTextual())) { - if (prefillingMapping.getSubSource() == null || prefillingMapping.getSubSource().isEmpty()) { - throw new IllegalArgumentException("Source value is an array but no subSource field have been set"); - } - String parsedValue; - for(int i = 0; i < valueNode.size(); i++){ - JsonNode jsonObj = valueNode.get(i); - String subSource = jsonObj.get(prefillingMapping.getSubSource()).asText(); - parsedValue = subSource.replaceAll(trimRegex, ""); - parsedValues.add(parsedValue); - } - parsedValues = parsedValues.stream().distinct().collect(Collectors.toList()); - } - String parsedValue = null; - if (valueNode.isTextual()) { - parsedValue = valueNode.textValue().replace(trimRegex, ""); - }else if (valueNode.isArray() && (valueNode.get(0) != null && valueNode.get(0).isTextual())) { - List values = new LinkedList<>(); - for (int i = 0; i < valueNode.size(); i++) { - values.add(valueNode.get(i).textValue().replace(trimRegex, "")); - } - parsedValue = String.join(", ", values); - } - - if (prefillingMapping.getTarget() != null) { - try { - String methodName = "set" + prefillingMapping.getTarget().substring(0, 1).toUpperCase(Locale.ROOT) + prefillingMapping.getTarget().substring(1); - Method setterMethod = Arrays.stream(DatasetWizardModel.class.getDeclaredMethods()) - .filter(method -> method.getName().equals(methodName)).collect(Collectors.toList()).get(0); - Class[] params = setterMethod.getParameterTypes(); - //GK: Tags Special logic - if (parsedValue != null && !parsedValue.equals("null") && prefillingMapping.getTarget().equals("tags")) { - parsedValue = mapper.valueToTree(parseTags(parsedValue)).toString(); - } - else if(!parsedValues.isEmpty() && prefillingMapping.getTarget().equals("tags")) { - parsedValue = mapper.valueToTree(parseTags(String.join(", ", parsedValues))).toString(); - } - else { - parsedValue = mapper.valueToTree(parsedValue).toString(); - } - setterMethod.invoke(datasetWizardModel, mapper.readValue(parsedValue, params[0])); - }catch (InvocationTargetException | IllegalAccessException | JsonProcessingException e) { - throw e; - } - } else { - List nodes = JsonSearcher.findNodes(parentNode, "schematics", prefillingMapping.getSemanticTarget()); - - // zenodo prefilling customizations - if(type.equals("zenodo")){ - if(prefillingMapping.getSemanticTarget().equals("rda.dataset.distribution.data_access")){ - if(parsedValue != null && parsedValue.equals("open")){ - List issuedNodes = JsonSearcher.findNodes(parentNode, "schematics", "rda.dataset.issued"); - if(!issuedNodes.isEmpty()){ - String issuedIdNode = issuedNodes.get(0).get("id").asText(); - String issuedValue = (String) properties.get(issuedIdNode); - List licStartDateNodes = JsonSearcher.findNodes(parentNode, "schematics", "rda.dataset.distribution.license.start_date"); - for (JsonNode licStartDateNode : licStartDateNodes) { - String licStartDateId = licStartDateNode.get(0) != null ? licStartDateNode.get(0).get("id").asText() : licStartDateNode.get("id").asText(); - properties.put(licStartDateId, issuedValue); - } - } - } - } - - if (prefillingMapping.getSemanticTarget().equals("rda.dataset.distribution.available_until") && parsedValue != null && !parsedValue.equals("null")) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd"); - LocalDate date = LocalDate.parse(parsedValue, formatter); - date = date.plusYears(20); - parsedValue = date.toString(); - } - } - - for (JsonNode node: nodes) { - String id = node.isArray() ? node.get(0).get("id").asText() : node.get("id").asText(); - String renderStyle = node.isArray() ? node.get(0).get("viewStyle").get("renderStyle").asText() : node.get("viewStyle").get("renderStyle").asText(); - - switch (FieldType.of(renderStyle)) { - case EXTERNAL_SELECT: - case SELECT: - if (parsedValues.isEmpty()) - parsedValues.add(parsedValue); - if (!parsedValues.stream().allMatch(Objects::isNull)) { - properties.put(id, parseComboBoxValues(node, parsedValues)); - } - break; - case TAGS: - if(parsedValues.isEmpty()) { - properties.put(id, mapper.valueToTree(parseTags(parsedValue)).toString()); - } - else { - properties.put(id, mapper.valueToTree(parseTags(String.join(", ", parsedValues))).toString()); - } - break; - case DATASET_IDENTIFIER: - JSONObject datasetID = new JSONObject(); - datasetID.put("identifier", parsedValue); - if(type.equals("zenodo")){ - datasetID.put("type", "doi"); - } - properties.put(id, datasetID.toString()); - break; - case LICENSES: -// try { -// List licenses = licenseManager.getLicenses("", ""); -// String finalParsedValue = parsedValue; -// licenses = licenses.stream().filter(license -> license.getPid().equals(finalParsedValue)).collect(Collectors.toList()); -// boolean isMultiAutocomplete = node.isArray() ? node.get(0).get("data").get("multiAutoComplete").booleanValue() : node.get("data").get("multiAutoComplete").booleanValue(); -// if(isMultiAutocomplete){ -// List lic = new ArrayList<>(); -// for(LicenseModel license: licenses){ -// lic.add(mapper.writeValueAsString(license)); -// } -// properties.put(id, mapper.writeValueAsString(lic)); -// } else { -// properties.put(id, mapper.writeValueAsString(licenses.get(0))); -// } -// } -// catch (MyNotFoundException | HugeResultSetException e){ -// properties.put(id, parsedValue); -// } - break; - default: - if (!parsedValues.isEmpty()) - properties.put(id, String.join(", ", parsedValues)); - else { - properties.put(id, parsedValue); - } - break; - } - } - } - } - - private Object parseComboBoxValues(JsonNode node, List parsedValues) throws JsonProcessingException { - List normalizedValues = new ArrayList<>(); - boolean isMultiSelect; - String type = node.isArray() ? node.get(0).get("data").get("type").asText() : node.get("data").get("type").asText(); - if(type.equals("autocomplete")) { - JsonNode dataNode = node.isArray() ? node.get(0).get("data") : node.get("data"); - ExternalSelectDataEntity externalSelectDataEntity = mapper.treeToValue(dataNode, ExternalSelectDataEntity.class); - isMultiSelect = externalSelectDataEntity.getMultipleSelect(); - for (String format : parsedValues) { - List result = new ArrayList<>(); - try { - result = datasetProfileManager.getAutocomplete(externalSelectDataEntity, format); - } - catch (Exception e) { - logger.error(e.getMessage(), e); - } - result = result.stream().filter(StreamDistinctBy.distinctByKey(ExternalAutocompleteFieldResult::getId)).collect(Collectors.toList()); - if(!result.isEmpty()){ - List tempValues = new LinkedList<>(); - for (ExternalAutocompleteFieldResult f : result) { - if (format.equals(f.getId()) || f.getLabel().toUpperCase(Locale.ROOT).contains(format.toUpperCase(Locale.ROOT))) - tempValues.add(mapper.valueToTree(f).toString()); - } - if (isMultiSelect) - normalizedValues.addAll(tempValues); - else if (!tempValues.isEmpty()) - normalizedValues.add(tempValues.get(0)); - } - } - return !normalizedValues.isEmpty() ? (isMultiSelect ? normalizedValues : normalizedValues.get(0)) : null; - } else { - JsonNode optionsNode = node.isArray() ? node.get(0).get("data").get("options") : node.get("data").get("options"); - isMultiSelect = node.isArray() ? node.get(0).get("data").get("multiList").booleanValue() : node.get("data").get("multiList").booleanValue(); - for (int i = 0; i < optionsNode.size(); i++) { - String value = optionsNode.get(i).get("value").textValue(); - if (parsedValues.contains(value)) { - normalizedValues.add(value); - } - } - List normalizedStringValues = normalizedValues.stream().map(Object::toString).collect(Collectors.toList()); - - return !normalizedValues.isEmpty() ? (isMultiSelect ? String.join(", ", normalizedStringValues) : normalizedValues.get(0)) : null; - } - } - - private static List parseTags(String value) throws JsonProcessingException { - if (value == null || value.isEmpty()) - return new LinkedList<>(); - String[] rawTags = value.split(", "); - List parsedTags = new LinkedList<>(); - for (String rawTag : rawTags) { - parsedTags.add(new TagEntity()); - } - return parsedTags; - } -} 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 1fed11fe0..44fd59e82 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 @@ -4,13 +4,6 @@ import eu.eudat.data.dao.entities.*; public interface DatabaseRepository { - - DatasetDao getDatasetDao(); - - - - - FileUploadDao getFileUploadDao(); void detachEntity(T entity); 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 a4ab22cb5..5db7935c4 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 @@ -8,8 +8,6 @@ import org.springframework.stereotype.Service; @Service("databaseRepository") public class DatabaseRepositoryImpl implements DatabaseRepository { - private DatasetDao datasetDao; - @@ -18,20 +16,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository { private EntityManager entityManager; - @Autowired - private void setDatasetDao(DatasetDao datasetDao) { - this.datasetDao = datasetDao; - } - - - @Autowired - - @Override - public DatasetDao getDatasetDao() { - return datasetDao; - } - - @Autowired public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDatasetModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDatasetModel.java deleted file mode 100644 index fd842d71b..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dashboard/recent/model/RecentDatasetModel.java +++ /dev/null @@ -1,83 +0,0 @@ -package eu.eudat.models.data.dashboard.recent.model; - -import eu.eudat.data.DescriptionEntity; - -public class RecentDatasetModel extends RecentActivityModel { - private String dmp; - private String dmpId; - - public String getDmp() { - return dmp; - } - - public void setDmp(String dmp) { - this.dmp = dmp; - } - - public String getDmpId() { - return dmpId; - } - - public void setDmpId(String dmpId) { - this.dmpId = dmpId; - } - - @Override - public RecentActivityModel fromEntity(DescriptionEntity entity) { - //TODO - this.setType(RecentActivityType.DATASET.getIndex()); -// this.setId(entity.getId().toString()); -// this.setTitle(entity.getLabel()); -// this.setCreated(entity.getCreated()); -// this.setModified(entity.getModified()); -// this.setStatus(entity.getStatus()); -// this.setVersion(entity.getDmp() != null ? entity.getDmp().getVersion(): 0); -// this.setFinalizedAt(entity.getFinalizedAt()); -// this.setPublishedAt(entity.getDmp() != null ? entity.getDmp().getPublishedAt() : new Date()); -// this.setProfile(entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()): null); -// if (entity.getDmp() != null && entity.getDmp().getGrant() != null) { -// this.setGrant(entity.getDmp().getGrant().getLabel()); -// } -// this.setDmp( entity.getDmp() != null ? entity.getDmp().getLabel() : ""); -// this.setDmpId(entity.getDmp() != null ? entity.getDmp().getId().toString() : ""); -// this.setPublic(entity.getDmp().isPublic()); -// this.setUsers(entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList())); - return this; - } - - public RecentDatasetModel fromDmpEntity(DescriptionEntity entity) { - //TODO - this.setType(RecentActivityType.DATASET.getIndex()); -// this.setId(entity.getId().toString()); -// this.setTitle(entity.getLabel()); -// this.setCreated(entity.getCreated()); -// this.setModified(entity.getModified()); -// this.setStatus(entity.getStatus()); -// this.setVersion(entity.getDmp() != null ? entity.getDmp().getVersion(): 0); -// this.setFinalizedAt(entity.getFinalizedAt()); -// this.setPublishedAt(entity.getDmp() != null ? entity.getDmp().getPublishedAt() : new Date()); -// this.setProfile(entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()) : null); -// if (entity.getDmp() != null && entity.getDmp().getGrant() != null) { -// this.setGrant(entity.getDmp().getGrant().getLabel()); -// } -// this.setDmp( entity.getDmp() != null ? entity.getDmp().getLabel() : ""); -// this.setDmpId(entity.getDmp() != null ? entity.getDmp().getId().toString() : ""); - return this; - } - - - @Override - public RecentDatasetModel fromDataModel(DescriptionEntity entity) { - return (RecentDatasetModel) this.fromEntity(entity); - } - - @Override - public DescriptionEntity toDataModel() throws Exception { - return null; - } - - @Override - public String getHint() { - return "recentDatasetModel"; - } -} 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 deleted file mode 100644 index f844cdf12..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/Dataset.java +++ /dev/null @@ -1,155 +0,0 @@ -package eu.eudat.models.data.dataset; - -import eu.eudat.data.DescriptionEntity; -import eu.eudat.models.DataModel; - -import java.util.Date; -import java.util.UUID; - -public class Dataset implements DataModel { - private UUID id; - private String label; - private String reference; - private String uri; - private String description; - private short status; - private String properties; - private Date created; - - 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 String getReference() { - return reference; - } - - public void setReference(String reference) { - this.reference = reference; - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public short getStatus() { - return status; - } - - public void setStatus(short status) { - this.status = status; - } - - public String getProperties() { - return properties; - } - - public void setProperties(String properties) { - this.properties = properties; - } - - - 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 DataManagementPlan getDmp() { -// return dmp; -// } -// -// public void setDmp(DataManagementPlan dmp) { -// this.dmp = dmp; -// } - - public Dataset fromDataModel(DescriptionEntity entity) { - //TODO -// this.id = entity.getId(); -// this.label = entity.getLabel(); -// this.properties = entity.getProperties(); -// this.reference = entity.getReference(); -// this.description = entity.getDescription(); -// this.profile = new DatasetProfileListingModel(); -// this.profile.fromDataModel(entity.getProfile()); -// this.registries = entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()); -// this.dataRepositories = entity.getDatasetDataRepositories().stream().map(item -> new DataRepository().fromDataModel(item.getDataRepository())).collect(Collectors.toList()); -// this.services = entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList()); -// this.created = entity.getCreated(); - return this; - } - - public DescriptionEntity toDataModel() throws Exception { - DescriptionEntity entity = new DescriptionEntity(); - //TODO -// entity.setId(this.id); -// entity.setLabel(this.label); -// entity.setReference(this.reference); -// entity.setUri(this.uri); -// entity.setProperties(this.properties); -// entity.setStatus(this.status); -// entity.setDmp(dmp.toDataModel()); -// entity.setDescription(this.description); -// entity.setCreated(this.created != null ? this.created : new Date()); -// entity.setModified(new Date()); -// entity.setProfile(profile.toDataModel()); ///TODO -// if (!this.registries.isEmpty()) { -// entity.setRegistries(new HashSet()); -// for (Registry registry : this.registries) { -// entity.getRegistries().add(registry.toDataModel()); -// } -// } -// -// if (!this.dataRepositories.isEmpty()) { -// entity.setDatasetDataRepositories(new HashSet<>()); -// for (DataRepository dataRepositoryModel : this.dataRepositories) { -// DatasetDataRepository datasetDataRepository = new DatasetDataRepository(); -// eu.eudat.data.old.DataRepository dataRepository = dataRepositoryModel.toDataModel(); -// datasetDataRepository.setDataRepository(dataRepository); -// entity.getDatasetDataRepositories().add(datasetDataRepository); -// } -// } -// -// if (!this.services.isEmpty()) { -// entity.setServices(new HashSet()); -// for (Service serviceModel : this.services) { -// eu.eudat.data.old.Service service = serviceModel.toDataModel(); -// DatasetService datasetService = new DatasetService(); -// datasetService.setService(service); -// entity.getServices().add(datasetService); -// } -// } - return entity; - } - - @Override - public String getHint() { - return null; - } -} 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 deleted file mode 100644 index 729a2f6ce..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/dataset/DatasetOverviewModel.java +++ /dev/null @@ -1,122 +0,0 @@ -package eu.eudat.models.data.dataset; - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.model.DmpUser; -import eu.eudat.models.DataModel; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; - -public class DatasetOverviewModel implements DataModel { - - private UUID id; - private String label; - private DescriptionStatus status; - private List users; -// private DataManagementPlanOverviewModel dmp; - private String description; - private Boolean isPublic; - private Instant modified; - private Instant created; - - 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 DescriptionStatus getStatus() { - return status; - } - public void setStatus(DescriptionStatus status) { - this.status = status; - } - - public List getUsers() { - return users; - } - - public void setUsers(List users) { - this.users = users; - } - -// public DataManagementPlanOverviewModel getDmp() { -// return dmp; -// } -// -// public void setDmp(DataManagementPlanOverviewModel dmp) { -// this.dmp = dmp; -// } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Boolean getPublic() { - return isPublic; - } - - public void setPublic(Boolean aPublic) { - isPublic = aPublic; - } - - public Instant getModified() { - return modified; - } - - public void setModified(Instant modified) { - this.modified = modified; - } - - public Instant getCreated() { - return created; - } - - public void setCreated(Instant created) { - this.created = created; - } - - @Override - public DatasetOverviewModel fromDataModel(DescriptionEntity entity) { - //TODO Implement it on transfer -// this.id = entity.getId(); -// this.label = entity.getLabel(); -// this.status = entity.getStatus(); -// this.datasetTemplate = new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()); -// this.users = entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()); -// this.dmp = new DataManagementPlanOverviewModel().fromDataModel(entity.getDmp()); -// if (entity.getDmp().getGrant() != null) { -// this.grant = new GrantOverviewModel().fromDataModel(entity.getDmp().getGrant()); -// } -// this.description = entity.getDescription(); -// this.isPublic = entity.getDmp().isPublic(); -// this.modified = entity.getCreatedAt(); -// this.created = entity.getUpdatedAt(); - - return this; - } - - @Override - public DescriptionEntity toDataModel() throws Exception { - 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 deleted file mode 100644 index 582dfa5d7..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetWizardModel.java +++ /dev/null @@ -1,274 +0,0 @@ -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.user.composite.PagedDatasetProfile; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; - - -public class DatasetWizardModel implements DataModel { - - private UUID id; - private String label; - private String reference; - private String uri; - private String description; - private DescriptionStatus status; - private Instant created; -// private DataManagementPlan dmp; - private Integer dmpSectionIndex; - private PagedDatasetProfile datasetProfileDefinition; -// private List tags; //TODO - private Boolean isProfileLatestVersion; - private Instant modified; - - 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 String getReference() { - return reference; - } - public void setReference(String reference) { - this.reference = reference; - } - - public String getUri() { - return uri; - } - public void setUri(String uri) { - this.uri = uri; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - public DescriptionStatus getStatus() { - return status; - } - public void setStatus(DescriptionStatus status) { - this.status = status; - } - - public Instant getCreated() { - return created; - } - public void setCreated(Instant created) { - this.created = created; - } - -// public DataManagementPlan getDmp() { -// return dmp; -// } -// public void setDmp(DataManagementPlan dmp) { -// this.dmp = dmp; -// } - - public Integer getDmpSectionIndex() { - return dmpSectionIndex; - } - public void setDmpSectionIndex(Integer dmpSectionIndex) { - this.dmpSectionIndex = dmpSectionIndex; - } - - public PagedDatasetProfile getDatasetProfileDefinition() { - return datasetProfileDefinition; - } - public void setDatasetProfileDefinition(PagedDatasetProfile datasetProfileDefinition) { - this.datasetProfileDefinition = datasetProfileDefinition; - } - - - -// public List getTags() { -// return tags; -// } -// public void setTags(List tags) { -// this.tags = tags; -// } - - public Boolean getIsProfileLatestVersion() { - return isProfileLatestVersion; - } - public void setIsProfileLatestVersion(Boolean profileLatestVersion) { - isProfileLatestVersion = profileLatestVersion; - } - - public Instant getModified() { - return modified; - } - public void setModified(Instant modified) { - this.modified = modified; - } - - @Override - public DatasetWizardModel fromDataModel(DescriptionEntity entity) { - //TODO Implement it on transfer -// this.id = entity.getId(); -// this.label = entity.getLabel(); -// this.status = entity.getStatus(); -// this.reference = entity.getReference(); -// this.description = entity.getDescription(); -// this.profile = new DatasetProfileOverviewModel(); -// this.profile = this.profile.fromDataModel(entity.getProfile()); -// this.uri = entity.getUri(); -// this.registries = entity.getRegistries() != null ? entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.dataRepositories = entity.getDatasetDataRepositories() != null ? entity.getDatasetDataRepositories().stream().map(item -> { -// DataRepository dataRepository = new DataRepository().fromDataModel(item.getDataRepository()); -// if (item.getData() != null) { -// Map> data = (Map>) JSONValue.parse(item.getData()); -// Map values = data.get("data"); -// dataRepository.setInfo(values.get("info")); -// } -// return dataRepository; -// }).collect(Collectors.toList()) : new ArrayList<>(); -// this.services = entity.getServices() != null ? entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList()) : new ArrayList<>(); -// this.created = entity.getCreated(); -// this.dmp = new DataManagementPlan().fromDataModelNoDatasets(entity.getDmp()); -// this.dmpSectionIndex = entity.getDmpSectionIndex(); -// this.externalDatasets = entity.getDatasetExternalDatasets() != null ? entity.getDatasetExternalDatasets().stream().map(item -> { -// ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(item.getExternalDataset()); -// if (item.getData() != null) { -// Map> data = (Map>) JSONValue.parse(item.getData()); -// Map values = data.get("data"); -// externalDatasetListingModel.setInfo(values.get("info")); -// externalDatasetListingModel.setType(Integer.parseInt(values.get("type"))); -// } -// return externalDatasetListingModel; -// }).collect(Collectors.toList()) : new ArrayList<>(); -// this.modified = entity.getUpdatedAt(); - return this; - } - - public DatasetWizardModel fromDataModelNoDmp(DescriptionEntity entity) { - //TODO Implement it on transfer -// this.id = entity.getId(); -// this.label = entity.getLabel(); -// this.status = entity.getStatus(); -// this.reference = entity.getReference(); -// this.description = entity.getDescription(); -// this.profile = new DatasetProfileOverviewModel(); -// this.profile = this.profile.fromDataModel(entity.getProfile()); -// this.uri = entity.getUri(); -// this.dmpSectionIndex = entity.getDmpSectionIndex(); -// this.registries = entity.getRegistries() != null ? entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); -// this.dataRepositories = entity.getDatasetDataRepositories() != null ? entity.getDatasetDataRepositories().stream().map(item -> { -// DataRepository dataRepository = new DataRepository().fromDataModel(item.getDataRepository()); -// if (item.getData() != null) { -// Map> data = (Map>) JSONValue.parse(item.getData()); -// Map values = data.get("data"); -// dataRepository.setInfo(values.get("info")); -// } -// return dataRepository; -// }).collect(Collectors.toList()) : new ArrayList<>(); -// this.services = entity.getServices() != null ? entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList()) : new ArrayList<>(); -// this.created = entity.getCreated(); -// this.externalDatasets = entity.getDatasetExternalDatasets() != null ? entity.getDatasetExternalDatasets().stream().map(item -> { -// ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(item.getExternalDataset()); -// if (item.getData() != null) { -// Map> data = (Map>) JSONValue.parse(item.getData()); -// Map values = data.get("data"); -// externalDatasetListingModel.setInfo(values.get("info")); -// externalDatasetListingModel.setType(Integer.parseInt(values.get("type"))); -// } -// return externalDatasetListingModel; -// }).collect(Collectors.toList()) : new ArrayList<>(); -// this.modified = entity.getModified(); - return this; - } - - @Override - public DescriptionEntity toDataModel() throws Exception { - DescriptionEntity entity = new DescriptionEntity(); - //TODO Implement it on transfer -// entity.setId(this.id); -// entity.setLabel(this.label); -// entity.setReference(this.reference); -// entity.setUri(this.uri); -// entity.setStatus(this.status); -// if (this.status == (int) DescriptionEntity.Status.FINALISED.getValue()) -// entity.setFinalizedAt(new Date()); -// DMP dmp = new DMP(); -// dmp.setId(this.dmp.getId()); -// entity.setDmp(dmp); -// entity.setDmpSectionIndex(this.dmpSectionIndex); -// entity.setDescription(this.description); -// entity.setCreated(this.created != null ? this.created : new Date()); -// entity.setModified(new Date()); -// DescriptionTemplateEntity profile = new DescriptionTemplateEntity(); -// profile.setId(this.profile.getId()); -// entity.setProfile(profile); -// if (this.registries != null && !this.registries.isEmpty()) { -// entity.setRegistries(new HashSet<>()); -// for (Registry registry : this.registries) { -// entity.getRegistries().add(registry.toDataModel()); -// } -// } -// -// if (this.dataRepositories != null && !this.dataRepositories.isEmpty()) { -// entity.setDatasetDataRepositories(new HashSet<>()); -// for (DataRepository dataRepositoryModel : this.dataRepositories) { -// eu.eudat.data.old.DataRepository dataRepository = dataRepositoryModel.toDataModel(); -// DatasetDataRepository datasetDataRepository = new DatasetDataRepository(); -// datasetDataRepository.setDataRepository(dataRepository); -// Map> data = new HashMap<>(); -// Map values = new HashMap<>(); -// values.put("info", dataRepositoryModel.getInfo()); -// data.put("data", values); -// datasetDataRepository.setData(JSONValue.toJSONString(data)); -// entity.getDatasetDataRepositories().add(datasetDataRepository); -// } -// } -// -// if (this.services != null && !this.services.isEmpty()) { -// entity.setServices(new HashSet<>()); -// for (Service serviceModel : this.services) { -// eu.eudat.data.old.Service service = serviceModel.toDataModel(); -// DatasetService datasetService = new DatasetService(); -// datasetService.setService(service); -// entity.getServices().add(datasetService); -// } -// } -// -// if (this.externalDatasets != null && !this.externalDatasets.isEmpty()) { -// entity.setDatasetExternalDatasets(new HashSet<>()); -// for (ExternalDatasetListingModel externalDataset : this.externalDatasets) { -// ExternalDataset externalDatasetEntity = externalDataset.toDataModel(); -// DatasetExternalDataset datasetExternalDataset = new DatasetExternalDataset(); -// datasetExternalDataset.setExternalDataset(externalDatasetEntity); -// Map> data = new HashMap<>(); -// Map values = new HashMap<>(); -// values.put("info",externalDataset.getInfo()); -// values.put("type",externalDataset.getType().toString()); -// data.put("data",values); -// datasetExternalDataset.setData(JSONValue.toJSONString(data)); -// entity.getDatasetExternalDatasets().add(datasetExternalDataset); -// } -// } - return entity; - } - - - @Override - public String getHint() { - return "datasetWizardModel"; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetsToBeFinalized.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetsToBeFinalized.java deleted file mode 100644 index 49ac82524..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/datasetwizard/DatasetsToBeFinalized.java +++ /dev/null @@ -1,15 +0,0 @@ -package eu.eudat.models.data.datasetwizard; - -import java.util.List; -import java.util.UUID; - -public class DatasetsToBeFinalized { - private List uuids; - - public List getUuids() { - return uuids; - } - public void setUuids(List uuids) { - this.uuids = uuids; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DatasetListingModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DatasetListingModel.java deleted file mode 100644 index 9dca7f902..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/listingmodels/DatasetListingModel.java +++ /dev/null @@ -1,186 +0,0 @@ -package eu.eudat.models.data.listingmodels; - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.model.DmpUser; -import eu.eudat.models.DataModel; - -import java.time.Instant; -import java.util.List; - - -public class DatasetListingModel implements DataModel { - private String id; - private String label; - private String grant; - private String dmp; - private String dmpId; - private DescriptionStatus status; - private Instant created; - private Instant modified; - private String description; - private Instant finalizedAt; - private Instant dmpPublishedAt; - private int version; - private List users; - private Boolean isPublic; - - 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 String getDmp() { - return dmp; - } - public void setDmp(String dmp) { - this.dmp = dmp; - } - - public String getDmpId() { - return dmpId; - } - public void setDmpId(String dmpId) { - this.dmpId = dmpId; - } - - public DescriptionStatus getStatus() { - return status; - } - public void setStatus(DescriptionStatus 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; - } - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - - public Instant getFinalizedAt() { - return finalizedAt; - } - public void setFinalizedAt(Instant finalizedAt) { - this.finalizedAt = finalizedAt; - } - - public Instant getDmpPublishedAt() { - return dmpPublishedAt; - } - public void setDmpPublishedAt(Instant dmpPublishedAt) { - this.dmpPublishedAt = dmpPublishedAt; - } - - public int getVersion() { - return version; - } - public void setVersion(int version) { - this.version = version; - } - - public List getUsers() { - return users; - } - - public void setUsers(List users) { - this.users = users; - } - - public Boolean getPublic() { - return isPublic; - } - - public void setPublic(Boolean aPublic) { - isPublic = aPublic; - } - - @Override - public DatasetListingModel fromDataModel(DescriptionEntity entity) { - //TODO Implement it on transfer -// this.id = entity.getId() != null ? entity.getId().toString() : ""; -// this.label = entity.getLabel(); -// this.created = entity.getCreatedAt(); -// this.modified = entity.getUpdatedAt(); -// this.grant = (entity.getDmp() != null && entity.getDmp().getGrant() != null) ? entity.getDmp().getGrant().getLabel() : ""; -// this.dmp = entity.getDmp() != null ? entity.getDmp().getLabel() : ""; -// this.dmpId = entity.getDmp() != null ? entity.getDmp().getId().toString() : ""; -// this.profile = entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()) : null; -// this.description = entity.getDescription(); -// this.status = entity.getStatus(); -// if (entity.getFinalizedAt() == null && entity.getStatus() == DescriptionStatus.Finalized) { -// this.finalizedAt = entity.getDmp().getFinalizedAt(); -// } else { -// this.finalizedAt = entity.getFinalizedAt(); -// } -// this.dmpPublishedAt = entity.getDmp().getPublishedAt(); -// this.version = entity.getDmp().getVersion(); -// this.users = entity.getDmp() != null ? entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()) : new ArrayList<>(); -// this.isPublic = entity.getDmp() != null ? entity.getDmp().isPublic() : false; - return this; - } - - @Override - public DescriptionEntity toDataModel() { - //TODO Implement it on transfer - DescriptionEntity entity = new DescriptionEntity(); -// entity.setId(UUID.fromString(this.getId())); -// entity.setLabel(this.getLabel()); -// entity.setCreatedAt(this.getCreated()); -// entity.setUpdatedAt(this.getModified()); -// entity.setDescription(this.getDescription()); -// entity.setFinalizedAt(this.getFinalizedAt()); -// entity.setStatus(this.getStatus()); -// DMP dmp = new DMP(); -// if (this.getGrant() != null && !this.getGrant().isEmpty()) { -// Grant grant = new Grant(); -// grant.setLabel(this.getGrant()); -// dmp.setGrant(grant); -// } -// dmp.setLabel(this.getDmp()); -// dmp.setId(UUID.fromString(this.getDmpId())); -// dmp.setPublishedAt(this.getDmpPublishedAt()); -// dmp.setVersion(this.getVersion()); -// dmp.setUsers(this.getUsers().stream().map(UserInfoListingModel::toDataModel).collect(Collectors.toSet())); -// dmp.setPublic(this.getPublic()); -// dmp.setFinalizedAt(this.getFinalizedAt()); -// entity.setDmp(dmp); -// entity.setProfile(this.getProfile() != null ? this.getProfile().toDataModel() : null); - return entity; - } - - @Override - public String getHint() { - return "datasetListingModel"; - } -} 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 deleted file mode 100644 index 072e894f5..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetCreateWizardModel.java +++ /dev/null @@ -1,14 +0,0 @@ -package eu.eudat.models.data.quickwizard; - -public class DatasetCreateWizardModel { - - private DatasetQuickWizardModel datasets; - - - public DatasetQuickWizardModel getDatasets() { - return datasets; - } - public void setDatasets(DatasetQuickWizardModel datasets) { - this.datasets = 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 deleted file mode 100644 index 21930b7f5..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetDescriptionQuickWizardModel.java +++ /dev/null @@ -1,40 +0,0 @@ -package eu.eudat.models.data.quickwizard; - - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; -import eu.eudat.models.data.user.composite.PagedDatasetProfile; - -import java.time.Instant; -import java.util.Date; - -public class DatasetDescriptionQuickWizardModel extends PagedDatasetProfile { - - private String datasetLabel; - - public String getDatasetLabel() { - return datasetLabel; - } - - public void setDatasetLabel(String datasetLabel) { - this.datasetLabel = datasetLabel; - } - - - 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.setStatus(DescriptionStatus.of((short)this.getStatus())); - //newDataset.setStatus(Dataset.Status.SAVED.getValue()); - - - newDataset.setDatasetProfileDefinition((PagedDatasetProfile) this); - return newDataset; - } - - -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetProfileCreateWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetProfileCreateWizardModel.java deleted file mode 100644 index 9efd07500..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetProfileCreateWizardModel.java +++ /dev/null @@ -1,14 +0,0 @@ -package eu.eudat.models.data.quickwizard; - -import java.util.UUID; - -public class DatasetProfileCreateWizardModel { - private UUID id; - private String label; - - 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; } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetQuickWizardModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetQuickWizardModel.java deleted file mode 100644 index b35ee75fd..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/DatasetQuickWizardModel.java +++ /dev/null @@ -1,15 +0,0 @@ -package eu.eudat.models.data.quickwizard; - -import java.util.List; - -public class DatasetQuickWizardModel { - private List datasetsList; - - public List getDatasetsList() { - return datasetsList; - } - - public void setDatasetsList(List datasetsList) { - this.datasetsList = datasetsList; - } -} 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 deleted file mode 100644 index 8e57910c0..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/quickwizard/QuickWizardModel.java +++ /dev/null @@ -1,22 +0,0 @@ -package eu.eudat.models.data.quickwizard; - - -public class QuickWizardModel { - - private DatasetQuickWizardModel datasets; - private int status; - - public DatasetQuickWizardModel getDatasets() { - return datasets; - } - public void setDatasets(DatasetQuickWizardModel datasets) { - this.datasets = datasets; - } - - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DatasetRDAExportModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DatasetRDAExportModel.java index 1ba028edc..844b89bf7 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DatasetRDAExportModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DatasetRDAExportModel.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import eu.eudat.data.DescriptionEntity; -import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.xml.XmlBuilder; import org.json.JSONArray; import org.json.JSONObject; @@ -150,7 +149,7 @@ public class DatasetRDAExportModel { } - public DatasetRDAExportModel fromDataModel(DescriptionEntity descriptionEntity, DatasetManager datasetManager) { + public DatasetRDAExportModel fromDataModel(DescriptionEntity descriptionEntity) { // Map of template Ids to rda values. JSONObject jObject = new JSONObject(descriptionEntity.getProperties()); Map templateIdsToValues = jObject.toMap(); @@ -166,9 +165,11 @@ public class DatasetRDAExportModel { // Transform the answered dataset description to json so we can parse it and fill the rda model. JSONObject datasetDescriptionJson = null; try { - String jsonResult = mapper.writeValueAsString(datasetManager.getSingle(descriptionEntity.getId().toString()).getDatasetProfileDefinition()); + //TODO + //String jsonResult = mapper.writeValueAsString(datasetManager.getSingle(descriptionEntity.getId().toString()).getDatasetProfileDefinition()); + String jsonResult = mapper.writeValueAsString(null); datasetDescriptionJson = new JSONObject(jsonResult); - } catch (JsonProcessingException | InvalidApplicationException e) { + } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); } setMultiplicityIdToFieldSetId(datasetDescriptionJson); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java index ee351689a..036eafecd 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/DmpRDAExportModel.java @@ -1,17 +1,8 @@ package eu.eudat.models.data.rda; -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.commons.enums.IsActive; import eu.eudat.data.DmpEntity; -import eu.eudat.data.EntityDoiEntity; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.logic.managers.DatasetManager; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; import java.util.List; -import java.util.stream.Collectors; public class DmpRDAExportModel { private ContactRDAExportModel contact; @@ -127,7 +118,7 @@ public class DmpRDAExportModel { this.title = title; } - public DmpRDAExportModel fromDataModel(DmpEntity entity, DatasetManager datasetManager) { + public DmpRDAExportModel fromDataModel(DmpEntity entity) { DmpRDAExportModel dmpRda = new DmpRDAExportModel(); //TODO // dmpRda.contact = new ContactRDAExportModel().fromDataModel(entity.getUsers().stream().filter(x -> x.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser()); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/RDAExportModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/RDAExportModel.java index cfa83ff4a..7074be825 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/RDAExportModel.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/rda/RDAExportModel.java @@ -1,7 +1,6 @@ package eu.eudat.models.data.rda; import eu.eudat.data.DmpEntity; -import eu.eudat.logic.managers.DatasetManager; public class RDAExportModel { private DmpRDAExportModel dmp; @@ -13,8 +12,8 @@ public class RDAExportModel { this.dmp = dmp; } - public RDAExportModel fromDataModel(DmpEntity dmp, DatasetManager datasetManager) { - this.dmp = new DmpRDAExportModel().fromDataModel(dmp, datasetManager); + public RDAExportModel fromDataModel(DmpEntity dmp) { + this.dmp = new DmpRDAExportModel().fromDataModel(dmp); return this; } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DatasetUrlListing.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DatasetUrlListing.java deleted file mode 100644 index 9ec92723c..000000000 --- a/dmp-backend/web/src/main/java/eu/eudat/models/data/urls/DatasetUrlListing.java +++ /dev/null @@ -1,30 +0,0 @@ -package eu.eudat.models.data.urls; - -import eu.eudat.data.DescriptionEntity; - -import java.util.UUID; - -/** - * Created by ikalyvas on 7/23/2018. - */ -public class DatasetUrlListing extends UrlListing { - @Override - public DatasetUrlListing fromDataModel(DescriptionEntity entity) { - this.setLabel(entity.getLabel()); - this.setUrl(entity.getId().toString()); - return this; - } - - @Override - public DescriptionEntity toDataModel() { - DescriptionEntity entity = new DescriptionEntity(); - entity.setId(UUID.fromString(this.getUrl())); - entity.setLabel(this.getLabel()); - return entity; - } - - @Override - public String getHint() { - return null; - } -} diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DatasetRDAMapper.java b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DatasetRDAMapper.java index bfbe1ab39..0a4b50e2b 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DatasetRDAMapper.java +++ b/dmp-backend/web/src/main/java/eu/eudat/models/rda/mapper/DatasetRDAMapper.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import eu.eudat.data.DescriptionEntity; import eu.eudat.data.DescriptionTemplateEntity; import eu.eudat.data.TagEntity; -import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.utilities.json.JsonSearcher; -import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.rda.*; import eu.eudat.query.DmpDescriptionTemplateQuery; import gr.cite.tools.data.query.QueryFactory; @@ -33,13 +31,11 @@ import java.util.stream.StreamSupport; public class DatasetRDAMapper { private static final Logger logger = LoggerFactory.getLogger(DatasetRDAMapper.class); - private DatasetManager datasetManager; private ApiContext apiContext; private final QueryFactory queryFactory; @Autowired - public DatasetRDAMapper(DatasetManager datasetManager, ApiContext apiContext, QueryFactory queryFactory) { - this.datasetManager = datasetManager; + public DatasetRDAMapper(ApiContext apiContext, QueryFactory queryFactory) { this.apiContext = apiContext; this.queryFactory = queryFactory; } @@ -57,10 +53,11 @@ public class DatasetRDAMapper { try { JSONObject jObject = new JSONObject(descriptionEntity.getProperties()); Map templateIdsToValues = jObject.toMap(); - DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(descriptionEntity); - datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, descriptionEntity)); +// DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(descriptionEntity); +// datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, descriptionEntity)); ObjectMapper mapper = new ObjectMapper(); - String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); +// String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); + String datasetDescriptionJson = mapper.writeValueAsString(null); JsonNode datasetDescriptionObj = mapper.readTree(datasetDescriptionJson); List idNodes = JsonSearcher.findNodes(datasetDescriptionObj, "schematics", "rda.dataset.dataset_id"); if (!idNodes.isEmpty()) { @@ -298,12 +295,13 @@ public class DatasetRDAMapper { } try { Map properties = new HashMap<>(); - DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); //TODO + //DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); //datasetWizardModel.setProfile(new DatasetProfileOverviewModel().fromDataModel(entity.getProfile())); - datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, entity)); +// datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, entity)); ObjectMapper mapper = new ObjectMapper(); - String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); +// String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); + String datasetDescriptionJson = mapper.writeValueAsString(null); JsonNode datasetDescriptionObj = mapper.readTree(datasetDescriptionJson); List typeNodes = JsonSearcher.findNodes(datasetDescriptionObj, "schematics", "rda.dataset.type");