Merge branch 'ui-refactoring' into Development

# Conflicts:
#	dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetProfileManager.java
#	dmp-frontend/src/app/dataset-profile-form/form/form.component.html
#	dmp-frontend/src/app/dataset-profile-form/form/form.component.ts
#	dmp-frontend/src/app/services/datasetProfileAdmin/datasetProfileAfmin.service.ts
This commit is contained in:
Diamantis Tziotzios 2019-05-17 10:34:37 +03:00
commit 6714ba99ee
1275 changed files with 45273 additions and 18854 deletions

View File

@ -1,6 +1,7 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Project;
import java.util.Date;
@ -10,39 +11,17 @@ import java.util.UUID;
public class DataManagementPlanCriteria extends Criteria<DMP> {
private Date periodStart;
private Date periodEnd;
private List<eu.eudat.data.entities.Project> projects;
private boolean allVersions;
private List<UUID> groupIds;
private List<eu.eudat.data.entities.Project> projects;
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
public List<UUID> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<UUID> groupIds) {
this.groupIds = groupIds;
}
private Integer status;
private List<String> organisations;
private Integer role;
private List<UUID> collaborators;
public Date getPeriodStart() {
return periodStart;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
@ -50,9 +29,56 @@ public class DataManagementPlanCriteria extends Criteria<DMP> {
public Date getPeriodEnd() {
return periodEnd;
}
public void setPeriodEnd(Date periodEnd) {
this.periodEnd = periodEnd;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
public List<UUID> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<UUID> groupIds) {
this.groupIds = groupIds;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<String> getOrganisations() {
return organisations;
}
public void setOrganisations(List<String> organisations) {
this.organisations = organisations;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public List<UUID> getCollaborators() {
return collaborators;
}
public void setCollaborators(List<UUID> collaborators) {
this.collaborators = collaborators;
}
}

View File

@ -0,0 +1,42 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.entities.DMP;
import eu.eudat.types.project.ProjectStateType;
import java.util.List;
import java.util.UUID;
public class DataManagementPlanPublicCriteria extends Criteria<DMP> {
private ProjectStateType projectStatus;
private List<UUID> projects;
public List<UUID> datasetProfile;
private List<String> dmpOrganisations;
public ProjectStateType getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(ProjectStateType projectStatus) {
this.projectStatus = projectStatus;
}
public List<UUID> getProjects() {
return projects;
}
public void setProjects(List<UUID> projects) {
this.projects = projects;
}
public List<UUID> getDatasetProfile() {
return datasetProfile;
}
public void setDatasetProfile(List<UUID> datasetProfile) {
this.datasetProfile = datasetProfile;
}
public List<String> getDmpOrganisations() {
return dmpOrganisations;
}
public void setDmpOrganisations(List<String> dmpOrganisations) {
this.dmpOrganisations = dmpOrganisations;
}
}

View File

@ -15,12 +15,15 @@ public class DatasetCriteria extends Criteria<Dataset> {
private List<UUID> dmpIds;
private List<Tag> tags;
private boolean allVersions;
private UUID profileDatasetId;
private List<String> organisations;
private Integer role;
private List<UUID> projects;
private List<UUID> collaborators;
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
@ -28,7 +31,6 @@ public class DatasetCriteria extends Criteria<Dataset> {
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@ -36,7 +38,6 @@ public class DatasetCriteria extends Criteria<Dataset> {
public Date getPeriodStart() {
return periodStart;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
@ -44,7 +45,6 @@ public class DatasetCriteria extends Criteria<Dataset> {
public Date getPeriodEnd() {
return periodEnd;
}
public void setPeriodEnd(Date periodEnd) {
this.periodEnd = periodEnd;
}
@ -52,7 +52,6 @@ public class DatasetCriteria extends Criteria<Dataset> {
public List<UUID> getDmpIds() {
return dmpIds;
}
public void setDmpIds(List<UUID> dmpIds) {
this.dmpIds = dmpIds;
}
@ -60,8 +59,42 @@ public class DatasetCriteria extends Criteria<Dataset> {
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public UUID getProfileDatasetId() {
return profileDatasetId;
}
public void setProfileDatasetId(UUID profileDatasetId) {
this.profileDatasetId = profileDatasetId;
}
public List<String> getOrganisations() {
return organisations;
}
public void setOrganisations(List<String> organisations) {
this.organisations = organisations;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public List<UUID> getProjects() {
return projects;
}
public void setProjects(List<UUID> projects) {
this.projects = projects;
}
public List<UUID> getCollaborators() {
return collaborators;
}
public void setCollaborators(List<UUID> collaborators) {
this.collaborators = collaborators;
}
}

View File

@ -2,6 +2,16 @@ package eu.eudat.data.dao.criteria;
import eu.eudat.data.entities.DatasetProfile;
import java.util.List;
import java.util.UUID;
public class DatasetProfileCriteria extends Criteria<DatasetProfile> {
private boolean allVersions;
private List<UUID> groupIds;
public boolean getAllVersions() { return allVersions; }
public void setAllVersions(boolean allVersions) { this.allVersions = allVersions; }
public List<UUID> getGroupIds() { return groupIds; }
public void setGroupIds(List<UUID> groupIds) { this.groupIds = groupIds; }
}

View File

@ -3,4 +3,20 @@ package eu.eudat.data.dao.criteria;
import eu.eudat.data.entities.Organisation;
public class OrganisationCriteria extends Criteria<Organisation> {
private String labelLike;
private Boolean isPublic;
public String getLabelLike() {
return labelLike;
}
public void setLabelLike(String labelLike) {
this.labelLike = labelLike;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
}

View File

@ -10,11 +10,11 @@ public class ProjectCriteria extends Criteria<Project> {
private Date periodEnd;
private String reference;
private Integer projectStateType;
private boolean isPublic;
public Date getPeriodStart() {
return periodStart;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
@ -22,7 +22,6 @@ public class ProjectCriteria extends Criteria<Project> {
public Date getPeriodEnd() {
return periodEnd;
}
public void setPeriodEnd(Date periodEnd) {
this.periodEnd = periodEnd;
}
@ -30,7 +29,6 @@ public class ProjectCriteria extends Criteria<Project> {
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
@ -38,8 +36,14 @@ public class ProjectCriteria extends Criteria<Project> {
public Integer getProjectStateType() {
return projectStateType;
}
public void setProjectStateType(Integer projectStateType) {
this.projectStateType = projectStateType;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
}

View File

@ -8,11 +8,11 @@ import java.util.List;
public class UserInfoCriteria extends Criteria<UserInfo> {
private String email;
private List<Integer> appRoles;
private String collaboratorLike;
public List<Integer> getAppRoles() {
return appRoles;
}
public void setAppRoles(List<Integer> appRoles) {
this.appRoles = appRoles;
}
@ -20,8 +20,14 @@ public class UserInfoCriteria extends Criteria<UserInfo> {
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCollaboratorLike() {
return collaboratorLike;
}
public void setCollaboratorLike(String collaboratorLike) {
this.collaboratorLike = collaboratorLike;
}
}

View File

@ -4,6 +4,7 @@ import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetWizardUserDmpCriteria;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
@ -15,6 +16,6 @@ public interface DMPDao extends DatabaseAccessLayer<DMP, UUID> {
QueryableList<DMP> getUserDmps(DatasetWizardUserDmpCriteria datasetWizardAutocompleteRequest, UserInfo userInfo);
QueryableList<DMP> getAuthenticated(QueryableList<DMP> query, UserInfo principal);
QueryableList<DMP> getAuthenticated(QueryableList<DMP> query, UUID principalId);
}

View File

@ -5,6 +5,7 @@ import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetWizardUserDmpCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
@ -12,7 +13,9 @@ import eu.eudat.queryable.types.SelectionField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import schemasMicrosoftComOfficeOffice.LeftDocument;
import javax.persistence.criteria.JoinType;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -45,12 +48,32 @@ public class DMPDaoImpl extends DatabaseAccess<DMP> implements DMPDao {
nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class)));
if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty())
query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds()));
if (criteria.getStatus() != null) {
if (criteria.getStatus() == DMP.DMPStatus.FINALISED.getValue()) {
query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.FINALISED.getValue()));
} else if (criteria.getStatus() == DMP.DMPStatus.ACTIVE.getValue()) {
query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.ACTIVE.getValue()));
}
}
if (criteria.getRole() != null) {
if (criteria.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())){
query.where((builder, root) -> builder.equal(root.join("users").get("role"), UserDMP.UserDMPRoles.OWNER.getValue()));
} else if (criteria.getRole().equals(UserDMP.UserDMPRoles.USER.getValue())){
query.where((builder, root) -> builder.equal(root.join("users").get("role"), UserDMP.UserDMPRoles.USER.getValue()));
}
}
if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) {
query.where((builder, root) -> root.join("organisations").get("reference").in(criteria.getOrganisations()));
}
if (criteria.getCollaborators() != null && !criteria.getCollaborators().isEmpty()) {
query.where((builder, root) -> root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id").in(criteria.getCollaborators()));
}
query.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()));
return query;
}
public QueryableList<DMP> getAuthenticated(QueryableList<DMP> query, UserInfo principal) {
query.where((builder, root) -> builder.or(builder.equal(root.get("creator"), principal), builder.isMember(principal, root.get("users"))));
public QueryableList<DMP> getAuthenticated(QueryableList<DMP> query, UUID principal) {
query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).join("user").get("id"), principal));
return query;
}

View File

@ -62,6 +62,7 @@ public class DMPProfileDaoImpl extends DatabaseAccess<DMPProfile> implements DMP
QueryableList<DMPProfile> query = getDatabaseService().getQueryable(DMPProfile.class);
if (criteria.getLike() != null && !criteria.getLike().isEmpty())
query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"));
query.where(((builder, root) -> builder.notEqual(root.get("status"), DMPProfile.Status.DELETED.getValue())));
return query;
}
}

View File

@ -14,4 +14,6 @@ public interface DatasetDao extends DatabaseAccessLayer<Dataset, UUID> {
QueryableList<Dataset> getAuthenticated(QueryableList<Dataset> query, UserInfo principal);
Dataset isPublicDataset(UUID id);
}

View File

@ -3,6 +3,7 @@ package eu.eudat.data.dao.entities;
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.entities.DMP;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
@ -12,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.persistence.criteria.JoinType;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -20,9 +22,7 @@ import java.util.concurrent.CompletableFuture;
public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDao {
@Autowired
public DatasetDaoImpl(DatabaseService<Dataset> databaseService) {
super(databaseService);
}
public DatasetDaoImpl(DatabaseService<Dataset> databaseService) { super(databaseService); }
@Override
public QueryableList<Dataset> getWithCriteria(DatasetCriteria criteria) {
@ -33,6 +33,8 @@ public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDa
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)
@ -41,6 +43,18 @@ public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDa
query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.<String>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.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()));
}
if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) {
query.where((builder, root) -> root.join("dmp").join("organisations").get("reference").in(criteria.getOrganisations()));
}
if (criteria.getProjects() != null && !criteria.getProjects().isEmpty()) {
query.where((builder, root) -> root.join("dmp").join("project").get("id").in(criteria.getProjects()));
}
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()));
}
query.where(((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.DELETED.getValue())));
return query;
}
@ -60,11 +74,19 @@ public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDa
return getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class).withHint(hint).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
}
@Override
public Dataset isPublicDataset(UUID id) {
QueryableList<Dataset> query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class);
query.where(((builder, root) -> builder.equal(root.get("id"), id)));
return query.withHint("datasetListingModel").getSingle();
}
@Override
public QueryableList<Dataset> getAuthenticated(QueryableList<Dataset> query, UserInfo principal) {
if (principal.getId() == null) query.where((builder, root) -> builder.equal(root.get("isPublic"), true));
else {
query.where((builder, root) -> builder.or(builder.equal(root.get("dmp").get("creator"), principal), builder.isMember(principal, root.get("dmp").get("users"))));
query.where((builder, root) -> builder.or(builder.equal(root.get("dmp").get("creator"), principal), builder.equal(root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal.getId())));
}
return query;
}

View File

@ -5,10 +5,13 @@ import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DatasetProfile;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -25,6 +28,13 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DatasetProfile> implem
QueryableList<DatasetProfile> query = getDatabaseService().getQueryable(DatasetProfile.class);
if (criteria.getLike() != null && !criteria.getLike().isEmpty())
query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"));
if (!criteria.getAllVersions())
query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"),
query.<String>subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"),
nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class)));
if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty())
query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds()));
query.where(((builder, root) -> builder.notEqual(root.get("status"), DatasetProfile.Status.DELETED.getValue())));
return query;
}

View File

@ -3,6 +3,7 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.entities.Organisation;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import java.util.UUID;
@ -10,5 +11,6 @@ import java.util.UUID;
public interface OrganisationDao extends DatabaseAccessLayer<Organisation, UUID> {
QueryableList<Organisation> getWithCriteria(OrganisationCriteria criteria);
QueryableList<Organisation> getAuthenticated(QueryableList<Organisation> query, UserInfo principal);
}

View File

@ -3,12 +3,15 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Organisation;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.persistence.criteria.JoinType;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -25,6 +28,12 @@ public class OrganisationDaoImpl extends DatabaseAccess<Organisation> implements
QueryableList<Organisation> query = this.getDatabaseService().getQueryable(Organisation.class);
if (criteria.getLike() != null)
query.where((builder, root) -> builder.equal(root.get("reference"), criteria.getLike()));
if (criteria.getLabelLike() != null) {
query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + criteria.getLabelLike().toUpperCase() + "%"));
}
if (criteria.getPublic() != null && criteria.getPublic()) {
query.where((builder, root) -> builder.equal(root.join("dmps", JoinType.LEFT).get("status"), DMP.DMPStatus.FINALISED.getValue()));
}
return query;
}
@ -54,6 +63,11 @@ public class OrganisationDaoImpl extends DatabaseAccess<Organisation> implements
return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
}
public QueryableList<Organisation> getAuthenticated(QueryableList<Organisation> query, UserInfo principal) {
query.where((builder, root) -> builder.equal(root.join("dmps").get("creator"), principal));
return query;
}
@Override
public Organisation find(UUID id, String hint) {
throw new UnsupportedOperationException();

View File

@ -3,6 +3,7 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.ProjectCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Project;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
@ -28,7 +29,7 @@ public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDa
public QueryableList<Project> getWithCriteria(ProjectCriteria criteria) {
QueryableList<Project> query = getDatabaseService().getQueryable(Project.class);
if (criteria.getLike() != null && !criteria.getLike().isEmpty())
query.where((builder, root) ->
query.where((builder, root) ->
builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"),
builder.or(builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))));
if (criteria.getPeriodEnd() != null)
@ -45,6 +46,9 @@ public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDa
builder.or(builder.greaterThan(root.get("enddate"), new Date())
, builder.isNull(root.get("enddate"))));
}
if (criteria.isPublic()) {
query.where((builder, root) -> builder.equal(root.join("dmps").get("status"), DMP.DMPStatus.FINALISED.getValue())).distinct();
}
query.where((builder, root) -> builder.notEqual(root.get("status"), Project.Status.DELETED.getValue()));
return query;
}
@ -70,7 +74,8 @@ public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDa
}
public QueryableList<Project> getAuthenticated(QueryableList<Project> query, UserInfo principal) {
query.where((builder, root) -> builder.or(builder.equal(root.get("creationUser"), principal), builder.isMember(principal, root.join("dmps", JoinType.LEFT).get("users")))).distinct();
//query.where((builder, root) -> builder.or(builder.equal(root.get("creationUser"), principal), builder.isMember(principal, root.join("dmps", JoinType.LEFT).get("users")))).distinct();
query.where((builder, root) -> builder.or(builder.equal(root.get("creationUser"), principal), builder.equal(root.join("dmps").join("users", JoinType.LEFT).get("id"), principal.getId()))).distinct();
return query;
}

View File

@ -22,11 +22,11 @@ public class ResearcherDaoImpl extends DatabaseAccess<Researcher> implements Res
@Override
public QueryableList<Researcher> getWithCriteria(ResearcherCriteria criteria) {
QueryableList<Researcher> query = this.getDatabaseService().getQueryable(Researcher.class);
if (criteria.getLike() != null)
query.where((builder, root) -> builder.equal(root.get("reference"), criteria.getLike()));
if (criteria.getName() != null)
query.where((builder, root) -> builder.equal(root.get("label"), criteria.getName()));
QueryableList<Researcher> query = asQueryable();
if (criteria.getLike() != null && !criteria.getLike().isEmpty())
query.where((builder, root) ->builder.or(builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%")));
if (criteria.getName() != null && !criteria.getName().isEmpty())
query.where((builder, root) ->builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getName().toUpperCase() + "%")));
return query;
}

View File

@ -17,7 +17,10 @@ import java.util.stream.Collectors;
@NamedEntityGraph(
name = "dataManagementPlanListingModel",
attributeNodes = {@NamedAttributeNode("organisations"), @NamedAttributeNode("researchers"),
@NamedAttributeNode("project"), @NamedAttributeNode("users"), @NamedAttributeNode("creator"), @NamedAttributeNode("profile"), @NamedAttributeNode("dataset")}
@NamedAttributeNode("project"), @NamedAttributeNode(value = "users", subgraph = "users"), @NamedAttributeNode("creator"), @NamedAttributeNode("profile"), @NamedAttributeNode("dataset")},
subgraphs = {
@NamedSubgraph(name = "users", attributeNodes = {@NamedAttributeNode("user")}),
}
),
@NamedEntityGraph(
name = "fullyDetailed",
@ -118,12 +121,13 @@ public class DMP implements DataEntity<DMP, UUID> {
private Set<Researcher> researchers;
@OneToMany(fetch = FetchType.LAZY)
@OneToMany(mappedBy = "dmp", fetch = FetchType.LAZY)
/*@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "\"UserDMP\"",
joinColumns = {@JoinColumn(name = "dmp", referencedColumnName = "\"ID\"")},
inverseJoinColumns = {@JoinColumn(name = "usr", referencedColumnName = "id")}
)
private Set<UserInfo> users;
)*/
private Set<UserDMP> users;
@Column(name = "\"Status\"", nullable = false)
@ -151,66 +155,48 @@ public class DMP implements DataEntity<DMP, UUID> {
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UserInfo getCreator() {
return creator;
}
public void setCreator(UserInfo creator) {
this.creator = creator;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Set<UserInfo> getUsers() {
public Set<UserDMP> getUsers() {
return users;
}
public void setUsers(Set<UserInfo> users) {
public void setUsers(Set<UserDMP> users) {
this.users = users;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@ -218,7 +204,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public UUID getGroupId() {
return groupId;
}
public void setGroupId(UUID groupId) {
this.groupId = groupId;
}
@ -226,7 +211,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@ -234,7 +218,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@ -242,7 +225,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
@ -250,7 +232,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public String getAssociatedDmps() {
return associatedDmps;
}
public void setAssociatedDmps(String associatedDmps) {
this.associatedDmps = associatedDmps;
}
@ -258,7 +239,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public DMPProfile getProfile() {
return profile;
}
public void setProfile(DMPProfile profile) {
this.profile = profile;
}
@ -266,7 +246,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public Set<Dataset> getDataset() {
return dataset;
}
public void setDataset(Set<Dataset> dataset) {
this.dataset = dataset;
}
@ -274,7 +253,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public Set<Organisation> getOrganisations() {
return organisations;
}
public void setOrganisations(Set<Organisation> organisations) {
this.organisations = organisations;
}
@ -282,7 +260,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public Set<Researcher> getResearchers() {
return researchers;
}
public void setResearchers(Set<Researcher> researchers) {
this.researchers = researchers;
}
@ -290,7 +267,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
@ -298,7 +274,6 @@ public class DMP implements DataEntity<DMP, UUID> {
public String getDmpProperties() {
return dmpProperties;
}
public void setDmpProperties(String dmpProperties) {
this.dmpProperties = dmpProperties;
}

View File

@ -17,6 +17,33 @@ import java.util.UUID;
@Table(name = "\"DMPProfile\"")
public class DMPProfile implements DataEntity<DMPProfile, UUID> {
public enum Status {
SAVED((short) 0), FINALIZED((short) 1), DELETED((short) 99);
private short value;
private Status(short value) {
this.value = value;
}
public short getValue() {
return value;
}
public static Status fromInteger(int value) {
switch (value) {
case 0:
return SAVED;
case 1:
return FINALIZED;
case 99:
return DELETED;
default:
throw new RuntimeException("Unsupported Dmp Profile Status");
}
}
}
@Id
@GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@ -109,6 +136,7 @@ public class DMPProfile implements DataEntity<DMPProfile, UUID> {
this.modified = new Date();
this.definition = entity.getDefinition();
this.label = entity.getLabel();
this.status= entity.getStatus();
}
@Override

View File

@ -81,13 +81,11 @@ public class Dataset implements DataEntity<Dataset, UUID> {
@Column(name = "\"Label\"")
private String label;
@ManyToOne(fetch = FetchType.LAZY)
// @Cascade(value=org.hibernate.annotations.CascadeType.ALL)
@JoinColumn(name = "\"DMP\"", nullable = false)
private DMP dmp;
@Column(name = "\"Uri\"")
private String uri;
@ -95,7 +93,6 @@ public class Dataset implements DataEntity<Dataset, UUID> {
@Column(name = "\"Properties\"", columnDefinition = "xml", nullable = true)
private String properties;
@ManyToOne(fetch = FetchType.LAZY)
//@Cascade(value=org.hibernate.annotations.CascadeType.ALL)
@JoinColumn(name = "\"Profile\"", nullable = true)
@ -112,18 +109,15 @@ public class Dataset implements DataEntity<Dataset, UUID> {
)
private Set<Registry> registries;
@OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<DatasetDataRepository> datasetDataRepositories;
@OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<DatasetService> services;
@OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<DatasetExternalDataset> datasetExternalDatasets;
@Column(name = "\"Status\"", nullable = false)
private Short status;

View File

@ -15,7 +15,33 @@ import java.util.UUID;
@Entity
@Table(name = "\"DatasetProfile\"")
public class DatasetProfile implements DataEntity<DatasetProfile,UUID> {
public class DatasetProfile implements DataEntity<DatasetProfile,UUID>{
public enum Status {
SAVED((short) 0), FINALIZED((short) 1), DELETED((short) 99);
private short value;
private Status(short value) {
this.value = value;
}
public short getValue() {
return value;
}
public static Status fromInteger(int value) {
switch (value) {
case 0:
return SAVED;
case 1:
return FINALIZED;
case 99:
return DELETED;
default:
throw new RuntimeException("Unsupported Dataset Profile Status");
}
}
}
@Id
@GeneratedValue
@ -33,11 +59,9 @@ public class DatasetProfile implements DataEntity<DatasetProfile,UUID> {
@Column(name = "\"Definition\"", columnDefinition = "xml", nullable = false)
private String definition;
@Column(name = "\"Status\"", nullable = false)
private Short status;
@Column(name = "\"Created\"")
@Convert(converter = DateToUTCConverter.class)
private Date created;
@ -49,90 +73,80 @@ public class DatasetProfile implements DataEntity<DatasetProfile,UUID> {
@Column(name = "\"Description\"")
private String description;
@Column(name = "\"GroupId\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID groupId;
@Column(name = "\"Version\"", nullable = false)
private Short version;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public void setId(UUID id) { this.id = id;}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public Set<Dataset> getDataset() {
return dataset;
}
public void setDataset(Set<Dataset> dataset) {
this.dataset = dataset;
}
public UUID getGroupId() { return groupId; }
public void setGroupId(UUID groupId) { this.groupId = groupId;}
public Short getVersion() { return version; }
public void setVersion(Short version) { this.version = version; }
@Override
public String toString() {
return "DatasetProfileListingModel [id=" + id + ", label=" + label + ", dataset=" + dataset + ", definition=" + definition + "]";
return "DatasetProfileListingModel [id=" + id + ", label=" + label + ", dataset=" + dataset + ", definition=" + definition + ", version=" + version + "]";
}
@Override
public void update(DatasetProfile entity) {
}
@Override

View File

@ -1,6 +1,5 @@
package eu.eudat.data.entities;
import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.hibernate.annotations.GenericGenerator;
@ -13,9 +12,14 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
@Entity
@Table(name = "\"Organisation\"")
@NamedEntityGraphs({
@NamedEntityGraph(
name = "organisationRecentActivity",
attributeNodes = {@NamedAttributeNode(value = "dmps")}
)
})
public class Organisation implements Serializable, DataEntity<Organisation,UUID> {
@Id
@ -41,19 +45,16 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
@Column(name = "\"Definition\"", columnDefinition = "xml", nullable = true)
private String definition;
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "\"DMPOrganisation\"",
joinColumns = {@JoinColumn(name = "\"Organisation\"", referencedColumnName = "\"ID\"")},
inverseJoinColumns = {@JoinColumn(name = "\"DMP\"", referencedColumnName = "\"ID\"")}
)
private Set<DMP> dMPs;
private Set<DMP> dmps;
@Column(name = "\"Status\"", nullable = false)
private Short status;
@Column(name = "\"Created\"")
@Convert(converter = DateToUTCConverter.class)
private Date created = null;
@ -66,37 +67,27 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@ -104,7 +95,6 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@ -112,7 +102,6 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
@ -120,7 +109,6 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
@ -128,7 +116,6 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@ -136,20 +123,17 @@ public class Organisation implements Serializable, DataEntity<Organisation,UUID>
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public Set<DMP> getdMPs() {
return dMPs;
public Set<DMP> getDmps() {
return dmps;
}
public void setdMPs(Set<DMP> dMPs) {
this.dMPs = dMPs;
public void setDmps(Set<DMP> dmps) {
this.dmps = dmps;
}
@Override
public void update(Organisation entity) {

View File

@ -0,0 +1,44 @@
package eu.eudat.data.query.items.table.dmp;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DataManagementPlanPublicCriteria;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.query.PaginationService;
import eu.eudat.data.query.definition.TableQuery;
import eu.eudat.queryable.QueryableList;
import eu.eudat.types.project.ProjectStateType;
import java.util.Date;
import java.util.UUID;
public class DataManagmentPlanPublicTableRequest extends TableQuery<DataManagementPlanPublicCriteria, DMP, UUID> {
public QueryableList<DMP> applyCriteria() {
QueryableList<DMP> query = this.getQuery();
query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.FINALISED.getValue()));
if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty())
query.where((builder, root) -> builder.or(
builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"),
builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%")));
if (this.getCriteria().getProjects() != null && !this.getCriteria().getProjects().isEmpty())
query.where(((builder, root) -> root.get("project").get("id").in(this.getCriteria().getProjects())));
if (this.getCriteria().getProjectStatus() != null) {
if (this.getCriteria().getProjectStatus().getValue().equals(ProjectStateType.FINISHED.getValue()))
query.where((builder, root) -> builder.lessThan(root.get("project").get("enddate"), new Date()));
if (this.getCriteria().getProjectStatus().getValue().equals(ProjectStateType.ONGOING.getValue()))
query.where((builder, root) ->
builder.or(builder.greaterThan(root.get("project").get("enddate"), new Date())
, builder.isNull(root.get("project").get("enddate"))));
}
if (this.getCriteria().datasetProfile != null && !this.getCriteria().datasetProfile.isEmpty()) query
.where(((builder, root) -> root.get("profile").get("id").in(this.getCriteria().datasetProfile)));
if (this.getCriteria().getDmpOrganisations() != null && !this.getCriteria().getDmpOrganisations().isEmpty()) query
.where(((builder, root) -> root.join("organisations").get("reference").in(this.getCriteria().getDmpOrganisations())));
return query;
}
@Override
public QueryableList<DMP> applyPaging(QueryableList<DMP> items) {
return PaginationService.applyPaging(items, this);
}
}

View File

@ -0,0 +1,25 @@
package eu.eudat.data.query.items.table.organisations;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.entities.Organisation;
import eu.eudat.data.query.PaginationService;
import eu.eudat.data.query.definition.TableQuery;
import eu.eudat.queryable.QueryableList;
import java.util.UUID;
public class OrganisationsTableRequest extends TableQuery<OrganisationCriteria, Organisation, UUID> {
@Override
public QueryableList<Organisation> applyCriteria() {
QueryableList<Organisation> query = this.getQuery();
if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) {
query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"));
}
return query;
}
@Override
public QueryableList<Organisation> applyPaging(QueryableList<Organisation> items) {
return PaginationService.applyPaging(items, this);
}
}

View File

@ -18,7 +18,6 @@
<module>web</module>
<module>data</module>
<module>logging</module>
<module>queryengine</module>
<module>elastic</module>
</modules>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dmp-backend</artifactId>
<groupId>eu.eudat</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>query-engine</artifactId>
<dependencies>
<dependency>
<groupId>eu.eudat</groupId>
<artifactId>data</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -1,23 +0,0 @@
import eu.eudat.data.entities.DataRepository;
import eu.eudat.query.engine.builder.QueryBuilder;
import eu.eudat.query.engine.builder.QueryBuilderImpl;
import eu.eudat.query.engine.predicates.ComparisonPredicate;
/**
* Created by ikalyvas on 7/5/2018.
*/
public class Main {
public static void main(String[] args){
new Main().Test();
}
public void Test(){
QueryBuilder<DataRepository> queryBuilder = new QueryBuilderImpl<>(DataRepository.class);
queryBuilder.<ComparisonPredicate>where((comparisonExpression) -> comparisonExpression.field("id").greaterThan(5) );
queryBuilder.<ComparisonPredicate>where((comparisonExpression) -> comparisonExpression.field("label").equal("mitsos") );
queryBuilder.toList();
QueryBuilder<DataRepository> queryBuilder2 = new QueryBuilderImpl<>(DataRepository.class);
queryBuilder2.<ComparisonPredicate>where((comparisonExpression) -> comparisonExpression.field("id").lessOrEqualThan(11111) );
queryBuilder2.toList();
}
}

View File

@ -1,16 +0,0 @@
package eu.eudat.query.engine.builder;
import eu.eudat.query.engine.expressions.Expression;
import eu.eudat.query.engine.predicates.Predicate;
import java.util.List;
/**
* Created by ikalyvas on 7/5/2018.
*/
public interface QueryBuilder<T> {
<P extends Predicate> Expression where(P wherePredicate);
List<T> toList();
}

View File

@ -1,50 +0,0 @@
package eu.eudat.query.engine.builder;
import eu.eudat.query.engine.expressions.ComparisonExpression;
import eu.eudat.query.engine.expressions.Expression;
import eu.eudat.query.engine.predicates.Predicate;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
/**
* Created by ikalyvas on 7/5/2018.
*/
public class QueryBuilderImpl<T> implements QueryBuilder<T> {
private List<Expression> expressions = new LinkedList<>();
private Class<T> tClass;
public QueryBuilderImpl(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public <P extends Predicate> Expression where(P wherePredicate) {
ComparisonExpression comparisonExpression = new ComparisonExpression();
Expression expression = wherePredicate.apply(comparisonExpression);
this.expressions.add(expression);
return expression;
}
@Override
public List<T> toList() {
String query = "Select * from ";
Optional<Annotation> optionalAnnotation = Arrays.stream(this.tClass.getAnnotations())
.filter(x-> x.annotationType().equals(javax.persistence.Table.class))
.findFirst();
javax.persistence.Table annotation = optionalAnnotation.isPresent() ? (javax.persistence.Table)optionalAnnotation.get() : null;
query += annotation.name()+" ";
for (Expression expression : expressions) {
if(expressions.indexOf(expression) > 0) query+= " and ";
else query += " where ";
query += expression.evaluate();
}
System.out.println(query);
return null;
}
}

View File

@ -1,17 +0,0 @@
package eu.eudat.query.engine.expressions;
/**
* Created by ikalyvas on 7/5/2018.
*/
public abstract class AbstractFieldExpression<T extends AbstractFieldExpression<T>> {
private String field;
protected String getField() {
return field;
}
public T field(String field) {
this.field = field;
return (T)this;
}
}

View File

@ -1,47 +0,0 @@
package eu.eudat.query.engine.expressions;
import eu.eudat.query.engine.types.expression.comparison.ComparisonExpressionType;
/**
* Created by ikalyvas on 7/5/2018.
*/
public class ComparisonExpression extends AbstractFieldExpression<ComparisonExpression> implements Expression {
private ComparisonExpressionType type;
private Object value;
public <T> Expression greaterThan(T value){
this.value = value;
this.type = ComparisonExpressionType.GREATER_THAN;
return this;
}
public <T> Expression greaterThanOrEqual(T value){
this.value = value;
this.type = ComparisonExpressionType.GREATER_OR_EQUAL_THAN;
return this;
}
public <T> Expression equal(T value){
this.value = value;
this.type = ComparisonExpressionType.EQUAL;
return this;
}
public <T> Expression lessThan(T value){
this.value = value;
this.type = ComparisonExpressionType.LESS_THAN;
return this;
}
public <T> Expression lessOrEqualThan(T value){
this.value = value;
this.type = ComparisonExpressionType.LESS_OR_EQUAL_THAN;
return this;
}
@Override
public String evaluate() {
return this.getField() +" " + type.toString() + " " + value ;
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.query.engine.expressions;
/**
* Created by ikalyvas on 7/5/2018.
*/
public interface Expression {
String evaluate();
}

View File

@ -1,10 +0,0 @@
package eu.eudat.query.engine.predicates;
import eu.eudat.query.engine.expressions.ComparisonExpression;
import eu.eudat.query.engine.expressions.Expression;
/**
* Created by ikalyvas on 7/5/2018.
*/
public interface ComparisonPredicate extends Predicate<ComparisonExpression> {
}

View File

@ -1,11 +0,0 @@
package eu.eudat.query.engine.predicates;
import eu.eudat.query.engine.expressions.ComparisonExpression;
import eu.eudat.query.engine.expressions.Expression;
/**
* Created by ikalyvas on 7/5/2018.
*/
public interface Predicate<E extends Expression> {
Expression apply( E expression);
}

View File

@ -1,8 +0,0 @@
package eu.eudat.query.engine.types.expression.comparison;
/**
* Created by ikalyvas on 7/5/2018.
*/
public enum ComparisonExpressionType {
EQUAL, GREATER_THAN, GREATER_OR_EQUAL_THAN, LESS_THAN, LESS_OR_EQUAL_THAN
}

View File

@ -69,9 +69,6 @@ public class DevelDatabaseConfiguration {
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL92Dialect");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
properties.setProperty("hibernate.c3p0.maxPoolSize", "70");
properties.setProperty("hibernate.c3p0.timeout", "5000");
properties.setProperty("hibernate.connection.release_mode", "after_transaction");
return properties;
}
}

View File

@ -37,5 +37,4 @@ public class WebMVCConfiguration extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor(this.apiContext.getHelpersService().getLoggerService()));
}
}

View File

@ -48,7 +48,7 @@ public class DynamicProjectConfigurationDevelImpl implements DynamicProjectConfi
JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
is = new URL("file:///"+current + "/dmp-backend/web/src/main/resources/ProjectConfiguration.xml").openStream();
is = new URL("file:///"+current + "/web/src/main/resources/ProjectConfiguration.xml").openStream();
this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is);
} catch (Exception ex) {
ex.printStackTrace();

View File

@ -1,12 +1,17 @@
package eu.eudat.controllers;
import eu.eudat.core.logger.Logger;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
import eu.eudat.exceptions.datasetprofile.DatasetProfileNewVersionException;
import eu.eudat.exceptions.datasetprofile.DatasetProfileWithDatasetsExeption;
import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.helpers.LoggerService;
import eu.eudat.models.data.admin.composite.DatasetProfile;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
@ -15,56 +20,132 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static eu.eudat.types.Authorities.ADMIN;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
@RequestMapping(value = {"/api/admin/"})
public class Admin extends BaseController {
@Autowired
public Admin(ApiContext apiContext, Logger logger) {
super(apiContext);
}
private DatasetProfileManager datasetProfileManager;
private UserManager userManager;
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
//this.getLoggerService().info(principal, "Admin Added Dataset Profile");
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
}
@Autowired
public Admin(ApiContext apiContext, DatasetProfileManager datasetProfileManager, UserManager userManager, Logger logger) {
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
this.userManager = userManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<UUID>> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
eu.eudat.data.entities.DatasetProfile datasetprofile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
datasetprofile.setDefinition(modelDefinition.getDefinition());
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addDmp"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
//this.getLoggerService().info(principal, "Admin Added Dataset Profile");
DatasetProfile shortenProfile = profile.toShort();
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext());
modelDefinition.setGroupId(UUID.randomUUID());
modelDefinition.setVersion((short) 0);
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
}
@RequestMapping(method = RequestMethod.GET, value = {"/admin/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<DatasetProfile>> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(datasetprofile));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addDmp/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<UUID>> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
DatasetProfile shortenProfile = profile.toShort();
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext());
eu.eudat.data.entities.DatasetProfile datasetprofile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
datasetprofile.setDefinition(modelDefinition.getDefinition());
datasetprofile.setStatus(modelDefinition.getStatus());
datasetprofile.setLabel(modelDefinition.getLabel());
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/newVersion/{id}"}, produces = "application/json")
public ResponseEntity newVersionDatasetProfile(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
try {
eu.eudat.data.entities.DatasetProfile modelDefinition = this.datasetProfileManager.createNewVersionDatasetProfile(id, profile);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
} catch (DatasetProfileNewVersionException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<DatasetProfile>> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(datasetprofile));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getPaged"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) throws Exception {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getPaged(datasetProfileTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}
@RequestMapping(method = RequestMethod.POST, value = {"/preview"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getPreview(@RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
eu.eudat.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(modelDefinition);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetProfile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.data.entities.DatasetProfile profile = this.datasetProfileManager.clone(id);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel() + " new ");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().payload(datasetprofile));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetProfile>> inactivate(@PathVariable String id, Principal principal) {
try {
eu.eudat.data.entities.DatasetProfile ret = AdminManager.inactivate(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (DatasetProfileWithDatasetsExeption exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.UNSUCCESS_DELETE).message(exception.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}, produces = "application/json")
public ResponseEntity getDatasetProfileXml(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
if (contentType.equals("application/xml")) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(profile);
datasetProfile.setStatus(profile.getStatus());
return this.datasetProfileManager.getDocument(datasetProfile, profile.getLabel());
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.ERROR_MESSAGE).message("NOT AUTHORIZE"));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<Object> setDatasetProfileXml(@RequestParam("file") MultipartFile file,
@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws IllegalAccessException, IOException {
eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile datasetProfileModel = this.datasetProfileManager.createDatasetProfileFromXml(file);
eu.eudat.models.data.admin.composite.DatasetProfile datasetProfileEntity = datasetProfileModel.toAdminCompositeModel(file.getOriginalFilename());
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(datasetProfileEntity, getApiContext());
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.data.entities.DatasetProfile>>()
.status(ApiMessageCode.SUCCESS_MESSAGE).message(""));
}
@RequestMapping(method = RequestMethod.POST, value = {"/admin/preview"}, consumes = "application/json",produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getPreview(@RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
eu.eudat.models.data.user.composite.DatasetProfile datasetProfile = UserManager.generateDatasetProfileModel(modelDefinition);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetProfile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
}
}

View File

@ -3,7 +3,9 @@ package eu.eudat.controllers;
import eu.eudat.data.entities.DMPProfile;
import eu.eudat.data.query.items.item.dmpprofile.DataManagementPlanProfileCriteriaRequest;
import eu.eudat.data.query.items.table.dmpprofile.DataManagementPlanProfileTableRequest;
import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DataManagementProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
@ -15,10 +17,14 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import static eu.eudat.types.Authorities.ADMIN;
/**
* Created by ikalyvas on 3/21/2018.
*/
@ -27,38 +33,55 @@ import java.util.List;
@RequestMapping(value = {"/api/dmpprofile"})
public class DMPProfileController extends BaseController {
private DataManagementProfileManager dataManagementProfileManager;
@Autowired
public DMPProfileController(ApiContext apiContext) {
public DMPProfileController(ApiContext apiContext, DataManagementProfileManager dataManagementProfileManager) {
super(apiContext);
this.dataManagementProfileManager = dataManagementProfileManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/createOrUpdate"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMPProfile>> createOrUpdate(@RequestBody DataManagementPlanProfileListingModel dataManagementPlan, Principal principal) throws Exception {
DataManagementProfileManager.createOrUpdate(this.getApiContext(), dataManagementPlan, principal);
this.dataManagementProfileManager.createOrUpdate(dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMPProfile>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getSingle/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlanProfileListingModel>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = new DataManagementProfileManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpProfileDao(), id, principal);
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = this.dataManagementProfileManager.getSingle(id, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanProfileListingModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlanProfileListingModel));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanProfileListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception {
DataTableData<DataManagementPlanProfileListingModel> dataTable = new DataManagementProfileManager().getPaged(this.getApiContext(), dataManagementPlanProfileTableRequest, principal);
DataTableData<DataManagementPlanProfileListingModel> dataTable = this.dataManagementProfileManager.getPaged(dataManagementPlanProfileTableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.POST, value = {"/get"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagementPlanProfileListingModel>>> getWithCriteria(@RequestBody DataManagementPlanProfileCriteriaRequest dataManagementPlanCriteria, Principal principal) throws InstantiationException, IllegalAccessException {
List<DataManagementPlanProfileListingModel> dataTable = new DataManagementProfileManager().getWithCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpProfileDao(), dataManagementPlanCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagementPlanProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
ResponseEntity getXml( @RequestHeader("Content-Type") String contentType, @PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException, IOException {
if (contentType.equals("application/xml")) {
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = this.dataManagementProfileManager.getSingle(id, principal);
return this.dataManagementProfileManager.getDocument(dataManagementPlanProfileListingModel,dataManagementPlanProfileListingModel.getLabel());
}else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanProfileListingModel>().status(ApiMessageCode.ERROR_MESSAGE).message("NOT AUTHORIZE"));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<Object> setDatasetProfileXml(@RequestParam("file") MultipartFile file,
@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws IllegalAccessException,IOException,Exception{
eu.eudat.logic.utilities.documents.xml.dmpXml.dmpProfileModel.DmpProfile dmpProfileModel = this.dataManagementProfileManager.createDmpProfileFromXml(file);
DataManagementPlanProfileListingModel dataManagementPlan = dmpProfileModel.toDmpProfileCompositeModel(file.getOriginalFilename());
this.dataManagementProfileManager.createOrUpdate(dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.data.entities.DatasetProfile>>()
.status(ApiMessageCode.SUCCESS_MESSAGE).message(""));
}
}

View File

@ -4,21 +4,29 @@ package eu.eudat.controllers;
import eu.eudat.configurations.dynamicproject.DynamicProjectConfiguration;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria;
import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.query.items.item.dmp.DataManagementPlanCriteriaRequest;
import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest;
import eu.eudat.data.query.items.table.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.exceptions.datamanagementplan.DMPNewVersionException;
import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException;
import eu.eudat.logic.managers.DataManagementPlanManager;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.FileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.files.ContentFile;
import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
@ -28,9 +36,11 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.validation.Valid;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -46,72 +56,92 @@ public class DMPs extends BaseController {
private DynamicProjectConfiguration dynamicProjectConfiguration;
private Environment environment;
private DataManagementPlanManager dataManagementPlanManager;
private DatasetManager datasetManager;
@Autowired
public DMPs(ApiContext apiContext, DynamicProjectConfiguration dynamicProjectConfiguration, Environment environment) {
public DMPs(ApiContext apiContext, DynamicProjectConfiguration dynamicProjectConfiguration, Environment environment,
DataManagementPlanManager dataManagementPlanManager, DatasetManager datasetManager) {
super(apiContext);
this.dynamicProjectConfiguration = dynamicProjectConfiguration;
this.environment = environment;
this.dataManagementPlanManager = dataManagementPlanManager;
this.datasetManager = datasetManager;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
new DataManagementPlanManager().unlock(this.getApiContext(), id);
this.dataManagementPlanManager.unlock(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal) throws Exception {
DataTableData<DataManagementPlanListingModel> dataTable = new DataManagementPlanManager().getPaged(this.getApiContext(), dataManagementPlanTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest,@RequestParam String fieldsGroup, Principal principal) throws Exception {
DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, fieldsGroup);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getSingle/{id}"}, produces = "application/json")
@RequestMapping(method = RequestMethod.GET, value = {"{id}"})
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlan>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = new DataManagementPlanManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, principal, this.dynamicProjectConfiguration);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
ResponseEntity getSingle(@PathVariable String id,@RequestHeader("Content-Type") String contentType, Principal principal) throws IllegalAccessException,InterruptedException, InstantiationException, IOException {
if(contentType.equals("application/xml") || contentType.equals("application/msword")){ //|| contentType.equals("application/pdf")
DMPDao dmpDao = this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao();
VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
ResponseEntity<byte[]> document = this.dataManagementPlanManager.getDocument(id, contentType);
return document;
}
else{
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, this.dynamicProjectConfiguration);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"})
public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id) throws IllegalAccessException,InterruptedException, InstantiationException, IOException {
try {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSinglePublic(id, this.dynamicProjectConfiguration);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
}
catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/createOrUpdate"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan, Principal principal) throws Exception {
DataManagementPlanManager.createOrUpdate(this.getApiContext(), dataManagementPlan, principal);
this.dataManagementPlanManager.createOrUpdate(this.getApiContext(), dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> newVersion(@PathVariable UUID id, @Valid @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DataManagementPlanManager.newVersion(this.getApiContext(), id, dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.NO_MESSAGE));
try {
this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.NO_MESSAGE));
} catch (DMPNewVersionException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DataManagementPlanManager.clone(this.getApiContext(), id, dataManagementPlan, principal);
this.dataManagementPlanManager.clone(id, dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/get"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagementPlan>>> getWithCriteria(@RequestBody DataManagementPlanCriteriaRequest dataManagementPlanCriteria, Principal principal) throws InstantiationException, IllegalAccessException {
List<DataManagementPlan> dataTable = new DataManagementPlanManager().getWithCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), dataManagementPlanCriteria, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagementPlan>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id, Principal principal) {
try{
DataManagementPlanManager.delete(this.getApiContext(), id);
this.dataManagementPlanManager.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan"));
}catch (DMPWithDatasetsDeleteException exception){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
@ -121,55 +151,16 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Tuple<String, String>>>> getWithCriteria(@RequestBody RequestItem<DynamicFieldsCriteria> criteriaRequestItem, Principal principal) throws InstantiationException, IllegalAccessException {
List<Tuple<String, String>> dataTable = new DataManagementPlanManager().getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicProjectConfiguration, criteriaRequestItem.getCriteria());
List<Tuple<String, String>> dataTable = this.dataManagementPlanManager.getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicProjectConfiguration, criteriaRequestItem.getCriteria());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tuple<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getXml(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = new DataManagementPlanManager().getXmlDocument(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("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);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".xml");
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = {"/getWord/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getWordDocument(@PathVariable String id) throws IOException, IllegalAccessException, InstantiationException {
File file = new DataManagementPlanManager().getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
InputStream resource = new FileInputStream(file);
System.out.println("Mime Type of " + file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getName());
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);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
File file = new DataManagementPlanManager().getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
File pdffile = new DatasetManager().convertToPDF(file, environment, file.getName());
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
System.out.println(contentType);
File file = this.dataManagementPlanManager.getWordDocument(id);
File pdffile = datasetManager.convertToPDF(file, environment, file.getName());
InputStream resource = new FileInputStream(pdffile);
System.out.println("Mime Type of " + file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file));
@ -185,5 +176,19 @@ public class DMPs extends BaseController {
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> dmpXmlUpload(@RequestParam("file") MultipartFile[] files, Principal principal) throws IOException, JAXBException, Exception {
this.dataManagementPlanManager.createDmpFromXml(this.getApiContext(), files, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List>()
.status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPublicPaged(@RequestBody DataManagmentPlanPublicTableRequest dmpTableRequest, @ClaimedAuthorities(claims = {Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DataManagementPlanListingModel> dmp = this.dataManagementPlanManager.getPaged(dmpTableRequest, "listing") ;
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dmp));
}
}

View File

@ -20,36 +20,34 @@ import java.util.List;
@RequestMapping(value = {"/api"})
public class DashBoardController extends BaseController {
private DashBoardManager dashBoardManager;
@Autowired
public DashBoardController(ApiContext apiContext) {
public DashBoardController(ApiContext apiContext, DashBoardManager dashBoardManager) {
super(apiContext);
this.dashBoardManager = dashBoardManager;
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics() {
DashBoardStatistics statistics = new DashBoardManager().getStatistics(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao());
DashBoardStatistics statistics = dashBoardManager.getStatistics();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DashBoardStatistics>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/me/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics(Principal principal) {
DashBoardStatistics statistics = new DashBoardManager().getMeStatistics(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), principal);
DashBoardStatistics statistics = dashBoardManager.getMeStatistics(principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DashBoardStatistics>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@RequestMapping(method = RequestMethod.GET, value = {"/user/recentActivity"}, produces = "application/json")
public ResponseEntity<ResponseItem<RecentActivity>> getRecentActivity(@RequestParam(name = "numOfActivities", required = false, defaultValue = "5") Integer numberOfActivities, Principal principal) {
RecentActivity statistics = new DashBoardManager().getRecentActivity(this.getApiContext(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), principal, numberOfActivities);
RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RecentActivity>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/search"}, produces = "application/json")
public ResponseEntity<ResponseItem<List<SearchBarItem>>> search(@RequestParam(name = "like") String like, Principal principal) {
List<SearchBarItem> searchBarItemList = new DashBoardManager().searchUserData(like, this.getApiContext(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), principal);
List<SearchBarItem> searchBarItemList = dashBoardManager.searchUserData(like, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<SearchBarItem>>().status(ApiMessageCode.NO_MESSAGE).payload(searchBarItemList));
}
}

View File

@ -23,15 +23,18 @@ import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
@RequestMapping(value = {"/api/external/datarepos"})
public class DataRepositories extends BaseController {
private DataRepositoryManager dataRepositoryManager;
@Autowired
public DataRepositories(ApiContext apiContext) {
public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) {
super(apiContext);
this.dataRepositoryManager = dataRepositoryManager;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/datarepos"}, produces = "application/json")
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Map<String, String>>>> listExternalDataRepositories(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
@ -41,10 +44,10 @@ public class DataRepositories extends BaseController {
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datarepos/create"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataRepository>> create(@RequestBody eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception {
DataRepository dataRepository = DataRepositoryManager.create(this.getApiContext(), dataRepositoryModel);
DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataRepository>().payload(dataRepository).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,9 +1,9 @@
package eu.eudat.controllers;
import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.entities.Project;
import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.components.commons.datafield.AutoCompleteData;
@ -12,8 +12,6 @@ import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.properties.PropertiesModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.DatasetProfile;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -29,25 +27,18 @@ import java.util.Map;
import java.util.UUID;
import static eu.eudat.types.Authorities.ADMIN;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
public class DatasetProfileController extends BaseController {
@Autowired
public DatasetProfileController(ApiContext apiContext) {
super(apiContext);
}
private DatasetProfileManager datasetProfileManager;
@RequestMapping(method = RequestMethod.GET, value = {"/datasetwizard/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = UserManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
@Autowired
public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager) {
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
}
@Transactional
@ -66,7 +57,7 @@ public class DatasetProfileController extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN})Principal principal) {
eu.eudat.data.entities.DatasetProfile profile = new DatasetProfileManager().clone(this.getApiContext(), id);
eu.eudat.data.entities.DatasetProfile profile = this.datasetProfileManager.clone(id);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel() + " new ");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().payload(datasetprofile));
@ -74,10 +65,11 @@ public class DatasetProfileController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> getDataForAutocomplete(@RequestBody RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException {
eu.eudat.data.entities.Dataset dataset = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID()));
eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field modelfield = DatasetProfileManager.queryForField(dataset.getProfile().getDefinition(), lookupItem.getCriteria().getFieldID());
eu.eudat.data.entities.DatasetProfile datasetProfile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID()));
eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field modelfield = this.datasetProfileManager.queryForField(datasetProfile.getDefinition(), lookupItem.getCriteria().getFieldID());
AutoCompleteData data = (AutoCompleteData) modelfield.getData();
List<Tuple<String, String>> items = DatasetProfileManager.getAutocomplete(data, lookupItem.getCriteria().getLike());
List<Tuple<String, String>> items = this.datasetProfileManager.getAutocomplete(data, lookupItem.getCriteria().getLike());
return ResponseEntity.status(HttpStatus.OK).body(items);
}
}

View File

@ -27,29 +27,25 @@ import java.util.UUID;
@RequestMapping(value = {"/api"})
public class DatasetProfiles extends BaseController {
private DatasetProfileManager datasetProfileManager;
@Autowired
public DatasetProfiles(ApiContext apiContext) {
public DatasetProfiles(ApiContext apiContext, DatasetProfileManager datasetProfileManager) {
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/dmps/datasetprofiles/get"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileAutocompleteItem>>> get(@RequestBody DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws InstantiationException, IllegalAccessException {
List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = DatasetProfileManager.getWithCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), datasetProfileAutocompleteRequest);
List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = this.datasetProfileManager.getWithCriteria(datasetProfileAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileAutocompleteItem>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileAutocompleteItems));
}
@RequestMapping(method = RequestMethod.POST, value = {"/admin/datasetprofiles/getPaged"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = DatasetProfileManager.getPaged(this.getApiContext(), datasetProfileTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}
@RequestMapping(method = RequestMethod.GET, value = {"/datasetprofiles/getAll"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileListingModel>>> getAll() throws InstantiationException, IllegalAccessException {
List<DatasetProfileListingModel> datasetProfileTableData = DatasetProfileManager.getAll(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao());
List<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getAll();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}

View File

@ -1,19 +1,23 @@
package eu.eudat.controllers;
import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest;
import eu.eudat.exceptions.datasetwizard.DatasetWizardCannotUnlockException;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.DatasetWizardManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -23,13 +27,16 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.transaction.Transactional;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
@ -42,11 +49,15 @@ import static eu.eudat.types.Authorities.ANONYMOUS;
public class DatasetWizardController extends BaseController {
private Environment environment;
private DatasetManager datasetManager;
private UserManager userManager;
@Autowired
public DatasetWizardController(ApiContext apiContext, Environment environment) {
public DatasetWizardController(ApiContext apiContext, Environment environment, DatasetManager datasetManager, UserManager userManager) {
super(apiContext);
this.environment = environment;
this.datasetManager = datasetManager;
this.userManager = userManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
@ -63,29 +74,75 @@ public class DatasetWizardController extends BaseController {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getSingle/{id}"}, produces = "application/json")
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetWizardModel>> getSingle(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
DatasetWizardModel dataset = new DatasetManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatasetRepository(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
if(contentType.equals("application/xml")){
DatasetDao datasetDao = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao();
VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
return this.datasetManager.getDocument(id, visibilityRuleService, contentType);
}
else if (contentType.equals("application/msword")){
File file = datasetManager.getWordDocument(this.environment, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
InputStream resource = new FileInputStream(file);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getName());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
else {
DatasetWizardModel dataset = this.datasetManager.getSingle(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
try {
DatasetWizardModel dataset = this.datasetManager.getSinglePublic(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/createOrUpdate"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
new DatasetWizardManager().delete(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception {
eu.eudat.data.entities.Dataset dataset = DatasetManager.createOrUpdate(this.getApiContext(), profile, principal);
this.datasetManager.createOrUpdate(profile, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(null));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
File file = new DatasetManager().getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
File pdffile = new DatasetManager().convertToPDF(file, environment, file.getName());
File file = datasetManager.getWordDocument(this.environment, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
String fileName = file.getName();
if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5);
}
File pdffile = datasetManager.convertToPDF(file, environment, fileName);
InputStream resource = new FileInputStream(pdffile);
System.out.println("Mime Type of " + file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(pdffile.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
@ -94,29 +151,20 @@ public class DatasetWizardController extends BaseController {
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
//Files.deleteIfExists(pdffile.toPath());
//Files.deleteIfExists(file.toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getXml(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = new DatasetManager().getXmlDocument(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("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);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".xml");
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
}
@Transactional
@ -131,11 +179,26 @@ public class DatasetWizardController extends BaseController {
}
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId, Principal principal) {
try {
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal);
if (dataset != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
}
else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
new DatasetWizardManager().delete(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
ResponseEntity getSingleProfileUpdate(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
}

View File

@ -24,33 +24,36 @@ import java.util.UUID;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
@RequestMapping(value = {"/api/datasets/"})
public class Datasets extends BaseController {
private DatasetManager datasetManager;
@Autowired
public Datasets(ApiContext apiContext) {
public Datasets(ApiContext apiContext, DatasetManager datasetManager) {
super(apiContext);
this.datasetManager = datasetManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasets/getPaged"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
DataTableData<DatasetListingModel> dataTable = new DatasetManager().getPaged(this.getApiContext(), datasetTableRequest, principal);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasets/public/paged"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest, @ClaimedAuthorities(claims = {Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DatasetListingModel> dataTable = new DatasetManager().getPaged(this.getApiContext(), datasetTableRequest, principal);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/datasets/makepublic/{id}"}, produces = "application/json")
@RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> makePublic(@PathVariable UUID id, Principal principal, Locale locale) throws Exception {
DatasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
this.datasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getHelpersService().getMessageSource().getMessage("dataset.public", new Object[]{}, locale)));
}

View File

@ -28,15 +28,18 @@ import java.util.UUID;
@RequestMapping(value = {"/api"})
public class ExternalDatasets extends BaseController {
private ExternalDatasetManager externalDatasetManager;
@Autowired
public ExternalDatasets(ApiContext apiContext) {
public ExternalDatasets(ApiContext apiContext, ExternalDatasetManager externalDatasetManager) {
super(apiContext);
this.externalDatasetManager = externalDatasetManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ExternalDatasetListingModel>>> getPaged(@RequestBody ExternalDatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
DataTableData<ExternalDatasetListingModel> dataTable = new ExternalDatasetManager().getPaged(this.getApiContext(), datasetTableRequest);
DataTableData<ExternalDatasetListingModel> dataTable = externalDatasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<ExternalDatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@ -45,22 +48,22 @@ public class ExternalDatasets extends BaseController {
ResponseEntity<ResponseItem<List<ExternalDatasetListingModel>>> getWithExternal(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<ExternalDatasetListingModel> dataTable = new ExternalDatasetManager().getWithExternal(this.getApiContext(), query, this.getApiContext().getOperationsContext().getRemoteFetcher());
List<ExternalDatasetListingModel> dataTable = externalDatasetManager.getWithExternal(query);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ExternalDatasetListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getSingle/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseItem<ExternalDatasetListingModel> getWithExternal(@PathVariable UUID id, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getExternalDatasetDao(), id);
ExternalDatasetListingModel externalDatasetModel = externalDatasetManager.getSingle(id);
return new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE);
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/create"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ExternalDataset>> create(@RequestBody eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception {
ExternalDataset externalDataset = ExternalDatasetManager.create(this.getApiContext(), externalDatasetModel);
ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ExternalDataset>().payload(externalDataset).status(ApiMessageCode.SUCCESS_MESSAGE));
}
}

View File

@ -25,27 +25,28 @@ import java.util.List;
@RequestMapping(value = {"/api/files"})
public class FileController extends BaseController {
private FileManager fileManager;
@Autowired
public FileController(ApiContext apiContext) {
public FileController(ApiContext apiContext, FileManager fileManager) {
super(apiContext);
this.fileManager = fileManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem<List<ContentFile>>> handleFileUpload(@RequestParam("file") MultipartFile[] files) throws IOException {
return ResponseEntity.status(HttpStatus.OK).body(
new ResponseItem<List<ContentFile>>().status(ApiMessageCode.NO_MESSAGE).payload(FileManager.saveTempFile(files, getApiContext().getOperationsContext().getFileStorageService())));
new ResponseItem<List<ContentFile>>().status(ApiMessageCode.NO_MESSAGE).payload(fileManager.saveTempFile(files)));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}"})
public ResponseEntity<Resource> handleFileUpload(@PathVariable(name = "id") String id,
@RequestParam(name = "type") String type,
@RequestParam(name = "location", required = false, defaultValue = "final") String location) throws IOException {
Resource resource = FileManager.getFile(id, type, getApiContext().getOperationsContext().getFileStorageService(), location);
Resource resource = fileManager.getFile(id, type, location);
if (!resource.exists())
resource = new UrlResource(FileController.class.getClassLoader().getResource("images/default.png"));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "." + type + "\"")
.body(resource);
}
}

View File

@ -38,14 +38,17 @@ public class Login {
private Logger logger;
private UserManager userManager;
@Autowired
public Login(CustomAuthenticationProvider customAuthenticationProvider, AuthenticationServiceImpl authenticationServiceImpl,
TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator, Logger logger) {
TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator,
UserManager userManager ,Logger logger) {
this.customAuthenticationProvider = customAuthenticationProvider;
this.authenticationServiceImpl = authenticationServiceImpl;
this.twitterTokenValidator = twitterTokenValidator;
this.b2AccessTokenValidator = b2AccessTokenValidator;
this.logger = logger;
this.userManager = userManager;
}
@Transactional
@ -61,7 +64,7 @@ public class Login {
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> nativelogin(@RequestBody Credentials credentials) {
this.logger.info(credentials.getUsername(), "Trying To Login");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(UserManager.authenticate(this.authenticationServiceImpl, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(userManager.authenticate(this.authenticationServiceImpl, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json")

View File

@ -1,16 +1,22 @@
package eu.eudat.controllers;
import eu.eudat.data.query.items.table.organisations.OrganisationsTableRequest;
import eu.eudat.logic.managers.OrganisationsManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dmp.Organisation;
import eu.eudat.models.data.external.OrganisationsExternalSourcesModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
@ -20,9 +26,13 @@ import java.util.Map;
@RequestMapping(value = {"/api"})
public class Organisations extends BaseController {
private OrganisationsExternalSourcesModel organisationsExternalSourcesModel;
private OrganisationsManager organisationsManager;
@Autowired
public Organisations(ApiContext apiContext) {
public Organisations(ApiContext apiContext, OrganisationsExternalSourcesModel organisationsExternalSourcesModel, OrganisationsManager organisationsManager) {
super(apiContext);
this.organisationsExternalSourcesModel = organisationsExternalSourcesModel;
this.organisationsManager = organisationsManager;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/organisations"}, produces = "application/json")
@ -31,9 +41,22 @@ public class Organisations extends BaseController {
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getOrganisations(query, type);
OrganisationsExternalSourcesModel projectsExternalSourcesModel = new OrganisationsExternalSourcesModel().fromExternalItem(remoteRepos);
OrganisationsExternalSourcesModel projectsExternalSourcesModel = this.organisationsExternalSourcesModel.fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OrganisationsExternalSourcesModel>().payload(projectsExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/internal/organisations"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception{
DataTableData<Organisation> organisationDataTableData = this.organisationsManager.getPagedOrganisations(organisationsTableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<Organisation>>().payload(organisationDataTableData).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/public/organisations"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPublicPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception{
DataTableData<Organisation> organisationDataTableData = this.organisationsManager.getPublicPagedOrganisations(organisationsTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<Organisation>>().payload(organisationDataTableData).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -33,79 +33,66 @@ import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
@RequestMapping(value = {"/api/projects/"})
public class Projects extends BaseController {
private ProjectManager projectManager;
@Autowired
public Projects(ApiContext apiContext) {
public Projects(ApiContext apiContext, ProjectManager projectManager) {
super(apiContext);
this.projectManager = projectManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/projects/getPaged"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) throws Exception {
DataTableData<eu.eudat.models.data.project.ProjectListingModel> dataTable = new ProjectManager().getPaged(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), projectTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, @RequestParam String fieldsGroup, Principal principal) throws Exception {
DataTableData<eu.eudat.models.data.project.ProjectListingModel> dataTable = this.projectManager.getPaged(projectTableRequest, principal, fieldsGroup);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.data.project.ProjectListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/projects/getSingle/{id}"}, produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"public/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest) throws Exception {
DataTableData<eu.eudat.models.data.project.ProjectListingModel> dataTable = this.projectManager.getPublicPaged(projectTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.data.project.ProjectListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.data.project.Project>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
eu.eudat.models.data.project.Project project = new ProjectManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), id);
eu.eudat.models.data.project.Project project = this.projectManager.getSingle(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.project.Project>().payload(project).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/projects/createOrUpdate"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Project>> addProject(@Valid @RequestBody eu.eudat.models.data.project.Project project, Principal principal) throws IOException, ParseException {
ProjectManager.createOrUpdate(this.getApiContext().getOperationsContext().getFileStorageService(), this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getContentDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao(), project, principal);
this.projectManager.createOrUpdate(project, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/projects/inactivate/{id}"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Project>> inactivate(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
Project project = new ProjectManager().inactivate(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), id);
this.projectManager.inactivate(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/projects/getWithExternal"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.project.Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<eu.eudat.models.data.project.Project> dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext(), projectCriteria, this.getApiContext().getOperationsContext().getRemoteFetcher());
List<eu.eudat.models.data.project.Project> dataTable = this.projectManager.getCriteriaWithExternal(projectCriteria, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/projects/get"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"get"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.project.Project>>> get(@RequestBody ProjectCriteriaRequest projectCriteria, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<eu.eudat.models.data.project.Project> dataTable = new ProjectManager().getCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getOperationsContext().getRemoteFetcher());
List<eu.eudat.models.data.project.Project> dataTable = this.projectManager.getCriteria(projectCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/projects"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ProjectsExternalSourcesModel>> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getProjects(query);
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ProjectsExternalSourcesModel>().payload(projectsExternalSourcesModel).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Project>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
try{
new ProjectManager().delete(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Project>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
}catch (ProjectWithDMPsDeleteException exception){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Project>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
}
}
}

View File

@ -0,0 +1,85 @@
package eu.eudat.controllers;
import eu.eudat.logic.managers.*;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel;
import eu.eudat.models.data.quickwizard.QuickWizardModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import eu.eudat.models.data.quickwizard.DatasetCreateWizardModel;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.UUID;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api/quick-wizard/"})
public class QuickWizardController extends BaseController {
private QuickWizardManager quickWizardManager;
private ProjectManager projectManager;
private DatasetManager datasetManager;
@Autowired
public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager, ProjectManager projectManager) {
super(apiContext);
this.quickWizardManager = quickWizardManager;
this.datasetManager = datasetManager;
this.projectManager = projectManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<QuickWizardModel>> addQuickWizardModel(@Valid @RequestBody QuickWizardModel quickWizard, Principal principal) throws Exception {
eu.eudat.data.entities.Project projectEntity;
//Create Project
if (quickWizard.getProject().getExistProject() == null) {
projectEntity = this.quickWizardManager.createOrUpdate(quickWizard.getProject().toDataProject(), principal);
} else {
projectEntity = quickWizard.getProject().getExistProject().toDataModel();
}
//Create Dmp
eu.eudat.data.entities.DMP dmpEntity = this.quickWizardManager.createOrUpdate(
quickWizard.getDmp().toDataDmp(
projectEntity,
principal),
principal);
//Create Datasets
quickWizard.getDmp().setId(dmpEntity.getId());
for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) {
DataManagementPlan dmp = quickWizard.getDmp().toDataDmp( projectEntity, principal);
UUID uuid = quickWizard.getDmp().getDatasetProfile().getId();
DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, uuid);
this.datasetManager.createOrUpdate(datasetWizardModel, principal);
}
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<QuickWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasetcreate"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetCreateWizardModel>> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel, Principal principal) throws Exception{
for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){
this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()), principal);
}
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetCreateWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Dataset added!"));
}
}

View File

@ -25,9 +25,12 @@ import java.util.Map;
@RequestMapping(value = {"/api"})
public class Registries extends BaseController {
private RegistryManager registryManager;
@Autowired
public Registries(ApiContext apiContext) {
public Registries(ApiContext apiContext, RegistryManager registryManager) {
super(apiContext);
this.registryManager = registryManager;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/registries"}, produces = "application/json")
@ -39,10 +42,10 @@ public class Registries extends BaseController {
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/registries/create"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Registry>> create(@RequestBody RegistryModel registryModel, Principal principal) throws Exception {
Registry registry = RegistryManager.create(this.getApiContext(), registryModel);
Registry registry = this.registryManager.create(registryModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Registry>().payload(registry).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -22,36 +22,29 @@ import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
@RequestMapping(value = {"/api/researchers"})
public class Researchers extends BaseController {
private ResearcherManager researcherManager;
@Autowired
public Researchers(ApiContext apiContext) {
public Researchers(ApiContext apiContext, ResearcherManager researcherManager) {
super(apiContext);
this.researcherManager = researcherManager;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/researchers"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ResearchersExternalSourcesModel>> listExternalResearchers(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getResearchers(query, type);
ResearchersExternalSourcesModel researchersExternalSourcesModel = new ResearchersExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ResearchersExternalSourcesModel>().payload(researchersExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/researchers/getWithExternal"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, value = {"/getWithExternal"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound {
List<eu.eudat.models.data.dmp.Researcher> dataTable = new ResearcherManager().getCriteriaWithExternal(this.getApiContext(), this.getApiContext().getOperationsContext().getRemoteFetcher(), researcherCriteriaRequest);
List<eu.eudat.models.data.dmp.Researcher> dataTable = this.researcherManager.getCriteriaWithExternal(researcherCriteriaRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/researchers/create"}, consumes = "application/json", produces = "application/json")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Researcher>> create(@RequestBody eu.eudat.models.data.researcher.Researcher researcher, Principal principal) throws Exception {
ResearcherManager.create(this.getApiContext(), researcher);
this.researcherManager.create(researcher);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Researcher>().status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,7 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.data.entities.Service;
import eu.eudat.logic.managers.RegistryManager;
import eu.eudat.logic.managers.ServiceManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
@ -25,26 +24,29 @@ import java.util.Map;
@RequestMapping(value = {"/api"})
public class Services extends BaseController {
@Autowired
public Services(ApiContext apiContext) {
super(apiContext);
}
private ServiceManager serviceManager;
@RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Map<String, String>>>> listExternalServices(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getServices(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Map<String, String>>>().payload(remoteRepos).status(ApiMessageCode.NO_MESSAGE));
}
@Autowired
public Services(ApiContext apiContext, ServiceManager serviceManager) {
super(apiContext);
this.serviceManager = serviceManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/services/create"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Service>> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception {
Service service = ServiceManager.create(this.getApiContext(), serviceModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Service>().payload(service).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Map<String, String>>>> listExternalServices(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getServices(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Map<String, String>>>().payload(remoteRepos).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Service>> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception {
Service service = serviceManager.create(serviceModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Service>().payload(service).status(ApiMessageCode.SUCCESS_MESSAGE));
}
}

View File

@ -1,5 +1,7 @@
package eu.eudat.controllers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.elastic.criteria.TagCriteria;
import eu.eudat.elastic.entities.Dataset;
import eu.eudat.elastic.repository.Repository;
@ -15,7 +17,10 @@ import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -35,20 +40,18 @@ public class TagController extends BaseController {
this.datasetRepository = tagRepository;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/tag/create"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> create(@RequestBody Dataset dataset) throws IOException {
Dataset tagEntity = this.datasetRepository.createOrUpdate(dataset);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().payload(dataset).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/tags"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<TagExternalSourcesModel>> listExternalTagModel(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound {
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getTags(query, type);
TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(remoteRepos);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound, IOException {
/* List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getTags(query, type);
TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(remoteRepos);*/
String path = "C:\\Users\\gkolokythas\\Documents\\openDmp\\dmp-backend\\web\\src\\main\\resources\\mockupTags.json";
ObjectMapper mapper = new ObjectMapper();
List<Map<String, String>> data = mapper.readValue(new File(path), new TypeReference<List<Map<String, String>>>(){});
TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(data);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<TagExternalSourcesModel>().payload(researchersExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -23,16 +23,18 @@ import java.util.UUID;
@CrossOrigin
public class UserInvitationController extends BaseController {
private InvitationsManager invitationsManager;
@Autowired
public UserInvitationController(ApiContext apiContext) {
public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager) {
super(apiContext);
this.invitationsManager = invitationsManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/users"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Invitation>> users(@RequestBody Invitation invitation, Principal principal) throws Exception {
InvitationsManager.inviteUsers(this.getApiContext(), invitation, principal);
this.invitationsManager.inviteUsers(invitation, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Invitation>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Users have beeen invited"));
}
@ -40,14 +42,14 @@ public class UserInvitationController extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/exchange/{invitationID}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> exchange(@PathVariable UUID invitationID, Principal principal) {
UUID dmpId = InvitationsManager.assignUserAcceptedInvitation(this.getApiContext(), invitationID, principal);
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(dmpId));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getUsers"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(@RequestBody UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException {
List<UserInfoInvitationModel> users = InvitationsManager.getUsers(this.getApiContext(), userInfoRequestItem);
List<UserInfoInvitationModel> users = invitationsManager.getUsers(userInfoRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserInfoInvitationModel>>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(users));
}
}

View File

@ -29,15 +29,17 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = "api/user")
public class Users extends BaseController {
private UserManager userManager;
@Autowired
public Users(ApiContext apiContext) {
public Users(ApiContext apiContext, UserManager userManager) {
super(apiContext);
this.userManager = userManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
DataTableData<UserListingModel> dataTable = UserManager.getPaged(this.getApiContext(), userInfoTableRequestItem);
DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@ -45,7 +47,7 @@ public class Users extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
UserManager.editRoles(this.getApiContext(), userListingModel);
userManager.editRoles(userListingModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
}
@ -53,7 +55,7 @@ public class Users extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id, Principal principal) throws Exception {
UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id);
UserProfile user = UserManager.getSingle(this.getApiContext(), userId);
UserProfile user = userManager.getSingle(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE));
}
@ -61,9 +63,16 @@ public class Users extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings, Principal principal) throws IOException {
UserManager.updateSettings(this.getApiContext(), settings, principal);
userManager.updateSettings(settings, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -0,0 +1,8 @@
package eu.eudat.exceptions.datamanagementplan;
public class DMPNewVersionException extends RuntimeException {
public DMPNewVersionException(String message) {
super(message);
}
}

View File

@ -0,0 +1,9 @@
package eu.eudat.exceptions.datasetprofile;
public class DatasetProfileNewVersionException extends RuntimeException {
public DatasetProfileNewVersionException(String message) {
super(message);
}
}

View File

@ -0,0 +1,19 @@
package eu.eudat.exceptions.datasetprofile;
public class DatasetProfileWithDatasetsExeption extends RuntimeException {
public DatasetProfileWithDatasetsExeption() {
}
public DatasetProfileWithDatasetsExeption(String message) {
super(message);
}
public DatasetProfileWithDatasetsExeption(String message, Throwable cause) {
super(message, cause);
}
public DatasetProfileWithDatasetsExeption(Throwable cause) {
super(cause);
}
}

View File

@ -60,5 +60,4 @@ public final class PrincipalArgumentResolver implements HandlerMethodArgumentRes
dt = c.getTime();
return dt;
}
}

View File

@ -1,5 +1,8 @@
package eu.eudat.logic.managers;
import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.data.dao.entities.DatasetProfileDao;
import eu.eudat.exceptions.datasetprofile.DatasetProfileWithDatasetsExeption;
import eu.eudat.logic.builders.entity.DatasetProfileBuilder;
import eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel;
import eu.eudat.models.data.admin.composite.DatasetProfile;
@ -10,6 +13,7 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.Date;
import java.util.UUID;
public class AdminManager {
@ -23,7 +27,7 @@ public class AdminManager {
String xml = XmlBuilder.generateXml(viewStyleDoc);
eu.eudat.data.entities.DatasetProfile datasetProfile = apiContext.getOperationsContext().getBuilderFactory().getBuilder(DatasetProfileBuilder.class).definition(xml).label(profile.getLabel())
.status((short) 1).created(new Date())
.status(profile.getStatus()).created(new Date())
.build();
return datasetProfile;
@ -38,4 +42,18 @@ public class AdminManager {
datasetprofile.buildProfile(viewstyle);
return datasetprofile;
}
public static eu.eudat.data.entities.DatasetProfile inactivate(DatasetProfileDao datasetProfileRepository, DatasetDao datasetDao, String id) {
eu.eudat.data.dao.criteria.DatasetCriteria datasetsForThatDatasetProfile = new eu.eudat.data.dao.criteria.DatasetCriteria();
datasetsForThatDatasetProfile.setProfileDatasetId(UUID.fromString(id));
if (datasetDao.getWithCriteria(datasetsForThatDatasetProfile).count() == 0) {
eu.eudat.data.entities.DatasetProfile detasetProfile = datasetProfileRepository.find(UUID.fromString(id));
detasetProfile.setStatus(eu.eudat.data.entities.DatasetProfile.Status.DELETED.getValue());
detasetProfile = datasetProfileRepository.createOrUpdate(detasetProfile);
return detasetProfile;
} else {
throw new DatasetProfileWithDatasetsExeption("This profile can not deleted, because Datasets are associated with it");
}
}
}

View File

@ -2,74 +2,107 @@ package eu.eudat.logic.managers;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.criteria.ProjectCriteria;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.data.dao.entities.OrganisationDao;
import eu.eudat.data.dao.entities.ProjectDao;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.logic.builders.model.models.RecentActivityDataBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.dashboard.recent.RecentActivity;
import eu.eudat.models.data.dashboard.recent.RecentActivityData;
import eu.eudat.models.data.dashboard.searchbar.SearchBarItem;
import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.searchbar.SearchBarItemType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class DashBoardManager {
public DashBoardStatistics getStatistics(DatasetDao datasetRepository, DMPDao dataManagementPlanRepository, ProjectDao projectRepository) {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public DashBoardManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
public DashBoardStatistics getStatistics() {
DashBoardStatistics statistics = new DashBoardStatistics();
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setAllVersions(false);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
OrganisationCriteria organisationCriteria = new OrganisationCriteria();
datasetCriteria.setAllVersions(false);
dataManagementPlanCriteria.setAllVersions(false);
organisationCriteria.setPublic(false);
CompletableFuture dmpFuture = dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria).countAsync()
CompletableFuture dmpFuture = databaseRepository.getDmpDao().getWithCriteria(dataManagementPlanCriteria).countAsync()
.whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
CompletableFuture datasetFuture = datasetRepository.getWithCriteria(datasetCriteria).countAsync()
CompletableFuture datasetFuture = databaseRepository.getDatasetDao().getWithCriteria(datasetCriteria).countAsync()
.whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
CompletableFuture projectFuture = projectRepository.asQueryable().countAsync()
CompletableFuture projectFuture = databaseRepository.getProjectDao().asQueryable().countAsync()
.whenComplete((projectsStats, throwable) -> statistics.setTotalProjectCount(projectsStats));
CompletableFuture organisationFuture = databaseRepository.getOrganisationDao().getWithCriteria(organisationCriteria).countAsync()
.whenComplete((organisationStats, throwable) -> statistics.setTotalOrganisationCount(organisationStats));
CompletableFuture.allOf(dmpFuture, datasetFuture, projectFuture).join();
CompletableFuture.allOf(dmpFuture, datasetFuture, projectFuture, organisationFuture).join();
return statistics;
}
public DashBoardStatistics getMeStatistics(DatasetDao datasetRepository, DMPDao dataManagementPlanRepository, ProjectDao projectRepository, Principal principal) {
public DashBoardStatistics getMeStatistics(Principal principal) {
DashBoardStatistics statistics = new DashBoardStatistics();
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
ProjectDao projectRepository = databaseRepository.getProjectDao();
OrganisationDao organisationRepository = databaseRepository.getOrganisationDao();
UserInfo user = new UserInfo();
user.setId(principal.getId());
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setAllVersions(false);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
dataManagementPlanCriteria.setAllVersions(false);
CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), user).countAsync()
ProjectCriteria projectCriteria = new ProjectCriteria();
OrganisationCriteria organisationCriteria = new OrganisationCriteria();
CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId()).countAsync()
.whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
CompletableFuture datasetFuture = datasetRepository.getAuthenticated(datasetRepository.getWithCriteria(datasetCriteria), user).countAsync()
.whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
CompletableFuture projectFuture = projectRepository.getAuthenticated(projectRepository.asQueryable(), user).countAsync()
CompletableFuture projectFuture = projectRepository.getAuthenticated(projectRepository.getWithCriteria(projectCriteria), user).countAsync()
.whenComplete((projectsStats, throwable) -> statistics.setTotalProjectCount(projectsStats));
CompletableFuture orgnanisationFuture = organisationRepository.getAuthenticated(organisationRepository.asQueryable().withHint("organisationRecentActivity"), user).countAsync()
.whenComplete((organisationStats, throwable) -> statistics.setTotalOrganisationCount(organisationStats));
CompletableFuture.allOf(dmpFuture, datasetFuture, projectFuture).join();
CompletableFuture.allOf(dmpFuture, datasetFuture, projectFuture, orgnanisationFuture).join();
return statistics;
}
public RecentActivity getRecentActivity(ApiContext apiContext, DatasetDao datasetRepository, DMPDao dataManagementPlanRepository, ProjectDao projectRepository, Principal principal, Integer numberofactivities) {
public RecentActivity getRecentActivity(Principal principal, Integer numberofactivities) {
RecentActivity activity = new RecentActivity();
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
ProjectDao projectRepository = databaseRepository.getProjectDao();
UserInfo user = new UserInfo();
user.setId(principal.getId());
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setAllVersions(false);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
dataManagementPlanCriteria.setAllVersions(false);
ProjectCriteria projectCriteria = new ProjectCriteria();
RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class);
CompletableFuture<List<RecentActivityData>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), user)
CompletableFuture<List<RecentActivityData>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId())
.withHint("dmpRecentActivity")
.orderBy((builder, root) -> builder.desc(root.get("modified")))
.take(numberofactivities)
@ -83,7 +116,7 @@ public class DashBoardManager {
.selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build())
.whenComplete((datasetActivities, throwable) -> activity.setRecentDatasetActivities(datasetActivities));
CompletableFuture<List<RecentActivityData>> projects = projectRepository.getAuthenticated(projectRepository.asQueryable(), user)
CompletableFuture<List<RecentActivityData>> projects = projectRepository.getAuthenticated(projectRepository.getWithCriteria(projectCriteria), user)
.withHint("projectRecentActivity")
.orderBy((builder, root) -> builder.desc(root.get("modified")))
.take(numberofactivities)
@ -94,13 +127,16 @@ public class DashBoardManager {
return activity;
}
public List<SearchBarItem> searchUserData(String like, ApiContext apiContext, DatasetDao datasetRepository, DMPDao dataManagementPlanRepository, ProjectDao projectRepository, Principal principal) {
public List<SearchBarItem> searchUserData(String like, Principal principal) {
RecentActivity activity = new RecentActivity();
UserInfo user = new UserInfo();
user.setId(principal.getId());
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
ProjectDao projectRepository = databaseRepository.getProjectDao();
List<SearchBarItem> searchBarItems = new LinkedList<>();
CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), user)
CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), principal.getId())
.withHint("dmpRecentActivity")
.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
.orderBy((builder, root) -> builder.desc(root.get("modified")))

View File

@ -2,19 +2,22 @@ package eu.eudat.logic.managers;
import eu.eudat.configurations.dynamicproject.DynamicProjectConfiguration;
import eu.eudat.configurations.dynamicproject.entities.Property;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.criteria.ProjectCriteria;
import eu.eudat.data.dao.criteria.ResearcherCriteria;
import eu.eudat.data.dao.criteria.*;
import eu.eudat.data.dao.entities.*;
import eu.eudat.data.entities.*;
import eu.eudat.data.entities.Organisation;
import eu.eudat.data.entities.Researcher;
import eu.eudat.data.query.items.item.dmp.DataManagementPlanCriteriaRequest;
import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest;
import eu.eudat.data.query.items.table.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.exceptions.datamanagementplan.DMPNewVersionException;
import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.builders.entity.UserInfoBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.services.utilities.UtilitiesService;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.types.ParagraphStyle;
@ -22,54 +25,93 @@ import eu.eudat.logic.utilities.documents.word.WordBuilder;
import eu.eudat.logic.utilities.documents.xml.ExportXmlBuilder;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel;
import eu.eudat.models.data.dmp.*;
import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue;
import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile;
import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.Field;
import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.queryable.QueryableList;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
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 javax.activation.MimetypesFileTypeMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Component
public class DataManagementPlanManager {
public DataTableData<DataManagementPlanListingModel> getPaged(ApiContext apiContext, DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal) throws Exception {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
private ApiContext apiContext;
private DatasetManager datasetManager;
private UtilitiesService utilitiesService;
private DatabaseRepository databaseRepository;
private Environment environment;
@Autowired
public DataManagementPlanManager(ApiContext apiContext, DatasetManager datasetManager, Environment environment) {
this.apiContext = apiContext;
this.datasetManager = datasetManager;
this.utilitiesService = apiContext.getUtilitiesService();
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.environment = environment;
}
public DataTableData<DataManagementPlanListingModel> getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal, String fieldsGroup) throws Exception {
UUID principalID = principal.getId();
QueryableList<DMP> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dataManagementPlanTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class));
QueryableList<DMP> authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, userInfo);
QueryableList<DMP> authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalID);
QueryableList<DMP> pagedItems = PaginationManager.applyPaging(authItems, dataManagementPlanTableRequest);
DataTableData<DataManagementPlanListingModel> dataTable = new DataTableData<>();
CompletableFuture itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))
.selectAsync(item -> {
item.setDataset(
item.getDataset().stream()
.filter(dataset -> dataset.getDmp().getCreator().getId().equals(userInfo.getId())
|| dataset.isPublic()
|| dataset.getDmp().getUsers().stream()
.filter(x -> x.getId().equals(userInfo.getId())).collect(Collectors.toList()).size() > 0).collect(Collectors.toSet()));
return new DataManagementPlanListingModel().fromDataModel(item);
})
.whenComplete((resultList, throwable) -> dataTable.setData(resultList));
CompletableFuture itemsFuture;
if(fieldsGroup.equals("listing")){
itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))
.selectAsync(item -> {
item.setDataset(
item.getDataset().stream()
.filter(ds -> !ds.getStatus().equals(Dataset.Status.DELETED.getValue())).collect(Collectors.toList()).stream()
.filter(dataset -> dataset.getDmp().getCreator().getId().equals(principalID)
|| dataset.isPublic()
|| dataset.getDmp().getUsers().stream()
.filter(x -> x.getUser().getId().equals(principalID))
.collect(Collectors.toList()).size() > 0)
.collect(Collectors.toSet()));
return new DataManagementPlanListingModel().fromDataModelDatasets(item);
})
.whenComplete((resultList, throwable) -> dataTable.setData(resultList));
}
else{
itemsFuture = pagedItems
.selectAsync(item -> new DataManagementPlanListingModel().fromDataModel(item))
.whenComplete((resultList, throwable) -> dataTable.setData(resultList));
}
CompletableFuture countFuture = authItems.countAsync().whenComplete((count, throwable) -> {
dataTable.setTotalCount(count);
@ -78,31 +120,74 @@ public class DataManagementPlanManager {
return dataTable;
}
public void unlock(ApiContext apiContext, UUID uuid) throws Exception {
public DataTableData<DataManagementPlanListingModel> getPaged(DataManagmentPlanPublicTableRequest dataManagementPlanPublicTableRequest, String fieldsGroup) throws Exception {
dataManagementPlanPublicTableRequest.setQuery(databaseRepository.getDmpDao().asQueryable().withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)));
QueryableList<DMP> items = dataManagementPlanPublicTableRequest.applyCriteria();
QueryableList<DMP> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanPublicTableRequest);
DataTableData<DataManagementPlanListingModel> dataTable = new DataTableData<>();
CompletableFuture itemsFuture;
if(fieldsGroup.equals("listing")){
itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))
.selectAsync(item -> {
item.setDataset(
item.getDataset().stream()
.filter(dataset -> dataset.isPublic()).collect(Collectors.toSet()));
return new DataManagementPlanListingModel().fromDataModelDatasets(item);
})
.whenComplete((resultList, throwable) -> dataTable.setData(resultList));
}
else{
itemsFuture = pagedItems
.selectAsync(item -> new DataManagementPlanListingModel().fromDataModel(item))
.whenComplete((resultList, throwable) -> dataTable.setData(resultList));
}
CompletableFuture countFuture = items.countAsync().whenComplete((count, throwable) -> {
dataTable.setTotalCount(count);
});
CompletableFuture.allOf(itemsFuture, countFuture).join();
return dataTable;
}
public void unlock(UUID uuid) throws Exception {
apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
.asQueryable().where((builder, root) -> builder.equal(root.get("id"), uuid))
.update(root -> root.get("status"), DMP.DMPStatus.ACTIVE.getValue());
return;
}
public File getWordDocument(Environment environment, DMPDao dmpRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
public File getWordDocument(String id) throws InstantiationException, IllegalAccessException, IOException {
WordBuilder wordBuilder = new WordBuilder();
VisibilityRuleService visibilityRuleService = this.utilitiesService.getVisibilityRuleService();
DatasetWizardModel dataset = new DatasetWizardModel();
String fileUrl = environment.getProperty("configuration.h2020template");
InputStream is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream();
XWPFDocument document = new XWPFDocument(is);
eu.eudat.data.entities.DMP dmpEntity = dmpRepository.find(UUID.fromString(id));
eu.eudat.data.entities.DMP dmpEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
wordBuilder.addParagraphContent(dmpEntity.getLabel(), document, ParagraphStyle.TITLE, BigInteger.ZERO);
wordBuilder.addParagraphContent(dmpEntity.getDescription(), document, ParagraphStyle.TEXT, BigInteger.ZERO);
wordBuilder.addParagraphContent("Organisations", document, ParagraphStyle.HEADER2, BigInteger.ZERO);
wordBuilder.addParagraphContent(dmpEntity.getOrganisations().stream().map(x -> x.getLabel()).collect(Collectors.joining(","))
, document, ParagraphStyle.TEXT, BigInteger.ZERO);
if (dmpEntity.getOrganisations().size() > 0) {
wordBuilder.addParagraphContent(dmpEntity.getOrganisations().stream().map(x -> x.getLabel()).collect(Collectors.joining(", "))
, document, ParagraphStyle.TEXT, BigInteger.ZERO);
}
wordBuilder.addParagraphContent("Researchers", document, ParagraphStyle.HEADER2, BigInteger.ZERO);
wordBuilder.addParagraphContent(dmpEntity.getResearchers().stream().map(x -> x.getLabel()).collect(Collectors.joining(","))
, document, ParagraphStyle.TEXT, BigInteger.ZERO);
if (dmpEntity.getResearchers().size() > 0) {
wordBuilder.addParagraphContent(dmpEntity.getResearchers().stream().map(x -> x.getLabel()).collect(Collectors.joining(", "))
, document, ParagraphStyle.TEXT, BigInteger.ZERO);
}
/*wordBuilder.addParagraphContent("DMP Profile", document, ParagraphStyle.HEADER2, BigInteger.ZERO);
if (dmpEntity.getProfile() != null){
wordBuilder.addParagraphContent(dmpEntity.getProfile().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO);
}*/
wordBuilder.addParagraphContent("Datasets", document, ParagraphStyle.TITLE, BigInteger.ZERO);
dmpEntity.getDataset().stream().forEach(datasetEntity -> {
@ -114,7 +199,7 @@ public class DataManagementPlanManager {
wordBuilder.addParagraphContent("Title: " + datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO);
wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.TEXT, BigInteger.ZERO);
wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER1, BigInteger.ZERO);
PagedDatasetProfile pagedDatasetProfile = new DatasetManager().getPagedProfile(dataset, datasetEntity);
PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
try {
@ -123,16 +208,28 @@ public class DataManagementPlanManager {
e.printStackTrace();
}
});
File exportFile = new File(dmpEntity.getLabel() + ".docx");
String fileName = dmpEntity.getLabel();
fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
File exportFile = new File(environment.getProperty("configuration.exportUrl") + fileName + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
return exportFile;
}
public eu.eudat.models.data.dmp.DataManagementPlan getSingle(DMPDao dmpsRepository, String id, Principal principal, DynamicProjectConfiguration dynamicProjectConfiguration) throws InstantiationException, IllegalAccessException {
DMP dataManagementPlanEntity = dmpsRepository.find(UUID.fromString(id));
if (dataManagementPlanEntity.getCreator().getId() != principal.getId() && dataManagementPlanEntity.getUsers().stream().filter(userInfo -> userInfo.getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
/*public File getPdfDocument(String id) throws InstantiationException, IllegalAccessException, InterruptedException, IOException {
File file = this.getWordDocument(id);
String fileName = file.getName();
if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5);
}
return this.datasetManager.convertToPDF(file, environment, fileName);
}*/
public eu.eudat.models.data.dmp.DataManagementPlan getSingle(String id, Principal principal, DynamicProjectConfiguration dynamicProjectConfiguration) throws InstantiationException, IllegalAccessException {
DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (dataManagementPlanEntity.getCreator().getId() != principal.getId() && dataManagementPlanEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
eu.eudat.models.data.dmp.DataManagementPlan datamanagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan();
datamanagementPlan.fromDataModel(dataManagementPlanEntity);
@ -156,11 +253,40 @@ public class DataManagementPlanManager {
return datamanagementPlan;
}
public eu.eudat.models.data.dmp.DataManagementPlan getSinglePublic(String id, DynamicProjectConfiguration dynamicProjectConfiguration) throws Exception {
DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (dataManagementPlanEntity != null && dataManagementPlanEntity.getStatus() == 1){
eu.eudat.models.data.dmp.DataManagementPlan datamanagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan();
datamanagementPlan.fromDataModel(dataManagementPlanEntity);
Map dmpProperties = dataManagementPlanEntity.getDmpProperties() != null ? new org.json.JSONObject(dataManagementPlanEntity.getDmpProperties()).toMap() : null;
datamanagementPlan.setDynamicFields(dynamicProjectConfiguration.getFields().stream().map(item -> {
DynamicFieldWithValue fieldWithValue = new DynamicFieldWithValue();
fieldWithValue.setId(item.getId());
fieldWithValue.setDependencies(item.getDependencies());
fieldWithValue.setName(item.getName());
fieldWithValue.setQueryProperty(item.getQueryProperty());
fieldWithValue.setRequired(item.getRequired());
return fieldWithValue;
}).collect(Collectors.toList()));
if (dmpProperties != null && datamanagementPlan.getDynamicFields() != null)
datamanagementPlan.getDynamicFields().forEach(item -> {
Map<String, String> properties = (Map<String, String>) dmpProperties.get(item.getId());
if (properties != null)
item.setValue(new Tuple<>(properties.get("id"), properties.get("label")));
});
return datamanagementPlan;
}
else {
throw new Exception("Selected DMP is not public");
}
}
public List<DataManagementPlan> getWithCriteria(DMPDao dmpsRepository, DataManagementPlanCriteriaRequest dataManagementPlanCriteria, Principal principal) throws IllegalAccessException, InstantiationException {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
UUID principalID = principal.getId();
QueryableList<DMP> items = dmpsRepository.getWithCriteria(dataManagementPlanCriteria.getCriteria()).withHint(HintedModelFactory.getHint(DataManagementPlan.class));
QueryableList<DMP> authenticatedItems = dmpsRepository.getAuthenticated(items, userInfo);
QueryableList<DMP> authenticatedItems = dmpsRepository.getAuthenticated(items, principalID);
List<eu.eudat.models.data.dmp.DataManagementPlan> datamanagementPlans = authenticatedItems.select(item -> new DataManagementPlan().fromDataModel(item));
return datamanagementPlans;
}
@ -208,13 +334,18 @@ public class DataManagementPlanManager {
return result;
}
public static void createOrUpdate(ApiContext apiContext, DataManagementPlan dataManagementPlan, Principal principal) throws Exception {
public void createOrUpdate(ApiContext apiContext, DataManagementPlan dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
List<UserDMP> users = new ArrayList<>();
UserDMP userDMP = new UserDMP();
userDMP.setUser(user);
users.add(userDMP);
newDmp.setUsers(new HashSet<>(users));
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
if (dataManagementPlan.getStatus() == DMP.DMPStatus.FINALISED.getValue()) {
apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao()
@ -226,7 +357,7 @@ public class DataManagementPlanManager {
assignUser(newDmp, user, apiContext);
}
public static void assignUser(DMP dmp, UserInfo userInfo, ApiContext apiContext) {
public void assignUser(DMP dmp, UserInfo userInfo, ApiContext apiContext) {
UserDMP userDMP = new UserDMP();
userDMP.setDmp(dmp);
userDMP.setUser(userInfo);
@ -234,22 +365,35 @@ public class DataManagementPlanManager {
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP);
}
public static void newVersion(ApiContext apiContext, UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
public void newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid);
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
newDmp.setGroupId(oldDmp.getGroupId());
newDmp.setVersion(oldDmp.getVersion() + 1);
newDmp.setId(null);
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao());
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
LinkedList<UUID> list = new LinkedList<>();
list.push(oldDmp.getGroupId());
criteria.setGroupIds(list);
criteria.setAllVersions(false);
QueryableList<DMP> dataManagementPlanQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria);
List<DMP> latestVersionDMP = dataManagementPlanQueryableList.toList();
if(latestVersionDMP.get(0).getVersion().equals(oldDmp.getVersion())){
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
newDmp.setGroupId(oldDmp.getGroupId());
newDmp.setVersion(oldDmp.getVersion() + 1);
newDmp.setId(null);
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao());
} else {
throw new DMPNewVersionException("Version to update not the latest.");
}
}
public static void clone(ApiContext apiContext, UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
public void clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
@ -263,15 +407,18 @@ public class DataManagementPlanManager {
copyDatasets(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao());
}
public static void delete(ApiContext apiContext, UUID uuid) throws DMPWithDatasetsDeleteException {
DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid);
if (oldDmp.getDataset().size() > 0)
public void delete(UUID uuid) throws DMPWithDatasetsDeleteException {
DatasetCriteria criteria = new DatasetCriteria();
List<UUID> dmpIds = Collections.singletonList(uuid);
criteria.setDmpIds(dmpIds);
if (apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).toList().size()>0)
throw new DMPWithDatasetsDeleteException("You cannot Remove Datamanagement Plan with Datasets");
DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid);
oldDmp.setStatus(DMP.DMPStatus.DELETED.getValue());
apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(oldDmp);
}
private static void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository) {
private void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository) {
if (newDmp.getResearchers() != null && !newDmp.getResearchers().isEmpty()) {
for (eu.eudat.data.entities.Researcher researcher : newDmp.getResearchers()) {
ResearcherCriteria criteria = new ResearcherCriteria();
@ -283,7 +430,7 @@ public class DataManagementPlanManager {
}
}
private static void createOrganisationsIfTheyDontExist(DMP newDmp, OrganisationDao organisationRepository) {
private void createOrganisationsIfTheyDontExist(DMP newDmp, OrganisationDao organisationRepository) {
if (newDmp.getOrganisations() != null && !newDmp.getOrganisations().isEmpty()) {
for (eu.eudat.data.entities.Organisation organisation : newDmp.getOrganisations()) {
OrganisationCriteria criteria = new OrganisationCriteria();
@ -295,7 +442,7 @@ public class DataManagementPlanManager {
}
}
private static void createProjectIfItDoesntExist(DMP newDmp, ProjectDao projectDao, UserInfo userInfo) {
private void createProjectIfItDoesntExist(DMP newDmp, ProjectDao projectDao, UserInfo userInfo) {
if (newDmp.getProject() != null) {
Project project = newDmp.getProject();
ProjectCriteria criteria = new ProjectCriteria();
@ -309,8 +456,7 @@ public class DataManagementPlanManager {
}
}
private static void copyDatasets(DMP newDmp, DatasetDao datasetDao) {
private void copyDatasets(DMP newDmp, DatasetDao datasetDao) {
List<CompletableFuture<Dataset>> futures = new LinkedList<>();
for (Dataset dataset : newDmp.getDataset()) {
datasetDao.asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)).where((builder, root) -> builder.equal(root.get("id"), dataset.getId())).getSingleAsync()
@ -370,36 +516,70 @@ public class DataManagementPlanManager {
}
}
public FileEnvelope getXmlDocument(DMPDao dmpRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
public FileEnvelope getXmlDocument(String id) throws InstantiationException, IllegalAccessException, IOException {
ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
eu.eudat.data.entities.DMP dmp = dmpRepository.find(UUID.fromString(id));
VisibilityRuleService visibilityRuleService = utilitiesService.getVisibilityRuleService();
eu.eudat.data.entities.DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id));
List<Dataset> datasets = dmp.getDataset().stream().collect(Collectors.toList());
File xmlFile = new File(UUID.randomUUID() + ".xml");
String fileName = dmp.getLabel();
fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
File xmlFile = new File(fileName + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument();
Element root = xmlDoc.createElement("root");
Element dmpElement = xmlDoc.createElement("dmp");
Element dmpDescription = xmlDoc.createElement("description");
dmpDescription.setTextContent(dmp.getDescription());
dmpElement.appendChild(dmpDescription);
Element dmpName = xmlDoc.createElement("dmpName");
dmpName.setTextContent(dmp.getLabel());
dmpElement.appendChild(dmpName);
Element projectName = xmlDoc.createElement("projectName");
projectName.setTextContent(dmp.getProject().getLabel());
dmpElement.appendChild(projectName);
DMPProfile dmpProfile = dmp.getProfile();
Element dmpProfileElement = xmlDoc.createElement("dmpProfile");
Element dmpProfileName = xmlDoc.createElement("dmpProfileName");
if (!(dmpProfile == null)){
dmpProfileName.setTextContent(dmpProfile.getLabel());
dmpProfileElement.appendChild(dmpProfileName);
Element dmpProfileId = xmlDoc.createElement("dmpProfileId");
dmpProfileId.setTextContent(dmpProfile.getId().toString());
dmpProfileElement.appendChild(dmpProfileId);
Element values = xmlDoc.createElement("values");
values.setTextContent(dmpProfile.getDefinition());
dmpProfileElement.appendChild(values);
}
dmpElement.appendChild(dmpProfileElement);
Element project = xmlDoc.createElement("project");
Element label = xmlDoc.createElement("label");
label.setTextContent(dmp.getProject().getLabel());
project.appendChild(label);
Element projectId = xmlDoc.createElement("id");
projectId.setTextContent(dmp.getProject().getId().toString());
project.appendChild(projectId);
dmpElement.appendChild(project);
Element organisationsElement = xmlDoc.createElement("organisations");
for (Organisation organisation : dmp.getOrganisations()) {
Element organisationElement = xmlDoc.createElement("organisation");
organisationElement.setAttribute("name", organisation.getLabel());
organisationElement.setAttribute("reference", organisation.getReference());
Element organisationNameElement = xmlDoc.createElement("name");
organisationNameElement.setTextContent(organisation.getLabel());
Element organisationReferenceElement = xmlDoc.createElement("reference");
organisationReferenceElement.setTextContent(organisation.getReference());
organisationElement.appendChild(organisationNameElement);
organisationElement.appendChild(organisationReferenceElement);
organisationsElement.appendChild(organisationElement);
}
dmpElement.appendChild(organisationsElement);
Element researchersElement = xmlDoc.createElement("researchers");
for (Researcher researcher : dmp.getResearchers()) {
Element researcherElement = xmlDoc.createElement("organisation");
researcherElement.setAttribute("name", researcher.getLabel());
researcherElement.setAttribute("reference", researcher.getReference());
organisationsElement.appendChild(researcherElement);
Element researcherElement = xmlDoc.createElement("researcher");
Element researcherNameElement = xmlDoc.createElement("name");
researcherNameElement.setTextContent(researcher.getLabel());
Element researcherReferenceElement = xmlDoc.createElement("reference");
researcherReferenceElement.setTextContent(researcher.getReference());
researcherElement.appendChild(researcherNameElement);
researcherElement.appendChild(researcherReferenceElement);
researchersElement.appendChild(researcherElement);
}
dmpElement.appendChild(researchersElement);
Element datasetsElement = xmlDoc.createElement("datasets");
@ -413,22 +593,162 @@ public class DataManagementPlanManager {
JSONObject jobject = new JSONObject(dataset.getProperties());
properties = jobject.toMap();
}
PagedDatasetProfile pagedDatasetProfile = new DatasetManager().getPagedProfile(datasetWizardModel, dataset);
PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(datasetWizardModel, dataset);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
datasetElement.appendChild(xmlBuilder.createPages(pagedDatasetProfile.getPages(), visibilityRuleService, xmlDoc));
datasetsElement.appendChild(datasetElement);
}
Element profiles = xmlDoc.createElement("profiles");
// Get DatasetProfiles from dmp to add to XML.
if (dmp.getAssociatedDmps() != null && !dmp.getAssociatedDmps().isEmpty()) {
Document viewStyleDoc = XmlBuilder.fromXml(dmp.getAssociatedDmps());
Element item = (Element) viewStyleDoc.getElementsByTagName("profiles").item(0);
if (item != null) {
NodeList associatedProfilesElement = item.getChildNodes();
for (int temp = 0; temp < associatedProfilesElement.getLength(); temp++) {
Node associatedProfileElement = associatedProfilesElement.item(temp);
if (associatedProfileElement.getNodeType() == Node.ELEMENT_NODE) {
Element profile = xmlDoc.createElement("profile");
Element profileLabel = xmlDoc.createElement("profilelabel");
Node labelNode = associatedProfileElement.getAttributes().item(0);
profileLabel.setTextContent(labelNode.getNodeValue());
profile.appendChild(profileLabel);
Element profileId = xmlDoc.createElement("profileId");
Node idNode = associatedProfileElement.getAttributes().item(1);
profileId.setTextContent(idNode.getNodeValue());
profile.appendChild(profileId);
profiles.appendChild(profile);
}
}
}
}
dmpElement.appendChild(profiles);
dmpElement.appendChild(datasetsElement);
root.appendChild(dmpElement);
xmlDoc.appendChild(root);
xmlDoc.appendChild(dmpElement);
String xml = XmlBuilder.generateXml(xmlDoc);
writer.write(xml);
writer.close();
FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(xmlFile);
fileEnvelope.setFilename(dmp.getLabel());
return fileEnvelope;
}
public ResponseEntity<byte[]> getDocument(String id, String contentType) throws InstantiationException, InterruptedException, IllegalAccessException, IOException{
File file;
VisibilityRuleService visibilityRuleService = this.utilitiesService.getVisibilityRuleService();
DMPDao dmpDao = databaseRepository.getDmpDao();
switch (contentType){
case "application/xml":
file = getXmlDocument(id).getFile();
break;
case "application/msword":
file = getWordDocument(id);
break;
/*case "application/pdf":
file = getPdfDocument(id);
break;*/
default:
file = getXmlDocument(id).getFile();
}
InputStream resource = new FileInputStream(file);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getName());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
public List<DmpImportModel> createDmpFromXml( ApiContext apiContext, MultipartFile[] files, Principal principal) throws IOException, JAXBException, Exception {
List<DmpImportModel> dataManagementPlans = new ArrayList<>();
// Jaxb approach.
JAXBContext jaxbContext;
for (MultipartFile multipartFile : Arrays.asList(files)){ // Gets one item from the array.
try{
InputStream in = multipartFile.getInputStream(); // Transforms item to InputStream.
jaxbContext = JAXBContext.newInstance(DmpImportModel.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DmpImportModel dmpImportModel = (DmpImportModel)jaxbUnmarshaller.unmarshal(in);
dataManagementPlans.add(dmpImportModel);
}
catch (IOException | JAXBException ex){
ex.printStackTrace();
}
// TODO Iterate through the list of dataManagmentPlans.
// Creates new dataManagmentPlan to fill it with the data model that was parsed from the xml.
// Creates properties.
DataManagementPlan dm = new DataManagementPlan();
DataManagementPlanProfile dmpProfile = new DataManagementPlanProfile();
List<Field> fieldList = new LinkedList<>();
Field field = new Field();
field.setLabel(dataManagementPlans.get(0).getDmpProfile().getDmpProfileName());
field.setId(dataManagementPlans.get(0).getDmpProfile().getDmpProfileId());
fieldList.add(field);
dmpProfile.setFields(fieldList);
/*Tuple tuple = new Tuple();
tuple.setId(dataManagementPlans.get(0).getDmpProfile().getDmpProfileId());
tuple.setLabel(dataManagementPlans.get(0).getDmpProfile().getDmpProfileName());*/
eu.eudat.models.data.project.Project project = new eu.eudat.models.data.project.Project();
ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImport();
project.setId(projectImport.getId());
project.setLabel(projectImport.getLabel());
project.setAbbreviation(projectImport.getAbbreviation());
project.setDescription(projectImport.getDescription());
List<eu.eudat.models.data.dmp.AssociatedProfile> associatedProfiles = new LinkedList<>();
for(AssociatedProfileImportModels a : dataManagementPlans.get(0).getProfilesImportModels()) {
AssociatedProfile associatedProfile = new AssociatedProfile();
associatedProfile.setId(a.getId());
associatedProfile.setLabel(a.getLabel());
associatedProfiles.add(associatedProfile);
}
List< eu.eudat.models.data.dmp.Organisation > organisations = new ArrayList<>();
for(OrganisationImportModel org : dataManagementPlans.get(0).getOrganisationImportModels()) {
eu.eudat.models.data.dmp.Organisation organisation = new eu.eudat.models.data.dmp.Organisation();
organisation.setLabel(org.getOrganaisationNameImport());
organisation.setId(org.getOrganaisationReferenceImport());
organisations.add(organisation);
}
List<eu.eudat.models.data.dmp.Researcher> researchers = new LinkedList<>();
for(ResearcherImportModels res : dataManagementPlans.get(0).getResearchersImportModels()) {
eu.eudat.models.data.dmp.Researcher researcher = new eu.eudat.models.data.dmp.Researcher();
researcher.setLabel(res.getResearcherImportName());
researcher.setId(res.getResearcherImportReference());
researchers.add(researcher);
}
List<UserListingModel> associatedUsers = new LinkedList<>();
List<DynamicFieldWithValue> dynamicFields = new LinkedList<>();
// Sets properties.
dm.setLabel(files[0].getOriginalFilename()); // Sets label.
dm.setProject(project); //Sets project property.
dm.setDescription(dataManagementPlans.get(0).getDescriptionImport()); // Sets description property.
dm.setProfiles(associatedProfiles);
dm.setOrganisations(organisations); // Sets organisations property.
dm.setResearchers(researchers); // Sets researchers property.
dm.setAssociatedUsers(associatedUsers); // Sets associatedUsers property.
dm.setDynamicFields(dynamicFields); // Sets dynamicFields property.
dm.setDefinition(dmpProfile);
createOrUpdate(apiContext, dm, principal);
System.out.println(dm);
}
return dataManagementPlans;
}
}

View File

@ -4,22 +4,45 @@ import eu.eudat.data.dao.entities.DMPProfileDao;
import eu.eudat.data.entities.DMPProfile;
import eu.eudat.data.query.items.item.dmpprofile.DataManagementPlanProfileCriteriaRequest;
import eu.eudat.data.query.items.table.dmpprofile.DataManagementPlanProfileTableRequest;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.xml.dmpXml.ExportXmlBuilderDmpProfile;
import eu.eudat.logic.utilities.documents.xml.dmpXml.ImportXmlBuilderDmpProfile;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.springframework.http.*;
import org.springframework.web.multipart.MultipartFile;
/**
* Created by ikalyvas on 3/21/2018.
*/
@Component
public class DataManagementProfileManager {
public DataTableData<DataManagementPlanProfileListingModel> getPaged(ApiContext apiContext, DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public DataManagementProfileManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
public DataTableData<DataManagementPlanProfileListingModel> getPaged(DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception {
QueryableList<DMPProfile> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteria(dataManagementPlanProfileTableRequest.getCriteria());
QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanProfileTableRequest);
@ -38,21 +61,74 @@ public class DataManagementProfileManager {
return dataTable;
}
public DataManagementPlanProfileListingModel getSingle(DMPProfileDao dmpProfileDao, String id, Principal principal) throws InstantiationException, IllegalAccessException {
DMPProfile dmpProfile = dmpProfileDao.find(UUID.fromString(id));
public DataManagementPlanProfileListingModel getSingle(String id, Principal principal) throws InstantiationException, IllegalAccessException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = new DataManagementPlanProfileListingModel();
dataManagementPlanProfileListingModel.fromDataModel(dmpProfile);
return dataManagementPlanProfileListingModel;
}
public List<DataManagementPlanProfileListingModel> getWithCriteria(DMPProfileDao dmpProfileDao, DataManagementPlanProfileCriteriaRequest dataManagementPlanProfileCriteriaRequest) throws IllegalAccessException, InstantiationException {
QueryableList<DMPProfile> items = dmpProfileDao.getWithCriteria(dataManagementPlanProfileCriteriaRequest.getCriteria());
public List<DataManagementPlanProfileListingModel> getWithCriteria(DataManagementPlanProfileCriteriaRequest dataManagementPlanProfileCriteriaRequest) throws IllegalAccessException, InstantiationException {
QueryableList<DMPProfile> items = databaseRepository.getDmpProfileDao().getWithCriteria(dataManagementPlanProfileCriteriaRequest.getCriteria());
List<DataManagementPlanProfileListingModel> datamanagementPlans = items.select(item -> new DataManagementPlanProfileListingModel().fromDataModel(item));
return datamanagementPlans;
}
public static void createOrUpdate(ApiContext apiContext, DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel, Principal principal) throws Exception {
public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel, Principal principal) throws Exception {
DMPProfile dmpProfile = dataManagementPlanProfileListingModel.toDataModel();
apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile);
}
public ResponseEntity<byte[]> getDocument(DataManagementPlanProfileListingModel dmpProfile, String label) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = getXmlDocument(dmpProfile, label);
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("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);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".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 FileEnvelope getXmlDocument(DataManagementPlanProfileListingModel dmpProfile, String label) throws InstantiationException, IllegalAccessException, IOException {
ExportXmlBuilderDmpProfile xmlBuilder = new ExportXmlBuilderDmpProfile();
File file = xmlBuilder.build(dmpProfile);
FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(file);
fileEnvelope.setFilename(label);
return fileEnvelope;
}
public eu.eudat.logic.utilities.documents.xml.dmpXml.dmpProfileModel.DmpProfile createDmpProfileFromXml(MultipartFile multiPartFile) {
ImportXmlBuilderDmpProfile xmlBuilder = new ImportXmlBuilderDmpProfile();
try {
return xmlBuilder.build(convert(multiPartFile));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
}

View File

@ -4,12 +4,22 @@ import eu.eudat.data.entities.DataRepository;
import eu.eudat.data.entities.Researcher;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by ikalyvas on 9/3/2018.
*/
@Component
public class DataRepositoryManager {
public static DataRepository create(ApiContext apiContext, eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel) throws Exception {
private ApiContext apiContext;
@Autowired
public DataRepositoryManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public DataRepository create(eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel) throws Exception {
DataRepository dataRepository = dataRepositoryModel.toDataModel();
return apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().createOrUpdate(dataRepository);
}

View File

@ -1,65 +1,105 @@
package eu.eudat.logic.managers;
import eu.eudat.data.dao.criteria.DataRepositoryCriteria;
import eu.eudat.data.dao.criteria.ExternalDatasetCriteria;
import eu.eudat.data.dao.criteria.RegistryCriteria;
import eu.eudat.data.dao.criteria.ServiceCriteria;
import eu.eudat.data.dao.criteria.*;
import eu.eudat.data.dao.entities.*;
import eu.eudat.data.entities.*;
import eu.eudat.data.query.items.table.dataset.DatasetPublicTableRequest;
import eu.eudat.data.query.items.table.dataset.DatasetTableRequest;
import eu.eudat.elastic.criteria.DatasetCriteria;
import eu.eudat.elastic.repository.DatasetRepository;
import eu.eudat.logic.builders.BuilderFactory;
import eu.eudat.logic.builders.entity.UserInfoBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.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.models.HintedModelFactory;
import eu.eudat.models.data.datasetImport.*;
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.security.Principal;
import eu.eudat.models.data.user.composite.DatasetProfilePage;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.queryable.QueryableList;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.activation.MimetypesFileTypeMap;
import javax.mail.Multipart;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@Component
public class DatasetManager {
public DataTableData<DatasetListingModel> getPaged(ApiContext apiContext, DatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private DatasetRepository datasetRepository;
private BuilderFactory builderFactory;
private UserManager userManager;
@Autowired
public DatasetManager(ApiContext apiContext, UserManager userManager) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.datasetRepository = apiContext.getOperationsContext().getDatasetRepository();
this.builderFactory = apiContext.getOperationsContext().getBuilderFactory();
this.userManager = userManager;
}
public DataTableData<DatasetListingModel> getPaged(DatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setTags(datasetTableRequest.getCriteria().getTags());
List<eu.eudat.elastic.entities.Dataset> datasets = apiContext.getOperationsContext().getDatasetRepository().exists() ?
apiContext.getOperationsContext().getDatasetRepository().query(datasetCriteria) : new LinkedList<>();
List<eu.eudat.elastic.entities.Dataset> datasets;
try {
datasets = datasetCriteria.getTags() != null && datasetCriteria.getTags().size() > 0 && datasetRepository.exists() ?
datasetRepository.query(datasetCriteria) : new LinkedList<>();
}
catch (Exception ex){
datasets = null;
}
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
QueryableList<eu.eudat.data.entities.Dataset> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));
if (datasetTableRequest.getCriteria().getTags() != null && !datasetTableRequest.getCriteria().getTags().isEmpty()) {
if (!datasets.isEmpty())
items.where((builder, root) -> root.get("id").in(datasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList())));
UserInfo userInfo = builderFactory.getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
QueryableList<eu.eudat.data.entities.Dataset> items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));
if (datasets != null && datasetTableRequest.getCriteria().getTags() != null && !datasetTableRequest.getCriteria().getTags().isEmpty()) {
if (!datasets.isEmpty()){
List<eu.eudat.elastic.entities.Dataset> finalDatasets = datasets;
items.where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList())));
}
else
items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()}));
}
QueryableList<eu.eudat.data.entities.Dataset> authItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getAuthenticated(items, userInfo);
QueryableList<eu.eudat.data.entities.Dataset> authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo);
QueryableList<eu.eudat.data.entities.Dataset> pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest);
DataTableData<DatasetListingModel> dataTable = new DataTableData<DatasetListingModel>();
@ -77,17 +117,24 @@ public class DatasetManager {
return dataTable;
}
public DataTableData<DatasetListingModel> getPaged(ApiContext apiContext, DatasetPublicTableRequest datasetTableRequest, Principal principal) throws Exception {
public DataTableData<DatasetListingModel> getPaged(DatasetPublicTableRequest datasetTableRequest, Principal principal) throws Exception {
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setTags(datasetTableRequest.getCriteria().getTags());
List<eu.eudat.elastic.entities.Dataset> datasets = apiContext.getOperationsContext().getDatasetRepository().exists() ?
apiContext.getOperationsContext().getDatasetRepository().query(datasetCriteria) : new LinkedList<>();
datasetTableRequest.setQuery(apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)));
List<eu.eudat.elastic.entities.Dataset> datasets;
try{
datasets = datasetCriteria.getTags() != null && datasetCriteria.getTags().size() > 0 && datasetRepository.exists() ?
datasetRepository.query(datasetCriteria) : new LinkedList<>();
}
catch (Exception ex){
datasets = null;
}
datasetTableRequest.setQuery(databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)));
QueryableList<Dataset> items = datasetTableRequest.applyCriteria();
if (datasetTableRequest.getCriteria().getTags() != null && !datasetTableRequest.getCriteria().getTags().isEmpty()) {
if (!datasets.isEmpty())
items.where((builder, root) -> root.get("id").in(datasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList())));
if (datasets != null && datasetTableRequest.getCriteria().getTags() != null && !datasetTableRequest.getCriteria().getTags().isEmpty()) {
if (!datasets.isEmpty()) {
List<eu.eudat.elastic.entities.Dataset> finalDatasets = datasets;
items.where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList())));
}
else
items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()}));
}
@ -107,19 +154,72 @@ public class DatasetManager {
return dataTable;
}
public DatasetWizardModel getSingle(DatasetDao datatasetRepository, DatasetRepository elasticDatasetRepository, String id) throws InstantiationException, IllegalAccessException, IOException {
public DatasetWizardModel getSingle(String id) throws InstantiationException, IllegalAccessException, IOException {
DatasetWizardModel dataset = new DatasetWizardModel();
eu.eudat.data.entities.Dataset datasetEntity = datatasetRepository.find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
eu.eudat.elastic.entities.Dataset datasetElastic = elasticDatasetRepository.exists() ?
elasticDatasetRepository.findDocument(id) : new eu.eudat.elastic.entities.Dataset();
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
eu.eudat.elastic.entities.Dataset datasetElastic;
try{
datasetElastic = datasetRepository.exists() ?
datasetRepository.findDocument(id) : new eu.eudat.elastic.entities.Dataset();
}
catch (Exception ex){
datasetElastic = new eu.eudat.elastic.entities.Dataset();
}
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
dataset.fromDataModel(datasetEntity);
// Creates the Criteria to get all version of DatasetProfile in question.
DatasetProfileCriteria profileCriteria = new DatasetProfileCriteria();
UUID profileId = datasetEntity.getProfile().getGroupId();
List<UUID> uuidList = new LinkedList<>();
uuidList.add(profileId);
profileCriteria.setGroupIds(uuidList);
profileCriteria.setAllVersions(true);
List<eu.eudat.data.entities.DatasetProfile> profileVersions = databaseRepository.getDatasetProfileDao().getWithCriteria(profileCriteria)
.orderBy(((builder, root) -> builder.desc(root.get("version"))))
.toList();
List<DatasetProfile> profileVersionsIncluded = new LinkedList<>();
// Iterate through the versions and remove those that are not included in the DMP of the dataset in question.
for(DatasetProfile version : profileVersions) {
for(AssociatedProfile p : dataset.getDmp().getProfiles()){
if(version.getId().toString().equals(p.getId().toString())) {
profileVersionsIncluded.add(version);
}
}
}
// Sort the list with the included Versions.
Stream<DatasetProfile> sorted = profileVersionsIncluded.stream().sorted(Comparator.comparing(DatasetProfile::getVersion).reversed());
// Make the Stream into List and get the first item.
DatasetProfile profile = sorted.collect(Collectors.toList()).iterator().next();
// Check if the dataset is on the latest Version.
boolean latestVersion = profile.getVersion().toString().equals(datasetEntity.getProfile().getVersion().toString());
dataset.setIsProfileLatestVersion(latestVersion);
dataset.setTags(datasetElastic.getTags());
return dataset;
}
public DatasetWizardModel getSinglePublic(String id) throws Exception {
DatasetWizardModel dataset = new DatasetWizardModel();
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().isPublicDataset(UUID.fromString(id));
if (datasetEntity != null && datasetEntity.getStatus() == 1 && datasetEntity.getDmp().getStatus() == 1){
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
dataset.fromDataModel(datasetEntity);
return dataset;
}
else {
throw new Exception("Selected dataset is not public");
}
}
public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, eu.eudat.data.entities.Dataset datasetEntity) {
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = UserManager.generateDatasetProfileModel(datasetEntity.getProfile());
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(datasetEntity.getProfile());
datasetprofile.setStatus(dataset.getStatus());
if (datasetEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
@ -131,13 +231,14 @@ public class DatasetManager {
return pagedDatasetProfile;
}
public File getWordDocument(Environment environment, DatasetDao datatasetRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
public File getWordDocument(Environment environment, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
WordBuilder wordBuilder = new WordBuilder();
DatasetWizardModel dataset = new DatasetWizardModel();
String fileUrl = environment.getProperty("configuration.h2020template");
InputStream is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream();
XWPFDocument document = new XWPFDocument(is);
eu.eudat.data.entities.Dataset datasetEntity = datatasetRepository.find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
wordBuilder.addParagraphContent(datasetEntity.getLabel(), document, ParagraphStyle.TITLE, BigInteger.ZERO);
Map<String, Object> properties = new HashMap<>();
if (datasetEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
@ -147,17 +248,18 @@ public class DatasetManager {
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService);
File exportFile = new File(datasetEntity.getLabel() + ".docx");
String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", "");
File exportFile = new File(environment.getProperty("configuration.exportUrl") + label + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
return exportFile;
}
public FileEnvelope getXmlDocument(DatasetDao datatasetRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
public FileEnvelope getXmlDocument(String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
DatasetWizardModel dataset = new DatasetWizardModel();
eu.eudat.data.entities.Dataset datasetEntity = datatasetRepository.find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
Map<String, Object> properties = new HashMap<>();
if (datasetEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
@ -166,7 +268,7 @@ public class DatasetManager {
PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, datasetEntity);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
File file = xmlBuilder.build(pagedDatasetProfile, visibilityRuleService);
File file = xmlBuilder.build(pagedDatasetProfile, datasetEntity.getProfile().getId(), visibilityRuleService);
FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(file);
fileEnvelope.setFilename(datasetEntity.getLabel());
@ -175,45 +277,24 @@ public class DatasetManager {
public File convertToPDF(File file, Environment environment, String label) throws IOException, InterruptedException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
map.add("files", new FileSystemResource(file));
map.add("filename", label + ".pdf");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("Content-disposition", "attachment; filename=" + label + ".docx");
headers.add("Content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
headers.add("Content-disposition", "attachment; filename=" + label + ".pdf");
headers.add("Content-type", "application/pdf");
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
Map queueResult = new RestTemplate().postForObject(
environment.getProperty("pdf.converter.url") +
"api/v1/", requestEntity, Map.class);
byte[] queueResult = new RestTemplate().postForObject(environment.getProperty("pdf.converter.url") + "convert/office"
, requestEntity, byte[].class);
Map mediaResult = new RestTemplate().getForObject(environment.getProperty("pdf.converter.url") +
"/api/v1/" + queueResult.get("id"), Map.class);
System.out.println("Status: " + mediaResult.get("status"));
while (!mediaResult.get("status").equals("finished")) {
Thread.sleep(500);
mediaResult = new RestTemplate().getForObject(environment.getProperty("pdf.converter.url") +
"api/v1/" + queueResult.get("id"), Map.class);
System.out.println("Polling");
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers2 = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers2);
File resultPdf = new File(environment.getProperty("configuration.exportUrl") + label + ".pdf");
FileOutputStream output = new FileOutputStream(resultPdf);
IOUtils.write(queueResult, output);
ResponseEntity<byte[]> response = restTemplate.exchange(environment.getProperty("pdf.converter.url") +
mediaResult.get("result_url"), HttpMethod.GET, entity, byte[].class, "1");
UUID uuid = UUID.randomUUID();
File zip = new File(uuid + ".zip");
if (response.getStatusCode().equals(HttpStatus.OK)) {
FileOutputStream output = new FileOutputStream(zip);
IOUtils.write(response.getBody(), output);
}
return extractFromZip(zip, label + ".pdf");
return resultPdf;
}
private File extractFromZip(File file, String filename) throws IOException {
@ -239,7 +320,7 @@ public class DatasetManager {
return newFile;
}
public static eu.eudat.data.entities.Dataset createOrUpdate(ApiContext apiContext, DatasetWizardModel datasetWizardModel, Principal principal) throws Exception {
public eu.eudat.data.entities.Dataset createOrUpdate(DatasetWizardModel datasetWizardModel, Principal principal) throws Exception {
eu.eudat.data.entities.Dataset dataset = datasetWizardModel.toDataModel();
propertiesModelToString(datasetWizardModel, dataset);
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
@ -247,12 +328,12 @@ public class DatasetManager {
updateTags(apiContext.getOperationsContext().getDatasetRepository(), datasetWizardModel);
createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), dataset);
createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset);
createServicesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDatasetServiceDao(), apiContext.getOperationsContext().getDatabaseRepository().getServiceDao(), dataset);
createExternalDatasetsIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDatasetExternalDatasetDao(), apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao(), dataset);
createServicesIfTheyDontExist(dataset);
createExternalDatasetsIfTheyDontExist(dataset);
return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset);
}
private static void propertiesModelToString(DatasetWizardModel datasetWizardModel, eu.eudat.data.entities.Dataset dataset) {
private void propertiesModelToString(DatasetWizardModel datasetWizardModel, eu.eudat.data.entities.Dataset dataset) {
Map<String, Object> values = new HashMap();
PagedDatasetProfile properties = datasetWizardModel.getDatasetProfileDefinition();
properties.toMap(values);
@ -260,7 +341,7 @@ public class DatasetManager {
dataset.setProperties(jobject.toString());
}
private static void updateTags(DatasetRepository datasetRepository, DatasetWizardModel datasetWizardModel) throws IOException {
private void updateTags(DatasetRepository datasetRepository, DatasetWizardModel datasetWizardModel) throws IOException {
if (datasetWizardModel.getTags() != null && !datasetWizardModel.getTags().isEmpty()) {
eu.eudat.elastic.entities.Dataset dataset = new eu.eudat.elastic.entities.Dataset();
dataset.setId(datasetWizardModel.getId().toString());
@ -269,7 +350,7 @@ public class DatasetManager {
}
}
private static void createRegistriesIfTheyDontExist(RegistryDao registryDao, eu.eudat.data.entities.Dataset dataset) {
private void createRegistriesIfTheyDontExist(RegistryDao registryDao, eu.eudat.data.entities.Dataset dataset) {
if (dataset.getRegistries() != null && !dataset.getRegistries().isEmpty()) {
for (eu.eudat.data.entities.Registry registry : dataset.getRegistries()) {
RegistryCriteria criteria = new RegistryCriteria();
@ -281,7 +362,7 @@ public class DatasetManager {
}
}
private static void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, eu.eudat.data.entities.Dataset dataset) {
private void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, eu.eudat.data.entities.Dataset dataset) {
Set<DatasetDataRepository> datasetDataRepositories = dataset.getDatasetDataRepositories();
dataset.setDatasetDataRepositories(new HashSet<>());
@ -304,20 +385,20 @@ public class DatasetManager {
}
}
private static void createServicesIfTheyDontExist(DatasetServiceDao datasetServiceDao, ServiceDao serviceDao, eu.eudat.data.entities.Dataset dataset) {
private void createServicesIfTheyDontExist(eu.eudat.data.entities.Dataset dataset) {
Set<DatasetService> services = dataset.getServices();
dataset.setServices(new HashSet<>());
if (services != null && !services.isEmpty()) {
for (eu.eudat.data.entities.DatasetService datasetService : services) {
ServiceCriteria criteria = new ServiceCriteria();
criteria.setLike(datasetService.getService().getLabel());
List<eu.eudat.data.entities.Service> entries = serviceDao.getWithCriteria(criteria).toList();
List<eu.eudat.data.entities.Service> entries = databaseRepository.getServiceDao().getWithCriteria(criteria).toList();
if (entries != null && !entries.isEmpty()) {
datasetService.getService().setId(entries.get(0).getId());
datasetService.setDataset(dataset);
dataset.getServices().add(datasetService);
} else {
Service service = serviceDao.createOrUpdate(datasetService.getService());
Service service = databaseRepository.getServiceDao().createOrUpdate(datasetService.getService());
datasetService.setService(service);
dataset.getServices().add(datasetService);
}
@ -325,20 +406,20 @@ public class DatasetManager {
}
}
private static void createExternalDatasetsIfTheyDontExist(DatasetExternalDatasetDao datasetExternalDatasetDao, ExternalDatasetDao externalDatasetDao, eu.eudat.data.entities.Dataset dataset) {
private void createExternalDatasetsIfTheyDontExist(eu.eudat.data.entities.Dataset dataset) {
Set<DatasetExternalDataset> externalDatasets = dataset.getDatasetExternalDatasets();
dataset.setDatasetExternalDatasets(new HashSet<>());
if (externalDatasets != null && !externalDatasets.isEmpty()) {
for (eu.eudat.data.entities.DatasetExternalDataset datasetExternalDataset : externalDatasets) {
ExternalDatasetCriteria criteria = new ExternalDatasetCriteria();
criteria.setLike(datasetExternalDataset.getExternalDataset().getLabel());
List<eu.eudat.data.entities.ExternalDataset> entries = externalDatasetDao.getWithCriteria(criteria).toList();
List<eu.eudat.data.entities.ExternalDataset> entries = databaseRepository.getExternalDatasetDao().getWithCriteria(criteria).toList();
if (entries != null && !entries.isEmpty()) {
datasetExternalDataset.getExternalDataset().setId(entries.get(0).getId());
datasetExternalDataset.setDataset(dataset);
dataset.getDatasetExternalDatasets().add(datasetExternalDataset);
} else {
ExternalDataset externalDataset = externalDatasetDao.createOrUpdate(datasetExternalDataset.getExternalDataset());
ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().createOrUpdate(datasetExternalDataset.getExternalDataset());
datasetExternalDataset.setExternalDataset(externalDataset);
dataset.getDatasetExternalDatasets().add(datasetExternalDataset);
}
@ -346,11 +427,152 @@ public class DatasetManager {
}
}
public static void makePublic(DatasetDao datasetDao, UUID id) throws Exception {
public void makePublic(DatasetDao datasetDao, UUID id) throws Exception {
eu.eudat.data.entities.Dataset dataset = datasetDao.find(id);
if (dataset.getStatus() != eu.eudat.data.entities.Dataset.Status.FINALISED.getValue())
throw new Exception("You cannot make public a Dataset That Has not Been Finalised");
datasetDao.createOrUpdate(dataset);
}
public ResponseEntity<byte[]> getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = getXmlDocument(id, visibilityRuleService);
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("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);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".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 eu.eudat.data.entities.Dataset createDatasetFromXml(MultipartFile importFile, String dmpId, String datasetProfileId, Principal principal) throws JAXBException, IOException {
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) {
e.printStackTrace();
}
// Checks if XML datasetProfileId GroupId matches the one selected.
try {
eu.eudat.data.entities.DatasetProfile importDatasetProfile = databaseRepository.getDatasetProfileDao().find(UUID.fromString(importModel.getDatasetProfileId()));
eu.eudat.data.entities.DatasetProfile latestVersionDatasetProfile = databaseRepository.getDatasetProfileDao().find(UUID.fromString(datasetProfileId));
if (latestVersionDatasetProfile.getGroupId() != importDatasetProfile.getGroupId()) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
// Creates the Hash Map to place the values of the data set.
Map<String, String> 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.
eu.eudat.data.entities.Dataset entity = new Dataset();
entity.setProperties(jsonDatasetProperties.toString());
entity.setLabel(importFile.getOriginalFilename());
DMP dmp = new DMP();
dmp.setId(UUID.fromString(dmpId));
entity.setDmp(dmp);
entity.setStatus((short) 0);
entity.setPublic(false);
entity.setCreated(new Date());
entity.setModified(new Date());
DatasetProfile profile = new DatasetProfile();
profile.setId(UUID.fromString(datasetProfileId));
entity.setProfile(profile);
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
entity.setCreator(userInfo);
updateTagsXmlImportDataset(apiContext.getOperationsContext().getDatasetRepository(), entity);
createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), entity);
createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), entity);
createServicesIfTheyDontExist(entity);
createExternalDatasetsIfTheyDontExist(entity);
return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(entity);
}
public void updateTagsXmlImportDataset(DatasetRepository datasetRepository, Dataset dataset) throws IOException {
// TODO: When tags functionality return.
}
public DatasetWizardModel datasetUpdateProfile(String id) {
DatasetWizardModel dataset = new DatasetWizardModel();
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
eu.eudat.elastic.entities.Dataset datasetElastic;
try{
datasetElastic = datasetRepository.exists() ?
datasetRepository.findDocument(id) : new eu.eudat.elastic.entities.Dataset();
}
catch (Exception ex){
datasetElastic = new eu.eudat.elastic.entities.Dataset();
}
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
dataset.fromDataModel(datasetEntity);
// Creates the Criteria to get all version of DatasetProfile in question.
DatasetProfileCriteria profileCriteria = new DatasetProfileCriteria();
UUID profileId = datasetEntity.getProfile().getGroupId();
List<UUID> uuidList = new LinkedList<>();
uuidList.add(profileId);
profileCriteria.setGroupIds(uuidList);
// Gets the latest version of the datasetProfile.
eu.eudat.data.entities.DatasetProfile item = databaseRepository.getDatasetProfileDao().getWithCriteria(profileCriteria).getSingle();
// Sets the latest version of dataet Profile to the Dataset in question.
dataset.setDatasetProfileDefinition(getLatestDatasetProfile(datasetEntity, item));
dataset.setProfile(item.getId());
// Now at latest version.
dataset.setIsProfileLatestVersion(true);
dataset.setTags(datasetElastic.getTags());
return dataset;
}
public PagedDatasetProfile getLatestDatasetProfile(Dataset datasetEntity, DatasetProfile profile) {
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
datasetprofile.setStatus(datasetEntity.getStatus());
if (datasetEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
Map<String, Object> properties = jobject.toMap();
datasetprofile.fromJsonObject(properties);
}
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return pagedDatasetProfile;
}
}

View File

@ -2,15 +2,19 @@ package eu.eudat.logic.managers;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.dao.entities.DatasetProfileDao;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.entities.DatasetProfile;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileAutocompleteRequest;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
import eu.eudat.exceptions.datasetprofile.DatasetProfileNewVersionException;
import eu.eudat.logic.builders.model.models.DataTableDataBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.ExportXmlBuilderDatasetProfile;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.ImportXmlBuilderDatasetProfile;
import eu.eudat.models.data.components.commons.datafield.AutoCompleteData;
import eu.eudat.models.data.datasetprofile.DatasetProfileAutocompleteItem;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
@ -18,44 +22,71 @@ import eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field;
import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.activation.MimetypesFileTypeMap;
import javax.xml.xpath.*;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.io.*;
@Component
public class DatasetProfileManager {
public static List<DatasetProfileAutocompleteItem> getWithCriteria(DatasetProfileDao datasetProfileRepository, DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws IllegalAccessException, InstantiationException {
QueryableList<DatasetProfile> items = datasetProfileRepository.getWithCriteria(datasetProfileAutocompleteRequest.getCriteria());
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public DatasetProfileManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
public eu.eudat.models.data.admin.composite.DatasetProfile getDatasetProfile(String id) {
eu.eudat.data.entities.DatasetProfile profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel());
datasetprofile.setStatus(profile.getStatus());
return datasetprofile;
}
public List<DatasetProfileAutocompleteItem> getWithCriteria(DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws IllegalAccessException, InstantiationException {
QueryableList<DatasetProfile> items = databaseRepository.getDatasetProfileDao().getWithCriteria(datasetProfileAutocompleteRequest.getCriteria());
List<DatasetProfileAutocompleteItem> datasetProfiles = items.select(item -> new DatasetProfileAutocompleteItem().fromDataModel(item));
return datasetProfiles;
}
public DatasetProfile clone(ApiContext apiContext, String id) {
DatasetProfile profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
public DatasetProfile clone(String id) {
DatasetProfile profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
apiContext.getOperationsContext().getDatabaseRepository().detachEntity(profile);
profile.setId(null);
return profile;
}
public static DataTableData<DatasetProfileListingModel> getPaged(ApiContext apiContext, DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
public DataTableData<DatasetProfileListingModel> getPaged(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
QueryableList<DatasetProfile> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
QueryableList<DatasetProfile> pagedItems = PaginationManager.applyPaging(items, datasetProfileTableRequestItem);
List<DatasetProfileListingModel> datasetProfiles = pagedItems.select(item -> new DatasetProfileListingModel().fromDataModel(item));
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(datasetProfiles).totalCount(items.count()).build();
}
public static List<DatasetProfileListingModel> getAll(DatasetProfileDao datasetProfileRepository) throws IllegalAccessException, InstantiationException {
QueryableList<DatasetProfile> items = datasetProfileRepository.getAll();
public List<DatasetProfileListingModel> getAll() throws IllegalAccessException, InstantiationException {
DatasetProfileCriteria criteria = new DatasetProfileCriteria();
QueryableList<DatasetProfile> items = databaseRepository.getDatasetProfileDao().getWithCriteria(criteria);
List<DatasetProfileListingModel> datasetProfiles = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
return datasetProfiles;
}
public static eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field queryForField(String xml, String fieldId) throws XPathExpressionException {
public eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field queryForField(String xml, String fieldId) throws XPathExpressionException {
eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field field = new Field();
Document document = XmlBuilder.fromXml(xml);
XPathFactory xpathFactory = XPathFactory.newInstance();
@ -67,7 +98,7 @@ public class DatasetProfileManager {
return field;
}
public static List<Tuple<String, String>> getAutocomplete(AutoCompleteData data, String like) {
public List<Tuple<String, String>> getAutocomplete(AutoCompleteData data, String like) {
List<Tuple<String, String>> result = new LinkedList<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
@ -83,10 +114,78 @@ public class DatasetProfileManager {
return result;
}
public void delete(ApiContext apiContext, UUID uuid) {
DatasetProfile datasetProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(uuid);
datasetProfile.setStatus(DMP.DMPStatus.DELETED.getValue());
apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetProfile);
public ResponseEntity<byte[]> getDocument(eu.eudat.models.data.user.composite.DatasetProfile datasetProfile, String label) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = getXmlDocument(datasetProfile, label);
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("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);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".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 FileEnvelope getXmlDocument(eu.eudat.models.data.user.composite.DatasetProfile datatasetProfile, String label) throws InstantiationException, IllegalAccessException, IOException {
ExportXmlBuilderDatasetProfile xmlBuilder = new ExportXmlBuilderDatasetProfile();
File file = xmlBuilder.build(datatasetProfile);
FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(file);
fileEnvelope.setFilename(label);
return fileEnvelope;
}
public eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile createDatasetProfileFromXml(MultipartFile multiPartFile) {
ImportXmlBuilderDatasetProfile xmlBuilder = new ImportXmlBuilderDatasetProfile();
try {
return xmlBuilder.build(convert(multiPartFile));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
public eu.eudat.data.entities.DatasetProfile createNewVersionDatasetProfile(String id, eu.eudat.models.data.admin.composite.DatasetProfile profile) throws Exception {
// Getting the DatasetProfile which we will create its new version.
eu.eudat.data.entities.DatasetProfile oldDatasetProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
// Getting the DatasetProfile with the latest Version.
DatasetProfileCriteria criteria = new DatasetProfileCriteria();
LinkedList<UUID> list = new LinkedList<>();
list.push(oldDatasetProfile.getGroupId());
criteria.setGroupIds(list);
criteria.setAllVersions(false);
QueryableList<DatasetProfile> datasetProfileQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria);
eu.eudat.data.entities.DatasetProfile latestVersionDatasetProfile = datasetProfileQueryableList.getSingle();
if (latestVersionDatasetProfile.getVersion().equals(oldDatasetProfile.getVersion())){
eu.eudat.models.data.admin.composite.DatasetProfile sortedProfile = profile.toShort();
eu.eudat.data.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(sortedProfile, apiContext);
modelDefinition.setLabel(oldDatasetProfile.getLabel());
modelDefinition.setVersion((short) (oldDatasetProfile.getVersion() + 1));
modelDefinition.setGroupId(oldDatasetProfile.getGroupId());
apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return modelDefinition;
} else {
throw new DatasetProfileNewVersionException("Version to update not the latest.");
}
}
}

View File

@ -1,6 +1,7 @@
package eu.eudat.logic.managers;
import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.word.WordBuilder;
@ -11,10 +12,12 @@ import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
@ -31,7 +34,16 @@ import java.util.zip.ZipInputStream;
/**
* Created by ikalyvas on 10/16/2018.
*/
@Service
public class DocumentManager {
private ApiContext context;
private DatasetManager datasetManager;
public DocumentManager(ApiContext context, DatasetManager datasetManager) {
this.context = context;
this.datasetManager = datasetManager;
}
public File getWordDocument(Environment environment, DatasetDao datatasetRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
WordBuilder wordBuilder = new WordBuilder();
DatasetWizardModel dataset = new DatasetWizardModel();
@ -44,11 +56,11 @@ public class DocumentManager {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
properties = jobject.toMap();
}
PagedDatasetProfile pagedDatasetProfile = new DatasetManager().getPagedProfile(dataset, datasetEntity);
PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService);
File exportFile = new File(dataset.getLabel() + ".docx");
File exportFile = new File(environment.getProperty("configuration.exportUrl") + dataset.getLabel() + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
@ -63,10 +75,10 @@ public class DocumentManager {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
properties = jobject.toMap();
}
PagedDatasetProfile pagedDatasetProfile = new DatasetManager().getPagedProfile(dataset, datasetEntity);
PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
File file = xmlBuilder.build(pagedDatasetProfile, visibilityRuleService);
File file = xmlBuilder.build(pagedDatasetProfile, UUID.fromString(id), visibilityRuleService);
FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(file);
fileEnvelope.setFilename(datasetEntity.getLabel());

View File

@ -5,6 +5,7 @@ import eu.eudat.logic.builders.model.models.DataTableDataBuilder;
import eu.eudat.data.dao.entities.ExternalDatasetDao;
import eu.eudat.data.entities.ExternalDataset;
import eu.eudat.data.dao.criteria.ExternalDatasetCriteria;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.externaldataset.ExternalDatasetListingModel;
import eu.eudat.data.query.items.table.externaldataset.ExternalDatasetTableRequest;
import eu.eudat.models.data.helpers.common.DataTableData;
@ -13,35 +14,47 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.UUID;
@Component
public class ExternalDatasetManager {
public DataTableData<ExternalDatasetListingModel> getPaged(ApiContext apiContext, ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private RemoteFetcher remoteFetcher;
@Autowired
public ExternalDatasetManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
}
public DataTableData<ExternalDatasetListingModel> getPaged(ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception {
QueryableList<ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(externalDatasetTableRequest.getCriteria());
QueryableList<ExternalDataset> pagedItems = PaginationManager.applyPaging(items, externalDatasetTableRequest);
List<ExternalDatasetListingModel> externalDatasetListingmodels = pagedItems.select(item -> new ExternalDatasetListingModel().fromDataModel(item));
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(externalDatasetListingmodels).totalCount(items.count()).build();
}
public List<ExternalDatasetListingModel> getWithExternal(ApiContext apiContext, String query, RemoteFetcher remoteFetcher) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
public List<ExternalDatasetListingModel> getWithExternal(String query) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build();
QueryableList<eu.eudat.data.entities.ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria);
List<ExternalDatasetListingModel> externalDatasets = items.select(item -> new ExternalDatasetListingModel().fromDataModel(item));
return externalDatasets;
}
public ExternalDatasetListingModel getSingle(ExternalDatasetDao externalDatasetDao, UUID id) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
ExternalDataset externalDataset = externalDatasetDao.find(id);
public ExternalDatasetListingModel getSingle(UUID id) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().find(id);
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetListingModel();
externalDatasetModel.fromDataModel(externalDataset);
return externalDatasetModel;
}
public static ExternalDataset create(ApiContext apiContext, eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel) throws Exception {
public ExternalDataset create(eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel) throws Exception {
ExternalDataset externalDataset = externalDatasetModel.toDataModel();
return apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().createOrUpdate(externalDataset);
}

View File

@ -2,7 +2,9 @@ package eu.eudat.logic.managers;
import eu.eudat.models.data.files.ContentFile;
import eu.eudat.logic.services.helpers.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@ -11,13 +13,21 @@ import java.util.List;
/**
* Created by ikalyvas on 3/15/2018.
*/
@Component
public class FileManager {
public static List<ContentFile> saveTempFile(MultipartFile file[], FileStorageService fileStorageService) throws IOException {
private FileStorageService fileStorageService;
@Autowired
public FileManager(FileStorageService fileStorageService) {
this.fileStorageService = fileStorageService;
}
public List<ContentFile> saveTempFile(MultipartFile file[]) throws IOException {
return fileStorageService.writeToTempFileSystem(file);
}
public static Resource getFile(String filename, String type, FileStorageService fileStorageService, String location) throws IOException {
public Resource getFile(String filename, String type, String location) throws IOException {
return fileStorageService.readFromFilesystem(filename, type, location);
}
}

View File

@ -1,6 +1,7 @@
package eu.eudat.logic.managers;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.data.invitation.Invitation;
@ -9,38 +10,59 @@ import eu.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.eudat.data.query.items.item.userinfo.UserInfoRequestItem;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class InvitationsManager {
public static void inviteUsers(ApiContext apiContext, Invitation invitation, Principal principal) throws Exception {
private ApiContext apiContext;
@Autowired
public InvitationsManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public void inviteUsers(Invitation invitation, Principal principal) throws Exception {
UserInfo principalUser = new UserInfo();
principalUser.setId(principal.getId());
List<UserInfoInvitationModel> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList());
List<UserInfo> alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(item -> item.toDataModel()).collect(Collectors.toList());
List<UserDMP> userInfoToUserDmp = new LinkedList<>();
for (UserInfo userInfo : alreadySignedInUsersEntities) {
UserDMP userDMP = new UserDMP();
userDMP.setUser(userInfo);
userInfoToUserDmp.add(userDMP);
}
DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(item -> item.toDataModel()).collect(Collectors.toList()), dataManagementPlan, principalUser);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), alreadySignedInUsersEntities, dataManagementPlan);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan);
}
public static List<UserInfoInvitationModel> getUsers(ApiContext apiContext, UserInfoRequestItem userInfoRequestItem) throws InstantiationException, IllegalAccessException {
public List<UserInfoInvitationModel> getUsers(UserInfoRequestItem userInfoRequestItem) throws InstantiationException, IllegalAccessException {
QueryableList<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoRequestItem.getCriteria());
List<UserInfoInvitationModel> userModels = users.select(item -> new UserInfoInvitationModel().fromDataModel(item));
return userModels;
}
public static UUID assignUserAcceptedInvitation(ApiContext apiContext, UUID invitationID, Principal principal) throws UnauthorisedException {
public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException {
eu.eudat.data.entities.Invitation invitation = apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().find(invitationID);
if (invitation == null)
throw new UnauthorisedException("There is no Data Management Plan assigned to this Link");
if (invitation.getAcceptedInvitation()) throw new UnauthorisedException("This Url Has Expired");
UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserDMP userDMP = new UserDMP();
userDMP.setUser(invitedUser);
userDMP.setDmp(invitation.getDmp());
userDMP.setRole(UserDMP.UserDMPRoles.USER.getValue());
DMP datamanagementPlan = invitation.getDmp();
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), invitedUser, datamanagementPlan);
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userDMP, datamanagementPlan);
invitation.setAcceptedInvitation(true);
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
return datamanagementPlan.getId();

View File

@ -0,0 +1,67 @@
package eu.eudat.logic.managers;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.entities.OrganisationDao;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.query.items.table.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.data.query.items.table.organisations.OrganisationsTableRequest;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.dmp.Organisation;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class OrganisationsManager {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public OrganisationsManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
public DataTableData<Organisation> getPagedOrganisations(OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception {
eu.eudat.data.entities.UserInfo userInfo = new eu.eudat.data.entities.UserInfo();
userInfo.setId(principal.getId());
OrganisationDao organisationDao = databaseRepository.getOrganisationDao();
QueryableList<eu.eudat.data.entities.Organisation> items = organisationDao.getWithCriteria(organisationsTableRequest.getCriteria());
QueryableList<eu.eudat.data.entities.Organisation> authItems = organisationDao.getAuthenticated(items, userInfo);
QueryableList<eu.eudat.data.entities.Organisation> pagedItems = PaginationManager.applyPaging(authItems, organisationsTableRequest);
List<Organisation> org = pagedItems.toList().stream().distinct().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList());
DataTableData<Organisation> organisationDataTableData = new DataTableData<>();
organisationDataTableData.setData(org);
organisationDataTableData.setTotalCount(pagedItems.count());
return organisationDataTableData;
}
public DataTableData<Organisation> getPublicPagedOrganisations(OrganisationsTableRequest organisationsTableRequest) throws Exception {
organisationsTableRequest.getCriteria().setPublic(true);
OrganisationDao organisationDao = databaseRepository.getOrganisationDao();
QueryableList<eu.eudat.data.entities.Organisation> items = organisationDao.getWithCriteria(organisationsTableRequest.getCriteria());
QueryableList<eu.eudat.data.entities.Organisation> pagedItems = PaginationManager.applyPaging(items, organisationsTableRequest);
List<Organisation> org = pagedItems.toList().stream().distinct().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList());
DataTableData<Organisation> organisationDataTableData = new DataTableData<>();
organisationDataTableData.setData(org);
organisationDataTableData.setTotalCount(pagedItems.count());
return organisationDataTableData;
}
}

View File

@ -9,6 +9,7 @@ import eu.eudat.data.dao.entities.UserInfoDao;
import eu.eudat.data.entities.Content;
import eu.eudat.data.entities.DMP;
import eu.eudat.exceptions.files.TempFileNotFoundException;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.external.ExternalSourcesItemModel;
import eu.eudat.models.data.external.ProjectsExternalSourcesModel;
@ -25,6 +26,7 @@ import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.helpers.FileStorageService;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.ParseException;
@ -35,53 +37,94 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Component
public class ProjectManager {
public DataTableData<eu.eudat.models.data.project.ProjectListingModel> getPaged(ProjectDao projectRepository, ProjectTableRequest projectTableRequest, Principal principal) throws Exception {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private FileStorageService fileStorageService;
private RemoteFetcher remoteFetcher;
public ProjectManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.fileStorageService = apiContext.getOperationsContext().getFileStorageService();
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
}
public DataTableData<eu.eudat.models.data.project.ProjectListingModel> getPaged(ProjectTableRequest projectTableRequest, Principal principal, String fieldsGroup) throws Exception {
eu.eudat.data.entities.UserInfo userInfo = new eu.eudat.data.entities.UserInfo();
userInfo.setId(principal.getId());
ProjectDao projectRepository = databaseRepository.getProjectDao();
QueryableList<eu.eudat.data.entities.Project> items = projectRepository.getWithCriteria(projectTableRequest.getCriteria());
QueryableList<eu.eudat.data.entities.Project> authItems = projectRepository.getAuthenticated(items, userInfo);
QueryableList<eu.eudat.data.entities.Project> pagedItems = PaginationManager.applyPaging(authItems, projectTableRequest);
DataTableData<eu.eudat.models.data.project.ProjectListingModel> dataTable = new DataTableData<>();
CompletableFuture projectsFuture = pagedItems.withHint(HintedModelFactory.getHint(ProjectListingModel.class)).selectAsync(item -> {
item.setDmps(item.getDmps().stream().filter(
dmp -> dmp.getCreator().getId().equals(principal.getId()) || dmp.getUsers().stream().filter(user -> user.getId().equals(principal.getId())).collect(Collectors.toList()).size() > 0)
.collect(Collectors.groupingBy(DMP::getGroupId))
.values().stream()
.map(dmps -> dmps.stream().reduce((first, second) -> {
if (first.getVersion() > second.getVersion()) return first;
else return second;
}).get())
.collect(Collectors.toSet()));
return new ProjectListingModel().fromDataModel(item);
}).whenComplete((results, throwable) -> {
dataTable.setData(results);
});
CompletableFuture projectsFuture;
if (fieldsGroup.equals("listing")) {
projectsFuture = pagedItems.withHint(HintedModelFactory.getHint(ProjectListingModel.class)).selectAsync(item -> {
item.setDmps(item.getDmps().stream().filter(
dmp -> dmp.getCreator().getId().equals(principal.getId()) || dmp.getUsers().stream().filter(user -> user.getUser().getId().equals(principal.getId())).collect(Collectors.toList()).size() > 0)
.collect(Collectors.groupingBy(DMP::getGroupId))
.values().stream()
.map(dmps -> dmps.stream().reduce((first, second) -> {
if (first.getVersion() > second.getVersion()) return first;
else return second;
}).get())
.collect(Collectors.toSet()));
return new ProjectListingModel().fromDataModelWIthDmps(item);
}).whenComplete((results, throwable) -> {
dataTable.setData(results);
});
} else {
projectsFuture = pagedItems.selectAsync(item -> new ProjectListingModel().fromDataModel(item))
.whenComplete((results, throwable) -> {
dataTable.setData(results);
});
}
CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count));
CompletableFuture.allOf(projectsFuture, countFuture).join();
return dataTable;
}
public eu.eudat.models.data.project.Project getSingle(ProjectDao projectRepository, String id) throws InstantiationException, IllegalAccessException {
public DataTableData<eu.eudat.models.data.project.ProjectListingModel> getPublicPaged(ProjectTableRequest projectTableRequest) throws Exception {
ProjectDao projectRepository = databaseRepository.getProjectDao();
projectTableRequest.getCriteria().setPublic(true);
QueryableList<eu.eudat.data.entities.Project> items = projectRepository.getWithCriteria(projectTableRequest.getCriteria());
QueryableList<eu.eudat.data.entities.Project> pagedItems = PaginationManager.applyPaging(items, projectTableRequest);
DataTableData<eu.eudat.models.data.project.ProjectListingModel> dataTable = new DataTableData<>();
CompletableFuture projectsFuture;
projectsFuture = pagedItems.selectAsync(item -> new ProjectListingModel().fromDataModel(item))
.whenComplete((results, throwable) -> {
dataTable.setData(results);
});
CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count));
CompletableFuture.allOf(projectsFuture, countFuture).join();
return dataTable;
}
public eu.eudat.models.data.project.Project getSingle(String id) throws InstantiationException, IllegalAccessException {
eu.eudat.models.data.project.Project project = new eu.eudat.models.data.project.Project();
project.fromDataModel(projectRepository.find(UUID.fromString(id)));
project.fromDataModel(databaseRepository.getProjectDao().find(UUID.fromString(id)));
return project;
}
public eu.eudat.data.entities.Project inactivate(ProjectDao projectRepository, String id) throws InstantiationException, IllegalAccessException {
public eu.eudat.data.entities.Project inactivate(String id) throws InstantiationException, IllegalAccessException {
ProjectDao projectRepository = databaseRepository.getProjectDao();
eu.eudat.data.entities.Project project = projectRepository.find(UUID.fromString(id));
project.setStatus(eu.eudat.data.entities.Project.Status.DELETED.getValue());
project = projectRepository.createOrUpdate(project);
return project;
}
public List<eu.eudat.models.data.project.Project> getCriteriaWithExternal(ApiContext apiContext, ProjectCriteriaRequest projectCriteria, RemoteFetcher remoteFetcher) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
public List<eu.eudat.models.data.project.Project> getCriteriaWithExternal(ProjectCriteriaRequest projectCriteria, Principal principal) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
eu.eudat.data.entities.UserInfo userInfo = new eu.eudat.data.entities.UserInfo();
userInfo.setId(principal.getId());
QueryableList<eu.eudat.data.entities.Project> items = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getWithCriteria(projectCriteria.getCriteria());
List<eu.eudat.models.data.project.Project> projects = items.select(item -> new Project().fromDataModel(item));
QueryableList<eu.eudat.data.entities.Project> authItems = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getAuthenticated(items, userInfo);
List<eu.eudat.models.data.project.Project> projects = authItems.select(item -> new Project().fromDataModel(item));
List<Map<String, String>> remoteRepos = remoteFetcher.getProjects(projectCriteria.getCriteria().getLike());
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);
for (ExternalSourcesItemModel externalListingItem : projectsExternalSourcesModel) {
@ -93,20 +136,21 @@ public class ProjectManager {
projects.add(project);
}
projects.sort(Comparator.comparing(x-> x.getLabel()));
projects.sort(Comparator.comparing(x -> x.getLabel()));
return projects;
}
public List<eu.eudat.models.data.project.Project> getCriteria(ProjectDao projectRepository, ProjectCriteriaRequest projectCriteria, RemoteFetcher remoteFetcher) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
public List<eu.eudat.models.data.project.Project> getCriteria(ProjectCriteriaRequest projectCriteria) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
ProjectDao projectRepository = databaseRepository.getProjectDao();
QueryableList<eu.eudat.data.entities.Project> items = projectRepository.getWithCriteria(projectCriteria.getCriteria());
if(projectCriteria.getLength() != null) items.take(projectCriteria.getLength());
if (projectCriteria.getLength() != null) items.take(projectCriteria.getLength());
List<eu.eudat.models.data.project.Project> projects = items.select(item -> new Project().fromDataModel(item));
return projects;
}
public static void createOrUpdate(FileStorageService fileStorageService, ProjectDao projectRepository, ContentDao contentRepository, UserInfoDao userInfoRepository, eu.eudat.models.data.project.Project project, Principal principal) throws ParseException, IOException {
public void createOrUpdate(eu.eudat.models.data.project.Project project, Principal principal) throws ParseException, IOException {
eu.eudat.data.entities.Project projectEntity = project.toDataModel();
if(project.getFiles() != null) {
if (project.getFiles() != null) {
for (ContentFile file : project.getFiles()) {
try {
ContentFile storedFile = fileStorageService.copyFromTempFileSystem(file);
@ -116,18 +160,18 @@ public class ProjectManager {
.parentType(Content.ParentType.PROJECT.getValue())
.uri("LOCAL:" + storedFile.getId())
.build();
projectEntity.setContent(contentRepository.createOrUpdate(content));
projectEntity.setContent(databaseRepository.getContentDao().createOrUpdate(content));
} catch (TempFileNotFoundException e) {
continue;
}
}
}
projectEntity.setType(eu.eudat.data.entities.Project.ProjectType.INTERNAL.getValue());
projectEntity.setCreationUser(userInfoRepository.find(principal.getId()));
projectRepository.createOrUpdate(projectEntity);
projectEntity.setCreationUser(databaseRepository.getUserInfoDao().find(principal.getId()));
databaseRepository.getProjectDao().createOrUpdate(projectEntity);
}
public void delete(ApiContext apiContext, UUID uuid) {
public void delete(UUID uuid) {
eu.eudat.data.entities.Project oldProject = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().find(uuid);
if (oldProject.getDmps().size() > 0)
throw new ProjectWithDMPsDeleteException("You cannot Remove Projects with DMPs");

View File

@ -0,0 +1,66 @@
package eu.eudat.logic.managers;
import eu.eudat.data.dao.criteria.ProjectCriteria;
import eu.eudat.data.dao.entities.ContentDao;
import eu.eudat.data.dao.entities.ProjectDao;
import eu.eudat.data.dao.entities.UserInfoDao;
import eu.eudat.data.entities.*;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.helpers.FileStorageService;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel;
import eu.eudat.models.data.quickwizard.QuickWizardModel;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.ParseException;
@Component
public class QuickWizardManager {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public QuickWizardManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
public Project createOrUpdate(eu.eudat.models.data.project.Project project, Principal principal) throws ParseException, IOException {
eu.eudat.data.entities.Project projectEntity = project.toDataModel();
projectEntity.setType(eu.eudat.data.entities.Project.ProjectType.INTERNAL.getValue());
projectEntity.setCreationUser(databaseRepository.getUserInfoDao().find(principal.getId()));
Project projectEntityRet = databaseRepository.getProjectDao().createOrUpdate(projectEntity);
return projectEntityRet;
}
public DMP createOrUpdate(DataManagementPlan dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel();
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
createProjectIfItDoesntExist(newDmp, user);
newDmp.setCreator(user);
DMP dmpret = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
return dmpret;
}
private void createProjectIfItDoesntExist(DMP newDmp, UserInfo userInfo) {
if (newDmp.getProject() != null) {
Project project = newDmp.getProject();
ProjectCriteria criteria = new ProjectCriteria();
criteria.setReference(project.getReference());
eu.eudat.data.entities.Project projectEntity = databaseRepository.getProjectDao().getWithCriteria(criteria).getSingleOrDefault();
if (projectEntity != null) project.setId(projectEntity.getId());
else {
project.setType(Project.ProjectType.EXTERNAL.getValue());
databaseRepository.getProjectDao().createOrUpdate(project);
}
}
}
}

View File

@ -5,12 +5,20 @@ import eu.eudat.data.entities.Registry;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.registries.RegistryModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by ikalyvas on 9/3/2018.
*/
@Component
public class RegistryManager {
public static Registry create(ApiContext apiContext, RegistryModel registryModel) throws Exception {
private ApiContext apiContext;
@Autowired
public RegistryManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public Registry create(RegistryModel registryModel) throws Exception {
Registry registry = registryModel.toDataModel();
return apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().createOrUpdate(registry);
}

View File

@ -10,21 +10,34 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by ikalyvas on 2/5/2018.
*/
@Component
public class ResearcherManager {
public static Researcher create(ApiContext apiContext, eu.eudat.models.data.researcher.Researcher researcher) throws Exception {
private ApiContext apiContext;
private RemoteFetcher remoteFetcher;
@Autowired
public ResearcherManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
}
public Researcher create(eu.eudat.models.data.researcher.Researcher researcher) throws Exception {
Researcher researcherEntity = researcher.toDataModel();
return apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcherEntity);
}
public static List<eu.eudat.models.data.dmp.Researcher> getCriteriaWithExternal(ApiContext apiContext, RemoteFetcher remoteFetcher, ResearcherCriteriaRequest researcherCriteriaRequest) throws HugeResultSet, NoURLFound {
public List<eu.eudat.models.data.dmp.Researcher> getCriteriaWithExternal(ResearcherCriteriaRequest researcherCriteriaRequest) throws HugeResultSet, NoURLFound {
QueryableList<eu.eudat.data.entities.Researcher> items = apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().getWithCriteria(researcherCriteriaRequest.getCriteria());
List<eu.eudat.models.data.dmp.Researcher> researchers = items.select(item -> new eu.eudat.models.data.dmp.Researcher().fromDataModel(item));
@ -32,12 +45,12 @@ public class ResearcherManager {
ResearchersExternalSourcesModel researchersExternalSourcesModel = new ResearchersExternalSourcesModel().fromExternalItem(remoteRepos);
for (ExternalSourcesItemModel externalListingItem : researchersExternalSourcesModel) {
eu.eudat.models.data.dmp.Researcher researcher = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ResearcherBuilder.class)
.label(externalListingItem.getAbbreviation()).id(externalListingItem.getId())
.label(externalListingItem.getAbbreviation())
.id(externalListingItem.getId())
.name(externalListingItem.getName())
.build();
researchers.add(researcher);
}
researchers.stream().distinct();
return researchers;
return researchers.stream().distinct().collect(Collectors.toList());
}
}

View File

@ -5,12 +5,23 @@ import eu.eudat.data.entities.Service;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.registries.RegistryModel;
import eu.eudat.models.data.services.ServiceModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by ikalyvas on 9/3/2018.
*/
@Component
public class ServiceManager {
public static Service create(ApiContext apiContext, ServiceModel serviceModel) throws Exception {
private ApiContext apiContext;
@Autowired
public ServiceManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public Service create(ServiceModel serviceModel) throws Exception {
Service service = serviceModel.toDataModel();
return apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().createOrUpdate(service);
}

View File

@ -1,7 +1,11 @@
package eu.eudat.logic.managers;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.UserInfoDao;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.exceptions.security.UnauthorisedException;
@ -15,22 +19,31 @@ import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserInfo;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.models.data.userinfo.UserProfile;
import eu.eudat.queryable.QueryableList;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class UserManager {
public static eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.data.entities.DatasetProfile profile) {
private ApiContext apiContext;
@Autowired
public UserManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.data.entities.DatasetProfile profile) {
Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition());
Element root = (Element) viewStyleDoc.getDocumentElement();
eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel viewstyle = new eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel().fromXml(root);
@ -41,7 +54,7 @@ public class UserManager {
return datasetprofile;
}
public static DataTableData<UserListingModel> getPaged(ApiContext apiContext, UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
public DataTableData<UserListingModel> getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
QueryableList<eu.eudat.data.entities.UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class));
QueryableList<eu.eudat.data.entities.UserInfo> pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);
@ -49,15 +62,15 @@ public class UserManager {
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build();
}
public static UserProfile getSingle(ApiContext apiContext, UUID userId) throws Exception {
public UserProfile getSingle(UUID userId) throws Exception {
eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId);
UserProfile profile = new UserProfile().fromDataModel(user);
List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable(), user).take(5).toList();
List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable(), userId).take(5).toList();
profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList()));
return profile;
}
public static void editRoles(ApiContext apiContext, UserListingModel user) {
public void editRoles(UserListingModel user) {
eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId());
userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item));
for (Integer role : user.getAppRoles()) {
@ -66,7 +79,7 @@ public class UserManager {
}
}
public static void updateSettings(ApiContext apiContext, Map<String, Object> settings, Principal principal) throws IOException {
public void updateSettings(Map<String, Object> settings, Principal principal) throws IOException {
eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo);
HashMap<String, Object> result =
@ -77,9 +90,54 @@ public class UserManager {
.createOrUpdate(userInfo);
}
public static Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) {
public Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) {
Principal principal = authenticationServiceImpl.Touch(credentials);
if (principal == null) throw new UnauthorisedException("Could not Sign In User");
return principal;
}
public DataTableData<UserListingModel> getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception {
//UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao();
DMPDao dmpDao = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao();
// Gets all the DMPs the user is associated.
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
QueryableList<DMP> dmpItmes = dmpDao.getWithCriteria(dataManagementPlanCriteria);
QueryableList<DMP> dmpAuthItems = dmpDao.getAuthenticated(dmpItmes, principal.getId());
List<DMP> dmpList = dmpAuthItems.toList();
// List to place the associated users.
List<UserListingModel> associatedUsersList = new LinkedList<>();
// Iterate through the DMP list and get the users associated.
for (DMP dmp : dmpList) {
for (UserDMP userDMP : dmp.getUsers()) {
if (userDMP.getUser().getId() != principal.getId()) {
associatedUsersList.add(new UserListingModel().fromDataModel(userDMP.getUser()));
}
}
}
// Remove duplicates from the associated users list.
associatedUsersList = associatedUsersList.stream().distinct().collect(Collectors.toList());
// Filter using the criteria.
List<UserListingModel> associatedUsersListFiltered = new LinkedList<>();
associatedUsersList.stream()
.filter(item -> item.getName().toLowerCase().contains(userInfoTableRequestItem.getCriteria().getCollaboratorLike().toLowerCase())).forEach(
o -> {
associatedUsersListFiltered.add(o);
}
);
/*QueryableList<eu.eudat.data.entities.UserInfo> users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class));
QueryableList<eu.eudat.data.entities.UserInfo> pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);*/
//List<UserListingModel> modelUsers = pagedUsers.select(item -> new listing model().fromDataModel(item));
DataTableData<UserListingModel> dataTableData = new DataTableData<>();
dataTableData.setData(associatedUsersListFiltered);
dataTableData.setTotalCount((long)associatedUsersListFiltered.size());
return dataTableData;
}
}

View File

@ -31,7 +31,7 @@ public class DevelConfigLoader implements ConfigLoader {
JAXBContext jaxbContext = JAXBContext.newInstance(ExternalUrls.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
is = new URL("file:///"+current+"/dmp-backend/web/src/main/resources/ExternalUrls.xml").openStream();
is = new URL("file:///"+current+"/web/src/main/resources/ExternalUrls.xml").openStream();
externalUrls = (ExternalUrls) jaxbUnmarshaller.unmarshal(is);
} catch (Exception ex) {

View File

@ -47,7 +47,7 @@ public class FacebookTokenValidator implements TokenValidator {
user.setEmail(profile.getEmail());
user.setId(profile.getId());
user.setIsVerified(profile.isVerified());
//user.setIsVerified(profile.isVerified());
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK);
String url = (String)((Map<String,Object> )((Map<String,Object> )profile.getExtraData().get("picture")).get("data")).get("url");

View File

@ -12,9 +12,9 @@ import java.util.concurrent.CompletableFuture;
public interface InvitationService {
void assignToDmp(DMPDao dmpDao, List<eu.eudat.data.entities.UserInfo> users, DMP dmp);
void assignToDmp(DMPDao dmpDao, List<eu.eudat.data.entities.UserDMP> users, DMP dmp);
void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserInfo user, DMP dmp);
void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserDMP user, DMP dmp);
void createInvitations(InvitationDao invitationDao, MailService mailService, List<eu.eudat.data.entities.UserInfo> users, DMP dmp, eu.eudat.data.entities.UserInfo creator) throws MessagingException;

View File

@ -36,16 +36,16 @@ public class InvitationServiceImpl implements InvitationService {
}
@Override
public void assignToDmp(DMPDao dmpDao, List<eu.eudat.data.entities.UserInfo> users, DMP dmp) {
for (eu.eudat.data.entities.UserInfo user : users) {
public void assignToDmp(DMPDao dmpDao, List<eu.eudat.data.entities.UserDMP> users, DMP dmp) {
for (eu.eudat.data.entities.UserDMP user : users) {
dmp.getUsers().add(user);
}
dmpDao.createOrUpdate(dmp);
}
@Override
public void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserInfo user, DMP dmp) {
if (!dmp.getUsers().stream().map(x -> x.getId()).collect(Collectors.toList()).contains(user.getId())) {
public void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserDMP user, DMP dmp) {
if (!dmp.getUsers().stream().map(x -> x.getUser().getId()).collect(Collectors.toList()).contains(user.getId())) {
dmp.getUsers().add(user);
dmpDao.createOrUpdate(dmp);
}

View File

@ -70,6 +70,7 @@ public class ModelBuilder {
if (type.equals("checkBox")) return (FieldData<U>) new CheckBoxData().fromData(data);
if (type.equals("freetext")) return (FieldData<U>) new FreeTextData().fromData(data);
if (type.equals("textarea")) return (FieldData<U>) new TextAreaData().fromData(data);
if (type.equals("datePicker")) return (FieldData<U>) new DatePickerData().fromData(data);
return null;
}
@ -86,6 +87,7 @@ public class ModelBuilder {
if (type.equals("checkBox")) return (FieldData<U>) new CheckBoxData().fromData(data);
if (type.equals("freetext")) return (FieldData<U>) new FreeTextData().fromData(data);
if (type.equals("textarea")) return (FieldData<U>) new TextAreaData().fromData(data);
if (type.equals("datePicker")) return (FieldData<U>) new DatePickerData().fromData(data);
return null;
}

View File

@ -134,7 +134,7 @@ public class WordBuilder {
public void createCompositeFields(List<FieldSet> compositeFields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService) {
if (createListing) this.addListing(mainDocumentPart, indent, true, true);
compositeFields.forEach(compositeField -> {
if (visibilityRuleService.isElementVisible(compositeField.getId())) {
if (visibilityRuleService.isElementVisible(compositeField.getId()) && hasVisibleFields(compositeField, visibilityRuleService)) {
if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty() && !createListing) {
XWPFParagraph paragraph = addParagraphContent(compositeField.getNumbering() + " " + compositeField.getTitle(), mainDocumentPart, ParagraphStyle.HEADER3, numId);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
@ -175,11 +175,6 @@ public class WordBuilder {
return paragraph;
}
public void addStyling(List<TextStyle> styles, String color) {
}
public void addListing(XWPFDocument document, int indent, Boolean question, Boolean hasIndication) {
CTLvl cTLvl = this.cTAbstractNum.addNewLvl();
@ -231,8 +226,13 @@ public class WordBuilder {
return field.getValue();
case "textarea":
return field.getValue();
case "datepicker":
return field.getValue();
}
return null;
}
private boolean hasVisibleFields(FieldSet compositeFields, VisibilityRuleService visibilityRuleService) {
return compositeFields.getFields().stream().anyMatch(field -> visibilityRuleService.isElementVisible(field.getId()));
}
}

View File

@ -22,12 +22,15 @@ import java.util.UUID;
*/
public class ExportXmlBuilder {
public File build(PagedDatasetProfile pagedDatasetProfile, VisibilityRuleService visibilityRuleService) throws IOException {
public File build(PagedDatasetProfile pagedDatasetProfile, UUID datasetProfileId, VisibilityRuleService visibilityRuleService) throws IOException {
File xmlFile = new File(UUID.randomUUID() + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument();
Element root = xmlDoc.createElement("root");
Element datasetProfile = xmlDoc.createElement("datasetProfileId");
datasetProfile.setTextContent(datasetProfileId.toString());
root.appendChild(datasetProfile);
root.appendChild(createPages(pagedDatasetProfile.getPages(), visibilityRuleService, xmlDoc));
xmlDoc.appendChild(root);
String xml = XmlBuilder.generateXml(xmlDoc);
@ -51,13 +54,9 @@ public class ExportXmlBuilder {
sections.forEach(section -> {
Element elementSection = element.createElement("section");
if (visibilityRuleService.isElementVisible(section.getId())) {
Element elementInnerSections = element.createElement("sections");
Element compositeFields = element.createElement("composite-field");
elementInnerSections.appendChild(createSections(section.getSections(), visibilityRuleService, element));
compositeFields.appendChild(createCompositeFields(section.getCompositeFields(), visibilityRuleService, element));
elementSection.appendChild(elementInnerSections);
elementSection.appendChild(createSections(section.getSections(), visibilityRuleService, element));
elementSection.appendChild(createCompositeFields(section.getCompositeFields(), visibilityRuleService, element));
elementSections.appendChild(elementSection);
elementSections.appendChild(compositeFields);
}
});
return elementSections;
@ -66,7 +65,7 @@ public class ExportXmlBuilder {
public Element createCompositeFields(List<FieldSet> compositeFields, VisibilityRuleService visibilityRuleService, Document element) {
Element elementComposites = element.createElement("composite-fields");
compositeFields.forEach(compositeField -> {
if (visibilityRuleService.isElementVisible(compositeField.getId())) {
if (visibilityRuleService.isElementVisible(compositeField.getId()) && hasVisibleFields(compositeField, visibilityRuleService)) {
Element composite = element.createElement("composite-field");
composite.setAttribute("id", compositeField.getId());
if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty()) {
@ -94,11 +93,17 @@ public class ExportXmlBuilder {
Element elementField = element.createElement("field");
elementField.setAttribute("id", field.getId());
if (field.getValue() != null && !field.getValue().isEmpty()) {
elementField.setTextContent(field.getValue());
Element valueField = element.createElement("value");
valueField.setTextContent(field.getValue());
elementField.appendChild(valueField);
}
elementFields.appendChild(elementField);
}
});
return elementFields;
}
private boolean hasVisibleFields(FieldSet compositeFields, VisibilityRuleService visibilityRuleService) {
return compositeFields.getFields().stream().anyMatch(field -> visibilityRuleService.isElementVisible(field.getId()));
}
}

View File

@ -0,0 +1,264 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml;
import eu.eudat.models.data.admin.components.datasetprofile.Page;
import eu.eudat.models.data.components.commons.datafield.*;
import eu.eudat.models.data.user.components.datasetprofile.Field;
import eu.eudat.models.data.user.components.datasetprofile.FieldSet;
import eu.eudat.models.data.user.components.datasetprofile.Section;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
public class ExportXmlBuilderDatasetProfile {
public File build(eu.eudat.models.data.user.composite.DatasetProfile datasetProfile) throws IOException {
File xmlFile = new File(UUID.randomUUID() + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument();
// Element root = xmlDoc.createElement("root");
// root.appendChild(createPages(datasetProfile.getPages(), datasetProfile.getSections(), xmlDoc));
xmlDoc.appendChild(createPages(datasetProfile.getPages(), datasetProfile.getSections(), xmlDoc));
String xml = XmlBuilder.generateXml(xmlDoc);
writer.write(xml);
writer.close();
return xmlFile;
}
public Element createPages(List<Page> datasetProfilePages, List<Section> sections, Document element) {
Element pages = element.createElement("pages");
datasetProfilePages.forEach(item -> {
Element page = element.createElement("page");
page.setAttribute("id", "" + item.getId());
page.setAttribute("ordinal", "" + item.getOrdinal());
page.setAttribute("title", "" + item.getTitle());
sections.forEach(sectionFromLis -> {
if (sectionFromLis.getPage().equals(item.getId())) {
Element elementSections = element.createElement("sections");
page.appendChild(createSections(sectionFromLis, element, elementSections));
}
});
pages.appendChild(page);
});
return pages;
}
public Element createSections(Section sections, Document element, Element elementSections) {
// if (sections.getSections() != null) {
sections.getSections().forEach(sectionFor -> {
Element elementSectionsChild = element.createElement("section");
elementSections.appendChild(createSections(sectionFor, element, elementSectionsChild));
});
// }
elementSections.setAttribute("defaultVisibility", "" + sections.getDefaultVisibility());
elementSections.setAttribute("id", "" + sections.getId());
elementSections.setAttribute("ordinal", "" + sections.getOrdinal());
elementSections.setAttribute("page", "" + sections.getPage());
elementSections.setAttribute("page", "" + sections.getPage());
if (sections.getCompositeFields() != null) {
elementSections.appendChild(createFieldSet(sections.getCompositeFields(), element));
}
if (sections.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(sections.getNumbering());
elementSections.appendChild(numbering);
}
if (sections.getDescription() != null) {
Element description = element.createElement("description");
description.setTextContent(sections.getDescription());
elementSections.appendChild(description);
}
if (sections.getTitle() != null) {
Element title = element.createElement("title");
title.setTextContent(sections.getTitle());
elementSections.appendChild(title);
}
return elementSections;
}
public Element createFieldSet(List<FieldSet> fieldSet, Document element) {
Element elementFieldSets = element.createElement("field-Sets");
fieldSet.forEach(field -> {
Element composite = element.createElement("field-Set");
composite.setAttribute("id", field.getId());
composite.setAttribute("ordinal", "" + field.getOrdinal());
if (field.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(field.getNumbering());
composite.appendChild(numbering);
}
Element commentField = element.createElement("CommentField");
commentField.setTextContent("" + field.getHasCommentField());
composite.appendChild(commentField);
composite.appendChild(createFields(field.getFields(), element));
if (field.getMultiplicity() != null) {
Element multiplicity = element.createElement("multiplicity");
multiplicity.setAttribute("max", "" + field.getMultiplicity().getMax());
multiplicity.setAttribute("min", "" + field.getMultiplicity().getMin());
composite.appendChild(multiplicity);
}
if (field.getTitle() != null && !field.getTitle().isEmpty()) {
Element title = element.createElement("title");
title.setTextContent(field.getTitle());
composite.appendChild(title);
}
if (field.getDescription() != null && !field.getDescription().isEmpty()) {
Element title = element.createElement("description");
title.setTextContent(field.getDescription());
composite.appendChild(title);
}
if (field.getExtendedDescription() != null && !field.getExtendedDescription().isEmpty()) {
Element extendedDescription = element.createElement("extendedDescription");
extendedDescription.setTextContent(field.getExtendedDescription());
composite.appendChild(extendedDescription);
}
if (field.getAdditionalInformation() != null && !field.getAdditionalInformation().isEmpty()) {
Element additionalInformation = element.createElement("additionalInformation");
additionalInformation.setTextContent(field.getAdditionalInformation());
composite.appendChild(additionalInformation);
}
elementFieldSets.appendChild(composite);
});
return elementFieldSets;
}
public Element createFields(List<Field> fields, Document element) {
Element elementFields = element.createElement("fields");
fields.forEach(field -> {
Element elementField = element.createElement("field");
elementField.setAttribute("id", field.getId());
elementField.setAttribute("ordinal", "" + field.getOrdinal());
if (field.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(field.getNumbering());
elementField.appendChild(numbering);
}
if (field.getValidations() != null) {
Element validations = element.createElement("validations");
field.getValidations().forEach(validation -> {
Element validationChild = element.createElement("validation");
validationChild.setAttribute("type", "" + validation);
validations.appendChild(validationChild);
});
elementField.appendChild(validations);
}
if (field.getDefaultValue() != null) {
Element defaultValue = element.createElement("defaultValue");
defaultValue.setAttribute("type", field.getDefaultValue().getType());
defaultValue.setAttribute("value", field.getDefaultValue().getValue());
elementField.appendChild(defaultValue);
}
if (field.getVisible() != null) {
Element visible = element.createElement("visible");
visible.setAttribute("style", "" + field.getVisible().getStyle());
field.getVisible().getRules().forEach(rule -> {
Element ruleChild = element.createElement("rule");
ruleChild.setAttribute("ruleStyle", "" + rule.getRuleStyle());
ruleChild.setAttribute("target", "" + rule.getTarget());
ruleChild.setAttribute("type", "" + rule.getRuleType());
Element ruleChildValue = element.createElement("value");
ruleChildValue.setAttribute("type", "" + rule.getValueType());
ruleChildValue.setTextContent(rule.getValue());
ruleChild.appendChild(ruleChildValue);
visible.appendChild(ruleChild);
});
elementField.appendChild(visible);
}
if (field.getViewStyle() != null) {
Element viewStyle = element.createElement("viewStyle");
viewStyle.setAttribute("cssClass", field.getViewStyle().getCssClass());
viewStyle.setAttribute("renderStyle", field.getViewStyle().getRenderStyle());
elementField.appendChild(viewStyle);
}
if (field.getData() != null) {
Element dataOut = element.createElement("data");
if (field.getViewStyle().getRenderStyle().equals("combobox")) {
ComboBoxData comboBoxDataObject = (ComboBoxData) field.getData();
if (comboBoxDataObject.getType().equals("wordlist")) {
WordListData wordListDataObject = (WordListData) field.getData();
dataOut.setAttribute("label", wordListDataObject.getLabel());
dataOut.setAttribute("type", wordListDataObject.getType());
Element options = element.createElement("options");
wordListDataObject.getOptions().forEach(optionChildFor -> {
Element optionChild = element.createElement("option");
optionChild.setAttribute("label", optionChildFor.getLabel());
optionChild.setAttribute("value", optionChildFor.getValue());
options.appendChild(optionChild);
});
dataOut.appendChild(options);
} else if (comboBoxDataObject.getType().equals("autocomplete")) {
AutoCompleteData autoCompleteDataObject = (AutoCompleteData) field.getData();
dataOut.setAttribute("label", autoCompleteDataObject.getLabel());
dataOut.setAttribute("type", autoCompleteDataObject.getType());
dataOut.setAttribute("optionsRoot", autoCompleteDataObject.getOptionsRoot());
dataOut.setAttribute("url", autoCompleteDataObject.getUrl());
if (autoCompleteDataObject.getAutoCompleteOptions() != null) {
Element optionChild = element.createElement("option");
optionChild.setAttribute("label", autoCompleteDataObject.getAutoCompleteOptions().getLabel());
optionChild.setAttribute("value", autoCompleteDataObject.getAutoCompleteOptions().getValue());
dataOut.appendChild(optionChild);
}
}
} else if (field.getViewStyle().getRenderStyle().equals("booleanDecision")) {
BooleanDecisionData booleanDecisionDataObject = (BooleanDecisionData) field.getData();
dataOut.setAttribute("label", booleanDecisionDataObject.getLabel());
} else if (field.getViewStyle().getRenderStyle().equals("radiobox")) {
RadioBoxData radioBoxDataObject = (RadioBoxData) field.getData();
dataOut.setAttribute("label", radioBoxDataObject.getLabel());
Element options = element.createElement("options");
radioBoxDataObject.getOptions().forEach(optionChildFor -> {
Element optionChild = element.createElement("option");
optionChild.setAttribute("label", optionChildFor.getLabel());
optionChild.setAttribute("value", optionChildFor.getValue());
options.appendChild(optionChild);
});
dataOut.appendChild(options);
} else if (field.getViewStyle().getRenderStyle().equals("checkBox")) {
CheckBoxData checkBoxDataObject = (CheckBoxData) field.getData();
dataOut.setAttribute("label", checkBoxDataObject.getLabel());
} else if (field.getViewStyle().getRenderStyle().equals("freetext")) {
FreeTextData freeTextDataObject = (FreeTextData) field.getData();
dataOut.setAttribute("label", freeTextDataObject.getLabel());
} else if (field.getViewStyle().getRenderStyle().equals("textarea")) {
TextAreaData textAreaDataObject = (TextAreaData) field.getData();
dataOut.setAttribute("label", textAreaDataObject.getLabel());
} else if (field.getViewStyle().getRenderStyle().equals("datePicker")) {
DatePickerData datePickerDataObject = (DatePickerData) field.getData();
dataOut.setAttribute("label", datePickerDataObject.getLabel());
}
elementField.appendChild(dataOut);
}
elementFields.appendChild(elementField);
});
return elementFields;
}
}

View File

@ -0,0 +1,26 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;
public class ImportXmlBuilderDatasetProfile {
public DatasetProfile build(File xmlFile) throws IOException {
DatasetProfile datasetProfile = new DatasetProfile();
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(DatasetProfile.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
datasetProfile = (DatasetProfile) unmarshaller.unmarshal(xmlFile);
} catch (JAXBException e) {
e.printStackTrace();
}
return datasetProfile;
}
}

View File

@ -0,0 +1,39 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;
@XmlRootElement(name = "pages")
public class DatasetProfile {
private List<Page> page;
@XmlElement(name = "page")
public List<Page> getPage() {
return page;
}
public void setPage(List<Page> page) {
this.page = page;
}
public eu.eudat.models.data.admin.composite.DatasetProfile toAdminCompositeModel(String label){
eu.eudat.models.data.admin.composite.DatasetProfile newDatasetEntityProfile = new eu.eudat.models.data.admin.composite.DatasetProfile();
newDatasetEntityProfile.setLabel(label);
newDatasetEntityProfile.setStatus(eu.eudat.data.entities.DatasetProfile.Status.SAVED.getValue());
List<eu.eudat.models.data.admin.components.datasetprofile.Page> pagesDatasetEntity = new LinkedList<>();
List<eu.eudat.models.data.admin.components.datasetprofile.Section> sectionDatasetEntity = new LinkedList<>();
for (Page xmlPage: page) {
pagesDatasetEntity.add(xmlPage.toAdminCompositeModelPage());
sectionDatasetEntity.add(xmlPage.toAdminCompositeModelSection());
}
newDatasetEntityProfile.setPages(pagesDatasetEntity);
newDatasetEntityProfile.setSections(sectionDatasetEntity);
return newDatasetEntityProfile;
}
}

View File

@ -0,0 +1,127 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel;
import eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "field-Set")
public class FieldSet {
private String id;
private int ordinal;
private Fields fields;
private String numbering;
private Boolean commentField;
private Multiplicity multiplicity;
private String description;
private String extendedDescription;
private String additionalInformation;
private String title;
@XmlAttribute(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name = "ordinal")
public int getOrdinal() {
return ordinal;
}
public void setOrdinal(int ordinal) {
this.ordinal = ordinal;
}
@XmlElement(name = "fields")
public Fields getFields() {
return fields;
}
public void setFields(Fields fields) {
this.fields = fields;
}
@XmlElement(name = "numbering")
public String getNumbering() {
return numbering;
}
public void setNumbering(String numbering) {
this.numbering = numbering;
}
@XmlElement(name = "CommentField")
public Boolean getCommentField() {
return commentField;
}
public void setCommentField(Boolean commentField) {
this.commentField = commentField;
}
@XmlElement(name = "multiplicity")
public Multiplicity getMultiplicity() {
return multiplicity;
}
public void setMultiplicity(Multiplicity multiplicity) {
this.multiplicity = multiplicity;
}
@XmlElement(name = "title")
public String getTitle() {
return title;
}
@XmlElement(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@XmlElement(name = "extendedDescription")
public String getExtendedDescription() {
return extendedDescription;
}
public void setExtendedDescription(String extendedDescription) {
this.extendedDescription = extendedDescription;
}
@XmlElement(name = "additionalInformation")
public String getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(String additionalInformation) {
this.additionalInformation = additionalInformation;
}
public void setTitle(String title) {
this.title = title;
}
public eu.eudat.models.data.admin.components.datasetprofile.FieldSet toAdminCompositeModelSection() {
eu.eudat.models.data.admin.components.datasetprofile.FieldSet fieldSet1Entity = new eu.eudat.models.data.admin.components.datasetprofile.FieldSet();
fieldSet1Entity.setId(this.id);
fieldSet1Entity.setOrdinal(this.ordinal);
fieldSet1Entity.setHasCommentField(this.commentField != null ? this.commentField : false);
fieldSet1Entity.setMultiplicity(this.multiplicity != null ? this.multiplicity.toAdminCompositeModelSection() : null);
fieldSet1Entity.setTitle(this.title);
fieldSet1Entity.setDescription(this.description);
fieldSet1Entity.setExtendedDescription(this.extendedDescription);
fieldSet1Entity.setAdditionalInformation(this.additionalInformation);
fieldSet1Entity.setFields(this.fields.toAdminCompositeModelSection());
return fieldSet1Entity;
}
}

View File

@ -0,0 +1,30 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;
@XmlRootElement(name = "field-Sets")
public class FieldSets {
List<FieldSet> fieldSet;
@XmlElement(name = "field-Set")
public List<FieldSet> getFieldSet() {
return fieldSet;
}
public void setFieldSet(List<FieldSet> fieldSet) {
this.fieldSet = fieldSet;
}
public List<eu.eudat.models.data.admin.components.datasetprofile.FieldSet> toAdminCompositeModelSection(){
List<eu.eudat.models.data.admin.components.datasetprofile.FieldSet> fieldSetEntity = new LinkedList<>();
if(this.fieldSet!=null)
for (FieldSet xmlFieldSet:this.fieldSet){
fieldSetEntity.add(xmlFieldSet.toAdminCompositeModelSection());
}
return fieldSetEntity;
}
}

View File

@ -0,0 +1,36 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "defaultValue")
public class DefaultValue {
private String type;
private String value;
@XmlAttribute(name = "type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@XmlAttribute(name = "value")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public eu.eudat.models.data.components.commons.DefaultValue toAdminCompositeModelSection(){
eu.eudat.models.data.components.commons.DefaultValue defaultValueEntity =new eu.eudat.models.data.components.commons.DefaultValue();
defaultValueEntity.setValue(value);
defaultValueEntity.setType(type);
return defaultValueEntity;
}
}

View File

@ -0,0 +1,123 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import eu.eudat.logic.utilities.builders.ModelBuilder;
import eu.eudat.models.data.components.commons.datafield.FieldData;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;
@XmlRootElement(name = "field")
public class Field {
private String id;
private int ordinal;
private String numbering;
private List<validations> validations;
private DefaultValue defaultValue;
private Visible visible;
private ViewStyle viewStyle;
private Object data;
@XmlAttribute(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name = "ordinal")
public int getOrdinal() {
return ordinal;
}
public void setOrdinal(int ordinal) {
this.ordinal = ordinal;
}
@XmlElement(name = "numbering")
public String getNumbering() {
return numbering;
}
public void setNumbering(String numbering) {
this.numbering = numbering;
}
@XmlElement(name = "validations")
public List<eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields.validations> getValidations() {
return validations;
}
public void setValidations(List<eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields.validations> validations) {
this.validations = validations;
}
@XmlElement(name = "defaultValue")
public DefaultValue getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(DefaultValue defaultValue) {
this.defaultValue = defaultValue;
}
@XmlElement(name = "visible")
public Visible getVisible() {
return visible;
}
public void setVisible(Visible visible) {
this.visible = visible;
}
@XmlElement(name = "viewStyle")
public ViewStyle getViewStyle() {
return viewStyle;
}
public void setViewStyle(ViewStyle viewStyle) {
this.viewStyle = viewStyle;
}
@XmlElement(name = "data")
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
public eu.eudat.models.data.admin.components.datasetprofile.Field toAdminCompositeModelSection() {
eu.eudat.models.data.admin.components.datasetprofile.Field fieldEntity =new eu.eudat.models.data.admin.components.datasetprofile.Field();
fieldEntity.setId(this.id);
fieldEntity.setOrdinal(this.ordinal);
List<Integer> validationList = new LinkedList<>();
for(validations validation:this.validations){
if(validation.getValidation()!=null)
validationList.add(validation.toAdminCompositeModelSection());
}
fieldEntity.setValidations(validationList);
fieldEntity.setDefaultValue(this.defaultValue.toAdminCompositeModelSection());
fieldEntity.setVisible(this.visible.toAdminCompositeModelSection());
fieldEntity.setViewStyle(this.viewStyle.toAdminCompositeModelSection());
FieldData data = new ModelBuilder().toFieldData(null, this.viewStyle.getRenderStyle(), (Element) this.data);
// fieldEntity.setData( data.fromXml((Element) this.data));
fieldEntity.setData( data.toMap((Element)this.data));
return fieldEntity;
}
}

View File

@ -0,0 +1,38 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;
@XmlRootElement(name = "fields")
public class Fields {
private List<Field> field;
@XmlElement(name = "field")
public List<Field> getField() {
return field;
}
public void setField(List<Field> field) {
this.field = field;
}
public List<eu.eudat.models.data.admin.components.datasetprofile.Field> toAdminCompositeModelSection() {
List<eu.eudat.models.data.admin.components.datasetprofile.Field> fieldsEntity = new LinkedList<>();
if (this.field != null)
for (Field xmlField : this.field) {
fieldsEntity.add(xmlField.toAdminCompositeModelSection());
}
return fieldsEntity;
}
}

View File

@ -0,0 +1,57 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "rule")
public class Rule{
private String ruleStyle;
private String target;
private String type;
private Value value;
@XmlAttribute(name = "ruleStyle")
public String getRuleStyle() {
return ruleStyle;
}
public void setRuleStyle(String ruleStyle) {
this.ruleStyle = ruleStyle;
}
@XmlAttribute(name = "target")
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
@XmlAttribute(name = "type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@XmlElement(name = "value")
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
public eu.eudat.models.data.components.commons.Rule toAdminCompositeModelSection(){
eu.eudat.models.data.components.commons.Rule ruleEntity = new eu.eudat.models.data.components.commons.Rule();
ruleEntity.setRuleStyle(ruleStyle);
ruleEntity.setTarget(target);
ruleEntity.setRuleType(type);
ruleEntity.setValueType(value.getType());
ruleEntity.setValue(value.getValue());
return ruleEntity;
}
}

View File

@ -0,0 +1,19 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "validation")
public class Validation {
private int type;
@XmlAttribute(name = "type")
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}

View File

@ -0,0 +1,30 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement(name = "value")
public class Value {
private String type;
private String value;
@XmlAttribute(name = "type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

View File

@ -0,0 +1,36 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "viewStyle")
public class ViewStyle {
private String cssClass;
private String renderStyle;
@XmlAttribute(name = "cssClass")
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
@XmlAttribute(name = "renderStyle")
public String getRenderStyle() {
return renderStyle;
}
public void setRenderStyle(String renderStyle) {
this.renderStyle = renderStyle;
}
public eu.eudat.models.data.components.commons.ViewStyle toAdminCompositeModelSection(){
eu.eudat.models.data.components.commons.ViewStyle viewStyleEntity = new eu.eudat.models.data.components.commons.ViewStyle();
viewStyleEntity.setCssClass(this.cssClass);
viewStyleEntity.setRenderStyle(this.renderStyle);
return viewStyleEntity;
}
}

Some files were not shown because too many files have changed in this diff Show More